当前位置: 首页>>代码示例>>Python>>正文


Python Foundation.NSDictionary类代码示例

本文整理汇总了Python中Foundation.NSDictionary的典型用法代码示例。如果您正苦于以下问题:Python NSDictionary类的具体用法?Python NSDictionary怎么用?Python NSDictionary使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NSDictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: makeDragImage

    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame)-20)
        uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(point,
              NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(NSLocalizedString("Drop outside to remove from conference", "Audio session label")).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [sess.hasStreamOfType("audio") for sess in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers]
            if self.delegate.transferEnabled:
                text = NSLocalizedString("Drop this over a session or contact", "Audio session label") if len(audio_sessions) > 1 else NSLocalizedString("Drop this over a contact to transfer", "Audio session label")
            else:
                text = NSLocalizedString("Drop this over a session to conference", "Audio session label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r, NSCompositeSourceOver, 0.5)

        image.unlockFocus()
        return image
开发者ID:uditha-atukorala,项目名称:blink,代码行数:53,代码来源:AudioSession.py

示例2: rename_project

def rename_project(project_dir, new_project_name, bundle_id):

    search_string = "find %s -name *.xcodeproj" % project_dir
    name_to_change = os.popen(search_string).readlines()[0].rstrip().split("/")[-1].split(".")[0]

    project_directories = os.walk(
        project_dir
    )  # [y for x in os.walk(project_dir) for y in glob(os.path.join(x[0], ''))]

    for directory in project_directories:
        if "git" in directory[0]:
            continue
        expression = re.compile(re.escape(name_to_change), re.IGNORECASE)
        new_directory = expression.sub(new_project_name, directory[0])
        print "creating %s" % new_directory
        os.makedirs(new_directory)
        files = [os.path.join(directory[0], x) for x in directory[2]]
        for dir_file in files:
            new_filename = expression.sub(new_project_name, dir_file)
            shutil.copyfile(dir_file, new_filename)
            replace_all(new_filename, name_to_change, new_project_name)

    plist_files = os.popen("find %s -name *Info.plist" % project_dir)

    for plist_file in plist_files:
        plist_file = plist_file.rstrip()
        plist = NSDictionary.dictionaryWithContentsOfFile_(plist_file)
        plist["CFBundleIdentifier"] = bundle_id
        plist.writeToFile_atomically_(plist_file, True)
开发者ID:akfreas,项目名称:FastApp,代码行数:29,代码来源:fastApp.py

示例3: GetAppInfo

  def GetAppInfo(self, user_info):
    """Grabs the application info from the user_info dictionary.
    Args:
      user_info: dictionary of application info
    Returns:
      tuple of bundle_id, app_version, app_path
    """
    bundle_id, app_version, app_path = None, None, None
    try:
      bundle_id = user_info['NSApplicationBundleIdentifier']
    except KeyError:
      # Malformed applications may not have NSApplicationBundleIdentifier
      # Return NSApplicationName instead
      logging.error('Error reading bundle identifier: %s', user_info)
      bundle_id = user_info['NSApplicationName']
    try:
      app_path = user_info['NSApplicationPath']
    except KeyError:
      # Malformed applications may not have NSApplicationPath
      logging.error('Error reading application path: %s', user_info)
    if app_path:
      try:
        app_info_plist = NSDictionary.dictionaryWithContentsOfFile_(
            '%s/Contents/Info.plist' % app_path)
        if app_info_plist:
          app_version = app_info_plist['CFBundleVersion']
      except KeyError:
        logging.error('Error reading application version from %s', app_path)

    return bundle_id, app_version, app_path
开发者ID:carriercomm,项目名称:munki-pkg-projects,代码行数:30,代码来源:ApplicationUsage.py

示例4: read_aae_file

def read_aae_file(path):

    plist = NSDictionary.dictionaryWithContentsOfFile_(path)
    
    if plist["adjustmentFormatIdentifier"] != "com.apple.photo":
        print "-- bad format identifier:", plist["adjustmentFormatIdentifier"]
        return None, None
    
    data = plist["adjustmentData"]
    
    d = ipaPASS.archiveFromData_error_(data, None)
    
    adjustments = d["adjustments"]
    orientation = d["metadata"]["orientation"]
    
    effect_names = [ d_["settings"]["effectName"] for d_ in d["adjustments"] if d_["identifier"] == "Effect"]
    
    if len(effect_names) == 0:
        print "-- no effect name"
        return None, None
    
    filter_name = "CIPhotoEffect" + effect_names[0]
    print "-- filter:", filter_name

    return filter_name, orientation
开发者ID:nst,项目名称:filters,代码行数:25,代码来源:filters.py

示例5: __init__

    def __init__(self):
        """Create a new Preferences object from the current settings.

        Examples:

            >>> preferences = Preferences()
            >>> keys = ['latexViewer', 'latexEngine', 'latexUselatexmk',
            ...         'latexVerbose', 'latexDebug', 'latexAutoView',
            ...         'latexKeepLogWin', 'latexEngineOptions']
            >>> all([key in preferences.prefs for key in keys])
            True

        """
        tm_preference_file = ('{}.plist'.format(environ['TM_APP_IDENTIFIER'])
                              if 'TM_APP_IDENTIFIER' in environ
                              else 'com.macromates.textmate.plist')
        self.default_values = {
            'latexAutoView': 1,
            'latexEngine': "pdflatex",
            'latexEngineOptions': "",
            'latexVerbose': 0,
            'latexUselatexmk': 0,
            'latexViewer': "TextMate",
            'latexKeepLogWin': 1,
            'latexDebug': 0,
        }
        self.prefs = self.default_values.copy()
        tm_prefs = NSDictionary.dictionaryWithContentsOfFile_(
            "{}/Library/Preferences/{}".format(environ["HOME"],
                                               tm_preference_file))
        # Only save the values we really need
        for key in self.prefs:
            if key in tm_prefs:
                self.prefs[key] = tm_prefs[key]
开发者ID:kt10aan,项目名称:latex.tmbundle,代码行数:34,代码来源:tmprefs.py

示例6: loadGlyphsInfo

def loadGlyphsInfo():
	try:
		GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs2")
		if GlyphsPath is None:
			GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs")
		if GlyphsPath is None:
			GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.Glyphs")
		if GlyphsPath is None:
			GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.GlyphsMini")
		GlyphsPath = GlyphsPath.path()
	except:
		return
	
	if GlyphsPath is not None:
		GlyphsInfoPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml"
		WeightCodesPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/weights.plist"
	
	parseGlyphDataFile(GlyphsInfoPath)
	
	CustomGlyphsInfoPath = applicationSupportFolder()
	if CustomGlyphsInfoPath:
		CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_("/Info/GlyphData.xml")
		if os.path.isfile(CustomGlyphsInfoPath):
			parseGlyphDataFile(CustomGlyphsInfoPath)
	
	global weightCodes
	weightCodes = NSDictionary.alloc().initWithContentsOfFile_(WeightCodesPath)
开发者ID:andreirobu,项目名称:Glyphs-Scripts-2,代码行数:27,代码来源:Glyphs+Import.py

示例7: readGlyphsFile

def readGlyphsFile(filePath):
	print "Import Glyphs File"
	pool = NSAutoreleasePool.alloc().init()
	GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)
	if GlyphsDoc is None:
		print "Could not load .glyphs file."
		pool.drain()
		return
	loadGlyphsInfo()
	from FL import fl, Font
	folder, base = os.path.split(filePath)
	base = base.replace(".glyphs", ".vfb")
	dest = os.path.join(folder, base)
	f = Font(  )
	fl.Add(f)
	global convertName
	try:
		convertName = GlyphsDoc["disablesNiceNames"] != None
	except:
		pass
	if not setFontInfo(f, GlyphsDoc):
		return False
	readGlyphs(f, GlyphsDoc)
	readKerning(f, GlyphsDoc)
	setLegacyNames(f)
	readFeatures(f, GlyphsDoc)
	
	fl.UpdateFont()
	f.modified = 0
	pool.drain()
开发者ID:andreirobu,项目名称:Glyphs-Scripts-2,代码行数:30,代码来源:Glyphs+Import.py

示例8: main

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 = logging.getLogger()
        logger.addHandler(hdlr)
        logger.setLevel(logging.INFO)
    else:
        logging.basicConfig()

    source, dest = map(os.path.normpath, args)
    if source == dest:
        parser.error("Source and destination may not be the same.")
        return
    
    if os.path.exists(dest):
        if options.killDest:
            deletePath(dest)
        else:
            parser.error("Destination already exists.  -k to destroy or use different destination.")
            return
    
    if options.templateFile and (not os.path.exists(options.templateFile)):
        parser.error("Template file specified, but does not exist.")
        return    

    info("Copying from '%s' to '%s'....", source, dest)
    shutil.copytree(source, dest)

    simplePathWalker(dest, killNasties, options)
    simplePathWalker(dest, doSubstitutions, options)
    if options.templateFile:
        options.template = NSDictionary.dictionaryWithContentsOfFile_(options.templateFile)
        if not options.template:
            parser.error("Failed to read template: %s" % options.templateFile)
            sys.exit(1)
        filesToRename = options.template['FilesToRename']
        for k in filesToRename:
            leftPath = os.path.join(dest, k)
            rightPath = os.path.join(dest, filesToRename[k])
            if not options.doReverse:
                info("rename %s ==> %s", rightPath, leftPath)
                os.rename(rightPath, leftPath)
            else:
                info("rename %s ==> %s", leftPath, rightPath)
                os.rename(leftPath, rightPath)                
开发者ID:Joey-Lee,项目名称:pyobjc,代码行数:58,代码来源:project-tool.py

示例9: load_puzzles

def load_puzzles():
    if len(sys.argv) == 1:
        puzzles = load_puzzles_from_ipa()
        if not puzzles:
            print "Couldn't find the Lights Off app in your iTunes library. Please specify a valid puzzles.plist file path."
            sys.exit(1)
        return puzzles
    if not os.path.isfile(sys.argv[1]):
        print "Please specify a valid puzzles.plist file path."
        sys.exit(1)
    return NSDictionary.dictionaryWithContentsOfFile_(sys.argv[1])['puzzles']
开发者ID:davea,项目名称:lightspad,代码行数:11,代码来源:import_puzzles.py

示例10: __init__

    def __init__(self, plist_path=BOOKS_PLIST_PATH):
        if FMT_BINARY is None:
            if not NSDictionary is None:
                self.plist = NSDictionary.alloc().initWithContentsOfFile_(plist_path)
            else:
                self.plist = Ibex._ibex_plutil_read_xml(plist_path)
        else:
            self.plist = readPlist(plist_path)

        if self.plist is None:
            raise IbexError('%s: failed to read property list' % plist_path)
开发者ID:moretension,项目名称:ibex,代码行数:11,代码来源:ibex.py

示例11: readGlyphsFile

def readGlyphsFile(filePath):
    print "Import Glyphs File"
    pool = None
    try:
        from Foundation import NSAutoreleasePool, NSDictionary
    except ImportError:
        # on Windows, PyObjC is not available
        with open(filePath, "rb") as f:
            data = f.read()
        if data.startswith("<?xml"):
            # use the built-in plistlib module for XML plist
            from plistlib import readPlistFromString

            GlyphsDoc = readPlistFromString(data)
        else:
            # use glyphsLib's Parser for ASCII plist.
            # Download it from: https://github.com/googlei18n/glyphsLib
            from glyphsLib.parser import Parser

            GlyphsDoc = Parser(dict_type=dict).parse(data)
    else:
        # on OS X, use NSDictionary
        pool = NSAutoreleasePool.alloc().init()
        GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)

    if not GlyphsDoc:
        print "Could not load .glyphs file."
        if pool:
            pool.drain()
        return

    from FL import fl, Font

    folder, base = os.path.split(filePath)
    base = base.replace(".glyphs", ".vfb")
    dest = os.path.join(folder, base)
    f = Font()
    fl.Add(f)
    global convertName
    try:
        convertName = GlyphsDoc["disablesNiceNames"] != None
    except:
        pass
    if not setFontInfo(f, GlyphsDoc):
        return False
    readGlyphs(f, GlyphsDoc)
    readKerning(f, GlyphsDoc)
    setLegacyNames(f)
    readFeatures(f, GlyphsDoc)

    fl.UpdateFont()
    f.modified = 0
    if pool:
        pool.drain()
