def selectLanguage(macOSVersion): if macOSVersion > 10.11: locale = NSLocale.currentLocale() languageCode = NSLocale.languageCode(locale) id = languageCode countryCode = NSLocale.countryCode(locale) localeIdentifier = NSLocale.localeIdentifier(locale) else: cmd = ["defaults", 'read', '.GlobalPreferences', 'AppleLocale'] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = proc.communicate() if proc.returncode: id = "en" localeIdentifier = "en_US" languageCode = id else: localeIdentifier = output id = languageCode = output.split('_')[0] # # Special cases for Apple's SU. # if languageCode == "pt" and localeIdentifier == "pt_PT": id = localeIdentifier elif languageCode == "es" and localeIdentifier == "es_419": id = localeIdentifier elif languageCode == "zh": if localeIdentifier == "zh_TW": id = localeIdentifier else: id = "zh_CN" return getICUName(id)
def current_locale(self) -> str: """ Detect the OS default language. """ # Guess the encoding if MAC: # Always UTF-8 on macOS encoding = "UTF-8" else: encoding = locale.getdefaultlocale()[1] or "" # Guess the current locale name if WINDOWS: import ctypes l10n_code = ( ctypes.windll.kernel32.GetUserDefaultUILanguage( ) # type: ignore ) l10n = locale.windows_locale[l10n_code] elif MAC: from Foundation import NSLocale l10n_code = NSLocale.currentLocale() l10n = NSLocale.localeIdentifier(l10n_code) else: l10n = locale.getdefaultlocale()[0] or "" return ".".join([l10n, encoding])
def current_locale(self): """ Detect the OS default language. """ encoding = locale.getdefaultlocale()[1] if AbstractOSIntegration.is_windows(): l10n_code = ctypes.windll.kernel32.GetUserDefaultUILanguage() l10n = locale.windows_locale[l10n_code] elif AbstractOSIntegration.is_mac(): l10n_code = NSLocale.currentLocale() l10n = NSLocale.localeIdentifier(l10n_code) encoding = 'UTF-8' else: l10n = locale.getdefaultlocale()[0] return '.'.join([l10n, encoding])
def current_locale(self) -> str: """ Detect the OS default language. """ encoding = locale.getdefaultlocale()[1] if WINDOWS: l10n_code = ctypes.windll.kernel32.GetUserDefaultUILanguage() l10n = locale.windows_locale[l10n_code] elif MAC: l10n_code = NSLocale.currentLocale() l10n = NSLocale.localeIdentifier(l10n_code) encoding = "UTF-8" else: l10n = locale.getdefaultlocale()[0] return ".".join([l10n, encoding])
def preferredLanguages(self): if platform == 'darwin': return NSLocale.preferredLanguages() or None elif platform == 'win32': def wszarray_to_list(array): offset = 0 while offset < len(array): sz = ctypes.wstring_at( ctypes.addressof(array) + offset * 2) if sz: yield sz offset += len(sz) + 1 else: break num = ctypes.c_ulong() size = ctypes.c_ulong(0) if (GetUserPreferredUILanguages( MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value): buf = ctypes.create_unicode_buffer(size.value) if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)): return wszarray_to_list(buf) return None else: # POSIX lang = locale.getlocale()[0] return lang and [lang.replace('_', '-')]
def preferredLanguages(self): if platform=='darwin': return NSLocale.preferredLanguages() or None elif platform=='win32': def wszarray_to_list(array): offset = 0 while offset < len(array): sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2) if sz: yield sz offset += len(sz)+1 else: break num = ctypes.c_ulong() size = ctypes.c_ulong(0) if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value): buf = ctypes.create_unicode_buffer(size.value) if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)): return wszarray_to_list(buf) return None else: # POSIX lang = locale.getlocale()[0] return lang and [lang.replace('_','-')]
def get_country_code(): try: if platform == 'linux': l = locale.getdefaultlocale()[0] if l is not None: return l.split(LOCALE_SPLITCHAR, 1)[1][:2].upper() elif platform == 'mac': from Foundation import NSAutoreleasePool, NSLocale, NSLocaleCountryCode pool = NSAutoreleasePool.alloc().init() try: return NSLocale.currentLocale().objectForKey_(NSLocaleCountryCode).upper() finally: del pool else: from dropbox.win32.version import WIN2K, WINDOWS_VERSION if WINDOWS_VERSION != WIN2K: GEO_ISO2 = 4 nation = ctypes.windll.kernel32.GetUserGeoID(16) buf = ctypes.create_string_buffer(20) if ctypes.windll.kernel32.GetGeoInfoA(nation, GEO_ISO2, ctypes.byref(buf), ctypes.sizeof(buf), 0): return buf.value.upper() except Exception: unhandled_exc_handler() return 'US'
def current_locale(self) -> str: """ Detect the OS default language. """ encoding = locale.getdefaultlocale()[1] or "" if WINDOWS: l10n_code = ( ctypes.windll.kernel32.GetUserDefaultUILanguage() # type: ignore ) l10n = locale.windows_locale[l10n_code] elif MAC: l10n_code = NSLocale.currentLocale() l10n = NSLocale.localeIdentifier(l10n_code) encoding = "UTF-8" else: l10n = locale.getdefaultlocale()[0] or "" return ".".join([l10n, encoding])
def __init__(self): if platform.system() == "Darwin": self.current_language = list( NSLocale.preferredLanguages())[0][:-3].lower() else: self.current_language = locale.getdefaultlocale()[0][:-3].lower() self.check_availability()
def selectLanguage(): locale = NSLocale.currentLocale() languageCode = NSLocale.languageCode(locale) id = languageCode countryCode = NSLocale.countryCode(locale) localeIdentifier = NSLocale.localeIdentifier(locale) # # Special cases for Apple SU. # if languageCode == "pt" and localeIdentifier == "pt_PT": id = localeIdentifier elif languageCode == "es" and localeIdentifier == "es_419": id = localeIdentifier elif languageCode == "zh": if localeIdentifier == "zh_TW": id = localeIdentifier else: id = "zh_CN" return getICUName(id)
def preferred(self): if platform == "darwin": from Foundation import NSLocale return [x.lower() for x in NSLocale.preferredLanguages()] or None elif platform == "win32": def wszarray_to_list(array): offset = 0 while offset < len(array): sz = ctypes.wstring_at(ctypes.addressof(array) + offset * 2) if sz: yield sz offset += len(sz) + 1 else: break # https://msdn.microsoft.com/en-us/library/windows/desktop/dd318124%28v=vs.85%29.aspx import ctypes MUI_LANGUAGE_ID = 4 MUI_LANGUAGE_NAME = 8 GetUserPreferredUILanguages = ctypes.windll.kernel32.GetUserPreferredUILanguages num = ctypes.c_ulong() size = ctypes.c_ulong(0) if ( GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value ): buf = ctypes.create_unicode_buffer(size.value) if GetUserPreferredUILanguages( MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size) ): return [x.lower() for x in wszarray_to_list(buf)] return None else: # POSIX import locale lang = locale.getdefaultlocale()[0] return lang and [lang.replace("_", "-").lower()]
def preferred(self): if platform == 'darwin': from Foundation import NSLocale return [x.lower() for x in NSLocale.preferredLanguages()] or None elif platform == 'win32': def wszarray_to_list(array): offset = 0 while offset < len(array): sz = ctypes.wstring_at( ctypes.addressof(array) + offset * 2) if sz: yield sz offset += len(sz) + 1 else: break # https://msdn.microsoft.com/en-us/library/windows/desktop/dd318124%28v=vs.85%29.aspx import ctypes MUI_LANGUAGE_ID = 4 MUI_LANGUAGE_NAME = 8 GetUserPreferredUILanguages = ctypes.windll.kernel32.GetUserPreferredUILanguages num = ctypes.c_ulong() size = ctypes.c_ulong(0) if (GetUserPreferredUILanguages( MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value): buf = ctypes.create_unicode_buffer(size.value) if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)): return [x.lower() for x in wszarray_to_list(buf)] return None else: # POSIX import locale lang = locale.getdefaultlocale()[0] return lang and [lang.replace('_', '-').lower()]
def getLanguage(config): """ If the language has been specified explicitly in the config, return it. Otherwise look it up via NSLocale on OS X. Failing that, return "en" @param config: The configuration object to examine @type config: ConfigDict @return: The two-letter language code -- on OS X the supported ones are: de, en, es, fr, it, ja, ko, nl @rtype: C{str} """ if config.Localization.Language: return config.Localization.Language try: language = NSLocale.preferredLanguages()[0] except: language = "en" return language
def getLanguage(config): """ If the language has been specified explicitly in the config, return it. Otherwise look it up via NSLocale on OS X. Failing that, return "en" @param config: The configuration object to examine @type config: ConfigDict @return: The language code -- on OS X the supported ones are: de, en, es, fr, it, ja, ko, nl, zh_CN, zh_TW @rtype: C{str} """ if config.Localization.Language: return config.Localization.Language try: language = NSLocale.preferredLanguages()[0] language = _remapLanguageCode(language) except: language = "en" return language
def main(): # # UNIX command 'date' # if False: pr("UNIX command 'date'") cmd = 'date' r = commands.getoutput(cmd) pr("UNIX date command", r) pr("r.split()[4]", r.split()[4]) # # Python datetime # if False: pr("Python datetime") pr('datetime.datetime.now() ', datetime.datetime.now() ) t = datetime.datetime.now() - datetime.datetime.utcnow() pr("datetime.now() - datetime.utcnow()", t) pr("timedelta(-1, 68399, 999998) == timedelta(-1, 68400, 0)", datetime.timedelta(-1, 68399, 999998) == datetime.timedelta(-1, 68400, 0) ) pr("datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 1)", datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 1)) # print datetime.timedelta(hours=-5, seconds = 0) < t < datetime.timedelta(hours=-5, seconds = 1) #False # print datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 0) #True t2 = datetime.datetime.utcnow() + t pr('strftime("%a %Y.%m.%d %I:%M:%S")', t2.strftime("%a %Y.%m.%d %I:%M:%S") ) d3 = datetime.datetime(2011, 7, 29, 23, 46, 39) pr( 'str(d3)', str(d3) ) prr("_DATETIME_to_python(d3)", _DATETIME_to_python(d3)) # # Cocoa (Foundation) NSDate, NSCalendar, NSDateFormatter, etc. # pr("Cocoa (Foundation) NSDate, etc.") date1 = NSDate.dateWithTimeIntervalSinceReferenceDate_(333675999.713839) date2 = NSDate.dateWithTimeIntervalSinceReferenceDate_(333675999.713839 - 6 * 30 * 24 *60 * 60) date3 = NSDate.distantPast() # dateWithTimeIntervalSinceNow_(0- 6 * 30 * 24 *60 * 60) pr( "date1" , date1) pr( "date2" , date2) pr( "date3" , date3) prr("_DATETIME_to_python(date1)", _DATETIME_to_python(date1)) # pr( "str(date1) ", str(date1) ) currentCalendar = NSCalendar.currentCalendar() # # time zones # def pr_tz(l, tz): s = tz.secondsFromGMT() / (60 * 60) print "%s:\n\n %r (%s) offset %d hours%s\n" % (l,tz.name(), tz.abbreviation(), s , " (**local**)" if "Local Time Zone " in tz.description() else "") # print tz.description() # timeZone_Current = currentCalendar.timeZone() # # pr_tz('timeZone_Local', timeZone_Local) # # # s = timeZone_GMT.secondsFromGMT() / (60 * 60) # # pr("timeZone_GMT", str(timeZone_GMT) + " offset: %d hours" % s ) # pr( "timeZone_Local.isDaylightSavingTime()", timeZone_Local.isDaylightSavingTime() ) # determines whether daylight saving time is currently in effect. # pr( "timeZone_Local.daylightSavingTimeOffset()", timeZone_Local.daylightSavingTimeOffset() ) # determines the current daylight saving time offset. For most time zones this is either zero or one. # pr( "timeZone_Local.nextDaylightSavingTimeTransition()", timeZone_Local.nextDaylightSavingTimeTransition()) # Formatting for Machines: Controlled Environment Needed # # It is a whole other matter if you need to create a date string according to # the specification of a certain file format or API. # In such a case, you usually have to follow a very strict spec to # make sure the other party can read the string you are generating. # By default, NSDateFormatter uses the user’s current calendar and time zone, # which are possibly different from the requirements. # Most file formats and web APIs use the western, Gregorian calendar, # so we need to make sure that our date formatter uses it, too. dateFormatter_Local = NSDateFormatter.alloc().init() dateFormatter_Current = NSDateFormatter.alloc().init() dateFormatter_GMT = NSDateFormatter.alloc().init() dateFormatter_GMT5 = NSDateFormatter.alloc().init() dateFormatter_NY = NSDateFormatter.alloc().init() # dateFormatter_Local.__name__ = 'dateFormatter_Local' formatter_names = [ ] time_zones = [ ('Local' , NSTimeZone.localTimeZone()) , ('Current' , currentCalendar.timeZone()) , ('GMT' , NSTimeZone.timeZoneForSecondsFromGMT_(0)) , ('GMT5' , NSTimeZone.timeZoneForSecondsFromGMT_(-18000)) , ('NY' , NSTimeZone.timeZoneWithName_(u'America/New_York')) , ('System', NSTimeZone. systemTimeZone() ) , ('G' , NSTimeZone.timeZoneWithAbbreviation_(u'GMT')) ] dx = [ {'name' : n , 'tz' : tz, 'df' : NSDateFormatter.alloc().init() } for n, tz in time_zones ] s = [ "%12s: %s" % (x['name'], "%r (%s) %s%s" % tz_pr(x['tz']) ) for x in dx ] print "\n".join(s) print def eq_classes(dx, k): # z = [] d = {} for n, x in enumerate(dx): if x[k] not in d: d[x[k]] = set([ x['name'] ]) for m in range(n): y = dx[m] if x != y and x[k] == y[k]: # z.append((x['name'], y['name'])) if x[k] in d: d[x[k]].add( x['name'] ) # else: # d[x[k]] = set([ x['name'] ]) if y[k] in d: d[y[k]].add( y['name'] ) # else: # d[y[k]] = [ y['name'] ] return d print "eq_classes of dx (under tz):" print eq_classes_dx = eq_classes(dx, 'tz') print "\n".join([ "%20s: %s" % (x.name(), list(eq_classes_dx[x])) for x in eq_classes_dx]) print eq_names = [ list(eq_classes_dx[x])[0] for x in eq_classes_dx ] dx = [ z for z in dx if z['name'] in eq_names ] s = [ "%12s: %s" % (x['name'], "%r (%s) %s%s" % tz_pr(x['tz']) ) for x in dx ] print "\n".join(s) print # print "\n".join([ "%20s: %r" % [k for k in x] for x in dx ]) # format string (formatter) # format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss VVVV" # ==> "AD 2011-07-29 19:46:39 United States (New York)" # format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss VVV" # ==> " 'Fri 2011-07-29 19:46:39 GMT-04:00' format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss z" # ==> 'Fri 2011-07-29 19:46:39 EDT') or 'EST', or 'GMT-04:00' map ( lambda y : NSDateFormatter.setDateFormat_(y, format_string) , [x['df'] for x in dx] ) # locale locale = NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX") pr("NSDate.date()", NSDate.date()) map ( lambda y : NSDateFormatter.setLocale_(y, locale) , [x['df'] for x in dx] ) map ( lambda y : NSDateFormatter.setTimeZone_(y[0], y[1]) , [ (x['df'], x['tz']) for x in dx] ) pr('descriptionWithCalendarFormat:timeZone:locale', date1.descriptionWithCalendarFormat_timeZone_locale_( None, None, locale) ) # format_string,NSTimeZone.timeZoneForSecondsFromGMT_(-18000),locale pr('descriptionWithCalendarFormat:timeZone:locale', date1.descriptionWithCalendarFormat_timeZone_locale_( None, NSTimeZone.timeZoneForSecondsFromGMT_(-18000), locale) ) # format_string,NSTimeZone.timeZoneForSecondsFromGMT_(-18000),locale for a in [date1, date2, date3]: dsd = get_datestrings(dx, a) s = [ "%12s: %r" % (x[0], x[1] ) for x in dsd ] print "\n".join(s) print # # date1_components # fcdc = currentCalendar.components_fromDate_( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit , date1 ) pr( "currentCalendar.components_fromDate", [ fcdc.year(), fcdc.month(), fcdc.day(), fcdc.hour(), fcdc.minute(), fcdc.second(), ] ) dateOfKeynote = currentCalendar.dateFromComponents_(fcdc) pr( "currentCalendar.dateFromComponents", dateOfKeynote )
def get(self, url): unsupported = 'could not find the "requests" library (try running "python setup.py build" first)' raise RuntimeError(unsupported) HTTP = Decoy() def binaryish(content, format): bin_types = ('pdf','eps','png','jpg','jpeg','gif','tiff','tif','zip','tar','gz') bin_formats = ('raw','bytes','img','image') if any(b in content for b in bin_types): return True if format: return any(b in format for b in bin_types+bin_formats) return False _nsdf = NSDateFormatter.alloc().init() _nsdf.setLocale_(NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX")) _nsdf.setDateFormat_("EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") _nsdf.setTimeZone_(NSTimeZone.timeZoneForSecondsFromGMT_(0)) def last_modified(resp): """Return the last modified date as a unix time_t""" last_mod = _nsdf.dateFromString_(resp.headers.get('Last-Modified')) if not last_mod: last_mod = NSDate.date() return last_mod.timeIntervalSince1970() ### File/URL Reader ### def read(pth, format=None, encoding=None, cols=None, **kwargs): """Returns the contents of a file into a string or format-dependent data
__author__ = "dbr/Ben" __version__ = "1.9" import os import time import errno import httplib import urllib2 import StringIO from hashlib import md5 from threading import RLock from Foundation import NSDateFormatter, NSLocale, NSTimeZone, NSDate _date_parser = NSDateFormatter.alloc().init() _date_parser.setLocale_(NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX")) _date_parser.setDateFormat_("EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") _date_parser.setTimeZone_(NSTimeZone.timeZoneForSecondsFromGMT_(0)) def GET(url): """Return the contents of a url (from cache if possible)""" opener = urllib2.build_opener(CacheHandler("/tmp/plod")) response = opener.open(url) last_mod = _date_parser.dateFromString_(response.headers.get('Last-Modified')) if not last_mod: last_mod = NSDate.date() return response, last_mod.timeIntervalSince1970() cache_lock = RLock()