Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HarmonicMean.py,v 1.5 2009/08/07 07:19:19 rliebscher Exp $" class HarmonicMean(Norm): def __init__(self): Norm.__init__(self,0) def __call__(self,*args): if 0. in args: return 0. <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import Norm,sum and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # def sum(*args): # """Calculate sum of args. # # If using numpy the builtin sum doesn't work always! # # @param args: list of floats to sum # @type args: list of float # @return: sum of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r += x # return r . Output only the next line.
return float(len(args))/sum(*[1.0/x for x in args])
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DualOfHarmonicMean.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" class DualOfHarmonicMean(Norm): def __init__(self): Norm.__init__(self,0) #XXX def __call__(self,*args): sum_ = sum(*args) if sum_ == len(args): return 1.0 <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import Norm,product,sum and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # def product(*args): # """Calculate product of args. # # @param args: list of floats to multiply # @type args: list of float # @return: product of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r *= x # return r # # def sum(*args): # """Calculate sum of args. # # If using numpy the builtin sum doesn't work always! # # @param args: list of floats to sum # @type args: list of float # @return: sum of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r += x # return r . Output only the next line.
product_ = product(*args)
Next line prediction: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DualOfHarmonicMean.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" class DualOfHarmonicMean(Norm): def __init__(self): Norm.__init__(self,0) #XXX def __call__(self,*args): <|code_end|> . Use current file imports: (from fuzzy.norm.Norm import Norm,product,sum) and context including class names, function names, or small code snippets from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # def product(*args): # """Calculate product of args. # # @param args: list of floats to multiply # @type args: list of float # @return: product of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r *= x # return r # # def sum(*args): # """Calculate sum of args. # # If using numpy the builtin sum doesn't work always! # # @param args: list of floats to sum # @type args: list of float # @return: sum of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r += x # return r . Output only the next line.
sum_ = sum(*args)
Here is a snippet: <|code_start|> and return them as dictionary {name,instance}""" package_name = package.__name__ classes_dir = os.path.dirname(package.__file__) suffixes = [suffix[0] for suffix in imp.get_suffixes()] objects = {} for class_file in os.listdir(classes_dir): for suffix in suffixes: class_name = class_file[:-len(suffix)] if class_name == "__init__": break if class_file[-len(suffix):] == suffix: module = __import__(package_name+"."+class_name) components = (package_name+"."+class_name).split('.') for comp in components[1:]: module = getattr(module, comp) try: objects.update({class_name: module.__dict__[class_name]()}) except: # probably no object with this name in file pass break return objects # possible parameter values for some allowed ranges of this parameter # tuples of ( allowed_range, list_of_values ) __params = ( ( [[0.,1.]] , [0.0,0.25,0.50,0.75,1.] ), ( [(0.,1.)] , [0.05,0.25,0.50,0.75,0.95] ), <|code_end|> . Write the next line using the current file imports: import os,imp from fuzzy.utils import inf_p,inf_n and context from other files: # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): , which may include functions, classes, or code. Output only the next line.
( [(0.,inf_p)] , [0.01,0.10,1.0,10.,100.] ),
Predict the next line for this snippet: <|code_start|> classes_dir = os.path.dirname(package.__file__) suffixes = [suffix[0] for suffix in imp.get_suffixes()] objects = {} for class_file in os.listdir(classes_dir): for suffix in suffixes: class_name = class_file[:-len(suffix)] if class_name == "__init__": break if class_file[-len(suffix):] == suffix: module = __import__(package_name+"."+class_name) components = (package_name+"."+class_name).split('.') for comp in components[1:]: module = getattr(module, comp) try: objects.update({class_name: module.__dict__[class_name]()}) except: # probably no object with this name in file pass break return objects # possible parameter values for some allowed ranges of this parameter # tuples of ( allowed_range, list_of_values ) __params = ( ( [[0.,1.]] , [0.0,0.25,0.50,0.75,1.] ), ( [(0.,1.)] , [0.05,0.25,0.50,0.75,0.95] ), ( [(0.,inf_p)] , [0.01,0.10,1.0,10.,100.] ), ( [(-1.,inf_p)] , [-0.99,-0.1,0.0,0.10,1.0,10.,100.] ), <|code_end|> with the help of current file imports: import os,imp from fuzzy.utils import inf_p,inf_n and context from other files: # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): , which may contain function names, class names, or code. Output only the next line.
( [(inf_n,-1.),(-1.,inf_p)] , [-100.,-10,-0.99,0.0,1.0,10.,100.] ),
Given snippet: <|code_start|> @ivar a: center of set. @type a: float @ivar delta: absolute distance between x-values for minimum and maximum. @type delta: float """ def __init__(self,a=0.0,delta=1.0): """Initialize a Pi-shaped fuzzy set. @param a: center of set @type a: float @param delta: absolute distance between x-values for minimum and maximum @type delta: float """ super(PiFunction,self).__init__() self.a = a self.delta = delta def __call__(self,x): """Return membership of x in this fuzzy set. This method makes the set work like a function. @param x: value for which the membership is to calculate @type x: float @return: membership @rtype: float """ a = self.a d = self.delta/2.0 if x < a: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.set.Function import Function from fuzzy.set.SFunction import SFunction from fuzzy.set.ZFunction import ZFunction and context: # Path: fuzzy/set/Function.py # class Function(Set): # """Base class for any fuzzy set defined by a function (not a polygon).""" # # # if converted if linear polygon form use # # at least x pieces # _resolution = 25 #: segments when converting into a polygon # # Path: fuzzy/set/SFunction.py # class SFunction(Function): # r""" # Realize a S-shaped fuzzy set:: # __ # /| # / | # /| | # _/ | | # | a | # | | # delta # # See also U{http://pyfuzzy.sourceforge.net/test/set/SFunction.png} # # @ivar a: center of set. # @type a: float # @ivar delta: absolute distance between x-values for minimum and maximum. # @type delta: float # """ # # def __init__(self,a=0.0,delta=1.0): # """Initialize a S-shaped fuzzy set. # # @param a: center of set # @type a: float # @param delta: absolute distance between x-values for minimum and maximum # @type delta: float # """ # super(SFunction, self).__init__() # self.a = a # self.delta = delta # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value for which the membership is to calculate # @type x: float # @return: membership # @rtype: float # """ # a = self.a # d = self.delta # if x <= a-d: # return 0.0 # if x <= a: # t = (x-a+d)/(2.0*d) # return 2.0*t*t # if x <= a+d: # t = (a-x+d)/(2.0*d) # return 1.0-2.0*t*t # return 1.0 # # def getCOG(self): # """Return center of gravity.""" # raise Exception("COG of SFunction uncalculable") # # class __IntervalGenerator(Function.IntervalGenerator): # def __init__(self,set): # self.set = set # # def nextInterval(self,prev,next): # a = self.set.a # d = self.set.delta # if prev is None: # if next is None: # return a-d # else: # return min(next,a-d) # else: # # right of our area of interest # if prev >= a+d: # return next # else: # # maximal interval length # stepsize = 2.0*d/Function._resolution # if next is None: # return min(a+d,prev + stepsize) # else: # if next - prev > stepsize: # # split interval in n equal sized interval of length < stepsize # return min(a+d,prev+(next-prev)/(int((next-prev)/stepsize)+1.0)) # else: # return next # # def getIntervalGenerator(self): # return self.__IntervalGenerator(self) # # Path: fuzzy/set/ZFunction.py # class ZFunction(SFunction): # r"""Realize a Z-shaped fuzzy set:: # __ # \ # |\ # | \ # | |\ # | | \__ # | a | # | | # delta # # see also U{http://pyfuzzy.sourceforge.net/test/set/ZFunction.png} # # @ivar a: center of set. # @type a: float # @ivar delta: absolute distance between x-values for minimum and maximum. # @type delta: float # """ # # def __init__(self,a=0.0,delta=1.0): # """Initialize a Z-shaped fuzzy set. # # @param a: center of set # @type a: float # @param delta: absolute distance between x-values for minimum and maximum # @type delta: float # """ # super(ZFunction, self).__init__(a,delta) # # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value for which the membership is to calculate # @type x: float # @return: membership # @rtype: float # """ # return 1.0 - SFunction.__call__(self,x) which might include code, classes, or functions. Output only the next line.
return SFunction(a-d,d)(x)
Given the code snippet: <|code_start|> @ivar delta: absolute distance between x-values for minimum and maximum. @type delta: float """ def __init__(self,a=0.0,delta=1.0): """Initialize a Pi-shaped fuzzy set. @param a: center of set @type a: float @param delta: absolute distance between x-values for minimum and maximum @type delta: float """ super(PiFunction,self).__init__() self.a = a self.delta = delta def __call__(self,x): """Return membership of x in this fuzzy set. This method makes the set work like a function. @param x: value for which the membership is to calculate @type x: float @return: membership @rtype: float """ a = self.a d = self.delta/2.0 if x < a: return SFunction(a-d,d)(x) else: <|code_end|> , generate the next line using the imports in this file: from fuzzy.set.Function import Function from fuzzy.set.SFunction import SFunction from fuzzy.set.ZFunction import ZFunction and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/set/Function.py # class Function(Set): # """Base class for any fuzzy set defined by a function (not a polygon).""" # # # if converted if linear polygon form use # # at least x pieces # _resolution = 25 #: segments when converting into a polygon # # Path: fuzzy/set/SFunction.py # class SFunction(Function): # r""" # Realize a S-shaped fuzzy set:: # __ # /| # / | # /| | # _/ | | # | a | # | | # delta # # See also U{http://pyfuzzy.sourceforge.net/test/set/SFunction.png} # # @ivar a: center of set. # @type a: float # @ivar delta: absolute distance between x-values for minimum and maximum. # @type delta: float # """ # # def __init__(self,a=0.0,delta=1.0): # """Initialize a S-shaped fuzzy set. # # @param a: center of set # @type a: float # @param delta: absolute distance between x-values for minimum and maximum # @type delta: float # """ # super(SFunction, self).__init__() # self.a = a # self.delta = delta # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value for which the membership is to calculate # @type x: float # @return: membership # @rtype: float # """ # a = self.a # d = self.delta # if x <= a-d: # return 0.0 # if x <= a: # t = (x-a+d)/(2.0*d) # return 2.0*t*t # if x <= a+d: # t = (a-x+d)/(2.0*d) # return 1.0-2.0*t*t # return 1.0 # # def getCOG(self): # """Return center of gravity.""" # raise Exception("COG of SFunction uncalculable") # # class __IntervalGenerator(Function.IntervalGenerator): # def __init__(self,set): # self.set = set # # def nextInterval(self,prev,next): # a = self.set.a # d = self.set.delta # if prev is None: # if next is None: # return a-d # else: # return min(next,a-d) # else: # # right of our area of interest # if prev >= a+d: # return next # else: # # maximal interval length # stepsize = 2.0*d/Function._resolution # if next is None: # return min(a+d,prev + stepsize) # else: # if next - prev > stepsize: # # split interval in n equal sized interval of length < stepsize # return min(a+d,prev+(next-prev)/(int((next-prev)/stepsize)+1.0)) # else: # return next # # def getIntervalGenerator(self): # return self.__IntervalGenerator(self) # # Path: fuzzy/set/ZFunction.py # class ZFunction(SFunction): # r"""Realize a Z-shaped fuzzy set:: # __ # \ # |\ # | \ # | |\ # | | \__ # | a | # | | # delta # # see also U{http://pyfuzzy.sourceforge.net/test/set/ZFunction.png} # # @ivar a: center of set. # @type a: float # @ivar delta: absolute distance between x-values for minimum and maximum. # @type delta: float # """ # # def __init__(self,a=0.0,delta=1.0): # """Initialize a Z-shaped fuzzy set. # # @param a: center of set # @type a: float # @param delta: absolute distance between x-values for minimum and maximum # @type delta: float # """ # super(ZFunction, self).__init__(a,delta) # # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value for which the membership is to calculate # @type x: float # @return: membership # @rtype: float # """ # return 1.0 - SFunction.__call__(self,x) . Output only the next line.
return ZFunction(a+d,d)(x)
Here is a snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: ArithmeticMean.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" class ArithmeticMean(Norm): def __init__(self): Norm.__init__(self,0) def __call__(self,*args): <|code_end|> . Write the next line using the current file imports: from fuzzy.norm.Norm import Norm,sum and context from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # def sum(*args): # """Calculate sum of args. # # If using numpy the builtin sum doesn't work always! # # @param args: list of floats to sum # @type args: list of float # @return: sum of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r += x # return r , which may include functions, classes, or code. Output only the next line.
return sum(*args)/float(len(args))
Predict the next line after this snippet: <|code_start|># # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: MaxLeft.py,v 1.4 2009/08/07 07:19:18 rliebscher Exp $" class MaxLeft(Base): """Defuzzyfication which uses the left global maximum.""" def __init__(self, INF=None, ACC=None, failsafe=None,*args,**keywords): """Initialize the defuzzification method with INF,ACC and an optional value in case defuzzification is not possible""" super(MaxLeft, self).__init__(INF,ACC,*args,**keywords) self.failsafe = failsafe # which value if value not calculable def getValue(self,variable): """Defuzzyfication.""" try: temp = self.accumulate(variable) # get polygon representation table = list(self.value_table(temp)) if len(table) == 0: <|code_end|> using the current file's imports: from fuzzy.defuzzify.Base import Base,DefuzzificationException and any relevant context from other files: # Path: fuzzy/defuzzify/Base.py # class Base(object): # """Abstract base class for defuzzification # which results in a numeric value. # # @ivar INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @ivar ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # @cvar _INF: default value when INF is None # @type _INF: L{fuzzy.norm.Norm.Norm} # @cvar _ACC: default value when ACC is None # @type _ACC: L{fuzzy.norm.Norm.Norm} # @ivar activated_sets: results of activation of adjectives of variable. # @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} # @ivar accumulated_set: result of accumulation of activated sets # @type accumulated_set: L{fuzzy.set.Polygon.Polygon} # """ # # # default values if instance values are not set # _INF = Min() # _ACC = Max() # # def __init__(self, INF=None, ACC=None): # """ # @param INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @param ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # """ # self.ACC = ACC # accumulation # self.INF = INF # inference # self.activated_sets = {} # self.accumulated_set = None # # def getValue(self,variable): # """Defuzzyfication.""" # raise DefuzzificationException("don't use the abstract base class") # # # helper methods for sub classes # # def accumulate(self,variable,segment_size=None): # """combining adjective values into one set""" # self.activated_sets = {} # temp = None # for name,adjective in variable.adjectives.items(): # # get precomputed adjective set # temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size) # self.activated_sets[name] = temp2 # # accumulate all adjectives # if temp is None: # temp = temp2 # else: # temp = merge((self.ACC or self._ACC),temp,temp2,segment_size) # self.accumulated_set = temp # return temp # # def value_table(self,set): # """get a value table of the polygon representation""" # # get polygon representation # ig = set.getIntervalGenerator() # next = ig.nextInterval(None,None) # while next is not None: # x = next # y = set(x) # yield (x,y) # # get next point from polygon # next = ig.nextInterval(next,None) # # class DefuzzificationException(fuzzy.Exception.Exception): # pass . Output only the next line.
raise DefuzzificationException("no value calculable: complete undefined set")
Given snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: FuzzyOr.py,v 1.4 2009/09/24 20:32:20 rliebscher Exp $" class FuzzyOr(ParametricNorm): _range = [ [0.,1.] ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) which might include code, classes, or functions. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Using the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: FrankIntersection.py,v 1.4 2009/08/31 21:02:06 rliebscher Exp $" class FrankIntersection(ParametricNorm): """Frank 1979""" _range = [ (0.,1.),(1.,inf_p) ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , determine the next line of code. You have imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from math import log from fuzzy.utils import inf_p and context (class names, function names, or code) available: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Based on the snippet: <|code_start|> # use only x value for sorting self.__points.sort(key = lambda p:p[Polygon.X]) def remove(self,x,where=END): r"""Remove a point from the polygon. The parameter where controls at which end it is removed. (The points are always sorted, but if two have the same x value their order is important. For example: removing the second point in the middle:: now where=END where=BEGIN *--* *--* * | \ \ | \ \ *--* * *--* """ # quick and dirty implementation range_p = range(len(self.__points)) if where == self.END: range_p.reverse() for i in range_p: if self.__points[i][Polygon.X] == x: self.__points.remove(i) return #raise Exception("Not in points list") def clear(self): """Reset polygon to zero.""" del self.__points[:] <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.set.Set import Set from fuzzy.utils import prop import copy import copy and context (classes, functions, sometimes code) from other files: # Path: fuzzy/set/Set.py # class Set(object): # """Base class for all types of fuzzy sets.""" # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value x # @type x: float # @return: membership for value x # @rtype: float # """ # return 0. # # class IntervalGenerator(object): # def nextInterval(self,prev,next): # """For conversion of any set to a polygon representation. # Return which end value should have the interval started # by prev. (next is the current proposal.) # The membership function has to be monotonic in this interval. # (eg. no minima or maxima) # To find left start point prev is None. # If no further splitting at right necessary return None.""" # return next # # def getIntervalGenerator(self): # """Internal helper function to help convert arbitrary fuzzy sets in # fuzzy sets represented by a polygon.""" # return self.IntervalGenerator() # # def getCOG(self): # """Returns center of gravity. # # @return: x-value of center of gravity # @rtype: float # """ # #raise Exception("abtract class %s has no center of gravity." % self.__class__.__name__) # return 0. # XXX # # Path: fuzzy/utils.py # def prop(func): # """Function decorator for defining property attributes # # The decorated function is expected to return a dictionary # containing one or more of the following pairs: # - fget - function for getting attribute value # - fset - function for setting attribute value # - fdel - function for deleting attribute # This can be conveniently constructed by the locals() builtin # function; see: # U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183} # """ # return property(doc=func.__doc__, **func()) . Output only the next line.
@prop
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerIntersection3.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerIntersection3(ParametricNorm): _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Continue the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerIntersection.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerIntersection(ParametricNorm): _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> . Use current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context (classes, functions, or code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Next line prediction: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: EinsteinSum.py,v 1.3 2009/08/07 07:19:19 rliebscher Exp $" class EinsteinSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> . Use current file imports: (from fuzzy.norm.Norm import Norm,NormException) and context including class names, function names, or small code snippets from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: BoundedSum.py,v 1.3 2009/08/07 07:19:19 rliebscher Exp $" class BoundedSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import Norm,NormException and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Predict the next line for this snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DubiosPradeIntersection.py,v 1.1 2009/08/31 21:06:40 rliebscher Exp $" class DubiosPradeIntersection(ParametricNorm): """Dubios Prade 1980""" _range = [ (0.,1.) ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> with the help of current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) , which may contain function names, class names, or code. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given snippet: <|code_start|># the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # """Describes a ... of a variable.""" __revision__ = "$Id: Adjective.py,v 1.13 2009/10/07 21:08:12 rliebscher Exp $" class Adjective(object): """Describes a ... of a variable. @ivar set: fuzzy set @type set: L{fuzzy.set.Set.Set} @ivar COM: norm (if None the class default _COM is used.) @type COM: L{fuzzy.norm.Norm.Norm} @ivar membership: set or calculated membership @type membership: float @cvar _COM: class default is instance variable is None @type _COM: L{fuzzy.norm.Norm.Norm} """ # default if not set in instance <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Max import Max from fuzzy.set.Set import Set and context: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/set/Set.py # class Set(object): # """Base class for all types of fuzzy sets.""" # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value x # @type x: float # @return: membership for value x # @rtype: float # """ # return 0. # # class IntervalGenerator(object): # def nextInterval(self,prev,next): # """For conversion of any set to a polygon representation. # Return which end value should have the interval started # by prev. (next is the current proposal.) # The membership function has to be monotonic in this interval. # (eg. no minima or maxima) # To find left start point prev is None. # If no further splitting at right necessary return None.""" # return next # # def getIntervalGenerator(self): # """Internal helper function to help convert arbitrary fuzzy sets in # fuzzy sets represented by a polygon.""" # return self.IntervalGenerator() # # def getCOG(self): # """Returns center of gravity. # # @return: x-value of center of gravity # @rtype: float # """ # #raise Exception("abtract class %s has no center of gravity." % self.__class__.__name__) # return 0. # XXX which might include code, classes, or functions. Output only the next line.
_COM = Max()
Using the snippet: <|code_start|># later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # """Describes a ... of a variable.""" __revision__ = "$Id: Adjective.py,v 1.13 2009/10/07 21:08:12 rliebscher Exp $" class Adjective(object): """Describes a ... of a variable. @ivar set: fuzzy set @type set: L{fuzzy.set.Set.Set} @ivar COM: norm (if None the class default _COM is used.) @type COM: L{fuzzy.norm.Norm.Norm} @ivar membership: set or calculated membership @type membership: float @cvar _COM: class default is instance variable is None @type _COM: L{fuzzy.norm.Norm.Norm} """ # default if not set in instance _COM = Max() <|code_end|> , determine the next line of code. You have imports: from fuzzy.norm.Max import Max from fuzzy.set.Set import Set and context (class names, function names, or code) available: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/set/Set.py # class Set(object): # """Base class for all types of fuzzy sets.""" # # def __call__(self,x): # """Return membership of x in this fuzzy set. # This method makes the set work like a function. # # @param x: value x # @type x: float # @return: membership for value x # @rtype: float # """ # return 0. # # class IntervalGenerator(object): # def nextInterval(self,prev,next): # """For conversion of any set to a polygon representation. # Return which end value should have the interval started # by prev. (next is the current proposal.) # The membership function has to be monotonic in this interval. # (eg. no minima or maxima) # To find left start point prev is None. # If no further splitting at right necessary return None.""" # return next # # def getIntervalGenerator(self): # """Internal helper function to help convert arbitrary fuzzy sets in # fuzzy sets represented by a polygon.""" # return self.IntervalGenerator() # # def getCOG(self): # """Returns center of gravity. # # @return: x-value of center of gravity # @rtype: float # """ # #raise Exception("abtract class %s has no center of gravity." % self.__class__.__name__) # return 0. # XXX . Output only the next line.
def __init__(self,set=Set(),COM=None):
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HamacherIntersection.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class HamacherIntersection(ParametricNorm): """Hamacher 1978""" _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerUnion.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerUnion(ParametricNorm): _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , generate the next line using the imports in this file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: GammaOperator.py,v 1.6 2009/09/24 20:32:20 rliebscher Exp $" class GammaOperator(ParametricNorm): _range = [ [0.,1.] ] def __init__(self,p=0.5): ParametricNorm.__init__(self,0,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , generate the next line using the imports in this file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: RM.py,v 1.2 2009/08/07 07:19:18 rliebscher Exp $" class RM(Base): """Defuzzyfication which uses the right most (local) maximum.""" def __init__(self, INF=None, ACC=None, failsafe=None,*args,**keywords): """Initialize the defuzzification method with INF,ACC and an optional value in case defuzzification is not possible""" super(RM, self).__init__(INF,ACC,*args,**keywords) self.failsafe = failsafe # which value if value not calculable def getValue(self,variable): """Defuzzyfication.""" try: temp = self.accumulate(variable) # get polygon representation table = list(self.value_table(temp)) if len(table) == 0: <|code_end|> , generate the next line using the imports in this file: from fuzzy.defuzzify.Base import Base,DefuzzificationException and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/defuzzify/Base.py # class Base(object): # """Abstract base class for defuzzification # which results in a numeric value. # # @ivar INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @ivar ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # @cvar _INF: default value when INF is None # @type _INF: L{fuzzy.norm.Norm.Norm} # @cvar _ACC: default value when ACC is None # @type _ACC: L{fuzzy.norm.Norm.Norm} # @ivar activated_sets: results of activation of adjectives of variable. # @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} # @ivar accumulated_set: result of accumulation of activated sets # @type accumulated_set: L{fuzzy.set.Polygon.Polygon} # """ # # # default values if instance values are not set # _INF = Min() # _ACC = Max() # # def __init__(self, INF=None, ACC=None): # """ # @param INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @param ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # """ # self.ACC = ACC # accumulation # self.INF = INF # inference # self.activated_sets = {} # self.accumulated_set = None # # def getValue(self,variable): # """Defuzzyfication.""" # raise DefuzzificationException("don't use the abstract base class") # # # helper methods for sub classes # # def accumulate(self,variable,segment_size=None): # """combining adjective values into one set""" # self.activated_sets = {} # temp = None # for name,adjective in variable.adjectives.items(): # # get precomputed adjective set # temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size) # self.activated_sets[name] = temp2 # # accumulate all adjectives # if temp is None: # temp = temp2 # else: # temp = merge((self.ACC or self._ACC),temp,temp2,segment_size) # self.accumulated_set = temp # return temp # # def value_table(self,set): # """get a value table of the polygon representation""" # # get polygon representation # ig = set.getIntervalGenerator() # next = ig.nextInterval(None,None) # while next is not None: # x = next # y = set(x) # yield (x,y) # # get next point from polygon # next = ig.nextInterval(next,None) # # class DefuzzificationException(fuzzy.Exception.Exception): # pass . Output only the next line.
raise DefuzzificationException("no value calculable: complete undefined set")
Given snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: FuzzyAnd.py,v 1.4 2009/09/24 20:32:20 rliebscher Exp $" class FuzzyAnd(ParametricNorm): _range = [ [0.,1.] ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) which might include code, classes, or functions. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DombiUnion.py,v 1.5 2009/09/24 20:32:20 rliebscher Exp $" class DombiUnion(ParametricNorm): """Dombi 1982""" _range = [ (0.,1.),(1.,inf_p) ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the following code snippet before the placeholder: <|code_start|># # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: YagerUnion.py,v 1.5 2009/09/24 20:32:20 rliebscher Exp $" class YagerUnion(ParametricNorm): """Yager 1980""" _range = [ (0,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerUnion3.py,v 1.4 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerUnion3(ParametricNorm): _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Using the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DualOfGeometricMean.py,v 1.6 2009/08/07 07:19:19 rliebscher Exp $" class DualOfGeometricMean(Norm): def __init__(self): Norm.__init__(self,0) # XXX def __call__(self,*args): <|code_end|> , determine the next line of code. You have imports: from fuzzy.norm.Norm import Norm,product and context (class names, function names, or code) available: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # def product(*args): # """Calculate product of args. # # @param args: list of floats to multiply # @type args: list of float # @return: product of args # @rtype: float # """ # r = args[0] # for x in args[1:]: # r *= x # return r . Output only the next line.
return 1.0 - pow(product(*[1.0-x for x in args]),1.0/len(args))
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: YagerIntersection.py,v 1.5 2009/09/24 20:32:20 rliebscher Exp $" class YagerIntersection(ParametricNorm): """Yager 1980""" _range = [ (0,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Predict the next line for this snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: AlgebraicSum.py,v 1.3 2009/08/07 07:19:18 rliebscher Exp $" class AlgebraicSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> with the help of current file imports: from fuzzy.norm.Norm import Norm,NormException and context from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass , which may contain function names, class names, or code. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Predict the next line after this snippet: <|code_start|># # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: MaxRight.py,v 1.5 2009/08/07 07:19:18 rliebscher Exp $" class MaxRight(Base): """Defuzzyfication which uses the right global maximum.""" def __init__(self, INF=None, ACC=None, failsafe=None,*args,**keywords): """Initialize the defuzzification method with INF,ACC and an optional value in case defuzzification is not possible""" super(MaxRight, self).__init__(INF,ACC,*args,**keywords) self.failsafe = failsafe # which value if value not calculable def getValue(self,variable): """Defuzzyfication.""" try: temp = self.accumulate(variable) # get polygon representation table = list(self.value_table(temp)) if len(table) == 0: <|code_end|> using the current file's imports: from fuzzy.defuzzify.Base import Base,DefuzzificationException and any relevant context from other files: # Path: fuzzy/defuzzify/Base.py # class Base(object): # """Abstract base class for defuzzification # which results in a numeric value. # # @ivar INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @ivar ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # @cvar _INF: default value when INF is None # @type _INF: L{fuzzy.norm.Norm.Norm} # @cvar _ACC: default value when ACC is None # @type _ACC: L{fuzzy.norm.Norm.Norm} # @ivar activated_sets: results of activation of adjectives of variable. # @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} # @ivar accumulated_set: result of accumulation of activated sets # @type accumulated_set: L{fuzzy.set.Polygon.Polygon} # """ # # # default values if instance values are not set # _INF = Min() # _ACC = Max() # # def __init__(self, INF=None, ACC=None): # """ # @param INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @param ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # """ # self.ACC = ACC # accumulation # self.INF = INF # inference # self.activated_sets = {} # self.accumulated_set = None # # def getValue(self,variable): # """Defuzzyfication.""" # raise DefuzzificationException("don't use the abstract base class") # # # helper methods for sub classes # # def accumulate(self,variable,segment_size=None): # """combining adjective values into one set""" # self.activated_sets = {} # temp = None # for name,adjective in variable.adjectives.items(): # # get precomputed adjective set # temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size) # self.activated_sets[name] = temp2 # # accumulate all adjectives # if temp is None: # temp = temp2 # else: # temp = merge((self.ACC or self._ACC),temp,temp2,segment_size) # self.accumulated_set = temp # return temp # # def value_table(self,set): # """get a value table of the polygon representation""" # # get polygon representation # ig = set.getIntervalGenerator() # next = ig.nextInterval(None,None) # while next is not None: # x = next # y = set(x) # yield (x,y) # # get next point from polygon # next = ig.nextInterval(next,None) # # class DefuzzificationException(fuzzy.Exception.Exception): # pass . Output only the next line.
raise DefuzzificationException("no value calculable: complete undefined set")
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerIntersection2.py,v 1.6 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerIntersection2(ParametricNorm): """Schweizer,Sklar 1960""" _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DubiosPradeUnion.py,v 1.1 2009/08/31 21:06:40 rliebscher Exp $" class DubiosPradeUnion(ParametricNorm): """Dubios Prade 1980""" _range = [ (0.,1.) ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) which might include code, classes, or functions. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: AlgebraicProdSum.py,v 1.4 2009/09/24 20:32:20 rliebscher Exp $" class AlgebraicProdSum(ParametricNorm): _range = [ [0.,1.] ] def __init__(self,p=0.5): ParametricNorm.__init__(self,0,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , generate the next line using the imports in this file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HamacherUnion.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class HamacherUnion(ParametricNorm): """Hamacher 1978""" _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): which might include code, classes, or functions. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: EinsteinProduct.py,v 1.3 2009/08/07 07:19:19 rliebscher Exp $" class EinsteinProduct(Norm): def __init__(self): Norm.__init__(self,Norm.T_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , generate the next line using the imports in this file: from fuzzy.norm.Norm import Norm,NormException and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: MinMax.py,v 1.4 2009/09/24 20:32:20 rliebscher Exp $" class MinMax(ParametricNorm): _range = [ [0.,1.] ] def __init__(self,p=0.5): ParametricNorm.__init__(self,0,p) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Predict the next line after this snippet: <|code_start|># this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: Base.py,v 1.7 2009/08/07 07:19:18 rliebscher Exp $" class DefuzzificationException(fuzzy.Exception.Exception): pass class Base(object): """Abstract base class for defuzzification which results in a numeric value. @ivar INF: inference norm, used with set of adjective and given value for it @type INF: L{fuzzy.norm.Norm.Norm} @ivar ACC: norm for accumulation of set of adjectives @type ACC: L{fuzzy.norm.Norm.Norm} @cvar _INF: default value when INF is None @type _INF: L{fuzzy.norm.Norm.Norm} @cvar _ACC: default value when ACC is None @type _ACC: L{fuzzy.norm.Norm.Norm} @ivar activated_sets: results of activation of adjectives of variable. @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} @ivar accumulated_set: result of accumulation of activated sets @type accumulated_set: L{fuzzy.set.Polygon.Polygon} """ # default values if instance values are not set _INF = Min() <|code_end|> using the current file's imports: from fuzzy.norm.Max import Max from fuzzy.norm.Min import Min from fuzzy.set.Set import norm,merge import fuzzy.Exception and any relevant context from other files: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/norm/Min.py # class Min(Norm): # # def __init__(self): # Norm.__init__(self,Norm.T_NORM) # # def __call__(self,*args): # """Return minimum of given values.""" # return min(args) # # Path: fuzzy/set/Set.py # class Set(object): # class IntervalGenerator(object): # def __call__(self,x): # def nextInterval(self,prev,next): # def getIntervalGenerator(self): # def getCOG(self): . Output only the next line.
_ACC = Max()
Predict the next line after this snippet: <|code_start|># You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: Base.py,v 1.7 2009/08/07 07:19:18 rliebscher Exp $" class DefuzzificationException(fuzzy.Exception.Exception): pass class Base(object): """Abstract base class for defuzzification which results in a numeric value. @ivar INF: inference norm, used with set of adjective and given value for it @type INF: L{fuzzy.norm.Norm.Norm} @ivar ACC: norm for accumulation of set of adjectives @type ACC: L{fuzzy.norm.Norm.Norm} @cvar _INF: default value when INF is None @type _INF: L{fuzzy.norm.Norm.Norm} @cvar _ACC: default value when ACC is None @type _ACC: L{fuzzy.norm.Norm.Norm} @ivar activated_sets: results of activation of adjectives of variable. @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} @ivar accumulated_set: result of accumulation of activated sets @type accumulated_set: L{fuzzy.set.Polygon.Polygon} """ # default values if instance values are not set <|code_end|> using the current file's imports: from fuzzy.norm.Max import Max from fuzzy.norm.Min import Min from fuzzy.set.Set import norm,merge import fuzzy.Exception and any relevant context from other files: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/norm/Min.py # class Min(Norm): # # def __init__(self): # Norm.__init__(self,Norm.T_NORM) # # def __call__(self,*args): # """Return minimum of given values.""" # return min(args) # # Path: fuzzy/set/Set.py # class Set(object): # class IntervalGenerator(object): # def __call__(self,x): # def nextInterval(self,prev,next): # def getIntervalGenerator(self): # def getCOG(self): . Output only the next line.
_INF = Min()
Given snippet: <|code_start|> """ # default values if instance values are not set _INF = Min() _ACC = Max() def __init__(self, INF=None, ACC=None): """ @param INF: inference norm, used with set of adjective and given value for it @type INF: L{fuzzy.norm.Norm.Norm} @param ACC: norm for accumulation of set of adjectives @type ACC: L{fuzzy.norm.Norm.Norm} """ self.ACC = ACC # accumulation self.INF = INF # inference self.activated_sets = {} self.accumulated_set = None def getValue(self,variable): """Defuzzyfication.""" raise DefuzzificationException("don't use the abstract base class") # helper methods for sub classes def accumulate(self,variable,segment_size=None): """combining adjective values into one set""" self.activated_sets = {} temp = None for name,adjective in variable.adjectives.items(): # get precomputed adjective set <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Max import Max from fuzzy.norm.Min import Min from fuzzy.set.Set import norm,merge import fuzzy.Exception and context: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/norm/Min.py # class Min(Norm): # # def __init__(self): # Norm.__init__(self,Norm.T_NORM) # # def __call__(self,*args): # """Return minimum of given values.""" # return min(args) # # Path: fuzzy/set/Set.py # class Set(object): # class IntervalGenerator(object): # def __call__(self,x): # def nextInterval(self,prev,next): # def getIntervalGenerator(self): # def getCOG(self): which might include code, classes, or functions. Output only the next line.
temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size)
Given snippet: <|code_start|> def __init__(self, INF=None, ACC=None): """ @param INF: inference norm, used with set of adjective and given value for it @type INF: L{fuzzy.norm.Norm.Norm} @param ACC: norm for accumulation of set of adjectives @type ACC: L{fuzzy.norm.Norm.Norm} """ self.ACC = ACC # accumulation self.INF = INF # inference self.activated_sets = {} self.accumulated_set = None def getValue(self,variable): """Defuzzyfication.""" raise DefuzzificationException("don't use the abstract base class") # helper methods for sub classes def accumulate(self,variable,segment_size=None): """combining adjective values into one set""" self.activated_sets = {} temp = None for name,adjective in variable.adjectives.items(): # get precomputed adjective set temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size) self.activated_sets[name] = temp2 # accumulate all adjectives if temp is None: temp = temp2 else: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Max import Max from fuzzy.norm.Min import Min from fuzzy.set.Set import norm,merge import fuzzy.Exception and context: # Path: fuzzy/norm/Max.py # class Max(Norm): # # def __init__(self): # Norm.__init__(self,Norm.S_NORM) # # def __call__(self,*args): # """Return maximum of given values.""" # return max(args) # # Path: fuzzy/norm/Min.py # class Min(Norm): # # def __init__(self): # Norm.__init__(self,Norm.T_NORM) # # def __call__(self,*args): # """Return minimum of given values.""" # return min(args) # # Path: fuzzy/set/Set.py # class Set(object): # class IntervalGenerator(object): # def __call__(self,x): # def nextInterval(self,prev,next): # def getIntervalGenerator(self): # def getCOG(self): which might include code, classes, or functions. Output only the next line.
temp = merge((self.ACC or self._ACC),temp,temp2,segment_size)
Here is a snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: SchweizerUnion2.py,v 1.5 2009/10/18 19:46:59 rliebscher Exp $" class SchweizerUnion2(ParametricNorm): _range = [ (0.,inf_p) ] def __init__(self,p=1.): ParametricNorm.__init__(self,ParametricNorm.S_NORM,p) def __call__(self,*args): if len(args) != 2: <|code_end|> . Write the next line using the current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p,inf_n and context from other files: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): , which may include functions, classes, or code. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Using the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HamacherSum.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" class HamacherSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , determine the next line of code. You have imports: from fuzzy.norm.Norm import Norm,NormException and context (class names, function names, or code) available: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DrasticSum.py,v 1.4 2009/08/31 21:02:06 rliebscher Exp $" class DrasticSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , generate the next line using the imports in this file: from fuzzy.norm.Norm import Norm,NormException and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Given the code snippet: <|code_start|># # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: LM.py,v 1.2 2009/08/07 07:19:18 rliebscher Exp $" class LM(Base): """Defuzzyfication which uses the left most (local) maximum.""" def __init__(self, INF=None, ACC=None, failsafe=None,*args,**keywords): """Initialize the defuzzification method with INF,ACC and an optional value in case defuzzification is not possible""" super(LM, self).__init__(INF,ACC,*args,**keywords) self.failsafe = failsafe # which value if value not calculable def getValue(self,variable): """Defuzzyfication.""" try: temp = self.accumulate(variable) # get polygon representation table = list(self.value_table(temp)) if len(table) == 0: <|code_end|> , generate the next line using the imports in this file: from fuzzy.defuzzify.Base import Base,DefuzzificationException and context (functions, classes, or occasionally code) from other files: # Path: fuzzy/defuzzify/Base.py # class Base(object): # """Abstract base class for defuzzification # which results in a numeric value. # # @ivar INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @ivar ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # @cvar _INF: default value when INF is None # @type _INF: L{fuzzy.norm.Norm.Norm} # @cvar _ACC: default value when ACC is None # @type _ACC: L{fuzzy.norm.Norm.Norm} # @ivar activated_sets: results of activation of adjectives of variable. # @type activated_sets: {string:L{fuzzy.set.Polygon.Polygon}} # @ivar accumulated_set: result of accumulation of activated sets # @type accumulated_set: L{fuzzy.set.Polygon.Polygon} # """ # # # default values if instance values are not set # _INF = Min() # _ACC = Max() # # def __init__(self, INF=None, ACC=None): # """ # @param INF: inference norm, used with set of adjective and given value for it # @type INF: L{fuzzy.norm.Norm.Norm} # @param ACC: norm for accumulation of set of adjectives # @type ACC: L{fuzzy.norm.Norm.Norm} # """ # self.ACC = ACC # accumulation # self.INF = INF # inference # self.activated_sets = {} # self.accumulated_set = None # # def getValue(self,variable): # """Defuzzyfication.""" # raise DefuzzificationException("don't use the abstract base class") # # # helper methods for sub classes # # def accumulate(self,variable,segment_size=None): # """combining adjective values into one set""" # self.activated_sets = {} # temp = None # for name,adjective in variable.adjectives.items(): # # get precomputed adjective set # temp2 = norm((self.INF or self._INF),adjective.set,adjective.getMembership(),segment_size) # self.activated_sets[name] = temp2 # # accumulate all adjectives # if temp is None: # temp = temp2 # else: # temp = merge((self.ACC or self._ACC),temp,temp2,segment_size) # self.accumulated_set = temp # return temp # # def value_table(self,set): # """get a value table of the polygon representation""" # # get polygon representation # ig = set.getIntervalGenerator() # next = ig.nextInterval(None,None) # while next is not None: # x = next # y = set(x) # yield (x,y) # # get next point from polygon # next = ig.nextInterval(next,None) # # class DefuzzificationException(fuzzy.Exception.Exception): # pass . Output only the next line.
raise DefuzzificationException("no value calculable: complete undefined set")
Given the following code snippet before the placeholder: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: BoundedDifference.py,v 1.3 2009/08/07 07:19:19 rliebscher Exp $" class BoundedDifference(Norm): def __init__(self): Norm.__init__(self,Norm.T_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the next line using imports from the current file: from fuzzy.norm.Norm import Norm,NormException and context including class names, function names, and sometimes code from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Here is a snippet: <|code_start|> opt = " [" + opt + "]" out.write("%s%s;\n" % (name,opt)) def make_connection(self,out,node1,node2,values={}): opt = "" for option,value in self.connection_style.items(): if value == None: continue if opt != "": opt += "," opt += '%s="%s"' % ( option , (value % values) ) if opt != "": opt = " [" + opt + "]" out.write("%s -> %s%s;\n" % (node1,node2,opt)) ######################### class Doc_Compound(DocBase): def __init__(self): super(Doc_Compound,self).__init__() #self.node_style.update( # { "comment":"XXX" } #) def __call__(self,obj,out,system,parent_name): norm_name = print_dot(obj.norm,out,system,parent_name) for i in obj.inputs: inp_node_name = print_dot(i,out,system,norm_name) self.make_connection(out,inp_node_name,norm_name) return norm_name <|code_end|> . Write the next line using the current file imports: from fuzzy.doc.structure.dot.dot import register_handler,print_dot import fuzzy.operator.Compound import fuzzy.operator.Const import fuzzy.operator.Input import fuzzy.operator.Not import fuzzy.norm.Norm import fuzzy.norm.ParametricNorm import fuzzy.Adjective import fuzzy.AdjectiveProxy import fuzzy.Rule import fuzzy.OutputVariable import fuzzy.Variable and context from other files: # Path: fuzzy/doc/structure/dot/dot.py # def register_handler(class_, handler): # _registered_handler[class_] = handler # # def print_dot(obj,out,system,parentname): # """Print object obj into output stream out""" # for class_ in type(obj).mro(): # if class_ in _registered_handler.keys(): # handler = _registered_handler[class_] # return handler(obj,out,system,parentname) # return "" , which may include functions, classes, or code. Output only the next line.
register_handler(fuzzy.operator.Compound.Compound,Doc_Compound())
Predict the next line after this snippet: <|code_start|> if value == None: continue if opt != "": opt += "," opt += '%s="%s"' % ( option , (value % values) ) if opt != "": opt = " [" + opt + "]" out.write("%s%s;\n" % (name,opt)) def make_connection(self,out,node1,node2,values={}): opt = "" for option,value in self.connection_style.items(): if value == None: continue if opt != "": opt += "," opt += '%s="%s"' % ( option , (value % values) ) if opt != "": opt = " [" + opt + "]" out.write("%s -> %s%s;\n" % (node1,node2,opt)) ######################### class Doc_Compound(DocBase): def __init__(self): super(Doc_Compound,self).__init__() #self.node_style.update( # { "comment":"XXX" } #) def __call__(self,obj,out,system,parent_name): <|code_end|> using the current file's imports: from fuzzy.doc.structure.dot.dot import register_handler,print_dot import fuzzy.operator.Compound import fuzzy.operator.Const import fuzzy.operator.Input import fuzzy.operator.Not import fuzzy.norm.Norm import fuzzy.norm.ParametricNorm import fuzzy.Adjective import fuzzy.AdjectiveProxy import fuzzy.Rule import fuzzy.OutputVariable import fuzzy.Variable and any relevant context from other files: # Path: fuzzy/doc/structure/dot/dot.py # def register_handler(class_, handler): # _registered_handler[class_] = handler # # def print_dot(obj,out,system,parentname): # """Print object obj into output stream out""" # for class_ in type(obj).mro(): # if class_ in _registered_handler.keys(): # handler = _registered_handler[class_] # return handler(obj,out,system,parentname) # return "" . Output only the next line.
norm_name = print_dot(obj.norm,out,system,parent_name)
Given snippet: <|code_start|># # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: DombiIntersection.py,v 1.5 2009/08/31 21:02:06 rliebscher Exp $" class DombiIntersection(ParametricNorm): """Dombi 1982""" _range = [ (0.,1.),(1.,inf_p) ] def __init__(self,p=0.5): ParametricNorm.__init__(self,ParametricNorm.T_NORM,p) def __call__(self,*args): """ """ if len(args) != 2: <|code_end|> , continue by predicting the next line. Consider current file imports: from fuzzy.norm.Norm import NormException from fuzzy.norm.ParametricNorm import ParametricNorm from fuzzy.utils import inf_p and context: # Path: fuzzy/norm/Norm.py # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass # # Path: fuzzy/norm/ParametricNorm.py # class ParametricNorm(Norm): # """Abstract base class for any parametric fuzzy norm # # @ivar p: parameter for norm # @type p: float # """ # _range = None # # def __init__(self,type,p): # """Initialize type and parameter # # @param p: parameter for norm # @type p: float # """ # super(ParametricNorm,self).__init__(type) # self.p = p # # @prop # def p(): # """x # @type: float""" # def fget(self): # return self._p # def fset(self,value): # self._checkParam(value) # self._p = value # return locals() # # @prop # def p_range(): # """range(s) of valid values for p""" # def fget(self): # return self._range # return locals() # # def _checkParam(self,value): # """check parameter if allowed for paramter p # @param value: the value to be checked # @type value: float""" # from fuzzy.utils import checkRange # if not checkRange(value,self._range): # raise Exception("Parameter value %s is not allowed" % str(value)) # # Path: fuzzy/utils.py # def prop(func): # def checkRange(value,ranges): which might include code, classes, or functions. Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Predict the next line after this snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HamacherProduct.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" class HamacherProduct(Norm): def __init__(self): Norm.__init__(self,Norm.T_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> using the current file's imports: from fuzzy.norm.Norm import Norm,NormException and any relevant context from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Based on the snippet: <|code_start|># -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: AlgebraicProduct.py,v 1.3 2009/08/07 07:19:18 rliebscher Exp $" class AlgebraicProduct(Norm): def __init__(self): Norm.__init__(self,Norm.T_NORM) def __call__(self,*args): if len(args) != 2: <|code_end|> , predict the immediate next line with the help of imports: from fuzzy.norm.Norm import Norm,NormException and context (classes, functions, sometimes code) from other files: # Path: fuzzy/norm/Norm.py # class Norm(object): # """Abstract Base class of any fuzzy norm""" # # # types of norm # UNKNOWN = 0 #: type of norm unknown # T_NORM = 1 #: norm is t-norm # S_NORM = 2 #: norm is s-norm # # def __init__(self,type=0): # """Initialize type of norm""" # self._type = type # # def __call__(self,*args): # """ # Calculate result of norm(arg1,arg2,...) # # @param args: list of floats as arguments for norm. # @type args: list of float # @return: result of norm calulation # @rtype: float # @raise NormException: any problem in calculation (wrong number of arguments, numerical problems) # """ # raise NormException("abstract class %s can't be called" % self.__class__.__name__) # # def getType(self): # """ # Return type of norm: # 0 = not defined or not classified # 1 = t-norm ( = Norm.T_NORM) # 2 = s-norm ( = Norm.S_NORM) # # """ # return self._type # # class NormException(Exception): # """Base class for any exception in norm calculations.""" # pass . Output only the next line.
raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ )
Here is a snippet: <|code_start|> class GalleryChildBase(GalleryBase): class Meta: abstract = True require_parent = True parent_classes = ['GalleryCMSPlugin'] def render(self, context, instance, placeholder): # get style from parent plugin, render chosen template context['instance'] = instance context['image'] = instance.image return context def get_slide_template(self, instance, name='slide'): if instance.parent is None: style = GalleryPlugin.STANDARD else: style = getattr(instance.parent.get_plugin_instance()[0], 'style', GalleryPlugin.STANDARD) return 'aldryn_gallery/plugins/{}/{}.html'.format(style, name) def get_render_template(self, context, instance, placeholder): return self.get_slide_template(instance=instance) # Plugins class GalleryCMSPlugin(GalleryBase): render_template = False name = _('Gallery') model = GalleryPlugin <|code_end|> . Write the next line using the current file imports: from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .forms import GalleryPluginForm from .models import GalleryPlugin, SlidePlugin, SlideFolderPlugin and context from other files: # Path: aldryn_gallery/forms.py # class GalleryPluginForm(forms.ModelForm): # # class Meta: # fields = ['style', 'extra_styles', 'engine', 'timeout', 'duration', 'shuffle'] # model = GalleryPlugin # # def clean_style(self): # style = self.cleaned_data.get('style') # # Check if template for style exists: # try: # select_template( # ['aldryn_gallery/plugins/{}/gallery.html'.format(style)]) # except TemplateDoesNotExist: # raise forms.ValidationError( # "Not a valid style (Template " # "'aldryn_gallery/plugins/{}/gallery.html' " # "does not exist)".format(style)) # return style # # Path: aldryn_gallery/models.py # class GalleryPlugin(CMSPlugin): # STANDARD = 'standard' # # STYLE_CHOICES = [ # (STANDARD, _('Standard')), # ] # # ENGINE_CHOICES = ( # ('fade', _('Fade')), # ('slide', _('Slide')) # ) # # cmsplugin_ptr = CMSPluginField() # style = models.CharField( # _('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50) # extra_styles = models.CharField( # _('Extra styles'), max_length=50, blank=True, # help_text=_('An arbitrary string of CSS classes to add')) # engine = models.CharField(_('Engine'), choices=ENGINE_CHOICES, default=ENGINE_CHOICES[0][0], max_length=50) # timeout = models.IntegerField(_('Timeout'), default=5000, help_text=_("Set to 0 to disable autoplay")) # duration = models.IntegerField(_('Duration'), default=300) # shuffle = models.BooleanField(_('Shuffle slides'), default=False) # # def __unicode__(self): # style = _('Style') # engine = _('Engine') # timeout = _('Timeout') # duration = _('Duration') # shuffle = _('Shuffle Slides') # return u'%s: %s, %s: %s, %s: %i, %s: %i, %s: %s' % ( # style, self.style.title(), engine, self.engine.title(), # timeout, self.timeout, duration, self.duration, shuffle, self.shuffle # ) # # class SlidePlugin(CMSPlugin): # LINK_TARGETS = ( # ('', _('same window')), # ('_blank', _('new window')), # ('_parent', _('parent window')), # ('_top', _('topmost frame')), # ) # # cmsplugin_ptr = CMSPluginField() # image = FilerImageField(verbose_name=_('image'), blank=True, null=True) # content = HTMLField("Content", blank=True, null=True) # url = models.URLField(_("Link"), blank=True, null=True) # page_link = PageField( # verbose_name=_('Page'), # blank=True, # null=True, # help_text=_("A link to a page has priority over a text link.") # ) # target = models.CharField( # verbose_name=_("target"), # max_length=100, # blank=True, # choices=LINK_TARGETS, # ) # link_anchor = models.CharField( # verbose_name=_("link anchor"), # max_length=128, # blank=True, # ) # link_text = models.CharField( # verbose_name=_('link text'), # max_length=200, # blank=True # ) # # def __unicode__(self): # image_text = content_text = '' # # if self.image_id: # image_text = u'%s' % (self.image.name or self.image.original_filename) # if self.content: # text = strip_tags(self.content).strip() # if len(text) > 100: # content_text = u'%s...' % text[:100] # else: # content_text = u'%s' % text # # if image_text and content_text: # return u'%s (%s)' % (image_text, content_text) # else: # return image_text or content_text # # def copy_relations(self, oldinstance): # self.image_id = oldinstance.image_id # self.page_link_id = oldinstance.page_link_id # # def get_link(self): # link = self.url or u'' # # if self.page_link_id: # link = self.page_link.get_absolute_url() # # if self.link_anchor: # link += u'#' + self.link_anchor # return link # # class SlideFolderPlugin(CMSPlugin): # cmsplugin_ptr = CMSPluginField() # folder = FilerFolderField(verbose_name=_('folder')) # # def copy_relations(self, oldinstance): # self.folder_id = oldinstance.folder_id , which may include functions, classes, or code. Output only the next line.
form = GalleryPluginForm
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # Base Classes class GalleryBase(CMSPluginBase): class Meta: abstract = True module = _('Gallery') class GalleryChildBase(GalleryBase): class Meta: abstract = True require_parent = True parent_classes = ['GalleryCMSPlugin'] def render(self, context, instance, placeholder): # get style from parent plugin, render chosen template context['instance'] = instance context['image'] = instance.image return context def get_slide_template(self, instance, name='slide'): if instance.parent is None: <|code_end|> , predict the immediate next line with the help of imports: from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .forms import GalleryPluginForm from .models import GalleryPlugin, SlidePlugin, SlideFolderPlugin and context (classes, functions, sometimes code) from other files: # Path: aldryn_gallery/forms.py # class GalleryPluginForm(forms.ModelForm): # # class Meta: # fields = ['style', 'extra_styles', 'engine', 'timeout', 'duration', 'shuffle'] # model = GalleryPlugin # # def clean_style(self): # style = self.cleaned_data.get('style') # # Check if template for style exists: # try: # select_template( # ['aldryn_gallery/plugins/{}/gallery.html'.format(style)]) # except TemplateDoesNotExist: # raise forms.ValidationError( # "Not a valid style (Template " # "'aldryn_gallery/plugins/{}/gallery.html' " # "does not exist)".format(style)) # return style # # Path: aldryn_gallery/models.py # class GalleryPlugin(CMSPlugin): # STANDARD = 'standard' # # STYLE_CHOICES = [ # (STANDARD, _('Standard')), # ] # # ENGINE_CHOICES = ( # ('fade', _('Fade')), # ('slide', _('Slide')) # ) # # cmsplugin_ptr = CMSPluginField() # style = models.CharField( # _('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50) # extra_styles = models.CharField( # _('Extra styles'), max_length=50, blank=True, # help_text=_('An arbitrary string of CSS classes to add')) # engine = models.CharField(_('Engine'), choices=ENGINE_CHOICES, default=ENGINE_CHOICES[0][0], max_length=50) # timeout = models.IntegerField(_('Timeout'), default=5000, help_text=_("Set to 0 to disable autoplay")) # duration = models.IntegerField(_('Duration'), default=300) # shuffle = models.BooleanField(_('Shuffle slides'), default=False) # # def __unicode__(self): # style = _('Style') # engine = _('Engine') # timeout = _('Timeout') # duration = _('Duration') # shuffle = _('Shuffle Slides') # return u'%s: %s, %s: %s, %s: %i, %s: %i, %s: %s' % ( # style, self.style.title(), engine, self.engine.title(), # timeout, self.timeout, duration, self.duration, shuffle, self.shuffle # ) # # class SlidePlugin(CMSPlugin): # LINK_TARGETS = ( # ('', _('same window')), # ('_blank', _('new window')), # ('_parent', _('parent window')), # ('_top', _('topmost frame')), # ) # # cmsplugin_ptr = CMSPluginField() # image = FilerImageField(verbose_name=_('image'), blank=True, null=True) # content = HTMLField("Content", blank=True, null=True) # url = models.URLField(_("Link"), blank=True, null=True) # page_link = PageField( # verbose_name=_('Page'), # blank=True, # null=True, # help_text=_("A link to a page has priority over a text link.") # ) # target = models.CharField( # verbose_name=_("target"), # max_length=100, # blank=True, # choices=LINK_TARGETS, # ) # link_anchor = models.CharField( # verbose_name=_("link anchor"), # max_length=128, # blank=True, # ) # link_text = models.CharField( # verbose_name=_('link text'), # max_length=200, # blank=True # ) # # def __unicode__(self): # image_text = content_text = '' # # if self.image_id: # image_text = u'%s' % (self.image.name or self.image.original_filename) # if self.content: # text = strip_tags(self.content).strip() # if len(text) > 100: # content_text = u'%s...' % text[:100] # else: # content_text = u'%s' % text # # if image_text and content_text: # return u'%s (%s)' % (image_text, content_text) # else: # return image_text or content_text # # def copy_relations(self, oldinstance): # self.image_id = oldinstance.image_id # self.page_link_id = oldinstance.page_link_id # # def get_link(self): # link = self.url or u'' # # if self.page_link_id: # link = self.page_link.get_absolute_url() # # if self.link_anchor: # link += u'#' + self.link_anchor # return link # # class SlideFolderPlugin(CMSPlugin): # cmsplugin_ptr = CMSPluginField() # folder = FilerFolderField(verbose_name=_('folder')) # # def copy_relations(self, oldinstance): # self.folder_id = oldinstance.folder_id . Output only the next line.
style = GalleryPlugin.STANDARD
Continue the code snippet: <|code_start|> def get_render_template(self, context, instance, placeholder): return self.get_slide_template(instance=instance) # Plugins class GalleryCMSPlugin(GalleryBase): render_template = False name = _('Gallery') model = GalleryPlugin form = GalleryPluginForm allow_children = True child_classes = ['SlideCMSPlugin', 'SlideFolderCMSPlugin'] def render(self, context, instance, placeholder): context['instance'] = instance if instance.child_plugin_instances: number_of_slides = sum([plugin.folder.file_count if isinstance(plugin, SlideFolderPlugin) else 1 for plugin in instance.child_plugin_instances]) else: number_of_slides = 0 context['slides'] = range(number_of_slides) return context def get_render_template(self, context, instance, placeholder): return 'aldryn_gallery/plugins/{}/gallery.html'.format(instance.style) class SlideCMSPlugin(GalleryChildBase): name = _('Slide') <|code_end|> . Use current file imports: from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .forms import GalleryPluginForm from .models import GalleryPlugin, SlidePlugin, SlideFolderPlugin and context (classes, functions, or code) from other files: # Path: aldryn_gallery/forms.py # class GalleryPluginForm(forms.ModelForm): # # class Meta: # fields = ['style', 'extra_styles', 'engine', 'timeout', 'duration', 'shuffle'] # model = GalleryPlugin # # def clean_style(self): # style = self.cleaned_data.get('style') # # Check if template for style exists: # try: # select_template( # ['aldryn_gallery/plugins/{}/gallery.html'.format(style)]) # except TemplateDoesNotExist: # raise forms.ValidationError( # "Not a valid style (Template " # "'aldryn_gallery/plugins/{}/gallery.html' " # "does not exist)".format(style)) # return style # # Path: aldryn_gallery/models.py # class GalleryPlugin(CMSPlugin): # STANDARD = 'standard' # # STYLE_CHOICES = [ # (STANDARD, _('Standard')), # ] # # ENGINE_CHOICES = ( # ('fade', _('Fade')), # ('slide', _('Slide')) # ) # # cmsplugin_ptr = CMSPluginField() # style = models.CharField( # _('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50) # extra_styles = models.CharField( # _('Extra styles'), max_length=50, blank=True, # help_text=_('An arbitrary string of CSS classes to add')) # engine = models.CharField(_('Engine'), choices=ENGINE_CHOICES, default=ENGINE_CHOICES[0][0], max_length=50) # timeout = models.IntegerField(_('Timeout'), default=5000, help_text=_("Set to 0 to disable autoplay")) # duration = models.IntegerField(_('Duration'), default=300) # shuffle = models.BooleanField(_('Shuffle slides'), default=False) # # def __unicode__(self): # style = _('Style') # engine = _('Engine') # timeout = _('Timeout') # duration = _('Duration') # shuffle = _('Shuffle Slides') # return u'%s: %s, %s: %s, %s: %i, %s: %i, %s: %s' % ( # style, self.style.title(), engine, self.engine.title(), # timeout, self.timeout, duration, self.duration, shuffle, self.shuffle # ) # # class SlidePlugin(CMSPlugin): # LINK_TARGETS = ( # ('', _('same window')), # ('_blank', _('new window')), # ('_parent', _('parent window')), # ('_top', _('topmost frame')), # ) # # cmsplugin_ptr = CMSPluginField() # image = FilerImageField(verbose_name=_('image'), blank=True, null=True) # content = HTMLField("Content", blank=True, null=True) # url = models.URLField(_("Link"), blank=True, null=True) # page_link = PageField( # verbose_name=_('Page'), # blank=True, # null=True, # help_text=_("A link to a page has priority over a text link.") # ) # target = models.CharField( # verbose_name=_("target"), # max_length=100, # blank=True, # choices=LINK_TARGETS, # ) # link_anchor = models.CharField( # verbose_name=_("link anchor"), # max_length=128, # blank=True, # ) # link_text = models.CharField( # verbose_name=_('link text'), # max_length=200, # blank=True # ) # # def __unicode__(self): # image_text = content_text = '' # # if self.image_id: # image_text = u'%s' % (self.image.name or self.image.original_filename) # if self.content: # text = strip_tags(self.content).strip() # if len(text) > 100: # content_text = u'%s...' % text[:100] # else: # content_text = u'%s' % text # # if image_text and content_text: # return u'%s (%s)' % (image_text, content_text) # else: # return image_text or content_text # # def copy_relations(self, oldinstance): # self.image_id = oldinstance.image_id # self.page_link_id = oldinstance.page_link_id # # def get_link(self): # link = self.url or u'' # # if self.page_link_id: # link = self.page_link.get_absolute_url() # # if self.link_anchor: # link += u'#' + self.link_anchor # return link # # class SlideFolderPlugin(CMSPlugin): # cmsplugin_ptr = CMSPluginField() # folder = FilerFolderField(verbose_name=_('folder')) # # def copy_relations(self, oldinstance): # self.folder_id = oldinstance.folder_id . Output only the next line.
model = SlidePlugin
Given the following code snippet before the placeholder: <|code_start|> def render(self, context, instance, placeholder): # get style from parent plugin, render chosen template context['instance'] = instance context['image'] = instance.image return context def get_slide_template(self, instance, name='slide'): if instance.parent is None: style = GalleryPlugin.STANDARD else: style = getattr(instance.parent.get_plugin_instance()[0], 'style', GalleryPlugin.STANDARD) return 'aldryn_gallery/plugins/{}/{}.html'.format(style, name) def get_render_template(self, context, instance, placeholder): return self.get_slide_template(instance=instance) # Plugins class GalleryCMSPlugin(GalleryBase): render_template = False name = _('Gallery') model = GalleryPlugin form = GalleryPluginForm allow_children = True child_classes = ['SlideCMSPlugin', 'SlideFolderCMSPlugin'] def render(self, context, instance, placeholder): context['instance'] = instance if instance.child_plugin_instances: <|code_end|> , predict the next line using imports from the current file: from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .forms import GalleryPluginForm from .models import GalleryPlugin, SlidePlugin, SlideFolderPlugin and context including class names, function names, and sometimes code from other files: # Path: aldryn_gallery/forms.py # class GalleryPluginForm(forms.ModelForm): # # class Meta: # fields = ['style', 'extra_styles', 'engine', 'timeout', 'duration', 'shuffle'] # model = GalleryPlugin # # def clean_style(self): # style = self.cleaned_data.get('style') # # Check if template for style exists: # try: # select_template( # ['aldryn_gallery/plugins/{}/gallery.html'.format(style)]) # except TemplateDoesNotExist: # raise forms.ValidationError( # "Not a valid style (Template " # "'aldryn_gallery/plugins/{}/gallery.html' " # "does not exist)".format(style)) # return style # # Path: aldryn_gallery/models.py # class GalleryPlugin(CMSPlugin): # STANDARD = 'standard' # # STYLE_CHOICES = [ # (STANDARD, _('Standard')), # ] # # ENGINE_CHOICES = ( # ('fade', _('Fade')), # ('slide', _('Slide')) # ) # # cmsplugin_ptr = CMSPluginField() # style = models.CharField( # _('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50) # extra_styles = models.CharField( # _('Extra styles'), max_length=50, blank=True, # help_text=_('An arbitrary string of CSS classes to add')) # engine = models.CharField(_('Engine'), choices=ENGINE_CHOICES, default=ENGINE_CHOICES[0][0], max_length=50) # timeout = models.IntegerField(_('Timeout'), default=5000, help_text=_("Set to 0 to disable autoplay")) # duration = models.IntegerField(_('Duration'), default=300) # shuffle = models.BooleanField(_('Shuffle slides'), default=False) # # def __unicode__(self): # style = _('Style') # engine = _('Engine') # timeout = _('Timeout') # duration = _('Duration') # shuffle = _('Shuffle Slides') # return u'%s: %s, %s: %s, %s: %i, %s: %i, %s: %s' % ( # style, self.style.title(), engine, self.engine.title(), # timeout, self.timeout, duration, self.duration, shuffle, self.shuffle # ) # # class SlidePlugin(CMSPlugin): # LINK_TARGETS = ( # ('', _('same window')), # ('_blank', _('new window')), # ('_parent', _('parent window')), # ('_top', _('topmost frame')), # ) # # cmsplugin_ptr = CMSPluginField() # image = FilerImageField(verbose_name=_('image'), blank=True, null=True) # content = HTMLField("Content", blank=True, null=True) # url = models.URLField(_("Link"), blank=True, null=True) # page_link = PageField( # verbose_name=_('Page'), # blank=True, # null=True, # help_text=_("A link to a page has priority over a text link.") # ) # target = models.CharField( # verbose_name=_("target"), # max_length=100, # blank=True, # choices=LINK_TARGETS, # ) # link_anchor = models.CharField( # verbose_name=_("link anchor"), # max_length=128, # blank=True, # ) # link_text = models.CharField( # verbose_name=_('link text'), # max_length=200, # blank=True # ) # # def __unicode__(self): # image_text = content_text = '' # # if self.image_id: # image_text = u'%s' % (self.image.name or self.image.original_filename) # if self.content: # text = strip_tags(self.content).strip() # if len(text) > 100: # content_text = u'%s...' % text[:100] # else: # content_text = u'%s' % text # # if image_text and content_text: # return u'%s (%s)' % (image_text, content_text) # else: # return image_text or content_text # # def copy_relations(self, oldinstance): # self.image_id = oldinstance.image_id # self.page_link_id = oldinstance.page_link_id # # def get_link(self): # link = self.url or u'' # # if self.page_link_id: # link = self.page_link.get_absolute_url() # # if self.link_anchor: # link += u'#' + self.link_anchor # return link # # class SlideFolderPlugin(CMSPlugin): # cmsplugin_ptr = CMSPluginField() # folder = FilerFolderField(verbose_name=_('folder')) # # def copy_relations(self, oldinstance): # self.folder_id = oldinstance.folder_id . Output only the next line.
number_of_slides = sum([plugin.folder.file_count if isinstance(plugin, SlideFolderPlugin) else 1
Predict the next line after this snippet: <|code_start|> models.OneToOneField, to=CMSPlugin, related_name='+', parent_link=True, ) else: # Once djangoCMS < 3.3.1 support is dropped # Remove the explicit cmsplugin_ptr field declarations CMSPluginField = partial( models.OneToOneField, to=CMSPlugin, related_name='%(app_label)s_%(class)s', parent_link=True, ) class GalleryPlugin(CMSPlugin): STANDARD = 'standard' STYLE_CHOICES = [ (STANDARD, _('Standard')), ] ENGINE_CHOICES = ( ('fade', _('Fade')), ('slide', _('Slide')) ) cmsplugin_ptr = CMSPluginField() style = models.CharField( <|code_end|> using the current file's imports: from functools import partial from django.db import models from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cms.models.fields import PageField from djangocms_text_ckeditor.fields import HTMLField from filer.fields.folder import FilerFolderField from filer.fields.image import FilerImageField from . import compat from .utils import get_additional_styles and any relevant context from other files: # Path: aldryn_gallery/utils.py # def get_additional_styles(): # """ # Get additional styles choices from settings # """ # choices = [] # raw = getattr(settings, 'GALLERY_STYLES', False) # if raw: # if isinstance(raw, basestring): # raw = raw.split(',') # for choice in raw: # clean = choice.strip() # choices.append((clean.lower(), clean.title())) # return choices . Output only the next line.
_('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class GalleryPluginForm(forms.ModelForm): class Meta: fields = ['style', 'extra_styles', 'engine', 'timeout', 'duration', 'shuffle'] <|code_end|> , predict the next line using imports from the current file: from django import forms from django.template import TemplateDoesNotExist from django.template.loader import select_template from .models import GalleryPlugin and context including class names, function names, and sometimes code from other files: # Path: aldryn_gallery/models.py # class GalleryPlugin(CMSPlugin): # STANDARD = 'standard' # # STYLE_CHOICES = [ # (STANDARD, _('Standard')), # ] # # ENGINE_CHOICES = ( # ('fade', _('Fade')), # ('slide', _('Slide')) # ) # # cmsplugin_ptr = CMSPluginField() # style = models.CharField( # _('Style'), choices=STYLE_CHOICES + get_additional_styles(), default=STANDARD, max_length=50) # extra_styles = models.CharField( # _('Extra styles'), max_length=50, blank=True, # help_text=_('An arbitrary string of CSS classes to add')) # engine = models.CharField(_('Engine'), choices=ENGINE_CHOICES, default=ENGINE_CHOICES[0][0], max_length=50) # timeout = models.IntegerField(_('Timeout'), default=5000, help_text=_("Set to 0 to disable autoplay")) # duration = models.IntegerField(_('Duration'), default=300) # shuffle = models.BooleanField(_('Shuffle slides'), default=False) # # def __unicode__(self): # style = _('Style') # engine = _('Engine') # timeout = _('Timeout') # duration = _('Duration') # shuffle = _('Shuffle Slides') # return u'%s: %s, %s: %s, %s: %i, %s: %i, %s: %s' % ( # style, self.style.title(), engine, self.engine.title(), # timeout, self.timeout, duration, self.duration, shuffle, self.shuffle # ) . Output only the next line.
model = GalleryPlugin
Here is a snippet: <|code_start|>""" ERP analysis EEG submodule. """ # ============================================================================== # ============================================================================== # ============================================================================== # ============================================================================== # ============================================================================== # ============================================================================== # ============================================================================== # ============================================================================== def eeg_erp(eeg, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, names="ERP", method="mean"): """ DOCS INCOMPLETE :( """ erp = {} <|code_end|> . Write the next line using the current file imports: from .eeg_data import eeg_select_electrodes from .eeg_data import eeg_to_df from .eeg_data import eeg_to_all_evokeds import numpy as np import pandas as pd import mne and context from other files: # Path: neurokit/eeg/eeg_data.py # def eeg_select_electrodes(eeg, include="all", exclude=None, hemisphere="both", central=True): # """ # Returns electrodes/sensors names of selected region (according to a 10-20 EEG montage). # # Parameters # ---------- # eeg : mne.Raw or mne.Epochs # EEG data. # include : str ot list # Sensor area to include. # exclude : str or list or None # Sensor area to exclude. # hemisphere : str # Select both hemispheres? "both", "left" or "right". # central : bool # Select the central line. # # Returns # ---------- # electrodes : list # List of electrodes/sensors corresponding to the selected area. # # Example # ---------- # >>> import neurokit as nk # >>> nk.eeg_select_electrodes(include="F", exclude="C") # # # Notes # ---------- # *Authors* # # - `Dominique Makowski <https://dominiquemakowski.github.io/>`_ # # """ # # Get all channel names # eeg = eeg.copy().pick_types(meg=False, eeg=True) # channel_list = eeg.ch_names # # # Include # if include == "all": # electrodes = channel_list # elif isinstance(include, str): # electrodes = [s for s in channel_list if include in s] # elif isinstance(include, list): # electrodes = [] # for i in include: # electrodes += [s for s in channel_list if i in s] # else: # print("NeuroKit Warning: eeg_select_electrodes(): 'include' parameter must be 'all', str or list.") # # # Exclude # if exclude is not None: # if isinstance(exclude, str): # to_remove = [s for s in channel_list if exclude in s] # electrodes = [s for s in electrodes if s not in to_remove] # elif isinstance(exclude, list): # to_remove = [] # for i in exclude: # to_remove += [s for s in channel_list if i in s] # electrodes = [s for s in electrodes if s not in to_remove] # else: # print("NeuroKit Warning: eeg_select_electrodes(): 'exclude' parameter must be None, str or list.") # # # Laterality # if hemisphere != "both": # if hemisphere.lower() == "left" or hemisphere.lower() == "l": # hemi = [s for s in electrodes if len(re.findall(r'\d+', s)) > 0 and int(re.findall(r'\d+', s)[0])%2 > 0] # elif hemisphere.lower() == "right" or hemisphere.lower() == "r": # hemi = [s for s in electrodes if len(re.findall(r'\d+', s)) > 0 and int(re.findall(r'\d+', s)[0])%2 == 0] # else: # print("NeuroKit Warning: eeg_select_electrodes(): 'hemisphere' parameter must be 'both', 'left' or 'right'. Returning both.") # # if central is True: # hemi += [s for s in electrodes if 'z' in s] # # electrodes = hemi # # return(electrodes) # # Path: neurokit/eeg/eeg_data.py # def eeg_to_df(eeg, index=None, include="all", exclude=None, hemisphere="both", central=True): # """ # Convert mne Raw or Epochs object to dataframe or dict of dataframes. # # DOCS INCOMPLETE :( # """ # if isinstance(eeg, mne.Epochs): # data = {} # # if index is None: # index = range(len(eeg)) # # for epoch_index, epoch in zip(index, eeg.get_data()): # # epoch = pd.DataFrame(epoch.T) # epoch.columns = eeg.ch_names # epoch.index = eeg.times # # selection = eeg_select_electrodes(eeg, include=include, exclude=exclude, hemisphere=hemisphere, central=central) # # data[epoch_index] = epoch[selection] # # else: # it might be a Raw object # data = eeg.get_data().T # data = pd.DataFrame(data) # data.columns = eeg.ch_names # data.index = eeg.times # # return(data) # # Path: neurokit/eeg/eeg_data.py # def eeg_to_all_evokeds(all_epochs, conditions=None): # """ # Convert all_epochs to all_evokeds. # # DOCS INCOMPLETE :( # """ # if conditions is None: # # Get event_id # conditions = {} # for participant, epochs in all_epochs.items(): # conditions.update(epochs.event_id) # # all_evokeds = {} # for participant, epochs in all_epochs.items(): # evokeds = {} # for cond in conditions: # try: # evokeds[cond] = epochs[cond].average() # except KeyError: # pass # all_evokeds[participant] = evokeds # # return(all_evokeds) , which may include functions, classes, or code. Output only the next line.
data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central)
Based on the snippet: <|code_start|> # Main plot = plt.figure(figsize=fig_size) layer1 = plot.add_subplot(111, projection="polar") bars1 = layer1.bar(theta+np.pi/len(scores), scores, width=width, bottom=0.0) layer1.yaxis.set_ticks(range(11)) layer1.yaxis.set_ticklabels([]) layer1.xaxis.set_ticks(theta+np.pi/len(scores)) layer1.xaxis.set_ticklabels(labels, fontsize=labels_size) for index, bar in enumerate(bars1): if colors is not None: bar.set_facecolor(colors[index]) bar.set_alpha(1) # Layer 2 if distribution_means is not None and distribution_sds is not None: # Sanity check if isinstance(distribution_means, int): distribution_means = [distribution_means]*N if isinstance(distribution_sds, int): distribution_sds = [distribution_sds]*N # TODO: add convertion if those parameter are dict <|code_end|> , predict the immediate next line with the help of imports: from .statistics import normal_range import numpy as np import pandas as pd import matplotlib.pyplot as plt and context (classes, functions, sometimes code) from other files: # Path: neurokit/statistics/statistics.py # def normal_range(mean, sd, treshold=1.28): # """ # Returns a bottom and a top limit on a normal distribution portion based on a treshold. # # Parameters # ---------- # treshold : float # maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = keeping 99%, 2.33 = keeping 98%, 1.96 = 95% and 1.28 = keeping 90%. # # Returns # ---------- # (bottom, top) : tuple # Lower and higher range. # # Example # ---------- # >>> import neurokit as nk # >>> bottom, top = nk.normal_range(mean=100, sd=15, treshold=2) # # Notes # ---------- # *Authors* # # - `Dominique Makowski <https://dominiquemakowski.github.io/>`_ # """ # bottom = mean - sd*treshold # top = mean + sd*treshold # return(bottom, top) . Output only the next line.
bottoms, tops = normal_range(np.array(distribution_means), np.array(distribution_sds), treshold=treshold)
Based on the snippet: <|code_start|> if ((self.options['exitstatus'] or self.options['startupsession'] and (self.options['alwaysloadstartupsession'] or len(sys.argv) <= 1 or not self.options['promptexitsave'])) and os.path.isfile(self.lastSessionFilename)): if self.LoadSession(self.lastSessionFilename, saverecentdir=False, resize=False, backup=True, startup=True): use_last_preview_placement = False else: self.loaderror.append(os.path.basename(self.lastSessionFilename)) shutil.copy2(self.lastSessionFilename, os.path.splitext(self.lastSessionFilename)[0] + '.BAD') if use_last_preview_placement and self.options['last_preview_placement'] != self.mainSplitter.GetSplitMode(): self.TogglePreviewPlacement() if not self.options['exitstatus']: self.options['exitstatus'] = 1 f = open(self.optionsfilename, mode='wb') cPickle.dump(self.options, f, protocol=0) f.close() if len(sys.argv)>1: self.ProcessArguments(sys.argv[1:]) #~ if not self.currentScript.sliderWindowShown: #~ self.HideSliderWindow(self.currentScript) #~ else: #~ newSliderWindow.Show() #~ self.ShowSliderWindow(self.currentScript) if self.previewWindowVisible: #~ self.HidePreviewWindow() self.need_to_show_preview = True else: self.need_to_show_preview = False # Misc self.UpdateProgramTitle() <|code_end|> , predict the immediate next line with the help of imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context (classes, functions, sometimes code) from other files: # Path: icons.py . Output only the next line.
self.SetIcon(AvsP_icon.getIcon())
Given the code snippet: <|code_start|> (''), (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Add or override AviSynth functions in the database')), #~ (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Edit the AviSynth function info for syntax highlighting and calltips')), (_('Fonts and colors...'), '', self.OnMenuOptionsFontsAndColors, _('Edit the various AviSynth script fonts and colors')), (_('Extension templates...'), '', self.OnMenuOptionsTemplates, _('Edit the extension-based templates for inserting sources')), (_('Snippets...'), '', self.OnMenuOptionsSnippets, _('Edit insertable text snippets')), (''), (_('Keyboard shortcuts...'), '', self.OnMenuConfigureShortcuts, _('Configure the program keyboard shortcuts')), (_('Program settings...'), '', self.OnMenuOptionsSettings, _('Configure program settings')), ), (_('&Help'), (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): bmpPlay = play_icon.getImage() bmpPause = pause_icon.getImage() bmpExternal = external_icon.getImage() <|code_end|> , generate the next line using the imports in this file: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context (functions, classes, or occasionally code) from other files: # Path: icons.py . Output only the next line.
bmpRight = next_icon.getImage()
Using the snippet: <|code_start|> #~(_('Enable line-by-line update'), '', self.OnMenuOptionsEnableLineByLineUpdate, _('Enable the line-by-line video update mode (update every time the cursor changes line position)'), wx.ITEM_CHECK, self.options['autoupdatevideo']), (''), (_('Associate .avs files with AvsP'), '', self.OnMenuOptionsAssociate, _('Configure this computer to open .avs files with AvsP when double-clicked. Run again to disassociate')), (''), (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Add or override AviSynth functions in the database')), #~ (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Edit the AviSynth function info for syntax highlighting and calltips')), (_('Fonts and colors...'), '', self.OnMenuOptionsFontsAndColors, _('Edit the various AviSynth script fonts and colors')), (_('Extension templates...'), '', self.OnMenuOptionsTemplates, _('Edit the extension-based templates for inserting sources')), (_('Snippets...'), '', self.OnMenuOptionsSnippets, _('Edit insertable text snippets')), (''), (_('Keyboard shortcuts...'), '', self.OnMenuConfigureShortcuts, _('Configure the program keyboard shortcuts')), (_('Program settings...'), '', self.OnMenuOptionsSettings, _('Configure program settings')), ), (_('&Help'), (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): <|code_end|> , determine the next line of code. You have imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context (class names, function names, or code) available: # Path: icons.py . Output only the next line.
bmpPlay = play_icon.getImage()
Predict the next line after this snippet: <|code_start|> (''), (_('Associate .avs files with AvsP'), '', self.OnMenuOptionsAssociate, _('Configure this computer to open .avs files with AvsP when double-clicked. Run again to disassociate')), (''), (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Add or override AviSynth functions in the database')), #~ (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Edit the AviSynth function info for syntax highlighting and calltips')), (_('Fonts and colors...'), '', self.OnMenuOptionsFontsAndColors, _('Edit the various AviSynth script fonts and colors')), (_('Extension templates...'), '', self.OnMenuOptionsTemplates, _('Edit the extension-based templates for inserting sources')), (_('Snippets...'), '', self.OnMenuOptionsSnippets, _('Edit insertable text snippets')), (''), (_('Keyboard shortcuts...'), '', self.OnMenuConfigureShortcuts, _('Configure the program keyboard shortcuts')), (_('Program settings...'), '', self.OnMenuOptionsSettings, _('Configure program settings')), ), (_('&Help'), (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): bmpPlay = play_icon.getImage() <|code_end|> using the current file's imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and any relevant context from other files: # Path: icons.py . Output only the next line.
bmpPause = pause_icon.getImage()
Next line prediction: <|code_start|> (_('Associate .avs files with AvsP'), '', self.OnMenuOptionsAssociate, _('Configure this computer to open .avs files with AvsP when double-clicked. Run again to disassociate')), (''), (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Add or override AviSynth functions in the database')), #~ (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Edit the AviSynth function info for syntax highlighting and calltips')), (_('Fonts and colors...'), '', self.OnMenuOptionsFontsAndColors, _('Edit the various AviSynth script fonts and colors')), (_('Extension templates...'), '', self.OnMenuOptionsTemplates, _('Edit the extension-based templates for inserting sources')), (_('Snippets...'), '', self.OnMenuOptionsSnippets, _('Edit insertable text snippets')), (''), (_('Keyboard shortcuts...'), '', self.OnMenuConfigureShortcuts, _('Configure the program keyboard shortcuts')), (_('Program settings...'), '', self.OnMenuOptionsSettings, _('Configure program settings')), ), (_('&Help'), (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): bmpPlay = play_icon.getImage() bmpPause = pause_icon.getImage() <|code_end|> . Use current file imports: (import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor) and context including class names, function names, or small code snippets from other files: # Path: icons.py . Output only the next line.
bmpExternal = external_icon.getImage()
Given snippet: <|code_start|> (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Add or override AviSynth functions in the database')), #~ (_('AviSynth function definition...'), '', self.OnMenuOptionsFilters, _('Edit the AviSynth function info for syntax highlighting and calltips')), (_('Fonts and colors...'), '', self.OnMenuOptionsFontsAndColors, _('Edit the various AviSynth script fonts and colors')), (_('Extension templates...'), '', self.OnMenuOptionsTemplates, _('Edit the extension-based templates for inserting sources')), (_('Snippets...'), '', self.OnMenuOptionsSnippets, _('Edit insertable text snippets')), (''), (_('Keyboard shortcuts...'), '', self.OnMenuConfigureShortcuts, _('Configure the program keyboard shortcuts')), (_('Program settings...'), '', self.OnMenuOptionsSettings, _('Configure program settings')), ), (_('&Help'), (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): bmpPlay = play_icon.getImage() bmpPause = pause_icon.getImage() bmpExternal = external_icon.getImage() bmpRight = next_icon.getImage() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context: # Path: icons.py which might include code, classes, or functions. Output only the next line.
bmpSkipRight = skip_icon.getImage()
Predict the next line for this snippet: <|code_start|> (_('Animated tutorial'), '', self.OnMenuHelpAnimatedTutorial, _('View an animated tutorial for AvsP (from the AvsP website)')), (''), (_('Text features'), '', self.OnMenuHelpTextFeatures, _('Learn more about AvsP text features (from the AvsP website)')), (_('Video features'), '', self.OnMenuHelpVideoFeatures, _('Learn more about AvsP video features (from the AvsP website)')), (_('User sliders'), '', self.OnMenuHelpUserSliderFeatures, _('Learn more about AvsP user sliders (from the AvsP website)')), (_('Macros'), '', self.OnMenuHelpMacroFeatures, _('Learn more about AvsP macros (from the AvsP website)')), (''), (_('Avisynth help'), 'F1', self.OnMenuHelpAvisynth, _('Open the avisynth help html')), (_('Open Avisynth plugins folder'), '', self.OnMenuHelpAvisynthPlugins, _('Open the avisynth plugins folder, or the last folder from which a plugin was loaded')), (''), (_('Changelog'), '', self.OnMenuHelpChangelog, _('Open the changelog file')), (_('About AvsPmod'), '', self.OnMenuHelpAbout, _('About this program')), ), ) def buttonInfo(self): bmpPlay = play_icon.getImage() bmpPause = pause_icon.getImage() bmpExternal = external_icon.getImage() bmpRight = next_icon.getImage() bmpSkipRight = skip_icon.getImage() if not self.options['largeui']: bmpPlay = bmpPlay.Scale(16,16) bmpPause = bmpPause.Scale(16,16) bmpExternal = bmpExternal.Scale(16,16) bmpRight = bmpRight.Scale(16,16) bmpSkipRight = bmpSkipRight.Scale(16,16) self.bmpPlay = wx.BitmapFromImage(bmpPlay) self.bmpPause = wx.BitmapFromImage(bmpPause) bmpExternal = wx.BitmapFromImage(bmpExternal) <|code_end|> with the help of current file imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context from other files: # Path: icons.py , which may contain function names, class names, or code. Output only the next line.
self.bmpRightTriangle = spin_icon.GetBitmap() #wx.BitmapFromImage(play_icon.getImage().Scale(10,10))
Given the following code snippet before the placeholder: <|code_start|> self.Bind(stc.EVT_STC_AUTOCOMP_SELECTION, self.OnAutocompleteSelection) self.Bind(stc.EVT_STC_USERLISTSELECTION, self.OnUserListSelection) self.Bind(stc.EVT_STC_CALLTIP_CLICK, self.OnCalltipClick) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) self.Bind(stc.EVT_STC_ZOOM, lambda event: self.fitNumberMarginWidth()) try: self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda event: self.ReleaseMouse()) except AttributeError: pass if self.GetLexer() == stc.STC_LEX_CONTAINER: self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded) def SetUserOptions(self): # AviSynth filter information #~ if not filterDict: #~ filterDict = self.defineFilterDict() #~ filterDict = dict([(name.lower(), (name,args,ftype)) for name, (args,ftype) in filterDict.items()]) #~ if not keywordLists: #~ keywords = ['default', 'end', 'return', 'global', 'function', 'last', 'true', 'false', 'try', 'catch',] #~ datatypes = ['clip', 'int', 'float', 'string', 'bool', 'val'] #~ operators = ('-', '*', ',', '.', '/', ':', '?', '\\', '+', '<', '>', '=', '(', ')', '[', ']', '{', '}', '!', '%', '&', '|') #~ miscwords = [] #~ keywordLists = (keywords, datatypes, operators, miscwords) self.SetTextStyles(self.app.options['textstyles'], self.app.options['usemonospacedfont']) if self.styling_refresh_needed: self.styling_refresh_needed = False self.Colourise(0, 0) # set self.GetEndStyled() to 0 if self.app.options['autocompleteicons']: <|code_end|> , predict the next line using imports from the current file: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context including class names, function names, and sometimes code from other files: # Path: icons.py . Output only the next line.
self.RegisterImage(1, ok_icon.GetBitmap())
Here is a snippet: <|code_start|> self.Bind(stc.EVT_STC_USERLISTSELECTION, self.OnUserListSelection) self.Bind(stc.EVT_STC_CALLTIP_CLICK, self.OnCalltipClick) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) self.Bind(stc.EVT_STC_ZOOM, lambda event: self.fitNumberMarginWidth()) try: self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda event: self.ReleaseMouse()) except AttributeError: pass if self.GetLexer() == stc.STC_LEX_CONTAINER: self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded) def SetUserOptions(self): # AviSynth filter information #~ if not filterDict: #~ filterDict = self.defineFilterDict() #~ filterDict = dict([(name.lower(), (name,args,ftype)) for name, (args,ftype) in filterDict.items()]) #~ if not keywordLists: #~ keywords = ['default', 'end', 'return', 'global', 'function', 'last', 'true', 'false', 'try', 'catch',] #~ datatypes = ['clip', 'int', 'float', 'string', 'bool', 'val'] #~ operators = ('-', '*', ',', '.', '/', ':', '?', '\\', '+', '<', '>', '=', '(', ')', '[', ']', '{', '}', '!', '%', '&', '|') #~ miscwords = [] #~ keywordLists = (keywords, datatypes, operators, miscwords) self.SetTextStyles(self.app.options['textstyles'], self.app.options['usemonospacedfont']) if self.styling_refresh_needed: self.styling_refresh_needed = False self.Colourise(0, 0) # set self.GetEndStyled() to 0 if self.app.options['autocompleteicons']: self.RegisterImage(1, ok_icon.GetBitmap()) <|code_end|> . Write the next line using the current file imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context from other files: # Path: icons.py , which may include functions, classes, or code. Output only the next line.
self.RegisterImage(2, smile_icon.GetBitmap())
Predict the next line after this snippet: <|code_start|> self.Bind(stc.EVT_STC_CALLTIP_CLICK, self.OnCalltipClick) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) self.Bind(stc.EVT_STC_ZOOM, lambda event: self.fitNumberMarginWidth()) try: self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda event: self.ReleaseMouse()) except AttributeError: pass if self.GetLexer() == stc.STC_LEX_CONTAINER: self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded) def SetUserOptions(self): # AviSynth filter information #~ if not filterDict: #~ filterDict = self.defineFilterDict() #~ filterDict = dict([(name.lower(), (name,args,ftype)) for name, (args,ftype) in filterDict.items()]) #~ if not keywordLists: #~ keywords = ['default', 'end', 'return', 'global', 'function', 'last', 'true', 'false', 'try', 'catch',] #~ datatypes = ['clip', 'int', 'float', 'string', 'bool', 'val'] #~ operators = ('-', '*', ',', '.', '/', ':', '?', '\\', '+', '<', '>', '=', '(', ')', '[', ']', '{', '}', '!', '%', '&', '|') #~ miscwords = [] #~ keywordLists = (keywords, datatypes, operators, miscwords) self.SetTextStyles(self.app.options['textstyles'], self.app.options['usemonospacedfont']) if self.styling_refresh_needed: self.styling_refresh_needed = False self.Colourise(0, 0) # set self.GetEndStyled() to 0 if self.app.options['autocompleteicons']: self.RegisterImage(1, ok_icon.GetBitmap()) self.RegisterImage(2, smile_icon.GetBitmap()) <|code_end|> using the current file's imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and any relevant context from other files: # Path: icons.py . Output only the next line.
self.RegisterImage(3, question_icon.GetBitmap())
Based on the snippet: <|code_start|> self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) self.Bind(stc.EVT_STC_ZOOM, lambda event: self.fitNumberMarginWidth()) try: self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda event: self.ReleaseMouse()) except AttributeError: pass if self.GetLexer() == stc.STC_LEX_CONTAINER: self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded) def SetUserOptions(self): # AviSynth filter information #~ if not filterDict: #~ filterDict = self.defineFilterDict() #~ filterDict = dict([(name.lower(), (name,args,ftype)) for name, (args,ftype) in filterDict.items()]) #~ if not keywordLists: #~ keywords = ['default', 'end', 'return', 'global', 'function', 'last', 'true', 'false', 'try', 'catch',] #~ datatypes = ['clip', 'int', 'float', 'string', 'bool', 'val'] #~ operators = ('-', '*', ',', '.', '/', ':', '?', '\\', '+', '<', '>', '=', '(', ')', '[', ']', '{', '}', '!', '%', '&', '|') #~ miscwords = [] #~ keywordLists = (keywords, datatypes, operators, miscwords) self.SetTextStyles(self.app.options['textstyles'], self.app.options['usemonospacedfont']) if self.styling_refresh_needed: self.styling_refresh_needed = False self.Colourise(0, 0) # set self.GetEndStyled() to 0 if self.app.options['autocompleteicons']: self.RegisterImage(1, ok_icon.GetBitmap()) self.RegisterImage(2, smile_icon.GetBitmap()) self.RegisterImage(3, question_icon.GetBitmap()) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context (classes, functions, sometimes code) from other files: # Path: icons.py . Output only the next line.
self.RegisterImage(4, rectangle_icon.GetBitmap())
Here is a snippet: <|code_start|> def OnGroupClearAllTabGroups(self, event): for index in xrange(self.scriptNotebook.GetPageCount()): self.AssignTabGroup(None, index) def OnGroupAssignTabGroup(self, event): id = event.GetId() context_menu = event.GetEventObject() group_menu = context_menu.FindItemById(context_menu.FindItem(_('Group'))).GetSubMenu() label = group_menu.FindItemById(id).GetLabel() self.AssignTabGroup(label) def AssignTabGroup(self, group, index=None): if group == _('None'): group = None current_tab = self.scriptNotebook.GetSelection() if index is None: index = current_tab script = self.scriptNotebook.GetPage(index) script.group = group script.group_frame = script.lastFramenum self.UpdateScriptTabname(index=index) def OnMouseMotionNotebook(self, event): if event.Dragging() and event.LeftIsDown(): self.scriptNotebook.dragging = True if self.titleEntry: self.scriptNotebook.SetFocus() index = self.scriptNotebook.GetSelection() ipage = self.scriptNotebook.HitTest(event.GetPosition())[0] if ipage != wx.NOT_FOUND: <|code_end|> . Write the next line using the current file imports: import os import sys import platform import traceback import cPickle import shutil import string import array import struct import codecs import re import functools import bisect import random, math, copy import subprocess, shlex import socket import thread import threading import time import StringIO import textwrap import ctypes import tempfile import zlib import glob import urllib2 import cgi import _winreg import __builtin__ import collections import global_vars import i18n import wx import wx.lib.buttons as wxButtons import wx.lib.colourselect as colourselect import wxp import avisynth_cffi as avisynth import avisynth import pyavs import pyavs_avifile as pyavs # VFW, not longer supported import _subprocess from hashlib import md5 from wx import stc from icons import AvsP_icon, next_icon, play_icon, pause_icon, external_icon, \ skip_icon, spin_icon, ok_icon, smile_icon, question_icon, \ rectangle_icon, dragdrop_cursor and context from other files: # Path: icons.py , which may include functions, classes, or code. Output only the next line.
self.scriptNotebook.SetCursor(wx.CursorFromImage(dragdrop_cursor.GetImage()))
Continue the code snippet: <|code_start|> okay = wx.Button(self, wx.ID_OK, _('OK')) #~ self.Bind(wx.EVT_BUTTON, self.OnButtonClick, okay) cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel')) #~ self.Bind(wx.EVT_BUTTON, self.OnButtonClick, cancel) btns = wx.StdDialogButtonSizer() if advanced: btns.Add(advanced) btns.AddButton(okay) btns.AddButton(cancel) btns.Realize() # Size the elements dlgSizer = wx.BoxSizer(wx.VERTICAL) dlgSizer.Add(listCtrl, 1, wx.EXPAND|wx.ALL, 5) if submessage is not None: dlgSizer.Add(wx.StaticText(self, wx.ID_ANY, submessage), 0, wx.ALIGN_LEFT|wx.LEFT|wx.BOTTOM, 10) message = _('Double-click or hit enter on an item in the list to edit the shortcut.') dlgSizer.Add(wx.StaticText(self, wx.ID_ANY, message), 0, wx.ALIGN_CENTER|wx.ALL, 5) dlgSizer.Add(btns, 0, wx.EXPAND|wx.ALL, 10) self.SetSizerAndFit(dlgSizer) width, height = self.GetSize() self.SetSize((width, height*2)) self.sizer = dlgSizer # Misc #okay.SetDefault() def OnAdvancedButton(self, event): dlg = wx.Dialog(self, wx.ID_ANY, _('Advanced'), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) class CheckListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin): def __init__(self, parent): wx.ListCtrl.__init__(self, parent, wx.ID_ANY, style=wx.LC_REPORT) <|code_end|> . Use current file imports: import wx import wx.lib.buttons as wxButtons import wx.lib.mixins.listctrl as listmix import wx.lib.filebrowsebutton as filebrowse import wx.lib.colourselect as colourselect import string import keyword import os import os.path import sys import copy import time import wx.lib.newevent import socket import thread import StringIO import cPickle import ctypes import fcntl from wx.lib.agw.floatspin import FloatSpin from wx.lib.agw.hyperlink import HyperLinkCtrl from wx import stc from icons import checked_icon, unchecked_icon from ctypes import windll, WinError and context (classes, functions, or code) from other files: # Path: icons.py . Output only the next line.
listmix.CheckListCtrlMixin.__init__(self, checked_icon.GetBitmap(), unchecked_icon.GetBitmap())
Given the following code snippet before the placeholder: <|code_start|> okay = wx.Button(self, wx.ID_OK, _('OK')) #~ self.Bind(wx.EVT_BUTTON, self.OnButtonClick, okay) cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel')) #~ self.Bind(wx.EVT_BUTTON, self.OnButtonClick, cancel) btns = wx.StdDialogButtonSizer() if advanced: btns.Add(advanced) btns.AddButton(okay) btns.AddButton(cancel) btns.Realize() # Size the elements dlgSizer = wx.BoxSizer(wx.VERTICAL) dlgSizer.Add(listCtrl, 1, wx.EXPAND|wx.ALL, 5) if submessage is not None: dlgSizer.Add(wx.StaticText(self, wx.ID_ANY, submessage), 0, wx.ALIGN_LEFT|wx.LEFT|wx.BOTTOM, 10) message = _('Double-click or hit enter on an item in the list to edit the shortcut.') dlgSizer.Add(wx.StaticText(self, wx.ID_ANY, message), 0, wx.ALIGN_CENTER|wx.ALL, 5) dlgSizer.Add(btns, 0, wx.EXPAND|wx.ALL, 10) self.SetSizerAndFit(dlgSizer) width, height = self.GetSize() self.SetSize((width, height*2)) self.sizer = dlgSizer # Misc #okay.SetDefault() def OnAdvancedButton(self, event): dlg = wx.Dialog(self, wx.ID_ANY, _('Advanced'), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) class CheckListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin): def __init__(self, parent): wx.ListCtrl.__init__(self, parent, wx.ID_ANY, style=wx.LC_REPORT) <|code_end|> , predict the next line using imports from the current file: import wx import wx.lib.buttons as wxButtons import wx.lib.mixins.listctrl as listmix import wx.lib.filebrowsebutton as filebrowse import wx.lib.colourselect as colourselect import string import keyword import os import os.path import sys import copy import time import wx.lib.newevent import socket import thread import StringIO import cPickle import ctypes import fcntl from wx.lib.agw.floatspin import FloatSpin from wx.lib.agw.hyperlink import HyperLinkCtrl from wx import stc from icons import checked_icon, unchecked_icon from ctypes import windll, WinError and context including class names, function names, and sometimes code from other files: # Path: icons.py . Output only the next line.
listmix.CheckListCtrlMixin.__init__(self, checked_icon.GetBitmap(), unchecked_icon.GetBitmap())
Given the code snippet: <|code_start|> 1. Combine data extracted from data sources. 2. Transform and validate combined data into IDs and enums in the Marcotti database. 3. Load transformed data into the database if it is not already there. :param entity: Data model name :param data: Data payloads from XML and/or CSV sources, in lists of dictionaries """ getattr(self.loader, entity)(getattr(self.transformer, entity)(self.combiner(*data))) @staticmethod def combiner(*data_dicts): """ Combine data from primary and supplemental data sources using unique ID of primary records. Returns a Pandas DataFrame of the combined data. :param data_dicts: List of data payloads from data sources, primary source first in list. :return: DataFrame of combined data. """ data_frames = [pd.DataFrame(data) for data in data_dicts] if len(data_frames) > 1: new_frames = [data_frame.dropna(axis=1, how='all') for data_frame in data_frames] return pd.merge(*new_frames, on=['remote_id']) return data_frames[0] class WorkflowBase(object): def __init__(self, session, supplier): self.session = session <|code_end|> , generate the next line using the imports in this file: from datetime import date from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from marcottievents.models.common.suppliers import Suppliers import pandas as pd and context (functions, classes, or occasionally code) from other files: # Path: marcottievents/models/common/suppliers.py # class Suppliers(BaseSchema): # __tablename__ = "suppliers" # # id = Column(Integer, Sequence('supplier_id_seq', start=1000), primary_key=True) # name = Column(Unicode(40), nullable=False) # # def __repr__(self): # return u"<Supplier(id={0}, name={1})>".format(self.id, self.name).encode('utf-8') . Output only the next line.
self.supplier_id = self.get_id(Suppliers, name=supplier) if supplier else None
Predict the next line after this snippet: <|code_start|> builder.append(TAG, {'name': text[1:]}, text) wikiparser = WikiParser() #: singleton instance # FIXME FIXME we are redefining Parser here ! class Parser(ParserClass): def __init__(self, version=WIKI_FORMAT_VERSION): self.backward = version not in ('zim 0.26', WIKI_FORMAT_VERSION) def parse(self, input, partial=False): if not isinstance(input, basestring): input = ''.join(input) lineend = input and input[-1] == '\n' input = prepare_text(input) if partial and input.endswith('\n') and not lineend: # reverse extension done by prepare_text() input = input[:-1] builder = ParseTreeBuilder(partial=partial) wikiparser.backward = self.backward # HACK wikiparser(builder, input) return builder.get_parsetree() <|code_end|> using the current file's imports: import re from zim.parser import * from zim.parsing import url_re, url_encode, URL_ENCODE_DATA from zim.formats import * from zim.formats.plain import Dumper as TextDumper and any relevant context from other files: # Path: zim/formats/plain.py # class Dumper(DumperClass): # # # We dump more constructs than we can parse. Reason for this # # is to ensure dumping a page to plain text will still be # # readable. # # BULLETS = { # UNCHECKED_BOX: u'[ ]', # XCHECKED_BOX: u'[x]', # CHECKED_BOX: u'[*]', # BULLET: u'*', # } # # # No additional formatting for these tags, otherwise copy-pasting # # as plain text is no longer plain text # TAGS = { # EMPHASIS: ('', ''), # STRONG: ('', ''), # MARK: ('', ''), # STRIKE: ('', ''), # VERBATIM: ('', ''), # TAG: ('', ''), # SUBSCRIPT: ('', ''), # SUPERSCRIPT: ('', ''), # } # # def dump_indent(self, tag, attrib, strings): # # Prefix lines with one or more tabs # if attrib and 'indent' in attrib: # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines(prefix, strings) # # TODO enforces we always end such a block with \n unless partial # else: # return strings # # dump_p = dump_indent # dump_div = dump_indent # dump_pre = dump_indent # # def dump_h(self, tag, attrib, strings): # # Markdown style headers # level = int(attrib['level']) # if level < 1: level = 1 # elif level > 5: level = 5 # # if level in (1, 2): # # setext-style headers for lvl 1 & 2 # if level == 1: char = '=' # else: char = '-' # heading = u''.join(strings) # underline = char * len(heading) # return [heading + '\n', underline] # else: # # atx-style headers for deeper levels # tag = '#' * level # strings.insert(0, tag + ' ') # return strings # # def dump_list(self, tag, attrib, strings): # if 'indent' in attrib: # # top level list with specified indent # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines('\t', strings) # elif self.context[-1].tag in (BULLETLIST, NUMBEREDLIST): # # indent sub list # prefix = '\t' # return self.prefix_lines('\t', strings) # else: # # top level list, no indent # return strings # # dump_ul = dump_list # dump_ol = dump_list # # def dump_li(self, tag, attrib, strings): # # Here is some logic to figure out the correct bullet character # # depends on parent list element # # # TODO accept multi-line content here - e.g. nested paras # # if self.context[-1].tag == BULLETLIST: # if 'bullet' in attrib \ # and attrib['bullet'] in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # else: # bullet = self.BULLETS[BULLET] # elif self.context[-1].tag == NUMBEREDLIST: # iter = self.context[-1].attrib.get('_iter') # if not iter: # # First item on this level # iter = self.context[-1].attrib.get('start', 1) # bullet = iter + '.' # self.context[-1].attrib['_iter'] = increase_list_iter(iter) or '1' # else: # # HACK for raw tree from pageview # # support indenting # # support any bullet type (inc numbered) # # bullet = attrib.get('bullet', BULLET) # if bullet in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # # else assume it is numbered.. # # if 'indent' in attrib: # prefix = int(attrib['indent']) * '\t' # bullet = prefix + bullet # # return (bullet, ' ') + tuple(strings) + ('\n',) # # def dump_link(self, tag, attrib, strings=None): # # Just plain text, either text of link, or link href # assert 'href' in attrib, \ # 'BUG: link misses href: %s "%s"' % (attrib, strings) # href = attrib['href'] # # if strings: # return strings # else: # return href # # def dump_img(self, tag, attrib, strings=None): # # Just plain text, either alt text or src # src = attrib['src'] # alt = attrib.get('alt') # if alt: # return alt # else: # return src # # def dump_object_fallback(self, tag, attrib, strings): # return strings . Output only the next line.
class Dumper(TextDumper):
Based on the snippet: <|code_start|> info = { 'name': 'plain', 'desc': 'Plain text', 'mimetype': 'text/plain', 'extension': 'txt', 'native': False, 'import': True, 'export': True, } class Parser(ParserClass): # TODO parse constructs like *bold* and /italic/ same as in email, # but do not remove the "*" and "/", just display text 1:1 # TODO also try at least to parse bullet and checkbox lists # common base class with wiki format # TODO parse markdown style headers def parse(self, input, partial=False): if not isinstance(input, basestring): input = ''.join(input) if not partial: <|code_end|> , predict the immediate next line with the help of imports: import re import zim.parser from zim.parser import prepare_text, Rule from zim.formats import * from zim.parsing import url_re and context (classes, functions, sometimes code) from other files: # Path: zim/parser.py # def prepare_text(text, tabstop=4): # '''Ensures text is properly formatted. # - Fixes missing line end # - Expands spaces to tabs # @param text: the intput text # @param tabstop: the number of spaces to represent a tab # @returns: the fixed text # ''' # # HACK this char is recognized as line end by splitlines() # # but not matched by \n in a regex. Hope there are no other # # exceptions like it (crosses fingers) # text = text.replace(u'\u2028', '\n') # # # Fix line end # if not text.endswith('\n'): # text = text + '\n' # # # Fix tabs # spaces = ' ' * tabstop # pattern = '(?m)^(\t*)((?:%s)+)' % spaces # text = re.sub( # pattern, # lambda m: m.group(1) + '\t' * (len(m.group(2)) / tabstop), # text # ) # # Specify "(?m)" instead of re.M since "flags" keyword is not # # supported in python 2.6 # # return text # # class Rule(object): # '''Class that defines a single parser rule. Typically used # to define a regex pattern for one specific wiki format string # and the processing to be done when this formatting is encountered # in the text. # # @ivar tag: L{Builder} tag for result of this rule. Used by the # default process method. # @ivar pattern: the regular expression for this parser as string # @ivar process: function (or object) to process matched text, or C{None} # The function should take a L{Builder} object as first argument, # followed by one or more parameters for matched groups in the # regular expression. If the regex pattern has no capturing groups # this function is called with the whole match. # The default function will use the C{tag} and C{descent} # attributes # @ivar decent: optional function (or object) to recursively parse the # text matched by this rule. Called in the same way as C{process}. # ''' # # def __init__(self, tag, pattern, process=None, descent=None): # '''Constructor # @param tag: L{Builder} tag for result of this rule. Used by the # default process method. # @param pattern: regex pattern as string # @param process: optional function to process matched text # @param descent: optional function to recursively parse matched text # ''' # assert tag is not None or process is not None, 'Need at least a tag or a process method' # self._re = None # self.tag = tag # self.pattern = pattern # self.descent = descent # self.process = process or self._process # # def __repr__(self): # return '<%s: %s: %s>' % (self.__class__.__name__, self.tag, self.pattern) # # def __or__(self, other): # '''Allow new parsers to be constructed by combining parser # objects with the "|" operator. # ''' # return Parser(self, other) # # def _process(self, builder, text): # # default action for matched text # if self.descent: # builder.start(self.tag) # self.descent(builder, *text) # builder.end(self.tag) # else: # builder.append(self.tag, None, text) . Output only the next line.
input = prepare_text(input)
Given the following code snippet before the placeholder: <|code_start|> info = { 'name': 'plain', 'desc': 'Plain text', 'mimetype': 'text/plain', 'extension': 'txt', 'native': False, 'import': True, 'export': True, } class Parser(ParserClass): # TODO parse constructs like *bold* and /italic/ same as in email, # but do not remove the "*" and "/", just display text 1:1 # TODO also try at least to parse bullet and checkbox lists # common base class with wiki format # TODO parse markdown style headers def parse(self, input, partial=False): if not isinstance(input, basestring): input = ''.join(input) if not partial: input = prepare_text(input) parser = zim.parser.Parser( <|code_end|> , predict the next line using imports from the current file: import re import zim.parser from zim.parser import prepare_text, Rule from zim.formats import * from zim.parsing import url_re and context including class names, function names, and sometimes code from other files: # Path: zim/parser.py # def prepare_text(text, tabstop=4): # '''Ensures text is properly formatted. # - Fixes missing line end # - Expands spaces to tabs # @param text: the intput text # @param tabstop: the number of spaces to represent a tab # @returns: the fixed text # ''' # # HACK this char is recognized as line end by splitlines() # # but not matched by \n in a regex. Hope there are no other # # exceptions like it (crosses fingers) # text = text.replace(u'\u2028', '\n') # # # Fix line end # if not text.endswith('\n'): # text = text + '\n' # # # Fix tabs # spaces = ' ' * tabstop # pattern = '(?m)^(\t*)((?:%s)+)' % spaces # text = re.sub( # pattern, # lambda m: m.group(1) + '\t' * (len(m.group(2)) / tabstop), # text # ) # # Specify "(?m)" instead of re.M since "flags" keyword is not # # supported in python 2.6 # # return text # # class Rule(object): # '''Class that defines a single parser rule. Typically used # to define a regex pattern for one specific wiki format string # and the processing to be done when this formatting is encountered # in the text. # # @ivar tag: L{Builder} tag for result of this rule. Used by the # default process method. # @ivar pattern: the regular expression for this parser as string # @ivar process: function (or object) to process matched text, or C{None} # The function should take a L{Builder} object as first argument, # followed by one or more parameters for matched groups in the # regular expression. If the regex pattern has no capturing groups # this function is called with the whole match. # The default function will use the C{tag} and C{descent} # attributes # @ivar decent: optional function (or object) to recursively parse the # text matched by this rule. Called in the same way as C{process}. # ''' # # def __init__(self, tag, pattern, process=None, descent=None): # '''Constructor # @param tag: L{Builder} tag for result of this rule. Used by the # default process method. # @param pattern: regex pattern as string # @param process: optional function to process matched text # @param descent: optional function to recursively parse matched text # ''' # assert tag is not None or process is not None, 'Need at least a tag or a process method' # self._re = None # self.tag = tag # self.pattern = pattern # self.descent = descent # self.process = process or self._process # # def __repr__(self): # return '<%s: %s: %s>' % (self.__class__.__name__, self.tag, self.pattern) # # def __or__(self, other): # '''Allow new parsers to be constructed by combining parser # objects with the "|" operator. # ''' # return Parser(self, other) # # def _process(self, builder, text): # # default action for matched text # if self.descent: # builder.start(self.tag) # self.descent(builder, *text) # builder.end(self.tag) # else: # builder.append(self.tag, None, text) . Output only the next line.
Rule(LINK, url_re.r, process=self.parse_url) # FIXME need .r atribute because url_re is a Re object
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2012,2013 Jaap Karssenberg <jaap.karssenberg@gmail.com> '''This module handles dumping markdown text with pandoc extensions''' # OPEN ISSUES # - how to deal with indented paragraphs ? # in pandoc indent is verbatim, so now all indent is dropped # - how to deal with image re-size ? # - how to deal with tags / anchors ? # - check does zim always produce a blank line before a heading ? # - add \ before line ends to match line breaks from user info = { 'name': 'markdown', 'desc': 'Markdown Text (pandoc)', 'mimetype': 'text/x-markdown', 'extension': 'markdown', # No official file extension, but this is often used 'native': False, 'import': False, 'export': True, } <|code_end|> with the help of current file imports: import re from zim.formats import * from zim.parsing import url_re from zim.formats.plain import Dumper as TextDumper and context from other files: # Path: zim/formats/plain.py # class Dumper(DumperClass): # # # We dump more constructs than we can parse. Reason for this # # is to ensure dumping a page to plain text will still be # # readable. # # BULLETS = { # UNCHECKED_BOX: u'[ ]', # XCHECKED_BOX: u'[x]', # CHECKED_BOX: u'[*]', # BULLET: u'*', # } # # # No additional formatting for these tags, otherwise copy-pasting # # as plain text is no longer plain text # TAGS = { # EMPHASIS: ('', ''), # STRONG: ('', ''), # MARK: ('', ''), # STRIKE: ('', ''), # VERBATIM: ('', ''), # TAG: ('', ''), # SUBSCRIPT: ('', ''), # SUPERSCRIPT: ('', ''), # } # # def dump_indent(self, tag, attrib, strings): # # Prefix lines with one or more tabs # if attrib and 'indent' in attrib: # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines(prefix, strings) # # TODO enforces we always end such a block with \n unless partial # else: # return strings # # dump_p = dump_indent # dump_div = dump_indent # dump_pre = dump_indent # # def dump_h(self, tag, attrib, strings): # # Markdown style headers # level = int(attrib['level']) # if level < 1: level = 1 # elif level > 5: level = 5 # # if level in (1, 2): # # setext-style headers for lvl 1 & 2 # if level == 1: char = '=' # else: char = '-' # heading = u''.join(strings) # underline = char * len(heading) # return [heading + '\n', underline] # else: # # atx-style headers for deeper levels # tag = '#' * level # strings.insert(0, tag + ' ') # return strings # # def dump_list(self, tag, attrib, strings): # if 'indent' in attrib: # # top level list with specified indent # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines('\t', strings) # elif self.context[-1].tag in (BULLETLIST, NUMBEREDLIST): # # indent sub list # prefix = '\t' # return self.prefix_lines('\t', strings) # else: # # top level list, no indent # return strings # # dump_ul = dump_list # dump_ol = dump_list # # def dump_li(self, tag, attrib, strings): # # Here is some logic to figure out the correct bullet character # # depends on parent list element # # # TODO accept multi-line content here - e.g. nested paras # # if self.context[-1].tag == BULLETLIST: # if 'bullet' in attrib \ # and attrib['bullet'] in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # else: # bullet = self.BULLETS[BULLET] # elif self.context[-1].tag == NUMBEREDLIST: # iter = self.context[-1].attrib.get('_iter') # if not iter: # # First item on this level # iter = self.context[-1].attrib.get('start', 1) # bullet = iter + '.' # self.context[-1].attrib['_iter'] = increase_list_iter(iter) or '1' # else: # # HACK for raw tree from pageview # # support indenting # # support any bullet type (inc numbered) # # bullet = attrib.get('bullet', BULLET) # if bullet in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # # else assume it is numbered.. # # if 'indent' in attrib: # prefix = int(attrib['indent']) * '\t' # bullet = prefix + bullet # # return (bullet, ' ') + tuple(strings) + ('\n',) # # def dump_link(self, tag, attrib, strings=None): # # Just plain text, either text of link, or link href # assert 'href' in attrib, \ # 'BUG: link misses href: %s "%s"' % (attrib, strings) # href = attrib['href'] # # if strings: # return strings # else: # return href # # def dump_img(self, tag, attrib, strings=None): # # Just plain text, either alt text or src # src = attrib['src'] # alt = attrib.get('alt') # if alt: # return alt # else: # return src # # def dump_object_fallback(self, tag, attrib, strings): # return strings , which may contain function names, class names, or code. Output only the next line.
class Dumper(TextDumper):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> @tests.slowTest class TestTableOfContents(tests.TestCase): def testMainWindowExtensions(self): plugin = ToCPlugin() notebook = tests.new_notebook(self.get_tmp_name()) <|code_end|> with the help of current file imports: import tests import gtk from tests.gui import setupGtkInterface from zim.plugins.tableofcontents import * from zim.gui.widgets import RIGHT_PANE, LEFT_PANE and context from other files: # Path: tests/gui.py # def setupGtkInterface(test, klass=None, notebook=None): # '''Setup a new GtkInterface object for testing. # Will have test notebook, and default preferences. # @param test: the test that wants to use this ui object # @param klass: the klass to use, defaults to L{GtkInterface}, but # could be partially mocked subclass # ''' # if klass is None: # klass = zim.gui.GtkInterface # # # start filtering # filter = FilterNoSuchImageWarning() # filter.wrap_test(test) # # # # create interface object with new notebook # if notebook is None: # dirpath = test.get_tmp_name() # notebook = tests.new_notebook(fakedir=dirpath) # # config = VirtualConfigManager() # ui = klass(config=config, notebook=notebook) # # ui.mainwindow.init_uistate() # ui.open_page(Path('Test:foo:bar')) # # return ui # # Path: zim/gui/widgets.py # RIGHT_PANE = 'right_pane' #: Right pane position in window # # LEFT_PANE = 'left_pane' #: Left pane position in window , which may contain function names, class names, or code. Output only the next line.
ui = setupGtkInterface(self, notebook=notebook)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> @tests.slowTest class TestTableOfContents(tests.TestCase): def testMainWindowExtensions(self): plugin = ToCPlugin() notebook = tests.new_notebook(self.get_tmp_name()) ui = setupGtkInterface(self, notebook=notebook) plugin.preferences['floating'] = True self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionFloating) plugin.extend(ui.mainwindow) ext = list(plugin.extensions) self.assertEqual(len(ext), 1) self.assertIsInstance(ext[0], MainWindowExtensionFloating) plugin.preferences.changed() # make sure no errors are triggered plugin.preferences['show_h1'] = True plugin.preferences['show_h1'] = False <|code_end|> , generate the next line using the imports in this file: import tests import gtk from tests.gui import setupGtkInterface from zim.plugins.tableofcontents import * from zim.gui.widgets import RIGHT_PANE, LEFT_PANE and context (functions, classes, or occasionally code) from other files: # Path: tests/gui.py # def setupGtkInterface(test, klass=None, notebook=None): # '''Setup a new GtkInterface object for testing. # Will have test notebook, and default preferences. # @param test: the test that wants to use this ui object # @param klass: the klass to use, defaults to L{GtkInterface}, but # could be partially mocked subclass # ''' # if klass is None: # klass = zim.gui.GtkInterface # # # start filtering # filter = FilterNoSuchImageWarning() # filter.wrap_test(test) # # # # create interface object with new notebook # if notebook is None: # dirpath = test.get_tmp_name() # notebook = tests.new_notebook(fakedir=dirpath) # # config = VirtualConfigManager() # ui = klass(config=config, notebook=notebook) # # ui.mainwindow.init_uistate() # ui.open_page(Path('Test:foo:bar')) # # return ui # # Path: zim/gui/widgets.py # RIGHT_PANE = 'right_pane' #: Right pane position in window # # LEFT_PANE = 'left_pane' #: Left pane position in window . Output only the next line.
plugin.preferences['pane'] = RIGHT_PANE
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> @tests.slowTest class TestTableOfContents(tests.TestCase): def testMainWindowExtensions(self): plugin = ToCPlugin() notebook = tests.new_notebook(self.get_tmp_name()) ui = setupGtkInterface(self, notebook=notebook) plugin.preferences['floating'] = True self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionFloating) plugin.extend(ui.mainwindow) ext = list(plugin.extensions) self.assertEqual(len(ext), 1) self.assertIsInstance(ext[0], MainWindowExtensionFloating) plugin.preferences.changed() # make sure no errors are triggered plugin.preferences['show_h1'] = True plugin.preferences['show_h1'] = False plugin.preferences['pane'] = RIGHT_PANE <|code_end|> with the help of current file imports: import tests import gtk from tests.gui import setupGtkInterface from zim.plugins.tableofcontents import * from zim.gui.widgets import RIGHT_PANE, LEFT_PANE and context from other files: # Path: tests/gui.py # def setupGtkInterface(test, klass=None, notebook=None): # '''Setup a new GtkInterface object for testing. # Will have test notebook, and default preferences. # @param test: the test that wants to use this ui object # @param klass: the klass to use, defaults to L{GtkInterface}, but # could be partially mocked subclass # ''' # if klass is None: # klass = zim.gui.GtkInterface # # # start filtering # filter = FilterNoSuchImageWarning() # filter.wrap_test(test) # # # # create interface object with new notebook # if notebook is None: # dirpath = test.get_tmp_name() # notebook = tests.new_notebook(fakedir=dirpath) # # config = VirtualConfigManager() # ui = klass(config=config, notebook=notebook) # # ui.mainwindow.init_uistate() # ui.open_page(Path('Test:foo:bar')) # # return ui # # Path: zim/gui/widgets.py # RIGHT_PANE = 'right_pane' #: Right pane position in window # # LEFT_PANE = 'left_pane' #: Left pane position in window , which may contain function names, class names, or code. Output only the next line.
plugin.preferences['pane'] = LEFT_PANE
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2012 Yao-Po Wang <blue119@gmail.com> # Copyright 2013 Jaap Karssenberg <jaap.karssenberg@gmail.com> '''This module handles dumping reStructuredText with sphinx extensions''' info = { 'name': 'reST', 'desc': 'reST (Octopress)', 'mimetype': 'text/x-rst', 'extension': 'rst', # No official file extension, but this is often used 'native': False, 'import': False, 'export': True, } <|code_end|> . Use current file imports: from zim.formats import * from zim.formats.plain import Dumper as TextDumper and context (classes, functions, or code) from other files: # Path: zim/formats/plain.py # class Dumper(DumperClass): # # # We dump more constructs than we can parse. Reason for this # # is to ensure dumping a page to plain text will still be # # readable. # # BULLETS = { # UNCHECKED_BOX: u'[ ]', # XCHECKED_BOX: u'[x]', # CHECKED_BOX: u'[*]', # BULLET: u'*', # } # # # No additional formatting for these tags, otherwise copy-pasting # # as plain text is no longer plain text # TAGS = { # EMPHASIS: ('', ''), # STRONG: ('', ''), # MARK: ('', ''), # STRIKE: ('', ''), # VERBATIM: ('', ''), # TAG: ('', ''), # SUBSCRIPT: ('', ''), # SUPERSCRIPT: ('', ''), # } # # def dump_indent(self, tag, attrib, strings): # # Prefix lines with one or more tabs # if attrib and 'indent' in attrib: # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines(prefix, strings) # # TODO enforces we always end such a block with \n unless partial # else: # return strings # # dump_p = dump_indent # dump_div = dump_indent # dump_pre = dump_indent # # def dump_h(self, tag, attrib, strings): # # Markdown style headers # level = int(attrib['level']) # if level < 1: level = 1 # elif level > 5: level = 5 # # if level in (1, 2): # # setext-style headers for lvl 1 & 2 # if level == 1: char = '=' # else: char = '-' # heading = u''.join(strings) # underline = char * len(heading) # return [heading + '\n', underline] # else: # # atx-style headers for deeper levels # tag = '#' * level # strings.insert(0, tag + ' ') # return strings # # def dump_list(self, tag, attrib, strings): # if 'indent' in attrib: # # top level list with specified indent # prefix = '\t' * int(attrib['indent']) # return self.prefix_lines('\t', strings) # elif self.context[-1].tag in (BULLETLIST, NUMBEREDLIST): # # indent sub list # prefix = '\t' # return self.prefix_lines('\t', strings) # else: # # top level list, no indent # return strings # # dump_ul = dump_list # dump_ol = dump_list # # def dump_li(self, tag, attrib, strings): # # Here is some logic to figure out the correct bullet character # # depends on parent list element # # # TODO accept multi-line content here - e.g. nested paras # # if self.context[-1].tag == BULLETLIST: # if 'bullet' in attrib \ # and attrib['bullet'] in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # else: # bullet = self.BULLETS[BULLET] # elif self.context[-1].tag == NUMBEREDLIST: # iter = self.context[-1].attrib.get('_iter') # if not iter: # # First item on this level # iter = self.context[-1].attrib.get('start', 1) # bullet = iter + '.' # self.context[-1].attrib['_iter'] = increase_list_iter(iter) or '1' # else: # # HACK for raw tree from pageview # # support indenting # # support any bullet type (inc numbered) # # bullet = attrib.get('bullet', BULLET) # if bullet in self.BULLETS: # bullet = self.BULLETS[attrib['bullet']] # # else assume it is numbered.. # # if 'indent' in attrib: # prefix = int(attrib['indent']) * '\t' # bullet = prefix + bullet # # return (bullet, ' ') + tuple(strings) + ('\n',) # # def dump_link(self, tag, attrib, strings=None): # # Just plain text, either text of link, or link href # assert 'href' in attrib, \ # 'BUG: link misses href: %s "%s"' % (attrib, strings) # href = attrib['href'] # # if strings: # return strings # else: # return href # # def dump_img(self, tag, attrib, strings=None): # # Just plain text, either alt text or src # src = attrib['src'] # alt = attrib.get('alt') # if alt: # return alt # else: # return src # # def dump_object_fallback(self, tag, attrib, strings): # return strings . Output only the next line.
class Dumper(TextDumper):
Using the snippet: <|code_start|>ENCODING = sys.getfilesystemencoding() #: file system encoding for paths if ENCODING.upper() in ( 'ASCII', 'US-ASCII', 'ANSI_X3.4-1968', 'ISO646-US', # some aliases for ascii 'LATIN1', 'ISO-8859-1', 'ISO_8859-1', 'ISO_8859-1:1987', # aliases for latin1 ): logger.warn('Filesystem encoding is set to ASCII or Latin1, using UTF-8 instead') ENCODING = 'utf-8' if ENCODING == 'mbcs': # Encoding 'mbcs' means we run on windows and filesystem can handle utf-8 natively # so here we just convert everything to unicode strings def encode(path): if isinstance(path, unicode): return path else: return unicode(path) def decode(path): if isinstance(path, unicode): return path else: return unicode(path) else: # Here we encode files to filesystem encoding. Fails if encoding is not possible. def encode(path): if isinstance(path, unicode): try: return path.encode(ENCODING) except UnicodeEncodeError: <|code_end|> , determine the next line of code. You have imports: import os import re import sys import shutil import errno import codecs import logging import threading import gobject import gio import xdg.Mime as xdgmime import mimetypes import tempfile import hashlib import time from zim.errors import Error, TrashNotSupportedError, TrashCancelledError from zim.parsing import url_encode, url_decode, URL_ENCODE_READABLE from zim.signals import SignalEmitter, SIGNAL_AFTER from zim.environ import environ and context (class names, function names, or code) available: # Path: zim/errors.py # class Error(Exception): # '''Base class for all errors in zim. # # This class is intended for application and usage errors, these will # be caught in the user interface and presented as error dialogs. # In contrast and Exception that does I{not} derive from this base # class will result in a "You found a bug" dialog. Do not use this # class e.g. to catch programming errors. # # Subclasses should define two attributes. The first is 'msg', which is # the short description of the error. Typically this gives the specific # input / page / ... which caused the error. In there should be an attribute # 'description' (either as class attribute or object attribute) with a verbose # description. This description can be less specific but should explain # the error in a user friendly way. The default behavior is to take 'msg' as # the single argument for the constructor. So a minimal subclass only needs # to define a class attribute 'description'. # # For a typical error dialog in the Gtk interface the short string from 'msg' # will be shown as the title in bold letters while the longer 'description' # is shown below it in normal letters. As a guideline error classes that are # used in the gui or that can be e.g. be raised on invalid input from the # user should be translated. # ''' # # description = '' # msg = '<Unknown Error>' # # in case subclass does not define instance attribute # # def __init__(self, msg, description=None): # self.msg = msg # self.description = description or '' # # def __str__(self): # msg = self.__unicode__() # return msg.encode('utf-8') # # def __unicode__(self): # msg = u'' + self.msg.strip() # if self.description: # msg += '\n\n' + self.description.strip() + '\n' # return msg # # def __repr__(self): # return '<%s: %s>' % (self.__class__.__name__, self.msg) # # class TrashNotSupportedError(Error): # '''Error raised when trashing is not supported and delete should # be used instead # ''' # pass # # class TrashCancelledError(Error): # '''Error raised when a trashign operation is cancelled. (E.g. on # windows the system will prompt the user with a confirmation # dialog which has a Cancel button.) # ''' # pass . Output only the next line.
raise Error, 'BUG: invalid filename %s' % path
Using the snippet: <|code_start|> with FS.get_async_lock(self): # Do we also need a lock for newpath (could be the same as lock for self) ? if newpath.isdir(): if self.isequal(newpath): # We checked name above, so must be case insensitive file system # but we still want to be able to rename to other case, so need to # do some moving around tmpdir = self.dir.new_subdir(self.basename) shutil.move(self.encodedpath, tmpdir.encodedpath) shutil.move(tmpdir.encodedpath, newpath.encodedpath) else: # Needed because shutil.move() has different behavior for this case raise AssertionError, 'Folder already exists: %s' % newpath.path else: # normal case newpath.dir.touch() shutil.move(self.encodedpath, newpath.encodedpath) FS.emit('path-moved', self, newpath) self.dir.cleanup() def trash(self): '''Trash a file or folder by moving it to the system trashcan if supported. Depends on the C{gio} library. @returns: C{True} when succesful @raises TrashNotSupportedError: if trashing is not supported or failed. @raises TrashCancelledError: if trashing was cancelled by the user ''' if not gio: <|code_end|> , determine the next line of code. You have imports: import os import re import sys import shutil import errno import codecs import logging import threading import gobject import gio import xdg.Mime as xdgmime import mimetypes import tempfile import hashlib import time from zim.errors import Error, TrashNotSupportedError, TrashCancelledError from zim.parsing import url_encode, url_decode, URL_ENCODE_READABLE from zim.signals import SignalEmitter, SIGNAL_AFTER from zim.environ import environ and context (class names, function names, or code) available: # Path: zim/errors.py # class Error(Exception): # '''Base class for all errors in zim. # # This class is intended for application and usage errors, these will # be caught in the user interface and presented as error dialogs. # In contrast and Exception that does I{not} derive from this base # class will result in a "You found a bug" dialog. Do not use this # class e.g. to catch programming errors. # # Subclasses should define two attributes. The first is 'msg', which is # the short description of the error. Typically this gives the specific # input / page / ... which caused the error. In there should be an attribute # 'description' (either as class attribute or object attribute) with a verbose # description. This description can be less specific but should explain # the error in a user friendly way. The default behavior is to take 'msg' as # the single argument for the constructor. So a minimal subclass only needs # to define a class attribute 'description'. # # For a typical error dialog in the Gtk interface the short string from 'msg' # will be shown as the title in bold letters while the longer 'description' # is shown below it in normal letters. As a guideline error classes that are # used in the gui or that can be e.g. be raised on invalid input from the # user should be translated. # ''' # # description = '' # msg = '<Unknown Error>' # # in case subclass does not define instance attribute # # def __init__(self, msg, description=None): # self.msg = msg # self.description = description or '' # # def __str__(self): # msg = self.__unicode__() # return msg.encode('utf-8') # # def __unicode__(self): # msg = u'' + self.msg.strip() # if self.description: # msg += '\n\n' + self.description.strip() + '\n' # return msg # # def __repr__(self): # return '<%s: %s>' % (self.__class__.__name__, self.msg) # # class TrashNotSupportedError(Error): # '''Error raised when trashing is not supported and delete should # be used instead # ''' # pass # # class TrashCancelledError(Error): # '''Error raised when a trashign operation is cancelled. (E.g. on # windows the system will prompt the user with a confirmation # dialog which has a Cancel button.) # ''' # pass . Output only the next line.
raise TrashNotSupportedError, 'gio not imported'
Given the following code snippet before the placeholder: <|code_start|> raise AssertionError, 'Folder already exists: %s' % newpath.path else: # normal case newpath.dir.touch() shutil.move(self.encodedpath, newpath.encodedpath) FS.emit('path-moved', self, newpath) self.dir.cleanup() def trash(self): '''Trash a file or folder by moving it to the system trashcan if supported. Depends on the C{gio} library. @returns: C{True} when succesful @raises TrashNotSupportedError: if trashing is not supported or failed. @raises TrashCancelledError: if trashing was cancelled by the user ''' if not gio: raise TrashNotSupportedError, 'gio not imported' if self.exists(): logger.info('Move %s to trash' % self) f = gio.File(uri=self.uri) try: ok = f.trash() except gobject.GError, error: if error.code == gio.ERROR_CANCELLED \ or (os.name == 'nt' and error.code == 0): # code 0 observed on windows for cancel logger.info('Trash operation cancelled') <|code_end|> , predict the next line using imports from the current file: import os import re import sys import shutil import errno import codecs import logging import threading import gobject import gio import xdg.Mime as xdgmime import mimetypes import tempfile import hashlib import time from zim.errors import Error, TrashNotSupportedError, TrashCancelledError from zim.parsing import url_encode, url_decode, URL_ENCODE_READABLE from zim.signals import SignalEmitter, SIGNAL_AFTER from zim.environ import environ and context including class names, function names, and sometimes code from other files: # Path: zim/errors.py # class Error(Exception): # '''Base class for all errors in zim. # # This class is intended for application and usage errors, these will # be caught in the user interface and presented as error dialogs. # In contrast and Exception that does I{not} derive from this base # class will result in a "You found a bug" dialog. Do not use this # class e.g. to catch programming errors. # # Subclasses should define two attributes. The first is 'msg', which is # the short description of the error. Typically this gives the specific # input / page / ... which caused the error. In there should be an attribute # 'description' (either as class attribute or object attribute) with a verbose # description. This description can be less specific but should explain # the error in a user friendly way. The default behavior is to take 'msg' as # the single argument for the constructor. So a minimal subclass only needs # to define a class attribute 'description'. # # For a typical error dialog in the Gtk interface the short string from 'msg' # will be shown as the title in bold letters while the longer 'description' # is shown below it in normal letters. As a guideline error classes that are # used in the gui or that can be e.g. be raised on invalid input from the # user should be translated. # ''' # # description = '' # msg = '<Unknown Error>' # # in case subclass does not define instance attribute # # def __init__(self, msg, description=None): # self.msg = msg # self.description = description or '' # # def __str__(self): # msg = self.__unicode__() # return msg.encode('utf-8') # # def __unicode__(self): # msg = u'' + self.msg.strip() # if self.description: # msg += '\n\n' + self.description.strip() + '\n' # return msg # # def __repr__(self): # return '<%s: %s>' % (self.__class__.__name__, self.msg) # # class TrashNotSupportedError(Error): # '''Error raised when trashing is not supported and delete should # be used instead # ''' # pass # # class TrashCancelledError(Error): # '''Error raised when a trashign operation is cancelled. (E.g. on # windows the system will prompt the user with a confirmation # dialog which has a Cancel button.) # ''' # pass . Output only the next line.
raise TrashCancelledError, 'Trashing cancelled'
Predict the next line after this snippet: <|code_start|> parser.add_option('-o', '--official', dest="official_only", default=False, action="store_true", help="Build using only the official toolchain for each target") parser.add_option("-j", "--jobs", type="int", dest="jobs", default=1, help="Number of concurrent jobs (default 1). Use 0 for auto based on host machine's number of CPUs") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose diagnostic output") parser.add_option("-t", "--toolchains", dest="toolchains", help="Use toolchains names separated by comma") parser.add_option("-p", "--platforms", dest="platforms", default="", help="Build only for the platform namesseparated by comma") parser.add_option("", "--report-build", dest="report_build_file_name", help="Output the build results to an html file") options, args = parser.parse_args() start = time() failures = [] successes = [] skips = [] build_report = [] platforms = None if options.platforms != "": platforms = set(options.platforms.split(",")) for target_name, toolchain_list in OFFICIAL_MBED_LIBRARY_BUILD: if platforms is not None and not target_name in platforms: print("Excluding %s from release" % target_name) continue if options.official_only: <|code_end|> using the current file's imports: import sys from time import time from os.path import join, abspath, dirname from optparse import OptionParser from workspace_tools.build_api import build_mbed_libs from workspace_tools.build_api import write_build_report from workspace_tools.targets import TARGET_MAP and any relevant context from other files: # Path: workspace_tools/targets.py # TARGET_MAP = {} . Output only the next line.
toolchains = (getattr(TARGET_MAP[target_name], 'default_toolchain', 'ARM'),)
Using the snippet: <|code_start|> exit(-1) # Get extra MUTs if applicable MUTs = get_json_data_from_file(opts.muts_spec_filename) if opts.muts_spec_filename else None if MUTs is None: if not opts.muts_spec_filename: parser.print_help() exit(-1) if opts.verbose_test_configuration_only: print "MUTs configuration in %s:" % ('auto-detected' if opts.auto_detect else opts.muts_spec_filename) if MUTs: print print_muts_configuration_from_json(MUTs, platform_filter=opts.general_filter_regex) print print "Test specification in %s:" % ('auto-detected' if opts.auto_detect else opts.test_spec_filename) if test_spec: print print_test_configuration_from_json(test_spec) exit(0) if get_module_avail('mbed_lstools'): if opts.operability_checks: # Check if test scope is valid and run tests test_scope = get_available_oper_test_scopes() if opts.operability_checks in test_scope: tests = IOperTestRunner(scope=opts.operability_checks) test_results = tests.run() # Export results in form of JUnit XML report to separate file if opts.report_junit_file_name: <|code_end|> , determine the next line of code. You have imports: import sys import mbed_lstools from os.path import join, abspath, dirname from workspace_tools.utils import check_required_modules from workspace_tools.build_api import mcu_toolchain_matrix from workspace_tools.test_api import SingleTestRunner from workspace_tools.test_api import singletest_in_cli_mode from workspace_tools.test_api import detect_database_verbose from workspace_tools.test_api import get_json_data_from_file from workspace_tools.test_api import get_avail_tests_summary_table from workspace_tools.test_api import get_default_test_options_parser from workspace_tools.test_api import print_muts_configuration_from_json from workspace_tools.test_api import print_test_configuration_from_json from workspace_tools.test_api import get_autodetected_MUTS_list from workspace_tools.test_api import get_autodetected_TEST_SPEC from workspace_tools.test_api import get_module_avail from workspace_tools.test_exporters import ReportExporter, ResultExporterType from workspace_tools.compliance.ioper_runner import IOperTestRunner from workspace_tools.compliance.ioper_runner import get_available_oper_test_scopes and context (class names, function names, or code) available: # Path: workspace_tools/test_exporters.py # class ReportExporter(): # CSS_STYLE = """<style> # .name{ # border: 1px solid; # border-radius: 25px; # width: 100px; # } # .tooltip{ # position:absolute; # background-color: #F5DA81; # display:none; # } # </style> # """ # JAVASCRIPT = """ # <script type="text/javascript"> # function show (elem) { # elem.style.display = "block"; # } # function hide (elem) { # elem.style.display = ""; # } # </script> # """ # RESULT_COLORS = {'OK': 'LimeGreen', # 'FAIL': 'Orange', # 'ERROR': 'LightCoral', # 'OTHER': 'LightGray', # } # def __init__(self, result_exporter_type): # def report(self, test_summary_ext, test_suite_properties=None): # def report_to_file(self, test_summary_ext, file_name, test_suite_properties=None): # def write_to_file(self, report, file_name): # def get_tooltip_name(self, toolchain, target, test_id, loop_no): # def get_result_div_sections(self, test, test_no): # def get_result_tree(self, test_results): # def get_all_unique_test_ids(self, test_result_ext): # def exporter_html(self, test_result_ext, test_suite_properties=None): # def exporter_junit_ioper(self, test_result_ext, test_suite_properties=None): # def exporter_junit(self, test_result_ext, test_suite_properties=None): . Output only the next line.
report_exporter = ReportExporter(ResultExporterType.JUNIT_OPER)
Given snippet: <|code_start|> exit(-1) # Get extra MUTs if applicable MUTs = get_json_data_from_file(opts.muts_spec_filename) if opts.muts_spec_filename else None if MUTs is None: if not opts.muts_spec_filename: parser.print_help() exit(-1) if opts.verbose_test_configuration_only: print "MUTs configuration in %s:" % ('auto-detected' if opts.auto_detect else opts.muts_spec_filename) if MUTs: print print_muts_configuration_from_json(MUTs, platform_filter=opts.general_filter_regex) print print "Test specification in %s:" % ('auto-detected' if opts.auto_detect else opts.test_spec_filename) if test_spec: print print_test_configuration_from_json(test_spec) exit(0) if get_module_avail('mbed_lstools'): if opts.operability_checks: # Check if test scope is valid and run tests test_scope = get_available_oper_test_scopes() if opts.operability_checks in test_scope: tests = IOperTestRunner(scope=opts.operability_checks) test_results = tests.run() # Export results in form of JUnit XML report to separate file if opts.report_junit_file_name: <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import mbed_lstools from os.path import join, abspath, dirname from workspace_tools.utils import check_required_modules from workspace_tools.build_api import mcu_toolchain_matrix from workspace_tools.test_api import SingleTestRunner from workspace_tools.test_api import singletest_in_cli_mode from workspace_tools.test_api import detect_database_verbose from workspace_tools.test_api import get_json_data_from_file from workspace_tools.test_api import get_avail_tests_summary_table from workspace_tools.test_api import get_default_test_options_parser from workspace_tools.test_api import print_muts_configuration_from_json from workspace_tools.test_api import print_test_configuration_from_json from workspace_tools.test_api import get_autodetected_MUTS_list from workspace_tools.test_api import get_autodetected_TEST_SPEC from workspace_tools.test_api import get_module_avail from workspace_tools.test_exporters import ReportExporter, ResultExporterType from workspace_tools.compliance.ioper_runner import IOperTestRunner from workspace_tools.compliance.ioper_runner import get_available_oper_test_scopes and context: # Path: workspace_tools/test_exporters.py # class ReportExporter(): # CSS_STYLE = """<style> # .name{ # border: 1px solid; # border-radius: 25px; # width: 100px; # } # .tooltip{ # position:absolute; # background-color: #F5DA81; # display:none; # } # </style> # """ # JAVASCRIPT = """ # <script type="text/javascript"> # function show (elem) { # elem.style.display = "block"; # } # function hide (elem) { # elem.style.display = ""; # } # </script> # """ # RESULT_COLORS = {'OK': 'LimeGreen', # 'FAIL': 'Orange', # 'ERROR': 'LightCoral', # 'OTHER': 'LightGray', # } # def __init__(self, result_exporter_type): # def report(self, test_summary_ext, test_suite_properties=None): # def report_to_file(self, test_summary_ext, file_name, test_suite_properties=None): # def write_to_file(self, report, file_name): # def get_tooltip_name(self, toolchain, target, test_id, loop_no): # def get_result_div_sections(self, test, test_no): # def get_result_tree(self, test_results): # def get_all_unique_test_ids(self, test_result_ext): # def exporter_html(self, test_result_ext, test_suite_properties=None): # def exporter_junit_ioper(self, test_result_ext, test_suite_properties=None): # def exporter_junit(self, test_result_ext, test_suite_properties=None): which might include code, classes, or functions. Output only the next line.
report_exporter = ReportExporter(ResultExporterType.JUNIT_OPER)
Using the snippet: <|code_start|> f.write(r.content) self.worker.download360SongCoverSuccessed.emit( self.artist, self.title, localUrl) except Exception, e: logger.error(e) class CoverWorker(QObject): __contextName__ = "CoverWorker" downloadArtistCoverSuccessed = pyqtSignal('QString', 'QString') downloadAlbumCoverSuccessed = pyqtSignal('QString', 'QString', 'QString') download360SongCoverSuccessed = pyqtSignal('QString', 'QString', 'QString') updateArtistCover = pyqtSignal('QString', 'QString') updateAlbumCover = pyqtSignal('QString', 'QString', 'QString') updateOnlineSongCover = pyqtSignal('QString', 'QString', 'QString') defaultArtistCover = os.path.join( get_parent_dir(__file__, 2), 'skin', 'images', 'bg1.jpg') defaultAlbumCover = os.path.join( get_parent_dir(__file__, 2), 'skin', 'images', 'bg1.jpg') defaultSongCover = os.path.join( get_parent_dir(__file__, 2), 'skin', 'images', 'bg1.jpg') defaultFolderCover = os.path.join( get_parent_dir(__file__, 2), 'skin', 'images', 'folder-music.svg') albumCoverThreadPool = QThreadPool() <|code_end|> , determine the next line of code. You have imports: import os import sys import copy import json import requests import urllib from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QThreadPool, QRunnable from PyQt5.QtGui import QImage from log import logger from .utils import registerContext from dwidgets import dthread, CoverRunnable from config.constants import ArtistCoverPath, AlbumCoverPath, SongCoverPath, OnlineSongCoverPath from deepin_utils.file import get_parent_dir and context (class names, function names, or code) available: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper . Output only the next line.
@registerContext
Based on the snippet: <|code_start|> logostyle = ''' QToolButton#logo{ background-color: transparent; } QToolButton#logo:hover{ background-color: transparent; } ''' def __init__(self, parent=None): super(FTitleBar, self).__init__(parent) self.initData() self.initUI() def initData(self): self.settingDownIcon = QIcon(":/icons/dark/appbar.control.down.png") self.clothesIcon = QIcon(":/icons/dark/appbar.clothes.shirt.png") self.lockIcon = QIcon(":/icons/dark/appbar.lock.png") self.unlockIcon = QIcon(":/icons/dark/appbar.unlock.keyhole.png") self.pinIcon = QIcon(":/icons/dark/appbar.pin.png") self.unPinIcon = QIcon(":/icons/dark/appbar.pin.remove.png") self.closeIcon = QIcon(":/icons/dark/appbar.close.png") self.max_flag = False self.lock_flag = False self.pin_flag = False def initUI(self): self.setFixedHeight(baseHeight) <|code_end|> , predict the immediate next line with the help of imports: from .qt.QtCore import * from .qt.QtGui import * from .fmoveablewidget import FMoveableWidget from .ftitlebar import BaseToolButton, baseHeight and context (classes, functions, sometimes code) from other files: # Path: src/qframer/ftitlebar.py # class BaseToolButton(QToolButton): # class FTitleBar(QFrame): # def __init__(self, parent=None): # def setMenu(self, menu): # def recover(self): # def __init__(self, parent=None): # def initData(self): # def initUI(self): # def swithModeIcon(self): # def swithLockIcon(self): # def swithPinIcon(self): # def swicthMaxIcon(self): # def mouseDoubleClickEvent(self, event): # def setLogo(self, icon): # def setTitle(self, text): # def getTitle(self): # def isLocked(self): # def isMax(self): . Output only the next line.
self.lockButton = BaseToolButton()
Given the following code snippet before the placeholder: <|code_start|> ''' logostyle = ''' QToolButton#logo{ background-color: transparent; } QToolButton#logo:hover{ background-color: transparent; } ''' def __init__(self, parent=None): super(FTitleBar, self).__init__(parent) self.initData() self.initUI() def initData(self): self.settingDownIcon = QIcon(":/icons/dark/appbar.control.down.png") self.clothesIcon = QIcon(":/icons/dark/appbar.clothes.shirt.png") self.lockIcon = QIcon(":/icons/dark/appbar.lock.png") self.unlockIcon = QIcon(":/icons/dark/appbar.unlock.keyhole.png") self.pinIcon = QIcon(":/icons/dark/appbar.pin.png") self.unPinIcon = QIcon(":/icons/dark/appbar.pin.remove.png") self.closeIcon = QIcon(":/icons/dark/appbar.close.png") self.max_flag = False self.lock_flag = False self.pin_flag = False def initUI(self): <|code_end|> , predict the next line using imports from the current file: from .qt.QtCore import * from .qt.QtGui import * from .fmoveablewidget import FMoveableWidget from .ftitlebar import BaseToolButton, baseHeight and context including class names, function names, and sometimes code from other files: # Path: src/qframer/ftitlebar.py # class BaseToolButton(QToolButton): # class FTitleBar(QFrame): # def __init__(self, parent=None): # def setMenu(self, menu): # def recover(self): # def __init__(self, parent=None): # def initData(self): # def initUI(self): # def swithModeIcon(self): # def swithLockIcon(self): # def swithPinIcon(self): # def swicthMaxIcon(self): # def mouseDoubleClickEvent(self, event): # def setLogo(self, icon): # def setTitle(self, text): # def getTitle(self): # def isLocked(self): # def isMax(self): . Output only the next line.
self.setFixedHeight(baseHeight)
Continue the code snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class LrcWorker(QObject): lrcFileExisted = pyqtSignal('QString') currentTextChanged = pyqtSignal('QString') __contextName__ = 'LrcWorker' <|code_end|> . Use current file imports: import os import re import requests from PyQt5.QtCore import (QObject, pyqtSignal, pyqtSlot, pyqtProperty, QUrl) from PyQt5.QtGui import QCursor, QDesktopServices from .utils import registerContext from config.constants import LRCPath from log import logger from dwidgets.coverlrc.lrc_download import TTPlayer, DUOMI, SOSO, TTPod from dwidgets.coverlrc.cover_query import poster from dwidgets.coverlrc.lrc_parser import LrcParser from dwidgets.dthreadutil import dthread from .signalmanager import signalManager and context (classes, functions, or code) from other files: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper # # Path: src/controllers/signalmanager.py # class SignalManager(QObject): # def __init__(self, parent=None): . Output only the next line.
@registerContext
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class LrcWorker(QObject): lrcFileExisted = pyqtSignal('QString') currentTextChanged = pyqtSignal('QString') __contextName__ = 'LrcWorker' @registerContext def __init__(self, parent=None): super(LrcWorker, self).__init__(parent) self._lrcDir = LRCPath self.lrcParser = LrcParser() self._currentText = '' self._lineMode = 1 self.initConnect() def initConnect(self): self.lrcFileExisted.connect(self.parserLrc) <|code_end|> with the help of current file imports: import os import re import requests from PyQt5.QtCore import (QObject, pyqtSignal, pyqtSlot, pyqtProperty, QUrl) from PyQt5.QtGui import QCursor, QDesktopServices from .utils import registerContext from config.constants import LRCPath from log import logger from dwidgets.coverlrc.lrc_download import TTPlayer, DUOMI, SOSO, TTPod from dwidgets.coverlrc.cover_query import poster from dwidgets.coverlrc.lrc_parser import LrcParser from dwidgets.dthreadutil import dthread from .signalmanager import signalManager and context from other files: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper # # Path: src/controllers/signalmanager.py # class SignalManager(QObject): # def __init__(self, parent=None): , which may contain function names, class names, or code. Output only the next line.
signalManager.downloadLrc.connect(self.getLrc)
Next line prediction: <|code_start|> ('setting_background2', 'QString', u'阴影颜色'), ('setting_backgroundSize', 'QString', u'阴影大小'), ('setting_download', 'QString', u'下载'), ('setting_downloadFolder', 'QString', u'下载目录'), ('setting_about', 'QString', u'关于'), ('search_online', 'QString', u'在线音乐'), ('search_local', 'QString', u'本地音乐'), ('suggestPlaylist', 'QString', u'推荐歌单'), ('keyBingTipMessage', 'QString', u'请输入新的快捷键'), ('info_songAbstract', 'QString', u'歌曲摘要'), ('info_songType', 'QString', u'类型'), ('info_songFormat', 'QString', u'格式'), ('info_songSize', 'QString', u'大小'), ('info_songDuration', 'QString', u'时长'), ('info_songAge', 'QString', u'年代'), ('info_songBitrate', 'QString', u'比特率'), ('info_songSampleRate', 'QString', u'采样率'), ('info_songPlayCount', 'QString', u'播放次数'), ('info_detail', 'QString', u'详细信息'), ('info_songTitle', 'QString', u'歌曲名'), ('info_songArtist', 'QString', u'艺术家'), ('info_songAlbum', 'QString', u'专辑'), ('info_albumArtist', 'QString', u'专辑艺术家'), ('info_songComposer', 'QString', u'作曲家'), ('info_songTracks', 'QString', u'曲目'), ('info_lyric', 'QString', u'歌词'), ('info_options', 'QString', u'选项'), ) __contextName__ = "I18nWorker" <|code_end|> . Use current file imports: (import os import sys import json from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty from PyQt5.QtGui import QCursor from .utils import registerContext, contexts from config.constants import ProjectPath from dwidgets import ModelMetaclass) and context including class names, function names, or small code snippets from other files: # Path: src/controllers/utils.py # def registerContext(func): # def wrapper(*args, **kwargs): # def registerObj(name, obj): # def duration_to_string(value, default="00:00", i=1000): # def openLocalUrl(url): . Output only the next line.
@registerContext
Continue the code snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class WindowManageWorker(QObject): mainWindowShowed = pyqtSignal() simpleWindowShowed = pyqtSignal() miniWindowShowed = pyqtSignal() currentMusicManagerPageNameChanged = pyqtSignal('QString') switchPageByID = pyqtSignal('QString') windowModeChanged = pyqtSignal('QString') __contextName__ = 'WindowManageWorker' <|code_end|> . Use current file imports: import os import sys from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty from PyQt5.QtGui import QCursor from .utils import registerContext from .signalmanager import signalManager and context (classes, functions, or code) from other files: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper # # Path: src/controllers/signalmanager.py # class SignalManager(QObject): # def __init__(self, parent=None): . Output only the next line.
@registerContext
Next line prediction: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class WindowManageWorker(QObject): mainWindowShowed = pyqtSignal() simpleWindowShowed = pyqtSignal() miniWindowShowed = pyqtSignal() currentMusicManagerPageNameChanged = pyqtSignal('QString') switchPageByID = pyqtSignal('QString') windowModeChanged = pyqtSignal('QString') __contextName__ = 'WindowManageWorker' @registerContext def __init__(self, parent=None): super(WindowManageWorker, self).__init__(parent) self._windowMode = 'Full' self._lastWindowMode = 'Full' self._currentMusicManagerPageName = 'ArtistPage' self.initConnect() def initConnect(self): <|code_end|> . Use current file imports: (import os import sys from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty from PyQt5.QtGui import QCursor from .utils import registerContext from .signalmanager import signalManager) and context including class names, function names, or small code snippets from other files: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper # # Path: src/controllers/signalmanager.py # class SignalManager(QObject): # def __init__(self, parent=None): . Output only the next line.
signalManager.simpleFullToggle.connect(self.actionSimpleFullToggle)
Next line prediction: <|code_start|> ('shortcut_next', 'QString', 'Right'), ('shortcut_volumnIncrease', 'QString', 'Up'), ('shortcut_volumeDecrease', 'QString', 'Down'), ('shortcut_playPause', 'QString', 'Space'), ('shortcut_simpleFullMode', 'QString', 'F11'), ('shortcut_miniFullMode', 'QString', 'F10'), ('shortcut_hideShowWindow', 'QString', 'F5'), ('shortcut_hideShowDesktopLRC', 'QString', 'F6'), ('desktopLRC_fontType', int, 0), ('fontType', list, ['A', 'B']), ('desktopLRC_fontSize', int, 30), ('desktopLRC_fontSize_minValue', int, 10), ('desktopLRC_fontSize_maxValue', int, 100), ('desktopLRC_fontItalic', int, 0), ('fontItalic', list, ['C', 'D']), ('desktopLRC_lineNumber', int, 1), ('lineNumber', list, ['1', '2']), ('desktopLRC_fontAlignment', int, 0), ('fontAlignment', list, ['F', 'G']), ('desktopLRC_background1', int, 0), ('background1', list, ['green', 'red']), ('desktopLRC_background2', int, 0), ('background2', list, ['yellow', 'gray']), ('desktopLRC_backgroundSize', int, 30), ('desktopLRC_backgroundSize_minValue', int, 10), ('desktopLRC_backgroundSize_maxValue', int, 100), ('DownloadSongPath', 'QString', DownloadSongPath)) __contextName__ = "ConfigWorker" <|code_end|> . Use current file imports: (import os import sys import json from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty from PyQt5.QtGui import QCursor from .utils import registerContext, contexts from config.constants import ProjectPath, DownloadSongPath from dwidgets import ModelMetaclass) and context including class names, function names, or small code snippets from other files: # Path: src/controllers/utils.py # def registerContext(func): # def wrapper(*args, **kwargs): # def registerObj(name, obj): # def duration_to_string(value, default="00:00", i=1000): # def openLocalUrl(url): . Output only the next line.
@registerContext
Based on the snippet: <|code_start|> ('shortcut_miniFullMode', 'QString', 'F10'), ('shortcut_hideShowWindow', 'QString', 'F5'), ('shortcut_hideShowDesktopLRC', 'QString', 'F6'), ('desktopLRC_fontType', int, 0), ('fontType', list, ['A', 'B']), ('desktopLRC_fontSize', int, 30), ('desktopLRC_fontSize_minValue', int, 10), ('desktopLRC_fontSize_maxValue', int, 100), ('desktopLRC_fontItalic', int, 0), ('fontItalic', list, ['C', 'D']), ('desktopLRC_lineNumber', int, 1), ('lineNumber', list, ['1', '2']), ('desktopLRC_fontAlignment', int, 0), ('fontAlignment', list, ['F', 'G']), ('desktopLRC_background1', int, 0), ('background1', list, ['green', 'red']), ('desktopLRC_background2', int, 0), ('background2', list, ['yellow', 'gray']), ('desktopLRC_backgroundSize', int, 30), ('desktopLRC_backgroundSize_minValue', int, 10), ('desktopLRC_backgroundSize_maxValue', int, 100), ('DownloadSongPath', 'QString', DownloadSongPath)) __contextName__ = "ConfigWorker" @registerContext def initialize(self, *agrs, **kwargs): self.load() def save(self): <|code_end|> , predict the immediate next line with the help of imports: import os import sys import json from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty from PyQt5.QtGui import QCursor from .utils import registerContext, contexts from config.constants import ProjectPath, DownloadSongPath from dwidgets import ModelMetaclass and context (classes, functions, sometimes code) from other files: # Path: src/controllers/utils.py # def registerContext(func): # def wrapper(*args, **kwargs): # def registerObj(name, obj): # def duration_to_string(value, default="00:00", i=1000): # def openLocalUrl(url): . Output only the next line.
mediaPlayer = contexts['MediaPlayer']
Predict the next line after this snippet: <|code_start|> lrcBackHalfSecond = pyqtSignal() lrcForwardHarfSecond = pyqtSignal() lrcThemeChanged = pyqtSignal() showLrcSingleLine = pyqtSignal() showLrcDoubleLine = pyqtSignal() kalaokChanged = pyqtSignal() locked = pyqtSignal() unlocked = pyqtSignal() lrcSetting = pyqtSignal() lrcSearch = pyqtSignal() lrcClosed = pyqtSignal() # window manager simpleFullToggle = pyqtSignal() miniFullToggle = pyqtSignal() fullMode = pyqtSignal() simpleMode = pyqtSignal() miniMode = pyqtSignal() hideShowWindowToggle = pyqtSignal() hideShowDesktopLrcToggle = pyqtSignal() # SystemTray systemTrayContext = pyqtSignal() #information Dialog show informationDialogShowed = pyqtSignal(dict) exited = pyqtSignal() <|code_end|> using the current file's imports: import os import sys from PyQt5.QtCore import (QObject, pyqtSignal, pyqtSlot, pyqtProperty, QUrl) from .utils import registerContext, contexts and any relevant context from other files: # Path: src/controllers/utils.py # def registerContext(func): # def wrapper(*args, **kwargs): # def registerObj(name, obj): # def duration_to_string(value, default="00:00", i=1000): # def openLocalUrl(url): . Output only the next line.
@registerContext
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class UtilWorker(QObject): __contextName__ = 'UtilWorker' @registerContext def __init__(self, parent=None): super(UtilWorker, self).__init__(parent) @pyqtSlot(int, result='QString') def int_to_string(self, value): return str(value) @pyqtSlot(int, result='QString') <|code_end|> using the current file's imports: import os import sys from PyQt5.QtCore import (QObject, pyqtSignal, pyqtSlot, pyqtProperty, QUrl) from PyQt5.QtGui import QCursor, QDesktopServices from .utils import registerContext, duration_to_string and any relevant context from other files: # Path: src/controllers/utils.py # def registerContext(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # self = args[0] # if hasattr(self, '__contextName__'): # contexts.update({self.__contextName__: self}) # func(*args, **kwargs) # # return wrapper # # def duration_to_string(value, default="00:00", i=1000): # ''' convert duration to string. ''' # if not value: return default # if (value / i) < 1: i = 1 # if value < 1000: # return default # else: # duration = "%02d:%02d" % (value / (60 * i), (value / i) % 60) # if value / (60 * i) / 60 >= 2: # duration = "%03d:%02d" % (value / (60 * i), (value / i) % 60) # return duration . Output only the next line.
def duration_to_string(self, duration):