开发者ID:schriftgestalt,项目名称:Glyphs-Scripts,代码行数:54,代码来源:Glyphs+Import.py

示例12: load_puzzles_from_ipa

def load_puzzles_from_ipa():
    for ipa in glob("/Users/*/Music/iTunes/iTunes*/Mobile Applications/Lights Off*ipa"):
        try:
            z = ZipFile(open(ipa, "r"))
            with NamedTemporaryFile() as f:
                f.write(z.read('Payload/Lights Off.app/puzzles.plist'))
                f.flush()
                print f.name
                return NSDictionary.dictionaryWithContentsOfFile_(f.name)['puzzles']
        except:
            continue
    return None
开发者ID:davea,项目名称:lightspad,代码行数:12,代码来源:import_puzzles.py

示例13: paramsDictionary

 def paramsDictionary(self):
     self.fCutoff = min(self.fCutoff, self.sampleRate/2.)
     
     return NSDictionary.dictionaryWithObjectsAndKeys_(
                 self.mean, BLWN_MEAN_KEY, 
                 self.var, BLWN_VAR_KEY, 
                 self.fCutoff, BLWN_FREQ_KEY, 
                 self.nPoles, BLWN_NPOLES_KEY, 
                 self.sampleRate, BLWN_SAMPLE_RATE_KEY, 
                 self.length, BLWN_LENGTH_KEY, 
                 pickle.dumps(self.rSource.get_state()[:3]), BLWN_RANDOM_STATE_KEY, 
                 numpy.__version__, 'numpyVersion', 
                 None)
