rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'qt' : { 'rc/qtcreator/template.pro' : '${IDE_DIR}/qtcreator/${PRJ_NAME}/${PRJ_NAME}.pro', 'rc/qtcreator/template.pro.user': '${IDE_DIR}/qtcreator/${PRJ_NAME}/$[PRJ_NAME}.pro.user', 'rc/qtcreator/template.qws' : opjoin(qt_default_dir, '${PRJ_NAME}.qws'), }, 'eclipse' : { 'rc/eclipse/template.project' : '${IDE_D...
'qt' : { 'rc/qtcreator/template.pro' : '${IDE_DIR}/qtcreator/${PRJ_NAME}/${PRJ_NAME}.pro', 'rc/qtcreator/template.pro.user': '${IDE_DIR}/qtcreator/${PRJ_NAME}/${PRJ_NAME}.pro.user', 'rc/qtcreator/template.qws' : opjoin(qt_default_dir, '${PRJ_NAME}.qws'), }, 'eclipse' : { 'rc/eclipse/template.project' : '${IDE_...
def install (self, opts = ['rc', 'deps'] ): result = self.result(deps_results = 'deps' in opts)
'DEPS' : [opjoin(ide_dir, i.base_name, self.prj.get_lower('IDE'), i.base_name) for i in deps], 'IDE_PRJ_PATH' : opjoin(ide_dir, self.prj.base_name, self.prj.get_lower('IDE'), self.prj.base_name),
'DEPS' : [opjoin(ide_dir, i.base_name , self.prj.get_lower('IDE'), i.base_name) for i in deps],
def install (self, opts = ['rc', 'deps'] ): result = self.result(deps_results = 'deps' in opts)
for k,v in env['ENV']:
for k,v in env['ENV'].items():
def CMake(target, source, env): assert len(source) == 1 cmake_prj_path = find_cmake_path(source[0].get_abspath()) cmake_build_path = target[0].get_abspath() env.Execute(SCons.Script.Mkdir(cmake_build_path)) cmd = [ env.WhereIs('cmake', path=os.environ['PATH']) ] cmd.append(cmake_prj_path) cmd.append(env.subst('$...
print ext print path
def get_files(self, path, ext, builddir=True, invert_matches=False): """Returns HXX source files of the project""" kwargs = { 'invert_matches': invert_matches} if builddir: kwargs['replace_dir'] = map(self.get_build_dir_for, path) else: kwargs['replace_dir'] = path
self.root_path,
[self.root_path],
def get_others(self, builddir = True): """Returns CXX source files of the project""" return self.get_files( self.root_path, constants.CXX_SOURCE_EXT + constants.CXX_HEADER_EXT, builddir, invert_matches = True )
_config_dir = None
def check(self): """Returns True if lib name defines at least name and version""" s = self._splited return len(s) > 1
build_options_dir = pathjoin(prj_path, 'bin')
build_options_dir = pathjoin(prj_path,'bin') config_dir = pathjoin(build_options_dir,'configs')
def __init__(self, build_options, prj_path=None, platform='', cxx='', debug='', config = None, locals=None, globals=None, projects_db = {}):
self._config_dir = pathjoin(build_options_dir,'configs')
def __init__(self, build_options, prj_path=None, platform='', cxx='', debug='', config = None, locals=None, globals=None, projects_db = {}):
pathjoin(self._config_dir, global_config))
pathjoin(config_dir, global_config))
def __init__(self, build_options, prj_path=None, platform='', cxx='', debug='', config = None, locals=None, globals=None, projects_db = {}):
path = self._config_dir,
path = config_dir,
def __init__(self, build_options, prj_path=None, platform='', cxx='', debug='', config = None, locals=None, globals=None, projects_db = {}):
'posix' ,
def generate(env): """Add Builders and construction variables for g++ to an Environment.""" compiler = get_option("CXX") if compiler: gplusplus.compilers = [compiler] gplusplus.generate(env) env.__class__.ManageOption = manage_options env.__class__.InstallFileFilter = install_file_filter CFLAGS = [ '-pipe', ] CXXFLAG...
cons = getattr(self, console, self.stdout)
self.cons = cons = getattr(self, console, self.stdout)
def __init__(self, fg = None, bg = None, txt = '', console='stdout', **kwargs): super(ColorText, self).__init__(**kwargs)
ARGS.append('--prefix=${BUILD_DIR}/local')
ARGS.append('--prefix=${LOCAL_DIR}') if prj.get('DEBUG') != 'release': ARGS.append('--enable-debug') else: ARGS.append('--disable-debug')
def __call__(self, *args, **kwargs): prj = self.prj ENV = prj.env['ENV'] ENV['CXXFLAGS'] = ENV.get('CXXFLAGS','') ENV['CFLAGS'] = ENV.get('CFLAGS','') ENV['LINKFLAGS'] = ENV.get('LINKFLAGS','') ENV['CXXFLAGS'] += ' -I'.join([''] + prj.deps_include_path) ENV['CFLAGS'] += ' -I'.join([''] + prj.deps_include_path) ...
ARGS.insert(0,'-DCMAKE_INCLUDE_PATH:PATH=$LIBEXT_INCLUDE_PATH') ARGS.insert(0,'-DCMAKE_LIBRARY_PATH:PATH=$LIBEXT_LIBRARY_PATH') ARGS.append('-DCMAKE_INSTALL_PREFIX:PATH=${BUILD_DIR}/local')
ARGS.insert(0,'-DCMAKE_INCLUDE_PATH:PATH=${DEPS_INCLUDE}') ARGS.insert(0,'-DCMAKE_LIBRARY_PATH:PATH=${DEPS_LIB}') ARGS.append('-DCMAKE_INSTALL_PREFIX:PATH=${LOCAL_DIR}') def build_type(): if prj.get('DEBUG') != 'release': return 'Debug' else: return 'Release' ARGS.append('-DCMAKE_BUILD_TYPE:STRING={0}'.format(build_t...
def __call__(self, *args, **kwargs): ARGS = kwargs.setdefault('ARGS', []) ARGS.insert(0,'-DCMAKE_INCLUDE_PATH:PATH=$LIBEXT_INCLUDE_PATH') ARGS.insert(0,'-DCMAKE_LIBRARY_PATH:PATH=$LIBEXT_LIBRARY_PATH') ARGS.append('-DCMAKE_INSTALL_PREFIX:PATH=${BUILD_DIR}/local')
'LIBEXT_INCLUDE_PATH' : os.pathsep.join(prj.deps_include_path), 'LIBEXT_LIBRARY_PATH' : os.pathsep.join(prj.deps_lib_path),
def environment(self): prj = self env = self.env deps = dict( ('DEP_{0}'.format(p.name).upper(), p.local_dir) for p in self.source_rec_deps ) items = deps.items() deps_include = dict(( k+'_INCLUDE' , v+'/include') for k,v in items) deps_lib = dict(( k+'_LIB' , v+'/lib' ) for k,v in items) deps_bin = dict...
'DEPS' : [opjoin(ide_dir, i.base_name , self.prj.get_lower('IDE'), i.base_name)
'DEPS' : [opjoin(ide_dir, self.prj.get_lower('IDE') ,i.base_name, i.base_name)
def install (self, opts = ['rc', 'deps'] ): result = self.result(deps_results = 'deps' in opts)
prj.build_dir,
src_build_dir(prj),
def qressources(prj): """Returns ui source files of the project""" qrc = rutils.DeepGlob( ['qrc'], prj.src_path, prj.build_dir, ) return qrc
dot = env.WhereIs('dot', os.environ['PATH']) env['ENV']['DOX_OUTPUTDIR'] = dot
def result(self, deps_results=True): prj = self env = self.env
matches = []
def install_bin_libext (self): env = self.env import fnmatch libext = self.get('LIBEXTFACTORY')
zlib = rlibext.register.get_lib_for_prj('z', prj)
def get_additive(self, prj): for builddir, incpath in zip( inc_build_dir(prj), prj.include_path ): prj.variant_dir( builddir, incpath ) env = prj.env
lib_path = zlib.ABS_BINPATH if racy.renv.is_windows() else zlib.ABS_LIBPATH env.PrependENVPath( racy.renv.LD_VAR, [ os.path.join(*dir) for dir in lib_path ] )
def get_additive(self, prj): for builddir, incpath in zip( inc_build_dir(prj), prj.include_path ): prj.variant_dir( builddir, incpath ) env = prj.env
@memoize def install (self, opts = ['rc','deps']):
@cached_property def install_nodes(self):
def build(self, build_deps = True): """build_deps = False is not available""" res = self.result(build_deps) return res
install_deps = 'deps' in opts result = prj.build(build_deps=install_deps)
def install (self, opts = ['rc','deps']): prj = self env = self.env
env.Depends(write, result) result = copy
return [copy, write] @memoize def install (self, opts = ['rc','deps']): prj = self env = self.env install_deps = 'deps' in opts result = prj.build(build_deps=install_deps) nodes = self.install_nodes env.Depends(nodes, result) result = nodes
def install (self, opts = ['rc','deps']): prj = self env = self.env
raise LibExtException, "Unable to find {0} base path"
raise LibExtException, "Unable to find {0} base path".format(name)
def __init__(self, name, debug, infosource=None): platform_init = getattr(self, racy.renv.system(), self.platform_not_managed)
'parse_configs'
'parse_configs' , 'scons_tools' , 'scons_env' ,
def __init__(self, name, debug, infosource=None): platform_init = getattr(self, racy.renv.system(), self.platform_not_managed)
classattr = getattr(infosource, name, getattr(self, name)) if not hasattr(classattr,'getter'): attr = getattr(infosource, name, getattr(self, name)) setattr(self,name, list(attr)) self.version = racy.rutils.Version(infosource.version) self.arch = infosource.arch
attr = getattr(infosource_instance, name, getattr(self, name)) if callable(attr): try: attr = attr() except TypeError: msg = ("libext callable members must take only one " "argument (self). '{attr}' method is" "invalid in '{lib}' __init__.py file.") raise LibExtException, msg.format(lib=self.name, attr=name) if hasa...
def __init__(self, name, debug, infosource=None): platform_init = getattr(self, racy.renv.system(), self.platform_not_managed)
patterns.append( env.subst('${SHLIBPREFIX}{0}${SHLIBSUFFIX}*'))
def install_bin_libext (self): env = self.env import fnmatch libext = self.get('LIBEXTFACTORY')
patterns.extend(libext.libs_install)
else: patterns.append( env.subst('${SHLIBPREFIX}{0}${SHLIBSUFFIX}*'))
def install_bin_libext (self): env = self.env import fnmatch libext = self.get('LIBEXTFACTORY')
sourceZip = zipfile.open(source[0].get_abspath(),'r')
sourceZip = zipfile.ZipFile(source[0].get_abspath(),'r')
def UnZip(target, source, env): # Code to build "target" from "source" here import zipfile sourceZip = zipfile.open(source[0].get_abspath(),'r') sourceZip.extractall(path=target[0].get_abspath()) sourceZip.close() return None
res = any(f.get_path().endswith(exit) for ext in to_install)
res = any(f.get_path().endswith(ext) for ext in to_install)
def install_file_filter(env, f): to_install = [ '.exe', '.dll', '.pdb'] res = hasattr(f,"get_path") if res: res = any(f.get_path().endswith(exit) for ext in to_install) return res
self.materials = materials if materials != None else bpy.data.textures
self.materials = materials if materials != None else bpy.data.materials
def __init__(self, target_file, target_dir, materials = None, textures = None): self.target_file = target_file self.target_dir = target_dir self.exported_materials = [] self.exported_textures = [] self.materials = materials if materials != None else bpy.data.textures self.textures = textures if textures != None else bp...
raise Exception('Failed to find material "%s"' % name)
raise Exception('Failed to find material "%s" in "%s"' % (name, str(self.materials)))
def findMaterial(self, name): if name in self.materials: return self.materials[name] else: raise Exception('Failed to find material "%s"' % name)
filename = bpy.props.StringProperty(name='Target filename')
filename = bpy.props.StringProperty(name='Target filename', subtype = 'FILE_PATH')
def execute(self, context): pv = [ 'bpy.context.material.mitsuba_material.%s'%v['attr'] for v in bpy.types.mitsuba_material.get_exportable_properties() ]
menu_func = lambda self, context: self.layout.operator("export.mitsuba", text="Export Mitsuba scene...")
def menu_func(self, context): default_path = os.path.splitext(os.path.basename(bpy.data.filepath))[0] + ".xml" self.layout.operator("export.mitsuba", text="Export Mitsuba scene...").filename = default_path
def execute(self, context): try: if self.properties.scene == '': scene = context.scene else: scene = bpy.data.scenes[self.properties.scene]
self.out.write('\n\t\t<luminaire id="%s-light" type="area">\n' % name)
self.out.write('\n\t\t<luminaire id="%s-arealight" type="area">\n' % name)
def exportLamp(self, lamp, idx): ltype = lamp.data.mitsuba_lamp.type name = translate_id(lamp.data.name) if ltype == 'POINT': self.out.write('\t<luminaire id="%s-light" type="point">\n' % name) mult = lamp.data.mitsuba_lamp.intensity self.exportWorldtrafo(lamp.matrix_world) self.out.write('\t\t<rgb name="intensity" val...
('composite', 'Compound material', 'Allows creating mixtures of different materials')
('composite', 'Composite material', 'Allows creating mixtures of different materials')
def dict_merge(*args): vis = {} for vis_dict in args: vis.update(deepcopy(vis_dict)) return vis
'zope.testbrowser']),
'zope.testbrowser', 'zope.login',]),
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
>>> IdPicker({}).checkName(u'bob\xfa', None) ... Traceback (most recent call last): ... UserError: Ids must contain only printable 7-bit non-space ASCII characters
>>> try: ... IdPicker({}).checkName(u'bob\xfa', None) ... except UserError, e: ... print e ... Ids must contain only printable 7-bit non-space ASCII characters
def checkName(self, name, object): """Limit ids
>>> IdPicker({}).checkName(u'big bob', None) ... Traceback (most recent call last): ... UserError: Ids must contain only printable 7-bit non-space ASCII characters
>>> try: ... IdPicker({}).checkName(u'big bob', None) ... except UserError, e: ... print e ... Ids must contain only printable 7-bit non-space ASCII characters
def checkName(self, name, object): """Limit ids
if not (parts[0], parts[1]) in substitutions: substitutions[(parts[0], parts[1])] = weight
if not (parts[0], parts[1]) in self.substitutions: self.substitutions[(parts[0], parts[1])] = weight
def process(self, specification): parts = specification.split('\t') if len(parts) != 3: raise ValueError("Got specification with " + str(len(parts)) +\ " parts, expected 3:\n" + specification) weight = float(parts[2]) if ',' in parts[0]: frompair = tuple(parts[0].split(',')) topair = tuple(parts[1].split(',')) if not (...
(global_options, global_args) = parser.parse_args()
(global_options, global_args) = parser.parse_args( argv[1:] )
def Start( parser = None, quiet = False, add_csv_options = False, add_mysql_options = False, add_psql_options = False, add_pipe_options = True, add_cluster_options = False, add_output_options = False ): """set up an experiment. returns a tuple containing (options, args). The options class is extended with a logger m...
Gerber Saxton Algorithm for Fourier CGH
Gerchberg - Saxton Algorithm for Fourier CGH
def GScgh(z,target,reference=1.,iterations=20,error=None): ''' Gerber Saxton Algorithm for Fourier CGH Function that calculates Fourier holographic optical elements using the Gerber Saxton algorithm. The algorithm uses the FFT implementation of the Fraunhoffer Transform. **ARGUMENTS:** ========== ===================...
Gerber Saxton Algorithm for Fresnel CGS
Gerchberg - Saxton Algorithm for Fresnel CGS
def GScghFr(z,target,reference=1.,iterations=20,error=None): ''' Gerber Saxton Algorithm for Fresnel CGS Function that calculates a Fresnel holographic optical elements using the Gerber Saxton algorithm. The algorithm uses the FFT implementation of the Fresnel transform. .. note:: A Fresnel CGH can be interpreted as ...
def gpu_eval(self,x,y): retval=self.poly.gpu_eval(x,y) return retval
def evalm(self,x,y,mask=True): ''' Evaluate the zernike polynomial Method used to evaluate the zernike polynomial at the coordinates given by the 2D arrays x,y **ARGUMENTS** ==== ============================================================== x 2D array containing the X coordinates where the Zernike polynomial is ...
It uses the Gerber Saxton algorithm for Fraunhoffer propagation.
It uses the Gerchberg - Saxton algorithm for Fraunhoffer propagation.
def ffGS(z,target,estimate=None, iterations=20,error=None): ''' Far field Gerchberg - Saxton Algorithm Calculates the phase distribution in a object plane (for a given amplitude constrain) to obtain an specific amplitude distribution in the target plane. It uses the Gerber Saxton algorithm for Fraunhoffer propagation....
if isfunction(obj):
if isfunction(obj) or isroutine(obj):
def get_function_list(module): r=[] try: oblist=module.__all__ except(AttributeError): return r for o in oblist: obj=module.__dict__[o] if isfunction(obj): r.append(o) return r
if (len(line)-len(line1))<=ide and (line1.split(" ")[0]=="def" or line1.split(" ")[0]=="cdef"):
if (len(line)-len(line1))<=ide and (line1.split(" ")[0]=="def" or line1.split(" ")[0]=="cdef" or line1.split(" ")[0]=="cpdef"):
def document_packages(packages): for i in packages: import_string = "import "+i+" as module" print "Documenting "+i exec import_string try: oblist=module.__all__ except(AttributeError): print "*****************************************************" print "Warning: Package "+i+" \n"+\ "has no __all__ attribute in the _...
print " ",o
def document_packages(packages): for i in packages: import_string = "import "+i+" as module" print "Documenting "+i exec import_string try: oblist=module.__all__ except(AttributeError): print "*****************************************************" print "Warning: Package "+i+" \n"+\ "has no __all__ attribute in the _...
if (line.split(" ")[0]=="def" or line.split(" ")[0]=="cpdef" ) and line.find(" _")==-1 and line.find(" class ")==-1 and line[0]=="d" and line.find(o)!=-1:
if (line.split(" ")[0]=="def" or line.split(" ")[0]=="cpdef" ) and line.find(" _")==-1 and line.find(" class ")==-1 and (line[0]=="d" or line[0]=="c") and line.find(o)!=-1:
def document_packages(packages): for i in packages: import_string = "import "+i+" as module" print "Documenting "+i exec import_string try: oblist=module.__all__ except(AttributeError): print "*****************************************************" print "Warning: Package "+i+" \n"+\ "has no __all__ attribute in the _...
if err!=None and err<error: break
if error!=None and err<error: break
def ffGS(z,target,estimate=None, iterations=20,error=None): ''' Far field Gerchberg - Saxton Algorithm Calculates the phase distribution in a object plane (for a given amplitude constrain) to obtain an specific amplitude distribution in the target plane. It uses the Gerber Saxton algorithm for Fraunhoffer propagation....
if err!=None and err<error: break
if error!=None and err<error: break
def frGS(z,target,estimate=None, iterations=20,error=None): ''' Fresnel transform Gerchberg - Saxton Algorithm Calculates the phase distribution in a object plane (for a given amplitude constrain) to obtain an specific amplitude distribution in the target plane. A FFT implementation of the Fresnel Transform is used. ...
self.node.setEventHandler(avg.CURSOROVER, avg.TOUCH|avg.MOUSE, self.onCursorDown)
self.node.setEventHandler(avg.CURSORDOWN, avg.TOUCH|avg.MOUSE, self.onCursorDown)
def init(self): global g_AudioInterface
updated = models.DateTimeField(_('Updated'), null=True)
updated = models.DateTimeField(_('Updated'), blank=True, null=True)
def posts(self): return Post.objects.filter(topic__forum__category=self).select_related()
hgrc.set("hooks", "pretxnchangegroup.subssh.permissions",
hgrc.set("hooks", "prechangegroup.subssh.permissions",
def create_repository(self, path, owner): from mercurial import ui, hg hg_repo = hg.repository(ui.ui(), path, create=True) hgrc = SafeConfigParser() hgrc_filepath = os.path.join(hg_repo.path, "hgrc") hgrc.read(hgrc_filepath) if not hgrc.has_section("hooks"): hgrc.add_section("hooks") hgrc.set("hooks", "pretxnchang...
def permissions_hook(ui, repo_hg, **kwargs):
def permissions_hook(url=None, source=None, ui=None, hooktype=None, repo=None):
def permissions_hook(ui, repo_hg, **kwargs):
user = subssh.get_user_object()
user = subssh.get_user()
def permissions_hook(ui, repo_hg, **kwargs):
upper = "/".join(repo_hg.path.split("/")[:-1])
upper = "/".join(repo.path.split("/")[:-1])
def permissions_hook(ui, repo_hg, **kwargs):
repo = Mercurial(upper, subssh.config.ADMIN)
repo_subssh = Mercurial(upper, subssh.config.ADMIN)
def permissions_hook(ui, repo_hg, **kwargs):
if not repo.has_permissions(user.username, "w"):
if not repo_subssh.has_permissions(user.username, "w"):
def permissions_hook(ui, repo_hg, **kwargs):
(user.username, repo.name ))
(user.username, repo_subssh.name ))
def permissions_hook(ui, repo_hg, **kwargs):
if self.repo_path.endswith(self.suffix):
if self.prefix and self.repo_path.startswith(self.suffix): name = name[len(self.suffix):] if self.suffix and self.repo_path.endswith(self.suffix):
def name(self): name = os.path.basename(self.repo_path) if self.repo_path.endswith(self.suffix): name = name[:-len(self.suffix)]
if self.repo_path.startswith(self.suffix): name = name[len(self.suffix):]
def name(self): name = os.path.basename(self.repo_path) if self.repo_path.endswith(self.suffix): name = name[:-len(self.suffix)]
def permissions_hook(url=None, source=None, ui=None, hooktype=None, repo=None):
def permissions_hook(ui=None, repo=None, **kwargs):
def permissions_hook(url=None, source=None, ui=None, hooktype=None, repo=None): user = subssh.get_user() upper = "/".join(repo.path.split("/")[:-1]) repo_subssh = Mercurial(upper, subssh.config.ADMIN) if not repo_subssh.has_permissions(user.username, "w"): from mercurial.util import Abort raise Abort('%s has no wri...
raise NotImplementedError(self.error)
self._stream.write('%s\n' % (message,))
def error(self, message): """Report an error.""" # XXX: Mostly used for user errors, sometimes used for errors in the # test framework, sometimes used to record layer setUp failure (!!!). # How should this be encoded? raise NotImplementedError(self.error)
'setdoctest._unittest_reportflags',
'set_unittest_reportflags',
def _test(): import doctest doctest.testmod()
args = linter.load_command_line_configuration(args)
try: args = linter.load_command_line_configuration(args) except SystemExit, exc: if exc.code == 2: exc.code = 32 raise
def __init__(self, args, reporter=None, exit=True): self._rcfile = None self._plugins = [] preprocess_options(args, { # option: (callback, takearg) 'rcfile': (self.cb_set_rcfile, True), 'load-plugins': (self.cb_add_plugins, True), }) self.linter = linter = self.LinterClass(( ('rcfile', {'action' : 'callback', 'ca...
cbs = self.visit_events.setdefault(cid, []) cbs.append(getattr(checker, member[6:]))
cid = member[6:] if cid != 'default': cbs = self.visit_events.setdefault(cid, []) cbs.append(getattr(checker, cid)) vcids.add(cid) else: hasvdefault = getattr(checker, cid)
def add_checker(self, checker): for member in dir(checker): if member.startswith('visit_'): cbs = self.visit_events.setdefault(cid, []) cbs.append(getattr(checker, member[6:])) if member.startswith('leave_'): cbs = self.leave_events.setdefault(cid, []) cbs.insert(0, getattr(checker, member[6:]))
cbs = self.leave_events.setdefault(cid, []) cbs.insert(0, getattr(checker, member[6:]))
if cid != 'default': cbs = self.leave_events.setdefault(cid, []) cbs.append(getattr(checker, cid)) lcids.add(cid) else: hasldefault = getattr(checker, cid) if hasvdefault: for cls in nodes.ALL_NODE_CLASSES: cid = cls.__name__.lower() if cid not in vcids: cbs = self.visit_events.setdefault(cid, []) cbs.append(getattr(ch...
def add_checker(self, checker): for member in dir(checker): if member.startswith('visit_'): cbs = self.visit_events.setdefault(cid, []) cbs.append(getattr(checker, member[6:])) if member.startswith('leave_'): cbs = self.leave_events.setdefault(cid, []) cbs.insert(0, getattr(checker, member[6:]))
for cb in self.visit_events[cid]:
for cb in self.visit_events.get(cid, ()):
def walk(self, astng): """call visit events of astng checkers for the given node, recurse on its children, then leave events. """ cid = node.__class__.__name__.lower() # generate events for this node on each checker for cb in self.visit_events[cid]: cb(astng) # recurse on children for child in astng.get_children(): sel...
for cb in self.leave_events[cid]:
for cb in self.leave_events.get(cid, ()):
def walk(self, astng): """call visit events of astng checkers for the given node, recurse on its children, then leave events. """ cid = node.__class__.__name__.lower() # generate events for this node on each checker for cb in self.visit_events[cid]: cb(astng) # recurse on children for child in astng.get_children(): sel...
strio = tempfile.TemporaryFile()
if sys.version_info < (3, 0): strio = tempfile.TemporaryFile() else: strio = StringIO()
def test_no_out_encoding(self): """test redirection of stdout with non ascii caracters """ #This test reproduces bug #48066 ; it happens when stdout is redirected # through '>' : the sys.stdout.encoding becomes then None, and if the # output contains non ascii, pylint will crash strio = tempfile.TemporaryFile() assert ...
msg_order = 'EWRCIF' def cmp_func(msgid1, msgid2): """comparison function for two message identifiers""" if msgid1[0] != msgid2[0]: return cmp(msg_order.index(msgid1[0]), msg_order.index(msgid2[0])) else: return cmp(msgid1, msgid2) msgids.sort(cmp_func) return msgids
msgs = {} for msg in msgids: msgs.setdefault(msg[0], []).append(msg) result = [] for m_id in _MSG_ORDER: if m_id in msgs: result.extend( sorted(msgs[m_id]) ) return result
def sort_msgs(msgids): """sort message identifiers according to their category first""" msg_order = 'EWRCIF' def cmp_func(msgid1, msgid2): """comparison function for two message identifiers""" if msgid1[0] != msgid2[0]: return cmp(msg_order.index(msgid1[0]), msg_order.index(msgid2[0])) else: return cmp(msgid1, msgid2) ...
scripts_ = [script + '.bat' for script in linux_scripts]
scripts_ = linux_scripts + [script + '.bat' for script in linux_scripts]
def ensure_scripts(linux_scripts): """ Creates the proper script names required for each platform (taken from 4Suite) """ from distutils import util if util.get_platform()[:3] == 'win': scripts_ = [script + '.bat' for script in linux_scripts] else: scripts_ = linux_scripts return scripts_
if node.attrname in self.config.generated_members:
if node.attrname in self.generated_members:
def visit_getattr(self, node): """check that the accessed attribute exists
if output is None: output = sys.stdout self.out = output
self.out = output or sys.stdout self.out_encoding = (self.out.encoding or locale.getdefaultlocale()[1] or sys.getdefaultencoding())
def set_output(self, output=None): """set output stream""" if output is None: output = sys.stdout self.out = output
print >> self.out, string
print >> self.out, (isinstance(string, unicode) and string.encode(self.out_encoding) or string)
def writeln(self, string=''): """write a line in the output buffer""" print >> self.out, string
scripts_ = [script + '.bat' for script in linux_scripts] else: scripts_ = linux_scripts return scripts_
return linux_scripts + [script + '.bat' for script in linux_scripts] return linux_scripts
def ensure_scripts(linux_scripts): """Creates the proper script names required for each platform (taken from 4Suite) """ from distutils import util if util.get_platform()[:3] == 'win': scripts_ = [script + '.bat' for script in linux_scripts] else: scripts_ = linux_scripts return scripts_
neededcheckers = []
neededcheckers = [self]
def needed_checkers(self): """return checkers needed for activated messages and reports""" neededcheckers = [] get_msg = self._msgs_state.get for checker in self.get_checkers(): if ( any(get_msg(msg, True) for msg in checker.msgs) or any(get_msg(msg[0], True) for msg in checker.reports) ): neededcheckers.append(checker...
for checker in self.get_checkers(): if ( any(get_msg(msg, True) for msg in checker.msgs) or any(get_msg(msg[0], True) for msg in checker.reports) ): neededcheckers.append(checker)
for checker in self.get_checkers()[1:]: if (any(get_msg(msg, True) for msg in checker.msgs) or any(self.is_report_enabled(r[0]) for r in checker.reports)): neededcheckers.append(checker)
def needed_checkers(self): """return checkers needed for activated messages and reports""" neededcheckers = [] get_msg = self._msgs_state.get for checker in self.get_checkers(): if ( any(get_msg(msg, True) for msg in checker.msgs) or any(get_msg(msg[0], True) for msg in checker.reports) ): neededcheckers.append(checker...
def __init__(self, linter=None): BaseChecker.__init__(self, linter)
def open(self):
def __init__(self, linter=None): BaseChecker.__init__(self, linter) self.generated_members = list(self.config.generated_members) if self.config.zope: self.generated_members.extend(('REQUEST', 'acl_users', 'aq_parent'))
def __ltp__(self, other):
def __lt__(self, other):
def __ltp__(self, other): return self.name < other.name
self.assertEqual(ulines(check_line('a=1', REPORTER)), ('C0322', 'a=1\n ^'))
self.assertEqual(ulines(check_line('a=1')), ('C0322', 'a=1\n ^'))
def test_known_values_opspace_1(self): self.assertEqual(ulines(check_line('a=1', REPORTER)), ('C0322', 'a=1\n ^'))
self.assertEqual(ulines(check_line('a= 1', REPORTER)), ('C0322', 'a= 1\n ^') )
self.assertEqual(ulines(check_line('a= 1')), ('C0322', 'a= 1\n ^') )
def test_known_values_opspace_2(self): self.assertEqual(ulines(check_line('a= 1', REPORTER)), ('C0322', 'a= 1\n ^') )
self.assertEqual(ulines(check_line('a =1', REPORTER)), ('C0323', 'a =1\n ^'))
self.assertEqual(ulines(check_line('a =1')), ('C0323', 'a =1\n ^'))
def test_known_values_opspace_3(self): self.assertEqual(ulines(check_line('a =1', REPORTER)), ('C0323', 'a =1\n ^'))
self.assertEqual(check_line('f(a=1)', REPORTER), None)
self.assertEqual(check_line('f(a=1)'), None)
def test_known_values_opspace_4(self): self.assertEqual(check_line('f(a=1)', REPORTER), None)
self.assertEqual(check_line('a[:1]', REPORTER), None)
self.assertEqual(check_line('a[:1]'), None)
def test_known_values_colonnl_2(self): self.assertEqual(check_line('a[:1]', REPORTER), None)
self.assertEqual(check_line('a[1:]', REPORTER), None)
self.assertEqual(check_line('a[1:]'), None)
def test_known_values_colonnl_3(self): self.assertEqual(check_line('a[1:]', REPORTER), None)
self.assertEqual(check_line('a[1:2]', REPORTER), None)
self.assertEqual(check_line('a[1:2]'), None)
def test_known_values_colonnl_4(self): self.assertEqual(check_line('a[1:2]', REPORTER), None)
self.assertEqual(check_line('def intersection(list1, list2):', REPORTER), None)
self.assertEqual(check_line('def intersection(list1, list2):'), None)
self.assertEqual(check_line('def intersection(list1, list2):', REPORTER), None)
self.assertEqual(check_line('def intersection(list1, list2):\n', REPORTER), None)
self.assertEqual(check_line('def intersection(list1, list2):\n'), None)
self.assertEqual(check_line('def intersection(list1, list2):\n', REPORTER), None)
self.assertEqual(check_line('if file[:pfx_len] == path:\n', REPORTER), None)
self.assertEqual(check_line('if file[:pfx_len] == path:\n'), None)
def test_known_values_colonnl_7(self): self.assertEqual(check_line('if file[:pfx_len] == path:\n', REPORTER), None)
self.assertEqual(check_line('if file[:pfx_len[1]] == path:\n', REPORTER), None)
self.assertEqual(check_line('if file[:pfx_len[1]] == path:\n'), None)
def test_known_values_colonnl_9(self): self.assertEqual(check_line('if file[:pfx_len[1]] == path:\n', REPORTER), None)
self.assertEqual(check_line('if file[pfx_len[1]] == path:\n', REPORTER), None)
self.assertEqual(check_line('if file[pfx_len[1]] == path:\n'), None)
def test_known_values_colonnl_10(self): self.assertEqual(check_line('if file[pfx_len[1]] == path:\n', REPORTER), None)
self.assertEqual(ulines(check_line('a, b = 1,2', REPORTER)),
self.assertEqual(ulines(check_line('a, b = 1,2')),
def test_known_values_commaspace_1(self): self.assertEqual(ulines(check_line('a, b = 1,2', REPORTER)), ('C0324', 'a, b = 1,2\n ^^'))
self.assertEqual(check_line('should_not_warn = [1, 2, 3,]\n', REPORTER),
self.assertEqual(check_line('should_not_warn = [1, 2, 3,]\n'),
def test_known_values_commaspace_2(self): self.assertEqual(check_line('should_not_warn = [1, 2, 3,]\n', REPORTER), None)
self.assertEqual(check_line('should_not_warn = {1:2, 3:4,}\n', REPORTER),
self.assertEqual(check_line('should_not_warn = {1:2, 3:4,}\n'),
def test_known_values_commaspace_3(self): self.assertEqual(check_line('should_not_warn = {1:2, 3:4,}\n', REPORTER), None)
self.assertEqual(check_line('should_not_warn = (1, 2, 3,)\n', REPORTER),
self.assertEqual(check_line('should_not_warn = (1, 2, 3,)\n'),
def test_known_values_commaspace_4(self): self.assertEqual(check_line('should_not_warn = (1, 2, 3,)\n', REPORTER), None)
self.assertEqual(check_line('f("a=1")', REPORTER), None)
self.assertEqual(check_line('f("a=1")'), None)
def test_known_values_instring_1(self): self.assertEqual(check_line('f("a=1")', REPORTER), None)
self.assertEqual(ulines(check_line('print >>1, ("a:1")', REPORTER)),
self.assertEqual(ulines(check_line('print >>1, ("a:1")')),
def test_known_values_instring_2(self): self.assertEqual(ulines(check_line('print >>1, ("a:1")', REPORTER)), ('C0323', 'print >>1, ("a:1")\n ^'))