rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print filename print self.__getdirname(filename)
def getstore(self, filename): print filename print self.__getdirname(filename) try: store = self.__stores[self.__getdirname(filename)] except KeyError: self.open(filename) store = self.__stores[self.__getdirname(filename)] return store
if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description":
if node.nodeType != xml.dom.Node.ELEMENT_NODE or node.tagName != "description": continue if node.hasChildNodes() and len(node.childNodes) == 1: if xmlutils.hasChildTextNode(node): return node child = node.firstChild if child.nodeType == xml.dom.Node.ELEMENT_NODE and child.tagName == "para" and xmlutils.hasChildTextNode...
def __get_description_element(self): children = self.__node.childNodes for node in children: # Here I assume that description is a text node; I am not sure # it's a good assumption if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description": return node else: return None return None
else: return None
def __get_description_element(self): children = self.__node.childNodes for node in children: # Here I assume that description is a text node; I am not sure # it's a good assumption if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description": return node else: return None return None
if desc_element != None and desc_element.hasChildNodes() and desc_element.firstChild.nodeType == xml.dom.Node.TEXT_NODE: value = desc_element.firstChild.data
if desc_element != None: if desc_element.firstChild.nodeType == xml.dom.Node.ELEMENT_NODE: node = desc_element.firstChild else: node = desc_element value = xmlutils.getChildTextNode(node)
def get_description(self, nonone = 0): desc_element = self.__get_description_element() if desc_element != None and desc_element.hasChildNodes() and desc_element.firstChild.nodeType == xml.dom.Node.TEXT_NODE: value = desc_element.firstChild.data else: value = None if nonone and value == None: value = "" return value
item.set_description(self.desc.get_buffer().get_text())
item.set_description(self.desc.get_buffer().get_text( self.desc.get_buffer().get_start_iter(), self.desc.get_buffer().get_end_iter()))
def save(self, obj): item = self.stores.get_item(self.filename, self) item.set_title(self.title.entry.get_text()) self.__combo_add_entry(self.title, self.title.entry.get_text()) item.set_description(self.desc.get_buffer().get_text())
parser = OptionParser ("usage: %prog [optoins] name")
parser = OptionParser ("usage: %prog [options] name")
def parse_args (): from optparse import OptionParser parser = OptionParser ("usage: %prog [optoins] name") parser.add_option ("-A", "--ACE", dest="project", action="store_const", help="Branch/tag only ACE", default=None, const="ace") parser.add_option ("-T", "--TAO", dest="project", action="store_const", help="Branch/...
o = super(MyCopyClass, self).copyWithZone_(zone)
o = self.__class__.alloc().init()
def copyWithZone_(self, zone): o = super(MyCopyClass, self).copyWithZone_(zone) o.foobar = 2 return o
NSApp = rt.NSApplication.sharedApplication()
def main(): pool = rt.NSAutoreleasePool() # Load Application Framework: rt.NSBundle.bundleWithPath_( '/System/Library/Frameworks/AppKit.framework').load() NSApp = rt.NSApplication.sharedApplication() win = rt.NSWindow.alloc() frame = ((200.0, 300.0), (250.0, 100.0)) win.initWithContentRect_styleMask_backing_defer_ ...
return +number_wrap(_num_to_python(numA))
return number_wrap(+_num_to_python(numA))
def __pos__CFNumber(numA): return +number_wrap(_num_to_python(numA))
Thread.__init__(target=self.doWork)
Thread.__init__(self)
def __init__(self): """Create a worker thread. Start it by calling the start() method.""" self.queue = Queue() Thread.__init__(target=self.doWork)
self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription)
if selectedRow == self.methodsTable.selectedRow(): self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription)
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDe...
methodDescription = self._methodDescriptions[selectedMethod]
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDe...
self.methodDescriptionTextView.setString_(methodDescription)
methodDescription = self._methodDescriptions[selectedMethod] self.methodDescriptionTextView.setString_(methodDescription)
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDe...
OSX_VERSION = LooseVersion(os.popen('/usr/bin/sw_vers -productVersion').read().strip())
OSX_VERSION = LooseVersion(tools.sw_vers())
def write_preflight_rm(path, files): fobj = file(path, 'w') fobj.write(PREFLIGHT_RM % dict(files=map(os.path.normpath, files))) fobj.close() os.chmod(path, 0775)
if not hasattr(plist, "CFBundleIdentifier"):
if self.bundle_id: plist.CFBundleIdentifier = self.bundle_id elif not hasattr(plist, "CFBundleIdentifier"):
def setup(self): # XXX rethink self.name munging, this is brittle. self.name, ext = os.path.splitext(self.name) if not ext: ext = ".bundle" bundleextension = ext # misc (derived) attributes self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
os.environ["PYTHONPATH"] = resdir if %(standalone)s: os.environ["PYTHONHOME"] = resdir
if %(standalone)s or %(semi_standalone)s: os.environ["PYTHONPATH"] = resdir if %(standalone)s: os.environ["PYTHONHOME"] = resdir else: pypath = os.getenv("PYTHONPATH", "") if pypath: pypath = ":" + pypath os.environ["PYTHONPATH"] = resdir + pypath
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
self.executable = sys.executable
if self.python: self.executable = self.python else: self.executable = sys.executable
def setup(self): if ((self.standalone or self.semi_standalone) and self.mainprogram is None): raise BundleBuilderError, ("must specify 'mainprogram' when " "building a standalone application.") if self.mainprogram is None and self.executable is None: raise BundleBuilderError, ("must specify either or both of " "'execut...
"lib=", "python=", "semi-standalone")
"lib=", "python=", "semi-standalone", "bundle-id=")
def main(builder=None): if builder is None: builder = AppBuilder(verbosity=1) shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" longopts = ("builddir=", "name=", "resource=", "file=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", "exclude=", "...
selection = self.outlineTreeController.election()
selection = self.outlineTreeController.selection()
def indentNote_(self, sender): selectionPath = self.outlineTreeController.selectionIndexPath() if not selectionPath: NSBeep() return
ssibling = children.objectAtIndex_(index - 1)
sibling = children.objectAtIndex_(index - 1)
def indentNote_(self, sender): selectionPath = self.outlineTreeController.selectionIndexPath() if not selectionPath: NSBeep() return
if gs_root is None:
if gs_root is not None:
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
def selectClass_(self, event):
def outlineViewSelectionDidChange_(self, notification):
def selectClass_(self, event): rowNr = self.classTable.selectedRow() if rowNr == -1: self.clearClassInfo() else: item = self.classTable.itemAtRow_(rowNr) self.setClassInfo(unwrap_object(item))
] + LINK_OPT_STRIP + LIBFFI_LDFLAGS)
] + LIBFFI_LDFLAGS)
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, ex...
] + LINK_OPT_STRIP),
]),
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, ex...
def setUp(self): self.data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) self.mutableData = NSMutableData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) def testInitWithBytes_Length_(self): self.assertEquals(len(self.data), self.data.length(), "len() and -length didn't match.") self.assertEqu...
def assertDataContents(self, d1, d2, rawData): self.assertEquals(len(d1), d1.length(), "d1: len() and -length didn't match.") self.assertEquals(len(d1), len(rawData), "d1: len(<data>) and len(<input>) didn't match.") self.assertEquals(len(d2), d2.length(), "d2: len() and -length didn't match.") self.assertEquals(len(d2...
def setUp(self): self.data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) self.mutableData = NSMutableData.alloc().initWithBytes_length_(rawBytes, len(rawBytes))
bytes = self.data.bytes()
data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) bytes = data.bytes()
def testBytes(self): bytes = self.data.bytes() self.assertEquals(len(bytes), len(rawBytes), "bytes() and rawBytes not equal length.") for i in range(0,len(bytes)): self.assertEquals(rawBytes[i], bytes[i], "byte %s of bytes and rawBytes are not equal." % i)
mutableBytes = self.mutableData.mutableBytes()
mutableData = NSMutableData.dataWithBytes_length_(rawBytes, len(rawBytes)) mutableBytes = mutableData.mutableBytes()
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
except TypeError: pass
except TypeError, r: if str(r).find('right operand length must match slice length') is not 0: raise def testVariousDataLengths(self): """Test data of different lengths. Data of different lengths may be stored in different subclasses within the class cluster. """ testFactor = [1, 10, 1000, 10000, 10000000] for aFactor...
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
self.assertDataContents(data, mutableData, bigRawBytes) mutableBytes = mutableData.mutableBytes() bytes = data.bytes() self.assertEquals(len(bytes), data.length()) self.assertEquals(len(mutableBytes), mutableData.length()) self.assertEquals(bytes, mutableBytes)
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
print "canInitWithRequest_"
def canInitWithRequest_(klass, request): print "canInitWithRequest_" if request.URL().scheme() == PYDOCSCHEME: return True return False
canInitWithRequest_ = objc.selector( canInitWithRequest_, signature=NSURLProtocol.canInitWithRequest_.signature, isClassMethod=True, )
def canInitWithRequest_(klass, request): print "canInitWithRequest_" if request.URL().scheme() == PYDOCSCHEME: return True return False
print "canonical", request.URL().standardizedURL().path()
def canonicalRequestForRequest_(klass, request): print "canonical", request.URL().standardizedURL().path() return request
canonicalRequestForRequest_= objc.selector( canonicalRequestForRequest_, signature=NSURLProtocol.canonicalRequestForRequest_.signature, isClassMethod=True, )
def canonicalRequestForRequest_(klass, request): print "canonical", request.URL().standardizedURL().path() return request
print "start"
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exc...
print 'urlpath', urlpath
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exc...
print 'modpath', modpath
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exc...
print repr(e), str(e)
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exc...
print "stop"
pass
def stopLoading(self): print "stop"
is_framework = os.path.dirname(os.path.dirname(sys.prefix)).endswith('.framework') if is_framework and self.scheme_map['scripts'].startswith(sys.prefix): self.scheme_map['scripts'] = '/usr/local/bin'
scripts = self.scheme_map.get('scripts') if scripts: is_framework = os.path.dirname(os.path.dirname(sys.prefix)).endswith('.framework') if is_framework and scripts.startswith(sys.prefix): self.scheme_map['scripts'] = '/usr/local/bin'
def finalize_options (self): self.set_undefined_options('bdist', ('bdist_base', 'bdist_base')) if self.pkg_base is None: self.pkg_base = os.path.join(self.bdist_base, 'mpkg')
rest2HTML(None, '.', ['Install.txt', 'ReadMe.txt', 'Examples/00ReadMe.txt', 'Installer Package/ReadMe.txt'])
rest2HTML(None, '.', ['Install.txt', 'ReadMe.txt', 'Examples/00ReadMe.txt', 'Installer Package/ReadMe.txt', 'ProjectBuilder Extras/Project Templates/00README.txt'], ) os.rename('ProjectBuilder Extras/Project Templates/00README.html', 'Doc/ProjectBuilder-Templates.html')
def escquotes(val): return val.replace("'", "'\"'\"'")
def getattr(self, attr):
def __getattr__(self, attr):
def getattr(self, attr): return getattr(self.__pyobjc_object__, attr)
return (*pid != nil);
if (PyErr_Occurred()) { return 0; } return 1;
typedef void* PYOBJC_VOIDPTR;
result = { 'meth': lambda : not getattr(ctests, name) }
def test_CheckNSInvoke(self): try: ctests.CheckNSInvoke() except AssertionError: return raise AssertionError, "NSInvocation works!" return test_CheckNSInvoke
def make_test(name): """ Create a method for use in a unittest, the exec is needed to get the proper function name """ result = { 'meth': getattr(ctests, name) } if sys.platform == 'darwin' and name == 'CheckNSInvoke': # There is a bug in Apple's implementation of NSInvocation # surpress the test failure until Apple f...
fp.write('\tif (tmp == NULL) { PyObjCErr_ToObjC(); return nil; }\n')
fp.write('\tif (tmp == NULL) { PyObjCErr_ToObjCWithGILState(&state); return nil; }\n')
fp.write('#ifdef HAVE_BOOL\n')
fp.write('\tif (PyErr_Occurred()) { PyObjCErr_ToObjC(); return nil; }\n')
fp.write('\tif (PyErr_Occurred()) { PyObjCErr_ToObjCWithGILState(&state); return nil; }\n') fp.write('\tPyGILState_Release(state);\n')
fp.write('#ifdef HAVE_BOOL\n')
return WSTConnectionWindowController.alloc().init().autorelease()
return WSTConnectionWindowController.alloc().init()
def connectionWindowController(self): return WSTConnectionWindowController.alloc().init().autorelease()
class ClassesDataSource (NibClassBuilder.AutoBaseClass, NSOutlineViewDataSource, NSTableDataSource): __slots__ = ('_classList', '_classTree', '_methodInfo')
class ClassesDataSource (NibClassBuilder.AutoBaseClass): __slots__ = ('_classList', '_classTree', '_methodInfo', '_classInfo')
def classBundle(cls): framework = NSBundle.bundleForClass_(cls).bundlePath() if framework.startswith(SYSFRAMEWORKS_DIR): framework = framework[len(SYSFRAMEWORKS_DIR):] if framework.endswith('.framework'): framework = framework[:-len('.framework')] return framework
item = wrap_object[super]
item = wrap_object(super)
def showClass(self, cls): # First expand the tree (to make item visible) super = cls.__bases__[0] if super == objc_object: return
item = wrap_object[cls]
item = wrap_object(cls)
def selectClass(self, cls): self.showClass(cls)
Extension("objc._objc", sourceFiles,
Extension("objc._objc", sourceFiles + LIBFFI_SOURCEFILES,
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, ex...
], extra_link_args=[ '-g', '-framework', 'Foundation' ])
] + LIBFFI_CFLAGS, extra_link_args=[ '-g', '-framework', 'Foundation', ] + LINK_OPT_STRIP + LIBFFI_LDFLAGS)
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, ex...
]),
] + LINK_OPT_STRIP),
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, ex...
req_ver = [ 2, 2] if sys.version_info[0] < req_ver[0] or ( sys.version_info[0] == req_ver[0] and sys.version_info[1] < req_ver[1]):
req_ver = (2, 2) if sys.version_info < req_ver:
def subprocess(taskName, cmd, validRes=None): print "Performing task: %s" % (taskName,) fd = os.popen(cmd, 'r') for ln in fd.xreadlines(): sys.stdout.write(ln) res = fd.close() if res is not validRes: sys.stderr.write("Task '%s' failed [%d]\n"%(taskName, res)) sys.exit(1)
if ' ' in os.path.realpath(LIBFFI_SOURCES): print >>sys.stderr, "LIBFFI can not build correctly in a path that contains spaces." print >>sys.stderr, "This limitation includes the entire path (all parents, etc.)" print >>sys.stderr, "Move the PyObjC and libffi source to a path without spaces and build again." sys.exit(1...
def subprocess(taskName, cmd, validRes=None): print "Performing task: %s" % (taskName,) fd = os.popen(cmd, 'r') for ln in fd.xreadlines(): sys.stdout.write(ln) res = fd.close() if res is not validRes: sys.stderr.write("Task '%s' failed [%d]\n"%(taskName, res)) sys.exit(1)
writer.writeln()
def _printClass(self, writer, clsInfo): nibs = clsInfo.nibs if len(nibs) > 1: nibs[-2] = nibs[-2] + " and " + nibs[-1] del nibs[-1] nibs = ", ".join(nibs) writer.writeln("# class defined in %s" % nibs) writer.writeln("class %s(AutoBaseClass):" % clsInfo.name) writer.indent() writer.writeln("# the actual base class is %...
print `container.storedObject()`, `type(container.storedObject())`
def testNSDecimalNumber(self): container = OC_TestIdentity.alloc().init()
elif funcName.startswith('removeObjectFrom') and funcName.endswith('AtIndex_'): return selector(func, signature='v@:i')
def accessor(func): """ Return an Objective-C method object that is conformant with key-value coding and key-value observing. """ if not isinstance(func, type(accessor)): raise ValueError, '%s is not a function'%(func,) argCount = func.func_code.co_argcount funcName = func.func_name if argCount == 3: if funcName.sta...
scripts = [ 'Scripts/nibclassbuilder', ],
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
self.NSObjectInstance = objc.runtime.NSObject.alloc()
self.NSObjectInstance = objc.runtime.NSObject.alloc().init()
def setUp(self): self.NSObjectInstance = objc.runtime.NSObject.alloc()
author = "bbum, RonaldO, SteveM, many others stretching back through the reachtes of time...",
author = "bbum, RonaldO, SteveM, LeleG, many others stretching back through the reaches of time...",
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
def debug(fn): rval = maybeutf(fn) print fn, rval return rval return debug
return maybeutf
def maybeutf(fn): header = file(fn).read(4) if header.startswith(codecs.BOM_UTF8): return 'utf_8' elif header.startswith(codecs.BOM_UTF16_BE): return 'utf_16_be' elif header.startswith(codecs.BOM_UTF16_LE): return 'utf_16_le' # some hacks to guess BOM-less UTF-16 text elif header[0::2] == '\x00\x00' and header[1::2] !=...
print "typedef int (*superfunc)();"
print "typedef int (*superfunc)(int);"
print "typedef int (*superfunc)();"
def doTemplateInfo(aFile, options): if not options.doReverse: basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, FORWARDTRANSLATOR)
def doTemplateInfo(aFile, options, translator): basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, translator)
def doTemplateInfo(aFile, options): if not options.doReverse: basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, FORWARDTRANSLATOR)
specialCommand(path, options)
specialCommand(path, options, translator)
def doSubstitutions(dirName, aName, options): if options.doReverse: translator = REVERSETRANSLATOR else: translator = FORWARDTRANSLATOR path = os.path.join(dirName, aName) if os.path.isdir(path): return specialCommand = SPECIALFILES.get(aName) if specialCommand is not None: specialCommand(path, options) return basen...
doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES): info('Making working copy of %s...', path) tail = aName.split("_", 1)[1] targetFile = os.path.join(dirName, "xcPROJECTNAMExc_%s" % (tail,)) inFile = codecs.EncodedFile(file(path, "rb"), encoding) outFile = codec...
if options.makeWorking and (extension in WORKINGCOPYFILES) and not options.doReverse and aName.split("_", 1)[0] == 'xcPROJECTNAMExc': deletePath(path) else: doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES) and options.doReverse: tail = aName.split("_", 1)[1] tar...
def doSubstitutions(dirName, aName, options): if options.doReverse: translator = REVERSETRANSLATOR else: translator = FORWARDTRANSLATOR path = os.path.join(dirName, aName) if os.path.isdir(path): return specialCommand = SPECIALFILES.get(aName) if specialCommand is not None: specialCommand(path, options) return basen...
lines = bytes.split(u'\n')
lines = bytes.splitlines(True)
def doFileSubstitution(aFile, encoding, translator): _tempFile = tempfile.TemporaryFile() # do the translation debug('encoding is: %s', encoding) inFile = codecs.getreader(encoding)(file(aFile, "rb")) outFile = codecs.getwriter(encoding)(_tempFile) try: for line in inFile: tline = translator(line) outFile.write(tline)...
info("Removing '%s'...", dest) shutil.rmtree(dest)
deletePath(dest)
def main(): parser = build_parser() options, args = parser.parse_args() if not args: parser.print_help() return if len(args) != 2: parser.error("Must specify both a source and destination") return if options.verbose: hdlr = logging.StreamHandler() fmt = logging.Formatter('%(message)s') hdlr.setFormatter(fmt) logger ...
self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.isInstance(PyObjC_TestClassAndInstanceInstanceOverride), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().isInstance(), objc.NO)
self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().pyobjc_instanceMethods.isInstance(), objc.NO)
def testClassAndInstanceInstanceOverrideWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.isInstance(PyObjC_TestClassAndInstanceInstanceOverride), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().isInstance(), objc.NO)
self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.isInstance(PyObjC_TestClassAndInstanceClassOverride), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.pyobjc_classMethods.isInstance(), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceClassOverrideWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.isInstance(PyObjC_TestClassAndInstanceClassOverride), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceSubclass.isInstance(PyObjC_TestClassAndInstanceSubclass), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceSubclass.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceSubclassWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceSubclass.isInstance(PyObjC_TestClassAndInstanceSubclass), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstance.isInstance(PyObjC_TestClassAndInstance), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstance.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstance.isInstance(PyObjC_TestClassAndInstance), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().isInstance(), objc.YES)
"-O0", "-g",
def IfFrameWork(name, packages, extensions, headername=None): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ for pth in ('/System/Library/Frameworks', '/Library/Frameworks'): basedir = os.path.join(pth, name) if os.path.exists(basedir): if (headername is None) or os.path....
>>> MyEnumerator <objective-c class MyEnumerator at 0x350fb0>
... def __del__(self):
NSApp.setDelegate_( AppDelegate.alloc().init() )
delegate = AppDelegate.alloc().init() NSApp.setDelegate_(delegate)
def main(): NSApp = NSApplication.sharedApplication() NSApp.setDelegate_( AppDelegate.alloc().init() ) win = NSWindow.alloc() frame = ((200.0, 300.0), (250.0, 100.0)) win.initWithContentRect_styleMask_backing_defer_ (frame, 15, 2, 0) win.setTitle_ ('HelloWorld') win.setLevel_ (3) # floating window hel = NSButton.a...
class TestTypeStr(unittest.TestCase):
class PyOCTestTypeStr(unittest.TestCase):
def makeCFloat(value): """ C floats and doubles have a different representation, this function returns the result of converting a python float (== C double) to a C float and back. """ return struct.unpack('f',struct.pack('f', value))[0]
class TestSimpleReturns(unittest.TestCase):
class PyOCTestSimpleReturns(unittest.TestCase):
def testAll(self):
class TestSimpleArguments(unittest.TestCase):
class PyOCTestSimpleArguments(unittest.TestCase):
def testStruct2(self): obj = OC_TestClass1.new()
class TestByReferenceArguments(unittest.TestCase):
class PyOCTestByReferenceArguments(unittest.TestCase):
def testStruct2(self): self.assertEquals(self.obj.dummy2Arg_(((1,2,3,4),)), ((8,6,4,2),))
class TestDecimalNumber (unittest.TestCase):
if isinstance(NSDecimalNumber.decimalNumberWithString_(u'1.00'), NSDecimalNumber): class TestDecimalNumber (unittest.TestCase):
def testPropertyList2(self): d = NSMutableDictionary.dictionary()
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00") self.assert_(isinstance(o, NSDecimalNumber))
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
self.assert_(isinstance(o, NSDecimalNumber))
else: class TestDecimalNumber (unittest.TestCase): def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00") self.assert_(isinstance(o, NSDecimal))
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
'%(varname)s',
'&%(varname)s',
def is_id(typestr): # Remove protocol 'declarations' (id <NSObject, NSString>) typestr = PROT_MATCHER.sub('', typestr).strip() if typestr == 'id': return 1 elif typestr[-1] != '*': return 0 try: objc.lookup_class(typestr[:-1]) return 1 except: return 0
fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]})
fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS|METH_KEYWORDS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]})
def process_list(fp, lst): ok_count = 0 total_count = 0 funcs=[] fp.write(HDR) for l in lst: l = l.strip() if not l: continue if l[0] == '#': continue total_count += 1 try: sys.stderr.write("Converting '%s' ..."%l.strip()) sys.stderr.flush() funcs.append((process_function(fp, l), l)) sys.stderr.write("done\n") sys.s...
executable=${execdir}/%(executable)s
executable="${execdir}/%(executable)s"
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
main=${resdir}/%(mainprogram)s PYTHONPATH=$resdir
main="${resdir}/%(mainprogram)s" PYTHONPATH="$resdir"
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
) CONVENIENCE_METHODS['removeObject:'] = ( ('remove', lambda self, elem: self.removeObject_(container_wrap(elem))),
def popitem_setObject_forKey_(self): try: k = self[iter(self).next()] except StopIteration: raise KeyError, "popitem on an empty %s" % (type(self).__name__,) else: return (k, self[k])
module = __import__(modName)
try: module = __import__(modName) except ImportError, msg: print "SKIP %s: %s"%(modName, msg) continue
def importExternalTestCases(pathPattern="test_*.py", root=".", package=None): """ Import all unittests in the PyObjC tree starting at 'root' """ testFiles = recursiveGlob(root, pathPattern) testModules = map(lambda x:x[len(root)+1:-3].replace('/', '.'), testFiles) if package is not None: testModules = [(package + '.' ...
if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- cannot test" % self.build_dir) return
def test (self): if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- cannot test" % self.build_dir) return
print 'checking', theURL, cachePolicy, timeoutInterval
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain(...
print 'checked'
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain(...
print 'got res'
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain(...
print 'checkURL', self, anURL
def checkURL_(self, anURL): print 'checkURL', self, anURL if anURL is None: return anURL host = anURL.host() if host is None: return anURL if encodings.idna.uace_prefix in host: uni = u'.'.join([encodings.idna.ToUnicode(part) for part in host.split(u'.')]) shouldDeny = self.HOSTS.get(uni) if shouldDeny is None: res = [...
print "*** Restored handlers and resignaling." % signum
print "*** Restored handlers and resignaling."
def dumpHandler(signum, frame): resetFatalSignals() print "*** Handling fatal signal '%d'." % signum traceback.print_stack(frame) print "*** Restored handlers and resignaling." % signum os.kill(os.getpid(), signum)
self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode(fourchar))
if sys.byteorder == 'little': self.assertEquals("'xftr'", Foundation.NSFileTypeForHFSTypeCode(fourchar)) else: self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode(fourchar))
def testNSFileTypeForHFSTypeCode(self): self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode('rtfx'))
- Attribute or accessor 'key'
- Accessor or attribute 'key' - Accessor or attribute 'isKey'
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these e...
m = getattr(obj, "get" + key.capitalize())
m = getattr(obj, "get" + keyCaps(key))
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these e...
try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m
for keyName in (key, "is" + keyCaps(key)): try: m = getattr(obj, keyName) except AttributeError: continue if isinstance(m, types.MethodType) and m.im_self is obj: return m()
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these e...
elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m
elif isinstance(m, objc.selector) and m.self is obj: return m()
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these e...
except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
try: return getattr(obj, "_" + key) except AttributeError: raise KeyError, "Key %s does not exist" % (key,)
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these e...
return getattr(obj, SETVALUEFORKEY)(value, key)
getattr(obj, SETVALUEFORKEY)(value, key) return
def setKey(obj, key, value): """ Set the attribute referenced by 'key' to 'value'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accessors are tried (in this order): - Accessor 'setKey' - Accessor 'set_key' - Attribute '_key' - Attribute 'key' Raises Key...