开发者ID:JonnyCode,项目名称:JCcode,代码行数:13,代码来源:BandLimitedWhiteNoiseGenerator.py

示例14: GetPlist

def GetPlist(plist):
  """Returns a dictionary from a given plist.

  Args:
    plist: plist to operate on
  Returns:
    Contents of the plist as a dict-like object.
  Raises:
    MissingImportsError: if NSDictionary is missing
  """
  if NSDictionary:
    return NSDictionary.dictionaryWithContentsOfFile_(plist)
  else:
    raise MissingImportsError('NSDictionary not imported successfully.')
开发者ID:SmithersJr,项目名称:macops,代码行数:14,代码来源:gmacpyutil.py

示例15: refreshLibrary

    def refreshLibrary(self):
        if not self.history:
            return

        settings = SIPSimpleSettings()
        own_icon_path = settings.presence_state.icon
        selected_icon = None
        def md5sum(filename):
            md5 = hashlib.md5()
            with open(filename,'rb') as f:
                for chunk in iter(lambda: f.read(128*md5.block_size), b''):
                    md5.update(chunk)
            return md5.hexdigest()

        if os.path.exists(self.storage_folder):
          files = os.listdir(self.storage_folder)
        else:
          files = []
        array = NSMutableArray.array()
        knownFiles = set()
        for item in self.contentArrayController.arrangedObjects():
            knownFiles.add(unicode(item.objectForKey_("path")))

        seen_md5sum = {}
        i = 0
        for f in files:
            if not f.startswith('user_icon') and not f.startswith('photo') and f != 'default_user_icon.tiff':
                continue
            p = os.path.normpath(self.storage_folder + "/" + f)
            if p not in knownFiles:
                photos_folder = unicodedata.normalize('NFC', self.storage_folder)
                filename = os.path.join(photos_folder, f)
                checksum = md5sum(filename)
                try:
                    seen_md5sum[filename]
                except KeyError:
                    seen_md5sum[filename] = checksum
                    image = NSImage.alloc().initWithContentsOfFile_(p)
                    if not image:
                        continue
                    item = NSDictionary.dictionaryWithObjectsAndKeys_(image, "picture", p, "path")
                    array.addObject_(item)
                    if own_icon_path is not None and filename == unicode(own_icon_path):
                        selected_icon = i
                    i += 1

        if array.count() > 0:
            self.contentArrayController.addObjects_(array)
            if selected_icon is not None:
                self.libraryCollectionView.setSelectionIndexes_(NSIndexSet.indexSetWithIndex_(selected_icon))
开发者ID:bitsworking,项目名称:blink-cocoa,代码行数:50,代码来源:PhotoPicker.py


注:本文中的Foundation.NSDictionary类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。