Ejemplo n.º 1
0
def configure_locale():
    logger.debug("Before %s", locale.nl_langinfo(locale.CODESET))
    current_locale = locale.getlocale()

    if current_locale[1] is None:
        logger.debug("No locale currently set. Attempting to get default locale.")
        default_locale = locale.getdefaultlocale()

        if default_locale[1] is None:
            logger.debug("No default locale exists. Let's try loading from /etc/default/locale")
            if os.path.exists("/etc/default/locale"):
                config = ConfigObj('/etc/default/locale')
                lang = config.get('LANG')
                new_locale = lang
            else:
                logger.error("/etc/default/locale could not be found! Please run 'sudo update-locale' from command-line.")
                sys.exit(1)
        else:
            new_locale = default_locale

        logger.info("New locale set to: %s", locale.setlocale(locale.LC_ALL, new_locale))



    reload(sys)
    sys.setdefaultencoding("UTF-8")
    current_locale_encoding = locale.getlocale()[1].lower()
    logger.debug("sys default encoding %s", sys.getdefaultencoding())
    logger.debug("After %s", locale.nl_langinfo(locale.CODESET))

    if current_locale_encoding not in ['utf-8', 'utf8']:
        logger.error("Need a UTF-8 locale. Currently '%s'. Exiting..." % current_locale_encoding)
        sys.exit(1)
Ejemplo n.º 2
0
    def __init__(self):
        # load the locale's month names and abbreviations
        self.months = {}
        for i in range(1, 13):
            for basename in ['MON_{}', 'ABMON_{}']:
                index = locale.__dict__[basename.format(i)]
                name = locale.nl_langinfo(index).lower()
                self.months[name] = i

        # load the locale's weekday names and abbreviations
        self.weekdays = {}
        for i in range(1, 8):
            for basename in ['DAY_{}', 'ABDAY_{}']:
                index = locale.__dict__[basename.format(i)]
                name = locale.nl_langinfo(index).lower()
                self.weekdays[name] = i

        # compile the cron entry pattern
        self.cron_pattern = re.compile(r'''
            (?: (?P<all> \*)
                (?: \s* / \s* (?P<allincr> \d+ ) )? [, \t]* ) |
            (?: (?P<start> \w+)
                (?: \s* - \s*
              (?P<end> \w+ )
                (?: \s* / \s* (?P<incr> \d+ ) )? )? [, \t]* ) |
            (?P<comma>,)|
            (?P<cruft>\S+?)
            ''',
            re.VERBOSE)
Ejemplo n.º 3
0
 def from_data(self, uid, fields, rows, model):
     pageSize=[210.0,297.0]
     new_doc = etree.Element("report")
     config = etree.SubElement(new_doc, 'config')
     def _append_node(name, text):
         n = etree.SubElement(config, name)
         n.text = text
     _append_node('date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
     _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize))
     _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,))
     _append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,))
     _append_node('PageFormat', 'a4')
     _append_node('header-date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
     l = []
     t = 0
     temp = []
     tsum = []
     header = etree.SubElement(new_doc, 'header')
     for f in fields:
         field = etree.SubElement(header, 'field')
         field.text = tools.ustr(f)
     lines = etree.SubElement(new_doc, 'lines')
     for row_lines in rows:
         node_line = etree.SubElement(lines, 'row')
         for row in row_lines:
             col = etree.SubElement(node_line, 'col', para='yes', tree='no')
             col.text = tools.ustr(row)
     transform = etree.XSLT(
         etree.parse(os.path.join(tools.config['root_path'],
                                  'addons/base/report/custom_new.xsl')))
     rml = etree.tostring(transform(new_doc))
     self.obj = trml2pdf.parseNode(rml, title='Printscreen')
     return self.obj
Ejemplo n.º 4
0
    def load_lang(self, cr, uid, lang, lang_name=None):
        # create the language with locale information
        fail = True
        iso_lang = tools.get_iso_codes(lang)
        for ln in tools.get_locales(lang):
            try:
                locale.setlocale(locale.LC_ALL, str(ln))
                fail = False
                break
            except locale.Error:
                continue
        if fail:
            lc = locale.getdefaultlocale()[0]
            msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.'
            _logger.warning(msg, lang, lc)

        if not lang_name:
            lang_name = tools.ALL_LANGUAGES.get(lang, lang)


        def fix_xa0(s):
            """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(),
               coercing to utf-8, as some platform seem to output localeconv() in their system
               encoding, e.g. Windows-1252"""
            if s == '\xa0':
                return '\xc2\xa0'
            return s

        def fix_datetime_format(format):
            """Python's strftime supports only the format directives
               that are available on the platform's libc, so in order to
               be 100% cross-platform we map to the directives required by
               the C standard (1989 version), always available on platforms
               with a C standard implementation."""
            # For some locales, nl_langinfo returns a D_FMT/T_FMT that contains
            # unsupported '%-' patterns, e.g. for cs_CZ
            format = format.replace('%-', '%')

            for pattern, replacement in tools.DATETIME_FORMATS_MAP.iteritems():
                format = format.replace(pattern, replacement)
            return str(format)

        conv = locale.localeconv()
        lang_info = {
            'code': lang,
            'iso_code': iso_lang,
            'name': lang_name,
            'translatable': 1,
            'date_format' : fix_datetime_format(locale.nl_langinfo(locale.D_FMT)),
            'time_format' : fix_datetime_format(locale.nl_langinfo(locale.T_FMT)),
            'decimal_point' : fix_xa0(str(conv['decimal_point'])),
            'thousands_sep' : fix_xa0(str(conv['thousands_sep'])),
            'grouping' : str(conv.get('grouping', [])),
        }
        lang_id = False
        try:
            lang_id = self.create(cr, uid, lang_info)
        finally:
            tools.resetlocale()
        return lang_id
Ejemplo n.º 5
0
    def confirm(self, msg):
        msg = unicode(msg)
        if ctx.config.options and ctx.config.options.yes_all:
            return True

        import re, tty

        try:
            locale.setlocale(locale.LC_ALL, "")
        except:
            # Ignore "unsupported locale setting" errors
            pass

        yes_expr = re.compile(locale.nl_langinfo(locale.YESEXPR))
        no_expr = re.compile(locale.nl_langinfo(locale.NOEXPR))
        locale.setlocale(locale.LC_ALL, "C")

        while True:
            tty.tcflush(sys.stdin.fileno(), 0)
            prompt = msg + pisi.util.colorize(_(' (yes/no)'), 'red')
            s = raw_input(prompt.encode('utf-8'))

            if yes_expr.search(s):
                return True

            if no_expr.search(s):
                return False
Ejemplo n.º 6
0
    def displayAttributeValue(self, value):
        '''
        Convert QGIS attribute data into readable values
        '''
        # QGIS version
        isQgis2 = self.QgisVersion > 10900

        # Get locale date representation
        locale.setlocale(locale.LC_TIME,'')
        if hasattr(locale, 'nl_langinfo'):
            date_format = locale.nl_langinfo(locale.D_FMT)
            datetime_format = locale.nl_langinfo(locale.D_T_FMT)
        else:
            date_format = "%x"
            datetime_format = "%x %X"

        # Convert value depending of type
        if hasattr(value, 'toPyDate'):
            output = value.toPyDate().strftime(date_format)
        elif hasattr(value, 'toPyDateTime'):
            output = value.toPyDateTime().strftime(datetime_format)
        else:
            output = u"%s" % value if isQgis2 else u"%s" % value.toString()

        return output
Ejemplo n.º 7
0
 def _fallback(self, loc):
     # Fallback to system locale
     l10n = {}
     
     # TIME
     old = locale.setlocale(locale.LC_TIME)
     l10n['LC_TIME'] = {}
     try:
         locale.setlocale(locale.LC_TIME, _normalize(loc))
     except locale.Error:
         return
     #
     
     try:
         for what in (
                      locale.D_T_FMT, locale.D_FMT, locale.T_FMT, locale.T_FMT_AMPM,
                      locale.DAY_1, locale.DAY_2, locale.DAY_3, locale.DAY_4,
                      locale.DAY_5, locale.DAY_6, locale.DAY_7,
                      locale.ABDAY_1, locale.ABDAY_2, locale.ABDAY_3, locale.ABDAY_4,
                      locale.ABDAY_5, locale.ABDAY_6, locale.ABDAY_7, 
                      locale.MON_1, locale.MON_2, locale.MON_3, locale.MON_4,
                      locale.MON_5, locale.MON_6, locale.MON_7, locale.MON_8,
                      locale.MON_9, locale.MON_10, locale.MON_11, locale.MON_12, 
                      locale.ABMON_1, locale.ABMON_2, locale.ABMON_3, locale.ABMON_4,
                      locale.ABMON_5, locale.ABMON_6, locale.ABMON_7, locale.ABMON_8,
                      locale.ABMON_9, locale.ABMON_10, locale.ABMON_11, locale.ABMON_12, 
                      locale.ERA, locale.ERA_D_T_FMT, locale.ERA_D_FMT,
                      ):
             l10n['LC_TIME'][what] = l10n[what] = locale.nl_langinfo(what)
         #
     finally:
         locale.setlocale(locale.LC_TIME, old)
     #
     
     # numbers
     # TIME
     old = locale.setlocale(locale.LC_NUMERIC)
     l10n['LC_NUMERIC'] = {}
     l10n['LC_MONETARY'] = {}
     
     try:
         locale.setlocale(locale.LC_NUMERIC, _normalize(loc))
     except locale.Error:
         return
     #
 
     try:
         l10n['LC_MONETARY'] = locale.localeconv()
         for what in (locale.ALT_DIGITS, locale.RADIXCHAR, locale.THOUSEP):
             l10n['LC_MONETARY'][what] = l10n[what] = locale.nl_langinfo(what)
     finally:
         locale.setlocale(locale.LC_NUMERIC, old)
     #
     l10n['LC_NUMERIC']['decimal_point'] = l10n['LC_MONETARY']['decimal_point'] 
     l10n['LC_NUMERIC']['thousands_sep'] = l10n['LC_MONETARY']['thousands_sep']
     l10n['LC_NUMERIC']['grouping'] = l10n['LC_MONETARY']['grouping']
     #
     
     self._loc_info = copy.deepcopy(l10n) # XXX Is this is really needed?
Ejemplo n.º 8
0
 def _get_date_text(self):
     if self.display_year:
         return datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_FMT))
     else:
         dformat = locale.nl_langinfo(locale.D_FMT)
         for s in [ "/%y", "/%Y", ".%y", ".%Y", ".%y", ".%Y" ]:
             dformat = dformat.replace(s, "")
         return datetime.datetime.now().strftime(dformat)    
Ejemplo n.º 9
0
 def getpreferredencoding(do_setlocale=True):
     if do_setlocale:
         oldloc = locale.setlocale(locale.LC_CTYPE)
         locale.setlocale(locale.LC_CTYPE, "")
         result = locale.nl_langinfo(locale.CODESET)
         locale.setlocale(locale.LC_CTYPE, oldloc)
         return result
     else:
         return locale.nl_langinfo(locale.CODESET)
Ejemplo n.º 10
0
    def testTrueDiv(self):
        x = SizeStruct.new_from_str("1024 B")
        y = SizeStruct.new_from_str("-102.4 B") # rounds to whole bytes
        divResult = float(x.true_div(y)[:15].replace(locale.nl_langinfo(locale.RADIXCHAR), ".")) # just some number to cover accurancy and not cross max float range
        self.assertAlmostEqual(divResult, 1024.0/-102.0)

        x = SizeStruct.new_from_str("1 MiB")
        y = SizeStruct.new_from_str("1 KiB")
        divResult = float(x.true_div(y)[:15].replace(locale.nl_langinfo(locale.RADIXCHAR), ".")) # just some number to cover accurancy and not cross max float range
        self.assertAlmostEqual(divResult, 1024.0)
Ejemplo n.º 11
0
def compile_filters(filter_list):
    """Compile a list of comma-separated-values into a single flat list"""
    result = []
    for filter_str in filter_list:
        items = csv.reader(StringIO(filter_str.encode(locale.nl_langinfo(locale.CODESET))),
                           quotechar='`',
                           skipinitialspace=True).next()
        for item in items:
            result.append(unicode(item, locale.nl_langinfo(locale.CODESET)))
    return result
Ejemplo n.º 12
0
 def from_data(self, uid, fields, rows, company_name):
     pageSize=[210.0,297.0]
     new_doc = etree.Element("report")
     config = etree.SubElement(new_doc, 'config')
     def _append_node(name, text):
         n = etree.SubElement(config, name)
         n.text = text
     _append_node('date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
     _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize))
     _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,))
     _append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,))
     _append_node('PageFormat', 'a4')
     _append_node('header-date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
     _append_node('company', company_name)
     l = []
     t = 0
     temp = []
     tsum = []
     skip_index = []
     header = etree.SubElement(new_doc, 'header')
     i = 0
     for f in fields:
         if f.get('header_data_id', False):
             value = f.get('header_name', "")
             field = etree.SubElement(header, 'field')
             field.text = tools.ustr(value)
         else:
             skip_index.append(i)
         i += 1
     lines = etree.SubElement(new_doc, 'lines')
     for row_lines in rows:
         node_line = etree.SubElement(lines, 'row')
         j = 0
         for row in row_lines:
             if not j in skip_index:
                 para = "yes"
                 tree = "no"
                 value = row.get('data', '')
                 if row.get('bold', False):
                     para = "group"
                 if row.get('number', False):
                     tree = "float"
                 col = etree.SubElement(node_line, 'col', para=para, tree=tree)
                 col.text = tools.ustr(value)
             j += 1
     transform = etree.XSLT(
         etree.parse(os.path.join(tools.config['root_path'],
                                  'addons/base/report/custom_new.xsl')))
     rml = etree.tostring(transform(new_doc))
     # Update system font database if it hasn't been called yet, so that system fonts are used by reportlab with better glyph coverage
     registry = openerp.registry(request.cr.dbname)
     registry['res.font'].font_scan(request.cr, SUPERUSER_ID, lazy=True, context=request.context)
     self.obj = trml2pdf.parseNode(rml, title='Printscreen')
     return self.obj
Ejemplo n.º 13
0
 def getpreferredencoding(do_setlocale = True):
     """Return the charset that the user is likely using,
     according to the system configuration."""
     if do_setlocale:
         oldloc = locale.setlocale(locale.LC_CTYPE)
         locale.setlocale(locale.LC_CTYPE, "")
         result = locale.nl_langinfo(locale.CODESET)
         locale.setlocale(locale.LC_CTYPE, oldloc)
         return result
     else:
         return locale.nl_langinfo(locale.CODESET)
Ejemplo n.º 14
0
def get_date(schedule=False, rule=None, last_date=None, tz=None, iso8601=False):
    """Returns a date stamp, given a recurrence rule.

    schedule - bool:
        whether to use the recurrence rule or not

    rule - str:
        an iCal RRULE string that specifies the rule for scheduling posts

    last_date - datetime:
        timestamp of the last post

    tz - tzinfo:
        the timezone used for getting the current time.

    iso8601 - bool:
        whether to force ISO 8601 dates (instead of locale-specific ones)

    """

    if tz is None:
        tz = dateutil.tz.tzlocal()
    date = now = datetime.datetime.now(tz)
    if schedule:
        try:
            from dateutil import rrule
        except ImportError:
            LOGGER.error('To use the --schedule switch of new_post, '
                         'you have to install the "dateutil" package.')
            rrule = None  # NOQA
    if schedule and rrule and rule:
        try:
            rule_ = rrule.rrulestr(rule, dtstart=last_date)
        except Exception:
            LOGGER.error('Unable to parse rule string, using current time.')
        else:
            date = rule_.after(max(now, last_date or now), last_date is None)

    offset = tz.utcoffset(now)
    offset_sec = (offset.days * 24 * 3600 + offset.seconds)
    offset_hrs = offset_sec // 3600
    offset_min = offset_sec % 3600
    if iso8601:
        tz_str = '{0:+03d}:{1:02d}'.format(offset_hrs, offset_min // 60)
        return date.strftime('%Y-%m-%dT%T') + tz_str
    else:
        if offset:
            tz_str = ' UTC{0:+03d}:{1:02d}'.format(offset_hrs, offset_min // 60)
        else:
            tz_str = ' UTC'
        return date.strftime('{0} {1}'.format(
            locale.nl_langinfo(locale.D_FMT),
            locale.nl_langinfo(locale.T_FMT),
        )) + tz_str
Ejemplo n.º 15
0
    def from_data(self, uid, fields, rows, company_name):
        pageSize = [210.0, 297.0]
        new_doc = etree.Element("report")
        config = etree.SubElement(new_doc, "config")

        def _append_node(name, text):
            n = etree.SubElement(config, name)
            n.text = text

        _append_node("date", time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace("%y", "%Y"))))
        _append_node("PageSize", "%.2fmm,%.2fmm" % tuple(pageSize))
        _append_node("PageWidth", "%.2f" % (pageSize[0] * 2.8346,))
        _append_node("PageHeight", "%.2f" % (pageSize[1] * 2.8346,))
        _append_node("PageFormat", "a4")
        _append_node("header-date", time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace("%y", "%Y"))))
        _append_node("company", company_name)
        l = []
        t = 0
        temp = []
        tsum = []
        skip_index = []
        header = etree.SubElement(new_doc, "header")
        i = 0
        for f in fields:
            if f.get("header_data_id", False):
                value = f.get("header_name", "")
                field = etree.SubElement(header, "field")
                field.text = tools.ustr(value)
            else:
                skip_index.append(i)
            i += 1
        lines = etree.SubElement(new_doc, "lines")
        for row_lines in rows:
            node_line = etree.SubElement(lines, "row")
            j = 0
            for row in row_lines:
                if not j in skip_index:
                    para = "yes"
                    tree = "no"
                    value = row.get("data", "")
                    if row.get("bold", False):
                        para = "group"
                    if row.get("number", False):
                        tree = "float"
                    col = etree.SubElement(node_line, "col", para=para, tree=tree)
                    col.text = tools.ustr(value)
                j += 1
        transform = etree.XSLT(
            etree.parse(os.path.join(tools.config["root_path"], "addons/base/report/custom_new.xsl"))
        )
        rml = etree.tostring(transform(new_doc))
        self.obj = trml2pdf.parseNode(rml, title="Printscreen")
        return self.obj
    def load_lang(self, cr, uid, lang, lang_name=None):
        # create the language with locale information
        fail = True
        iso_lang = tools.get_iso_codes(lang)
        for ln in tools.get_locales(lang):
            try:
                locale.setlocale(locale.LC_ALL, str(ln))
                fail = False
                break
            except locale.Error:
                continue
        if fail:
            lc = locale.getdefaultlocale()[0]
            msg = "Unable to get information for locale %s. Information from the default locale (%s) have been used."
            _logger.warning(msg, lang, lc)

        if not lang_name:
            lang_name = tools.ALL_LANGUAGES.get(lang, lang)

        def fix_xa0(s):
            """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(),
               coercing to utf-8, as some platform seem to output localeconv() in their system
               encoding, e.g. Windows-1252"""
            if s == "\xa0":
                return "\xc2\xa0"
            return s

        def fix_datetime_format(format):
            """Python's strftime supports only the format directives
               that are available on the platform's libc, so in order to
               be 100% cross-platform we map to the directives required by
               the C standard (1989 version), always available on platforms
               with a C standard implementation."""
            for pattern, replacement in tools.DATETIME_FORMATS_MAP.iteritems():
                format = format.replace(pattern, replacement)
            return str(format)

        lang_info = {
            "code": lang,
            "iso_code": iso_lang,
            "name": lang_name,
            "translatable": 1,
            "date_format": fix_datetime_format(locale.nl_langinfo(locale.D_FMT)),
            "time_format": fix_datetime_format(locale.nl_langinfo(locale.T_FMT)),
            "decimal_point": fix_xa0(str(locale.localeconv()["decimal_point"])),
            "thousands_sep": fix_xa0(str(locale.localeconv()["thousands_sep"])),
        }
        lang_id = False
        try:
            lang_id = self.create(cr, uid, lang_info)
        finally:
            tools.resetlocale()
        return lang_id
Ejemplo n.º 17
0
 def _dt_format(self, cfg=None):
     """
     Not sure how reliable this method of formatting the dt string is.
     Different locales may impact formatting items. Need unit-tests heh
     """
     if cfg is None:
         cfg = self.config
     dt_format = ""
     if cfg.show_time:
         if cfg.show_dt:
             dt_format = locale.nl_langinfo(locale.D_T_FMT)
         else:  # NOT show_dt
             dt_format = locale.nl_langinfo(locale.T_FMT)
             debug_log("dt_format:in1: '" + dt_format + "'")
         if "%r" in dt_format:
             if cfg.show_sec:
                 if cfg.show_12hr:
                     dt_format = re.sub("%r", "%I:%M:%S %p", dt_format)
                 else:
                     dt_format = re.sub("%r", "%H:%M:%S", dt_format)
             else:
                 if cfg.show_12hr:
                     dt_format = re.sub("%r", "%I:%M %p", dt_format)
                 else:
                     dt_format = re.sub("%r", "%H:%M", dt_format)
         if cfg.show_tz:
             if "%Z" not in dt_format:
                 dt_format = dt_format + " %Z"
         else:
             if "%Z" in dt_format:
                 dt_format = re.sub("\s*%Z", "", dt_format)
     else:  # NOT show_time
         dt_format = locale.nl_langinfo(locale.D_T_FMT)
         debug_log("dt_format:in2: '" + dt_format + "'")
         if "%r" in dt_format:
             dt_format = re.sub("\s??%r", "", dt_format)
         if "%Z" in dt_format:
             dt_format = re.sub("\s??%Z", "", dt_format)
     if " %Y" in dt_format:
         if cfg.show_yr and not self.config.show_dt:
             dt_format = "%Y, " + dt_format
         elif cfg.show_yr:
             if cfg.show_time:
                 dt_format = re.sub(" %Y ", ", %Y, ", dt_format)
             else:
                 dt_format = re.sub(" %Y", ", %Y", dt_format)
         else:
             dt_format = re.sub(" %Y", "", dt_format)
     if cfg.show_time and cfg.show_dt and not cfg.show_yr:
         dt_format = re.sub("%b %", "%b, %", dt_format)
     debug_log("dt_format:out: '" + dt_format + "'")
     return dt_format
Ejemplo n.º 18
0
def datestampConvert(datestamp):
    try:
      dtFormat = "%Y%m%d%H%M%S"
      dtString = str(datestamp)
      dtConverted = datetime.datetime.strptime(dtString, dtFormat)
      # Localise date and time
      dtLocaleDate = locale.nl_langinfo(locale.D_FMT)
      dtLocaleTime = locale.nl_langinfo(locale.T_FMT)
      dtShow = dtConverted.strftime(dtLocaleDate)
    except:
      # Could not get datestamp from file
      dtShow='-'
    return dtShow
Ejemplo n.º 19
0
 def __init__(self, code='fr', conv=None):
     self.tz = pytz.timezone(pytz.country_timezones[code][0])
     days_sym = [locale.DAY_1, locale.DAY_2, locale.DAY_3, locale.DAY_4,
                 locale.DAY_5, locale.DAY_6, locale.DAY_7]
     months_sym = [locale.DAY_1, locale.DAY_2, locale.DAY_3, locale.DAY_4,
                   locale.DAY_5, locale.DAY_6, locale.DAY_7, locale.MON_8,
                   locale.MON_9, locale.MON_10, locale.MON_11, locale.MON_12]
     self.days = [locale.nl_langinfo(d) for d in days_sym]
     self.months = [locale.nl_langinfo(d) for d in months_sym]
     if conv is None:
         locale.setlocale(locale.LC_ALL, '')
     self.date_fmt = locale.nl_langinfo(locale.D_FMT) + ' %Z%z'
     self.hour_fmt = locale.nl_langinfo(locale.T_FMT) + ' %Z%z'
Ejemplo n.º 20
0
 def test_get_set_from_str(self):
     datetime_obj = datetime(1977, 12, 31, 12, 34, 56)
     datetime_fmt = "%s %s" %(locale.nl_langinfo(locale.D_FMT),
                        locale.nl_langinfo(locale.T_FMT))
     datetime_str = datetime.strftime(datetime_obj, datetime_fmt)
     datetime_uni = unicode(datetime_str)
     variable = DateTimeVariable()
     variable.set(datetime_str, from_db=False)
     self.assertEquals(variable.get(), datetime_obj)
     variable.set(datetime_uni, from_db=False)
     self.assertEquals(variable.get(), datetime_obj)
     variable.set(datetime_obj, from_db=False)
     self.assertEquals(variable.get(), datetime_obj)
Ejemplo n.º 21
0
	def process_dates(self, date_from, date_to):
		"""Wrap the process_dates method in log_time to log total execution time"""

		log_time(
			target=super().process_dates,
			target_args=[
				date_from,
				date_to
			],
			message='{prefix} {date_from} to {date_to}'.format(
				prefix=self.message_prefix,
				date_from=date_from.strftime(locale.nl_langinfo(locale.D_FMT)),
				date_to=date_to.strftime(locale.nl_langinfo(locale.D_FMT))
				)
			)
Ejemplo n.º 22
0
def size_from_input(input_str, units=None):
    """ Get a Size object from an input string.

        :param str input_str: a string forming some representation of a size
        :param units: use these units if none specified in input_str
        :type units: str or NoneType
        :returns: a Size object corresponding to input_str
        :rtype: :class:`blivet.size.Size` or NoneType

        Units default to bytes if no units in input_str or units.
    """

    if not input_str:
        # Nothing to parse
        return None

    # A string ending with a digit contains no units information.
    if re.search(r'[\d.%s]$' % locale.nl_langinfo(locale.RADIXCHAR), input_str):
        input_str += units or ""

    try:
        size = Size(input_str)
    except ValueError:
        return None

    return size
Ejemplo n.º 23
0
    def testTranslated(self):
        s = Size("56.19 MiB")
        for lang in  self.TEST_LANGS:
            os.environ['LANG'] = lang
            locale.setlocale(locale.LC_ALL, '')

            # Check English parsing
            self.assertEqual(s, Size("56.19 MiB"))

            # Check native parsing
            self.assertEqual(s, Size("56.19 %s%s" % (_("Mi"), _("B"))))

            # Check native parsing, all lowercase
            self.assertEqual(s, Size(("56.19 %s%s" % (_("Mi"), _("B"))).lower()))

            # Check native parsing, all uppercase
            self.assertEqual(s, Size(("56.19 %s%s" % (_("Mi"), _("B"))).upper()))

            # If the radix separator is not a period, repeat the tests with the
            # native separator
            radix = locale.nl_langinfo(locale.RADIXCHAR)
            if radix != '.':
                self.assertEqual(s, Size("56%s19 MiB" % radix))
                self.assertEqual(s, Size("56%s19 %s%s" % (radix, _("Mi"), _("B"))))
                self.assertEqual(s, Size(("56%s19 %s%s" % (radix, _("Mi"), _("B"))).lower()))
                self.assertEqual(s, Size(("56%s19 %s%s" % (radix, _("Mi"), _("B"))).upper()))
Ejemplo n.º 24
0
    def stats(self):
        """Prints a nicely formatted list of statistics about the package"""

        self.downloads  # explicitly call, so we have first/last upload data
        fmt = locale.nl_langinfo(locale.D_T_FMT)
        sep = lambda s: locale.format('%d', s, 3)
        val = lambda dt: dt and dt.strftime(fmt) or '--'

        params = (
            self.package_name,
            val(self.first_upload),
            self.first_upload_rel,
            val(self.last_upload),
            self.last_upload_rel,
            sep(len(self.releases)),
            sep(self.max()),
            sep(self.min()),
            sep(self.average()),
            sep(self.total()),
        )

        print """PyPI Package statistics for: %s

    First Upload: %40s (%s)
    Last Upload:  %40s (%s)
    Number of releases: %34s
    Most downloads:    %35s
    Fewest downloads:  %35s
    Average downloads: %35s
    Total downloads:   %35s
""" % params
Ejemplo n.º 25
0
def _date_localed_sequence():
	s = locale.nl_langinfo(locale.D_FMT).lower()
	s2 = [ c for c in s if c in ("y", "m", "d") ]
	if len(s2) < 3:
		# Eeek!
		return ['y', 'm', 'd']
	return s2
Ejemplo n.º 26
0
def udecode(data, encoding='ascii'):
    if (encoding and encoding.lower() == 'unicode'
        or isinstance(data, UnicodeType)):
        return unicode(data)
    encodings = [encoding, 'utf-8']
    try:
        encodings.append(locale.nl_langinfo(locale.CODESET))
    except:
        pass
    try:
        encodings.append(locale.getlocale()[1])
    except:
        pass
    try:
        encodings.append(locale.getdefaultlocale()[1])
    except:
        pass
    encodings.append('latin-1')
    for enc in encodings:
        if not enc:
            continue
        try:
            return unicode(data, enc)
        except (UnicodeError, LookupError):
            pass
    raise UnicodeError(
        'Unable to decode input data.  Tried the following encodings: %s.'
        % ', '.join([repr(enc) for enc in encodings if enc]))
Ejemplo n.º 27
0
    def time_format(self, abbreviated=False):
        """ The format string for a time value.

        Parameters
        ----------
        abbreviated : bool, optional
            If True, return the abbreviate version of the time format.
            The defaults is False.

        Returns
        -------
        result : string
            The time format string.

        """
        if sys.platform == 'win32':
            if abbreviated:
                key = 'ab_time'
            else:
                key = 'time'
            r = _win_defaults[key]
        else:
            flag = locale.T_FMT if abbreviated else locale.T_FMT_AMPM
            r = locale.nl_langinfo(flag)
        return unicode(r)
Ejemplo n.º 28
0
    def datetime_format(self, abbreviated=False):
        """ The format string for a datetime value.

        Parameters
        ----------
        abbreviated : bool, optional
            If True, return the abbreviated version of the datetime
            format. The defaults is False.

        Returns
        -------
        result : string
            The datetime format string.

        Notes
        -----
        Python's builtin locale (based on langinfo) does not distinguish
        abbreviated and non-abbreviated datetime formats. So the keyword
        argument is ignored in this implementation.

        """
        if sys.platform == 'win32':
            r = _win_defaults['datetime']
        else:
            # Python doesn't support %e in strptime, but %d is equivalent
            r = locale.nl_langinfo(locale.D_T_FMT).replace('%e', '%d')
        return unicode(r)
Ejemplo n.º 29
0
def currency(value, request=None, grouping=True):
    """
    e.g.
    import locale
    locale.setlocale(locale.LC_ALL, 'de_CH.UTF-8')
    currency(123456.789)  # Fr. 123'456.79
    currency(-123456.789) # <span class="negative">Fr. -123'456.79</span>
    """
    if not value:
        value = 0.0

    shop = lfs.core.utils.get_default_shop(request)
    try:
        result = locale.currency(value, grouping=grouping, international=shop.use_international_currency_code)
    except ValueError:
        result = value

    # add css class if value is negative
    if value < 0:
        # replace the minus symbol if needed
        if result[-1] == '-':
            length = len(locale.nl_langinfo(locale.CRNCYSTR))
            result = '%s-%s' % (result[0:length], result[length:-1])
        return mark_safe('<span class="negative">%s</span>' % result)
    return result
Ejemplo n.º 30
0
    def day_name(self, day_int, abbreviated=False):
        """ The day name for the given day integer.

        Parameters
        ----------
        day_int : int
            An integer in the range 1 to 7 inclusive.
        
        abbreviated : bool, optional
            If True, return the abbreviate version of the day name.
            The default is False.
        
        Returns
        -------
        result : string
            The day name or an empty string in the day int is out
            of range.

        """
        if day_int < 1 or day_int > 7:
            return ''
        if sys.platform == 'win32':
            if abbreviated:
                key = 'ab_days'
            else:
                key = 'days'
            r = _win_defaults[key][day_int]
        else:
            prefix = 'AB' if abbreviated else ''
            attr = prefix + ('DAY_%i' % day_int)
            flag = getattr(locale, attr)
            r = locale.nl_langinfo(flag)
        return unicode(r)
Ejemplo n.º 31
0
    def writeScript(self, expPath=None, target="PsychoPy", modular=True):
        """Write a PsychoPy script for the experiment
        """
        self.integrityCheck()

        self.psychopyVersion = psychopy.__version__  # make sure is current
        # set this so that params write for approp target
        utils.scriptTarget = target
        self.expPath = expPath
        script = IndentingBuffer(u'')  # a string buffer object

        # get date info, in format preferred by current locale as set by app:
        if hasattr(locale, 'nl_langinfo'):
            fmt = locale.nl_langinfo(locale.D_T_FMT)
            localDateTime = data.getDateStr(format=fmt)
        else:
            localDateTime = data.getDateStr(format="%B %d, %Y, at %H:%M")

        # Remove disabled components, but leave original experiment unchanged.
        self_copy = deepcopy(self)
        for _, routine in list(self_copy.routines.items()):  # PY2/3 compat
            for component in routine:
                try:
                    if component.params['disabled'].val:
                        routine.removeComponent(component)
                except KeyError:
                    pass

        if target == "PsychoPy":
            self_copy.settings.writeInitCode(script, self_copy.psychopyVersion,
                                             localDateTime)

            # Write "run once" code sections
            for entry in self_copy.flow:
                # NB each entry is a routine or LoopInitiator/Terminator
                self_copy._currentRoutine = entry
                if hasattr(entry, 'writeRunOnceInitCode'):
                    entry.writeRunOnceInitCode(script)
            script.write("\n\n")

            # present info, make logfile
            self_copy.settings.writeStartCode(script,
                                              self_copy.psychopyVersion)
            # writes any components with a writeStartCode()
            self_copy.flow.writeStartCode(script)
            self_copy.settings.writeWindowCode(
                script)  # create our visual.Window()
            # for JS the routine begin/frame/end code are funcs so write here

            # write the rest of the code for the components
            self_copy.flow.writeBody(script)
            self_copy.settings.writeEndCode(script)  # close log file
            script = script.getvalue()
        elif target == "PsychoJS":
            script.oneIndent = "  "  # use 2 spaces rather than python 4
            self_copy.settings.writeInitCodeJS(script,
                                               self_copy.psychopyVersion,
                                               localDateTime, modular)
            self_copy.flow.writeFlowSchedulerJS(script)
            self_copy.settings.writeExpSetupCodeJS(script,
                                                   self_copy.psychopyVersion)

            # initialise the components for all Routines in a single function
            script.writeIndentedLines("\nfunction experimentInit() {")
            script.setIndentLevel(1, relative=True)

            # routine init sections
            for entry in self_copy.flow:
                # NB each entry is a routine or LoopInitiator/Terminator
                self_copy._currentRoutine = entry
                if hasattr(entry, 'writeInitCodeJS'):
                    entry.writeInitCodeJS(script)

            # create globalClock etc
            code = ("// Create some handy timers\n"
                    "globalClock = new util.Clock();"
                    "  // to track the time since experiment started\n"
                    "routineTimer = new util.CountdownTimer();"
                    "  // to track time remaining of each (non-slip) routine\n"
                    "\nreturn Scheduler.Event.NEXT;")
            script.writeIndentedLines(code)
            script.setIndentLevel(-1, relative=True)
            script.writeIndentedLines("}\n")

            # This differs to the Python script. We can loop through all
            # Routines once (whether or not they get used) because we're using
            # functions that may or may not get called later.
            # Do the Routines of the experiment first
            routinesToWrite = list(self_copy.routines)
            for thisItem in self_copy.flow:
                if thisItem.getType() in ['LoopInitiator', 'LoopTerminator']:
                    self_copy.flow.writeLoopHandlerJS(script, modular)
                elif thisItem.name in routinesToWrite:
                    self_copy._currentRoutine = self_copy.routines[
                        thisItem.name]
                    self_copy._currentRoutine.writeRoutineBeginCodeJS(
                        script, modular)
                    self_copy._currentRoutine.writeEachFrameCodeJS(
                        script, modular)
                    self_copy._currentRoutine.writeRoutineEndCodeJS(
                        script, modular)
                    routinesToWrite.remove(thisItem.name)
            self_copy.settings.writeEndCodeJS(script)

            # Add JS variable declarations e.g., var msg;
            script = py2js.addVariableDeclarations(script.getvalue(),
                                                   fileName=self.expPath)

            # Reset loop controller ready for next call to writeScript
            self_copy.flow._resetLoopController()

        return script
Ejemplo n.º 32
0
        lfs.core.views.one_time_setup()

    if not value:
        value = 0.0

    shop = lfs.core.utils.get_default_shop(request)
    try:
        result = locale.currency(value, grouping=grouping, international=shop.use_international_currency_code)
    except ValueError, e:
        result = value
        logger.error("currency filter: %s" % e)

    if value < 0:
        # replace the minus symbol if needed
        if result[-1] == '-':
            length = len(locale.nl_langinfo(locale.CRNCYSTR))
            result = '%s-%s' % (result[0:length], result[length:-1])
    return result


@register.filter
def currency(value, request=None, grouping=True):
    """
    Returns the currency based on the given locale within settings.LFS_LOCALE

    e.g.

    import locale
    locale.setlocale(locale.LC_ALL, 'de_CH.UTF-8')
    currency(123456.789)  # <span class="money">Fr. 123'456.79</span>
    currency(-123456.789) # <span class="money negative">Fr. -123'456.79</span>
Ejemplo n.º 33
0
    def _create_table(self,
                      uid,
                      ids,
                      fields,
                      fields_order,
                      results,
                      context,
                      title=''):
        pageSize = [297.0, 210.0]

        new_doc = etree.Element("report")
        config = etree.SubElement(new_doc, 'config')

        def _append_node(name, text):
            n = etree.SubElement(config, name)
            n.text = text

        #_append_node('date', time.strftime('%d/%m/%Y'))
        _append_node(
            'date',
            time.strftime(
                str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))))
        _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize))
        _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346, ))
        _append_node('PageHeight', '%.2f' % (pageSize[1] * 2.8346, ))
        _append_node('report-header', title)

        _append_node(
            'company',
            pooler.get_pool(self.cr.dbname).get('res.users').browse(
                self.cr, uid, uid).company_id.name)
        rpt_obj = pooler.get_pool(self.cr.dbname).get('res.users')
        rml_obj = report_sxw.rml_parse(self.cr, uid, rpt_obj._name, context)
        _append_node(
            'header-date',
            str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
            ' ' + str(time.strftime("%H:%M")))
        l = []
        t = 0
        strmax = (pageSize[0] - 40) * 2.8346
        temp = []
        tsum = []
        for i in range(0, len(fields_order)):
            temp.append(0)
            tsum.append(0)
        ince = -1
        for f in fields_order:
            s = 0
            ince += 1
            if fields[f]['type'] in ('date', 'time', 'datetime', 'float',
                                     'integer'):
                s = 60
                strmax -= s
                if fields[f]['type'] in ('float', 'integer'):
                    temp[ince] = 1
            else:
                t += fields[f].get('size', 80) / 28 + 1

            l.append(s)
        for pos in range(len(l)):
            if not l[pos]:
                s = fields[fields_order[pos]].get('size', 80) / 28 + 1
                l[pos] = strmax * s / t

        _append_node('tableSize', ','.join(map(str, l)))

        header = etree.SubElement(new_doc, 'header')
        for f in fields_order:
            field = etree.SubElement(header, 'field')
            field.text = tools.ustr(fields[f]['string'] or '')

        lines = etree.SubElement(new_doc, 'lines')
        for line in results:
            node_line = etree.SubElement(lines, 'row')
            count = -1
            for f in fields_order:
                float_flag = 0
                count += 1
                if fields[f]['type'] == 'many2one' and line[f]:
                    if not line.get('__group'):
                        line[f] = line[f][1]
                if fields[f]['type'] == 'selection' and line[f]:
                    for key, value in fields[f]['selection']:
                        if key == line[f]:
                            line[f] = value
                            break
                if fields[f]['type'] in ('one2many', 'many2many') and line[f]:
                    line[f] = '( ' + tools.ustr(len(line[f])) + ' )'
                if fields[f]['type'] == 'float' and line[f]:
                    precision = (('digits' in fields[f])
                                 and fields[f]['digits'][1]) or 2
                    prec = '%.' + str(precision) + 'f'
                    line[f] = prec % (line[f])
                    float_flag = 1

                if fields[f]['type'] == 'date' and line[f]:
                    new_d1 = line[f]
                    if not line.get('__group'):
                        format = str(
                            locale.nl_langinfo(locale.D_FMT).replace(
                                '%y', '%Y'))
                        d1 = datetime.strptime(line[f], '%Y-%m-%d')
                        new_d1 = d1.strftime(format)
                    line[f] = new_d1

                if fields[f]['type'] == 'time' and line[f]:
                    new_d1 = line[f]
                    if not line.get('__group'):
                        format = str(locale.nl_langinfo(locale.T_FMT))
                        d1 = datetime.strptime(line[f], '%H:%M:%S')
                        new_d1 = d1.strftime(format)
                    line[f] = new_d1

                if fields[f]['type'] == 'datetime' and line[f]:
                    new_d1 = line[f]
                    if not line.get('__group'):
                        format = str(
                            locale.nl_langinfo(locale.D_FMT).replace(
                                '%y', '%Y')) + ' ' + str(
                                    locale.nl_langinfo(locale.T_FMT))
                        d1 = datetime.strptime(line[f], '%Y-%m-%d %H:%M:%S')
                        new_d1 = d1.strftime(format)
                    line[f] = new_d1

                if line.get('__group'):
                    col = etree.SubElement(node_line,
                                           'col',
                                           para='group',
                                           tree='no')
                else:
                    col = etree.SubElement(node_line,
                                           'col',
                                           para='yes',
                                           tree='no')

                # Prevent empty labels in groups
                if f == line.get('__grouped_by') and line.get(
                        '__group'
                ) and not line[f] and not float_flag and not temp[count]:
                    col.text = line[f] = 'Undefined'
                    col.set('tree', 'undefined')

                if line[f] != None:
                    col.text = tools.ustr(line[f] or '')
                    if float_flag:
                        col.set('tree', 'float')
                    if line.get('__no_leaf') and temp[
                            count] == 1 and f != 'id' and not line[
                                '__context']['group_by']:
                        tsum[count] = float(tsum[count]) + float(line[f])
                    if not line.get(
                            '__group') and f != 'id' and temp[count] == 1:
                        tsum[count] = float(tsum[count]) + float(line[f])
                else:
                    col.text = '/'

        node_line = etree.SubElement(lines, 'row')
        for f in range(0, len(fields_order)):
            col = etree.SubElement(node_line, 'col', para='group', tree='no')
            col.set('tree', 'float')
            if tsum[f] != None:
                if tsum[f] != 0.0:
                    digits = fields[fields_order[f]].get('digits', (16, 2))
                    prec = '%%.%sf' % (digits[1], )
                    total = prec % (tsum[f], )
                    txt = str(total or '')
                else:
                    txt = str(tsum[f] or '')
            else:
                txt = '/'
            if f == 0:
                txt = 'Total'
                col.set('tree', 'no')
            col.text = tools.ustr(txt or '')

        transform = etree.XSLT(
            etree.parse(
                os.path.join(tools.config['root_path'],
                             'addons/base/report/custom_new.xsl')))
        rml = etree.tostring(transform(new_doc))
        self.obj = render.rml(rml, title=self.title)
        self.obj.render()
        return True
Ejemplo n.º 34
0
#!/usr/bin/env python3
#
# Copyright 2007 Doug Hellmann.
#
"""Print dates in locale-specfic format.
"""
#end_pymotw_header

import locale
import time

sample_locales = [
    ('USA', 'en_US'),
    ('France', 'fr_FR'),
    ('Spain', 'es_ES'),
    ('Portugal', 'pt_PT'),
    ('Poland', 'pl_PL'),
]

for name, loc in sample_locales:
    locale.setlocale(locale.LC_ALL, loc)
    format = locale.nl_langinfo(locale.D_T_FMT)
    print('{:>10}: {}'.format(name, time.strftime(format)))
Ejemplo n.º 35
0
def main(argv):
    locale.setlocale(locale.LC_ALL, '')
    deflang = locale.getlocale(locale.LC_COLLATE)[0] or 'en_GB'
    defenc = locale.nl_langinfo(locale.CODESET) or 'utf-8'

    argparser = argparse.ArgumentParser()

    argparser.add_argument(
        '-e',
        '--encoding',
        action='store',
        dest='encoding',
        help='Character encoding to use for I/O (locale default: %s)' % defenc)
    argparser.add_argument(
        '-l',
        '--language',
        action='store',
        dest='language',
        help='The language to lookup the hyphenation rules for '
        '(locale default: %s)' % deflang)

    typearg = argparser.add_mutually_exclusive_group()
    typearg.add_argument('-t',
                         '--text',
                         action='store_const',
                         dest='processor',
                         const=hyph_text,
                         help='Process files as plain text files (default)')
    typearg.add_argument('-x',
                         '--xhtml',
                         action='store_const',
                         dest='processor',
                         const=hyph_xhtml,
                         help='Process files as XHTML')

    argparser.add_argument('file', nargs='+')
    argparser.set_defaults(encoding=defenc,
                           language=deflang,
                           processor=hyph_text)

    opts = argparser.parse_args()

    try:
        h = pyphen.Pyphen(lang=opts.language)
    except IOError as e:
        argparser.error('unknown language: %s (%s)' % (opts.language, str(e)))

    for path in opts.file:
        try:
            with codecs.open(path, 'r', opts.encoding) as f:
                try:
                    with tempfile.NamedTemporaryFile(
                            delete=False, mode='w',
                            encoding=opts.encoding) as outf:
                        opts.processor(f, outf, h)
                    shutil.move(outf.name, path)
                except Exception as e:
                    try:
                        os.unlink(outf.name)
                    except:
                        pass
                    raise e

        except IOError as e:
            sys.stderr.write('open() failed: %s\n' % str(e))
        except LookupError as e:
            argparser.error(str(e))

    return 0
    sys.path.append(NETCONFDIR)

# Workaround for buggy gtk/gnome commandline parsing python bindings.
cmdline = sys.argv[1:]
sys.argv = sys.argv[:1]

import locale
try:
    locale.setlocale(locale.LC_ALL, "")
except locale.Error, e:
    import os
    os.environ['LC_ALL'] = 'C'
    locale.setlocale(locale.LC_ALL, "")
import gettext

gettext.bind_textdomain_codeset(PROGNAME, locale.nl_langinfo(locale.CODESET))
gettext.bindtextdomain(PROGNAME, '/usr/share/locale')
gettext.textdomain(PROGNAME)
_ = lambda x: gettext.lgettext(x)
import __builtin__

__builtin__.__dict__['_'] = _

import signal
import os
import os.path

try:
    import gtk
except RuntimeError:
    sys.stderr.write(
Ejemplo n.º 37
0
def date_to_str(date, fmt=locale.nl_langinfo(locale.D_FMT)):
    return date.strftime(fmt)
Ejemplo n.º 38
0
 def confirm(self):
     response = self.ttyask('apt-listchanges: ' +
                            _('Do you want to continue? [Y/n] '))
     return response == '' or re.search(locale.nl_langinfo(locale.YESEXPR),
                                        response)
Ejemplo n.º 39
0
    def display(self, models):
        self._models = models
        if not self.chart:
            if self._type == 'pie':
                self.chart = GraphicsPieChartItem()
            else:
                self.chart = GraphicsBarChartItem()
                if self._orientation == Qt.Horizontal:
                    self.chart.setAggregated(True)
            self.chart.setSize(self.size())
            self.scene.addItem(self.chart)

        # Put all values to be shown in the records list
        records = []

        # Models could be None
        if models:
            # Fill in records with data from all models for all necessary fields.
            # records will be a list of dictionaries:
            # records = [
            #	{ 'field1': value, 'field2': value }, #record 1
            #	{ 'field1': value, 'field2': value }  #record 2
            #	...
            # }
            for m in models:
                res = {}
                for x in list(self._axisData.keys()):
                    type = self._fields[x]['type']
                    if type in ('many2one', 'char', 'time', 'text'):
                        res[x] = m.value(x)
                    elif type == 'selection':
                        res[x] = ''
                        for y in self._fields[x]['selection']:
                            if y[0] == m.value(x):
                                res[x] = str(y[1])
                                break
                    elif type == 'date':
                        if m.value(x):
                            date = time.strptime(m.value(x), DT_FORMAT)
                            res[x] = time.strftime(locale.nl_langinfo(
                                locale.D_FMT).replace('%y', '%Y'), date)
                        else:
                            res[x] = ''
                    elif type == 'datetime':
                        if m.value(x):
                            date = time.strptime(m.value(x), DHM_FORMAT)
                            if 'tz' in Rpc.session.context:
                                try:
                                    import pytz
                                    lzone = pytz.timezone(
                                        Rpc.session.context['tz'])
                                    szone = pytz.timezone(Rpc.session.timezone)
                                    dt = datetime.datetime(
                                        date[0], date[1], date[2], date[3], date[4], date[5], date[6])
                                    sdt = szone.localize(dt, is_dst=True)
                                    ldt = sdt.astimezone(lzone)
                                    date = ldt.timetuple()
                                except:
                                    pass
                            res[x] = time.strftime(locale.nl_langinfo(
                                locale.D_FMT).replace('%y', '%Y') + ' %H:%M:%S', date)
                        else:
                            res[x] = ''
                    else:
                        res[x] = float(m.value(x) or 0.0)
                records.append(res)

        # Calculate the rest of values
        operators = {
            '+': lambda x, y: x + y,
            '*': lambda x, y: x * y,
            'min': lambda x, y: min(x, y),
            'max': lambda x, y: max(x, y),
            '**': lambda x, y: x**y
        }
        # Fill in aggRecords (aggregated records). So it basically aggregates records
        # appropiately. For example, a view may be defined:
        #
        # <graph string="Timesheet by user" type="bar">
        #     <field name="name"/>
        #     <field name="quantity" operator="+"/>
        #     <field group="True" name="user_id"/>
        # </graph>
        #
        # So here we "execute" the operator="+" attribute. And the group tag.
        aggRecords = []
        groups = {}
        for field in self._axis[1:]:
            data = {}
            for d in records:
                data.setdefault(d[self._axis[0]], {})

                groupEval = ','.join(self.replaceFalse(
                    [d[x] for x in self._groups]))
                groups[groupEval] = 1

                if groupEval in data[d[self._axis[0]]]:
                    oper = operators[self._axisData[field].get(
                        'operator', '+')]
                    data[d[self._axis[0]]][groupEval] = oper(
                        data[d[self._axis[0]]][groupEval], d[field])
                else:
                    data[d[self._axis[0]]][groupEval] = d[field]
            aggRecords.append(data)
        groups = list(groups.keys())
        groups.sort()

        fields = set()
        for field in self._axis[1:]:
            fields.add(self._fields[field]['name'])
        fields = list(fields)
        fields.sort()

        labels = [self._fields[x]['string'] for x in self._axis[1:]]

        categories = set()
        for x in records:
            categories.add(x[self._axis[0]])
        categories = list(categories)
        categories.sort()

        if self._type == 'pie':
            categories = list(data.keys())
            values = [reduce(lambda x, y=0: x + y, list(data[x].values()), 0)
                      for x in categories]
            self.chart.setValues(values)
            # Ensure all categories are strings
            self.chart.setLabels(self.replaceFalse(categories))
        else:
            # Prepare values depending in different ways if there are 'group' tags in the
            # view or not.
            if groups and groups[0]:
                # GTK client leaves only the last part with the following line:
                #    groups = [x.split('/')[-1] for x in groups]
                # However that may remove important information. For example, in product types:
                #   'Class A / Subclass A' -> 'Subclass A'
                #   'Class B / Subclass A' -> 'Subclass A'
                values = []
                for x in categories:
                    value = []
                    for y in groups:
                        for z in aggRecords:
                            value.append(z[x].get(y, 0.0))
                    values.append(value)
                # If we're grouping we need to change the labels
                labels = groups
            else:
                values = []
                for x in categories:
                    value = []
                    for y in aggRecords:
                        value.append(y[x][''])
                    values.append(value)

            self.chart.setValues(values)
            # Ensure all labels are strings
            self.chart.setLabels(self.replaceFalse(labels))
            # Ensure all categories are strings
            self.chart.setCategories(self.replaceFalse(categories))
Ejemplo n.º 40
0
    def load_lang(self, cr, uid, lang, lang_name=None):
        # create the language with locale information
        fail = True
        iso_lang = tools.get_iso_codes(lang)
        for ln in tools.get_locales(lang):
            try:
                locale.setlocale(locale.LC_ALL, str(ln))
                fail = False
                break
            except locale.Error:
                continue
        if fail:
            lc = locale.getdefaultlocale()[0]
            msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.'
            _logger.warning(msg, lang, lc)

        if not lang_name:
            lang_name = tools.ALL_LANGUAGES.get(lang, lang)

        def fix_xa0(s):
            """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(),
               coercing to utf-8, as some platform seem to output localeconv() in their system
               encoding, e.g. Windows-1252"""
            if s == '\xa0':
                return '\xc2\xa0'
            return s

        def fix_datetime_format(format):
            """Python's strftime supports only the format directives
               that are available on the platform's libc, so in order to
               be 100% cross-platform we map to the directives required by
               the C standard (1989 version), always available on platforms
               with a C standard implementation."""
            # For some locales, nl_langinfo returns a D_FMT/T_FMT that contains
            # unsupported '%-' patterns, e.g. for cs_CZ
            format = format.replace('%-', '%')

            for pattern, replacement in tools.DATETIME_FORMATS_MAP.iteritems():
                format = format.replace(pattern, replacement)
            return str(format)

        lang_info = {
            'code': lang,
            'iso_code': iso_lang,
            'name': lang_name,
            'translatable': 1,
            'date_format':
            fix_datetime_format(locale.nl_langinfo(locale.D_FMT)),
            'time_format':
            fix_datetime_format(locale.nl_langinfo(locale.T_FMT)),
            'decimal_point':
            fix_xa0(str(locale.localeconv()['decimal_point'])),
            'thousands_sep':
            fix_xa0(str(locale.localeconv()['thousands_sep'])),
        }
        lang_id = False
        try:
            lang_id = self.create(cr, uid, lang_info)
        finally:
            tools.resetlocale()
        return lang_id
Ejemplo n.º 41
0
locale_encoding = 'ascii'
if sys.platform == 'win32':
    # On Windows, we could use "mbcs". However, to give the user
    # a portable encoding name, we need to find the code page
    try:
        locale_encoding = locale.getdefaultlocale()[1]
        codecs.lookup(locale_encoding)
    except LookupError:
        pass
else:
    try:
        # Different things can fail here: the locale module may not be
        # loaded, it may not offer nl_langinfo, or CODESET, or the
        # resulting codeset may be unknown to Python. We ignore all
        # these problems, falling back to ASCII
        locale_encoding = locale.nl_langinfo(locale.CODESET)
        if locale_encoding is None or locale_encoding is '':
            # situation occurs on Mac OS X
            locale_encoding = 'ascii'
        codecs.lookup(locale_encoding)
    except (NameError, AttributeError, LookupError):
        # Try getdefaultlocale: it parses environment variables,
        # which may give a clue. Unfortunately, getdefaultlocale has
        # bugs that can cause ValueError.
        try:
            locale_encoding = locale.getdefaultlocale()[1]
            if locale_encoding is None or locale_encoding is '':
                # situation occurs on Mac OS X
                locale_encoding = 'ascii'
            codecs.lookup(locale_encoding)
        except (ValueError, LookupError):
Ejemplo n.º 42
0
    def get(self):
        result = super(ComputerResource, self).get()
        node_collection = self.request.db.nodes

        if not result.get('node_chef_id', None):
            return result

        logger.info("/api/computers/: node_chef_id: %s" %
                    (str(result.get('node_chef_id', None))))

        try:
            api = get_chef_api(self.request.registry.settings,
                               self.request.user)
            computer_node = ChefNode(result['node_chef_id'], api)
            ohai = to_deep_dict(computer_node.attributes)
            nodeid = result.get('_id', None)
            usernames = [
                i['username']
                for i in ohai.get('ohai_gecos', {}).get('users', [])
            ]
            users = list(
                node_collection.find(
                    {
                        "$and": [{
                            "$or": [{
                                "name": {
                                    "$in": usernames
                                }
                            }]
                        }, {
                            "type": "user"
                        }, {
                            "computers": {
                                "$elemMatch": {
                                    "$eq": ObjectId(nodeid)
                                }
                            }
                        }]
                    }, {
                        '_id': 1,
                        'name': 1,
                        'path': 1
                    }))
            # ObjectId to string for JSON serialize
            [d.update({'_id': str(d['_id'])}) for d in users]

            # Create a list of users that provides at least one user policy to this computer
            users_inheritance_pre = list(
                node_collection.find(
                    {
                        "$and": [{
                            "$or": [{
                                "name": {
                                    "$in": usernames
                                }
                            }]
                        }, {
                            "type": "user"
                        }, {
                            "computers": {
                                "$elemMatch": {
                                    "$eq": ObjectId(nodeid)
                                }
                            }
                        }]
                    }, {
                        '_id': 1,
                        'name': 1,
                        'path': 1,
                        'inheritance': 1
                    }))
            [d.update({'_id': str(d['_id'])}) for d in users_inheritance_pre]

            users_inheritance = []
            for usr_inh in users_inheritance_pre:
                if 'inheritance' in usr_inh:
                    policies_list = get_inheritance_tree_policies_list(
                        usr_inh['inheritance'], [])
                    if len(policies_list) > 0:
                        users_inheritance.append(usr_inh)

            cpu = ohai.get('cpu', {}).get('0', {})
            dmi = ohai.get('dmi', {})

            # debug_mode flag for logs tab
            debug_mode = False
            try:
                debug_mode = computer_node.attributes.get_dotted(
                    DEBUG_MODE_ENABLE_ATTR_PATH)
            except KeyError:
                pass

            # Get logs info
            logs_data = node_collection.find_one(
                {
                    "type": "computer",
                    "_id": ObjectId(nodeid)
                }, {"logs": True})
            logs = {}
            if logs_data is not None and 'logs' in logs_data:
                logs_data = logs_data['logs']

                date_format = locale.nl_langinfo(locale.D_T_FMT)
                date = datetime.datetime(
                    *map(int,
                         re.split('[^\d]', logs_data['date'])[:-1]))
                localename = locale.normalize(
                    get_current_request().locale_name + '.UTF-8')
                logger.debug("/api/computers/: localename: %s" %
                             (str(localename)))
                locale.setlocale(locale.LC_TIME, localename)
                logs['date'] = date.strftime(date_format)
                logger.debug("/api/computers/: date: %s" % (str(logs['date'])))

                logs['files'] = logs_data['files']
                for filedata in logs_data['files']:
                    # Do not send file contents
                    del filedata['content']

            # Get Help Channel info
            help_channel_enabled = True
            helpchannel_data = self.request.db.helpchannel.find({
                "computer_node_id":
                result['node_chef_id']
            }).sort([("last_modified", pymongo.DESCENDING)]).limit(6)
            helpchannel = {}
            helpchannel['current'] = None
            helpchannel['last'] = []
            if helpchannel_data is not None:
                c = 0
                for hcdata in helpchannel_data:
                    # Format date
                    date_format = locale.nl_langinfo(locale.D_T_FMT)
                    logger.info("last_modified: {0}".format(
                        hcdata['last_modified']))
                    last_mod = re.split('[^\d]', str(hcdata['last_modified']))
                    logger.info("last_mod: {0}".format(last_mod))

                    date = datetime.datetime(*map(int, last_mod[:-2]))
                    localename = locale.normalize(
                        get_current_request().locale_name + '.UTF-8')
                    logger.debug("/api/computers/: localename: %s" %
                                 (str(localename)))
                    locale.setlocale(locale.LC_TIME, localename)
                    hcdata['last_modified'] = date.strftime(date_format)

                    if hcdata['user_node_id']:
                        # Format user
                        user_data = node_collection.find_one({
                            "type":
                            "user",
                            "_id":
                            ObjectId(hcdata['user_node_id'])
                        })
                        if user_data:
                            hcdata['user'] = user_data['name']
                        else:
                            logger.error("User not found: {0}".format(
                                hcdata['user_node_id']))
                    else:
                        hcdata['user'] = ''

                    if hcdata['adminuser_id']:
                        # Format user
                        user_data = self.request.db.adminusers.find_one(
                            {"_id": ObjectId(hcdata['adminuser_id'])})
                        if user_data:
                            hcdata['admin'] = user_data['username']
                        else:
                            logger.error("Admin user not found: {0}".format(
                                hcdata['adminuser_id']))
                    else:
                        hcdata['admin'] = ''

                    # Translate status info
                    hcdata['status'] = _('Unknown status')
                    if hcdata['action'] == 'request':
                        hcdata['status'] = _('User is requesting support')
                    elif hcdata['action'] == 'accepted':
                        hcdata['status'] = _('User is requesting support')
                    elif hcdata['action'] == 'finished user':
                        hcdata['status'] = _('Terminated by user')
                    elif hcdata['action'] == 'finished tech':
                        hcdata['status'] = _('Terminated by technician')
                    elif hcdata['action'] == 'finished error':
                        hcdata['status'] = _(
                            'Terminated because of a communication error')
                    elif hcdata['action'] == 'giving support':
                        hcdata['status'] = _(
                            'The technician is giving support to the user')

                    hcdata['_id'] = str(hcdata['_id'])

                    if (c == 0 and hcdata['action'] == 'accepted'):
                        helpchannel['current'] = hcdata
                    else:
                        helpchannel['last'].append(hcdata)

                    c = c + 1

            result.update({
                'ohai':
                ohai,
                'users':
                users,  # Users related with this computer
                'users_inheritance':
                users_inheritance,  # Users related with this computer that provides at least one user policy
                'uptime':
                ohai.get('uptime', ''),
                #'gcc_link': ohai.get('gcc_link',True),
                'ipaddress':
                ohai.get('ipaddress', ''),
                'cpu':
                '%s %s' %
                (cpu.get('vendor_id', ''), cpu.get('model_name', '')),
                'product_name':
                dmi.get('system', {}).get('product_name', ''),
                'manufacturer':
                dmi.get('system', {}).get('manufacturer', ''),
                'ram':
                ohai.get('memory', {}).get('total', ''),
                'lsb':
                ohai.get('lsb', {}),
                'kernel':
                ohai.get('kernel', {}),
                'filesystem':
                ohai.get('filesystem', {}),
                'debug_mode':
                debug_mode,
                'logs':
                logs,
                'helpchannel':
                helpchannel,
                'help_channel_enabled':
                help_channel_enabled
            })
        except (urllib2.URLError, ChefError, ChefServerError):
            logger.error(
                "/api/computers/: error getting data: node_chef_id: %s " %
                (str(result.get('node_chef_id', None))))
            logger.error(traceback.format_exc())

        return result
Ejemplo n.º 43
0
    '%-M': 'FMMI',  # Minute
    '%S': 'SS',  # zero padded second
    '%-S': 'FMSS',  # Second
    '%f': 'US',  # zero padded microsecond
    '%z': 'OF',  # utf offset
    '%Z': 'TZ',  # uppercase timezone name
    '%j': 'DDD',  # zero padded day of year
    '%-j': 'FMDDD',  # day of year
    '%U': 'WW',  # 1-based week of year
    # 'W': ?,  # meh
}

try:
    _strftime_to_postgresql_rules.update({
        '%c':
        locale.nl_langinfo(locale.D_T_FMT),  # locale date and time
        '%x':
        locale.nl_langinfo(locale.D_FMT),  # locale date
        '%X':
        locale.nl_langinfo(locale.T_FMT),  # locale time
    })
except AttributeError:
    warnings.warn(
        'locale specific date formats (%%c, %%x, %%X) are not yet implemented '
        'for %s' % platform.system())

# translate strftime spec into mostly equivalent PostgreSQL spec
_scanner = re.Scanner(  # type: ignore # re does have a Scanner attribute
    # double quotes need to be escaped
    [('"', lambda *_: r'\"')] + [(
        '|'.join(
Ejemplo n.º 44
0
def get_month_name(month):
 """Schreibt den Monatsnamen aus."""
 if   (month == 1):
  return locale.nl_langinfo(locale.MON_1)
 elif (month == 2):
  return locale.nl_langinfo(locale.MON_2)
 elif (month == 3):
  return locale.nl_langinfo(locale.MON_3)
 elif (month == 4):
  return locale.nl_langinfo(locale.MON_4)
 elif (month == 5):
  return locale.nl_langinfo(locale.MON_5)
 elif (month == 6):
  return locale.nl_langinfo(locale.MON_6)
 elif (month == 7):
  return locale.nl_langinfo(locale.MON_7)
 elif (month == 8):
  return locale.nl_langinfo(locale.MON_8)
 elif (month == 9):
  return locale.nl_langinfo(locale.MON_9)
 elif (month == 10):
  return locale.nl_langinfo(locale.MON_10)
 elif (month == 11):
  return locale.nl_langinfo(locale.MON_11)
 elif (month == 12):
  return locale.nl_langinfo(locale.MON_12)
Ejemplo n.º 45
0
def format_date(loc, d):
    with switchlocale(loc):
        fmt = locale.nl_langinfo(locale.D_T_FMT)
        return d.strftime(fmt)
Ejemplo n.º 46
0
#!/usr/bin/env python
#
# Copyright 2007 Doug Hellmann.
#
"""Print dates in locale-specfic format.
"""
#end_pymotw_header

import locale
import time

sample_locales = [
    ('USA', 'en_US'),
    ('France', 'fr_FR'),
    ('Spain', 'es_ES'),
    ('Portugal', 'pt_PT'),
    ('Poland', 'pl_PL'),
]

for name, loc in sample_locales:
    locale.setlocale(locale.LC_ALL, loc)
    print '%20s: %s' % (name, time.strftime(locale.nl_langinfo(
        locale.D_T_FMT)))
Ejemplo n.º 47
0
def internal_date_to_str(date, ifmt, fmt=locale.nl_langinfo(locale.D_FMT)):
    date = datetime.datetime.strptime(date, ifmt)
    return date_to_str(datetime.date(date.year, date.month, date.day), fmt)
Ejemplo n.º 48
0
     * fuzzy is when a date is just a string not representing a real date
       (like `someday`)
     * date is a datetime.date accurate to the day (see datetime.date)
     * datetime is a datetime.datetime accurate to the microseconds
       (see datetime.datetime)
     * timezone ia a datetime.datetime accurate to the microseconds with tzinfo
    """
    fuzzy = 'fuzzy'
    date = 'date'
    datetime = 'datetime'
    timezone = 'timezone'


# ISO 8601 date format
# get date format from locale
DATE_FORMATS = [(locale.nl_langinfo(locale.D_T_FMT), Accuracy.datetime),
                ('%Y-%m-%dT%H:%M%S.%f%z', Accuracy.timezone),
                ('%Y-%m-%d %H:%M%S.%f%z', Accuracy.timezone),
                ('%Y-%m-%dT%H:%M%S.%f', Accuracy.datetime),
                ('%Y-%m-%d %H:%M%S.%f', Accuracy.datetime),
                ('%Y-%m-%dT%H:%M%S', Accuracy.datetime),
                ('%Y-%m-%d %H:%M%S', Accuracy.datetime),
                (locale.nl_langinfo(locale.D_FMT), Accuracy.date),
                ('%Y-%m-%d', Accuracy.date)]


class Date:
    """A date class that supports fuzzy dates.

    A Date can be constructed with:
      - the fuzzy strings 'now', 'soon', '' (no date, default), or 'someday'
Ejemplo n.º 49
0
        date_fmt = plugins['usbobserver'][0].date_format()
        parse_date_day_first = date_fmt.index(u'd') < date_fmt.index(u'M')
    except:
        parse_date_day_first = False
else:
    try:
        def first_index(raw, queries):
            for q in queries:
                try:
                    return raw.index(q)
                except ValueError:
                    pass
            return -1

        import locale
        raw = locale.nl_langinfo(locale.D_FMT)
        parse_date_day_first = first_index(raw, ('%d', '%a', '%A')) < first_index(raw, ('%m', '%b', '%B'))
        del raw, first_index
    except:
        parse_date_day_first = False

UNDEFINED_DATE = datetime(101,1,1, tzinfo=utc_tz)
DEFAULT_DATE = datetime(2000,1,1, tzinfo=utc_tz)
EPOCH = datetime(1970, 1, 1, tzinfo=_utc_tz)

def is_date_undefined(qt_or_dt):
    d = qt_or_dt
    if d is None:
        return True
    if hasattr(d, 'toString'):
        if hasattr(d, 'date'):
Ejemplo n.º 50
0
 def strtime(self, secs):
     try:
         from locale import nl_langinfo, D_T_FMT
         return time.strftime(nl_langinfo(D_T_FMT), time.localtime(secs))
     except ImportError, ValueError:
         return time.ctime(secs)
Ejemplo n.º 51
0
def resolve_date_format(year, month, day, fail_safe=True):
    """
    Puts the year, month and day objects in the right order according to the
    currently set locale and provides format specification for each of the
    fields.

    :param year: any object or value representing year
    :type year: any
    :param month: any object or value representing month
    :type month: any
    :param day: any object or value representing day
    :type day: any
    :param bool fail_safe: whether to fall back to default in case of invalid
                           format or raise exception instead
    :returns: a pair where the first field contains a tuple with the year, month
              and day objects/values put in the right order and where the second
              field contains a tuple with three :class:`_DateFieldSpec` objects
              specifying formats respectively to the first (year, month, day)
              field, e.g. ((year, month, day), (y_fmt, m_fmt, d_fmt))
    :rtype: tuple
    :raise ValueError: in case currently set locale has unsupported date
                       format and fail_safe is set to False

    """

    FAIL_SAFE_DEFAULT = "%Y-%m-%d"

    def order_terms_formats(fmt_str):
        # see date (1), 'O' (not '0') is a mystery, 'E' is Buddhist calendar, '(.*)'
        # is an arbitrary suffix
        field_spec_re = re.compile(r'([-_0OE^#]*)([yYmbBde])(.*)')

        # see date (1)
        fmt_str = fmt_str.replace("%F", "%Y-%m-%d")

        # e.g. "%d.%m.%Y" -> ['d.', 'm.', 'Y']
        fields = fmt_str.split("%")[1:]

        ordered_terms = []
        ordered_formats = []
        for field in fields:
            match = field_spec_re.match(field)
            if not match:
                # ignore fields we are not interested in (like %A for weekday name, etc.)
                continue

            prefix, item, suffix = match.groups()
            if item in ("d", "e"):
                # "e" is the same as "_d"
                ordered_terms.append(day)
            elif item in ("Y", "y"):
                # 4-digit year, 2-digit year
                ordered_terms.append(year)
            elif item in ("m", "b", "B"):
                # month number, short month name, long month name
                ordered_terms.append(month)

            # "%" + prefix + item gives a format for date/time formatting functions
            ordered_formats.append(
                _DateFieldSpec("%" + prefix + item, suffix.strip()))

        if len(ordered_terms) != 3 or len(ordered_formats) != 3:
            raise ValueError(
                "Not all fields successfully identified in the format '%s'" %
                fmt_str)

        return (tuple(ordered_terms), tuple(ordered_formats))

    fmt_str = locale_mod.nl_langinfo(locale_mod.D_FMT)

    if not fmt_str or "%" not in fmt_str:
        if fail_safe:
            # use some sane default
            fmt_str = FAIL_SAFE_DEFAULT
        else:
            raise ValueError(
                "Invalid date format string for current locale: '%s'" %
                fmt_str)

    try:
        return order_terms_formats(fmt_str)
    except ValueError:
        if not fail_safe:
            raise
        else:
            # if this call fails too, something is going terribly wrong and we
            # should be informed about it
            return order_terms_formats(FAIL_SAFE_DEFAULT)
Ejemplo n.º 52
0
    def writeScript(self, expPath=None, target="PsychoPy"):
        """Write a PsychoPy script for the experiment
        """

        self.flow._prescreenValues()
        self.expPath = expPath
        script = IndentingBuffer(u'')  # a string buffer object

        # get date info, in format preferred by current locale as set by app:
        if hasattr(locale, 'nl_langinfo'):
            fmt = locale.nl_langinfo(locale.D_T_FMT)
            localDateTime = data.getDateStr(format=fmt)
        else:
            localDateTime = data.getDateStr(format="%B %d, %Y, at %H:%M")

        if target == "PsychoPy":
            self.settings.writeInitCode(script, self.psychopyVersion,
                                        localDateTime)
            self.settings.writeStartCode(script)  # present info, make logfile
            # writes any components with a writeStartCode()
            self.flow.writeStartCode(script)
            self.settings.writeWindowCode(script)  # create our visual.Window()
            # for JS the routine begin/frame/end code are funcs so write here

            # write the rest of the code for the components
            self.flow.writeBody(script)
            self.settings.writeEndCode(script)  # close log file

        elif target == "PsychoJS":
            script.oneIndent = "  "  # use 2 spaces rather than python 4
            self.settings.writeInitCodeJS(script, self.psychopyVersion,
                                          localDateTime)
            self.settings.writeWindowCodeJS(script)

            # initialise the components for all Routines in a single function
            script.writeIndentedLines("\nfunction experimentInit() {")
            script.setIndentLevel(1, relative=True)

            # routine init sections
            for entry in self.flow:
                # NB each entry is a routine or LoopInitiator/Terminator
                self._currentRoutine = entry
                if hasattr(entry, 'writeInitCodeJS'):
                    entry.writeInitCodeJS(script)

            # create globalClock etc
            code = ("\n// Create some handy timers\n"
                    "globalClock = new psychoJS.core.Clock();"
                    "  // to track the time since experiment started\n"
                    "routineTimer = new psychoJS.core.CountdownTimer();"
                    "  // to track time remaining of each (non-slip) routine\n"
                    "\nreturn psychoJS.NEXT;")
            script.writeIndentedLines(code)
            script.setIndentLevel(-1, relative=True)
            script.writeIndentedLines("}")

            # This differs to the Python script. We can loop through all
            # Routines once (whether or not they get used) because we're using
            # functions that may or may not get called later.
            # Do the Routines of the experiment first
            for thisRoutine in list(self.routines.values()):
                self._currentRoutine = thisRoutine
                thisRoutine.writeRoutineBeginCodeJS(script)
                thisRoutine.writeEachFrameCodeJS(script)
                thisRoutine.writeRoutineEndCodeJS(script)
            # loao resources files (images, csv files etc
            self.flow.writeResourcesCodeJS(script)
            # create the run() function and schedulers
            self.flow.writeBodyJS(
                script)  # functions for loops and for scheduler
            self.settings.writeEndCodeJS(script)

        return script
Ejemplo n.º 53
0
def _str_to_decimal(num_str):
    radix = locale.nl_langinfo(locale.RADIXCHAR)
    if radix != '.':
        num_str = num_str.replace(radix, '.')

    return Decimal(num_str)
Ejemplo n.º 54
0
 def _get_human_time(self, timestamp):
     fmt = locale.nl_langinfo(locale.D_T_FMT)
     return datetime.datetime.fromtimestamp(timestamp).strftime(fmt)
Ejemplo n.º 55
0
 def get_date(self):
     return self.added.strftime(locale.nl_langinfo(locale.D_T_FMT))
Ejemplo n.º 56
0
    def _show_changes(self):
        def show_packages(pkgs):
            """Format the pkgs in a nice way."""
            line = " "
            pkgs.sort()
            for pkg in pkgs:
                try:
                    name, version = pkg.split("=", 1)[0:2]
                except ValueError:
                    name = pkg
                    version = None
                if self._details and version:
                    output = "%s=%s" % (name, version)
                else:
                    output = name
                if (len(line) + 1 + len(output) > self._terminal_width
                        and line != " "):
                    print(line)
                    line = " "
                line += " %s" % output
            if line != " ":
                print(line)

        self._stop_custom_progress()
        self._clear_progress()
        (installs, reinstalls, removals, purges, upgrades,
         downgrades) = self._transaction.packages
        (dep_installs, dep_reinstalls, dep_removals, dep_purges, dep_upgrades,
         dep_downgrades, dep_kepts) = self._transaction.dependencies
        installs.extend(dep_installs)
        upgrades.extend(dep_upgrades)
        removals.extend(purges)
        removals.extend(dep_removals)
        removals.extend(dep_purges)
        reinstalls.extend(dep_reinstalls)
        downgrades.extend(dep_downgrades)
        kepts = dep_kepts
        if installs:
            # TRANSLATORS: %s is the number of packages
            print((ngettext(
                "The following NEW package will be installed "
                "(%(count)s):", "The following NEW packages will be installed "
                "(%(count)s):", len(installs)) % {
                    "count": len(installs)
                }))
            show_packages(installs)
        if upgrades:
            # TRANSLATORS: %s is the number of packages
            print((ngettext(
                "The following package will be upgraded "
                "(%(count)s):", "The following packages will be upgraded "
                "(%(count)s):", len(upgrades)) % {
                    "count": len(upgrades)
                }))
            show_packages(upgrades)
        if removals:
            # TRANSLATORS: %s is the number of packages
            print((ngettext(
                "The following package will be REMOVED "
                "(%(count)s):", "The following packages will be REMOVED "
                "(%(count)s):", len(removals)) % {
                    "count": len(removals)
                }))
            # FIXME: mark purges
            show_packages(removals)
        if downgrades:
            # TRANSLATORS: %s is the number of packages
            print((ngettext(
                "The following package will be DOWNGRADED "
                "(%(count)s):", "The following packages will be DOWNGRADED "
                "(%(count)s):", len(downgrades)) % {
                    "count": len(downgrades)
                }))
            show_packages(downgrades)
        if reinstalls:
            # TRANSLATORS: %s is the number of packages
            print((ngettext(
                "The following package will be reinstalled "
                "(%(count)s):", "The following packages will be reinstalled "
                "(%(count)s):", len(reinstalls)) % {
                    "count": len(reinstalls)
                }))
            show_packages(reinstalls)
        if kepts:
            print((ngettext(
                "The following package has been kept back "
                "(%(count)s):", "The following packages have been kept back "
                "(%(count)s):", len(kepts)) % {
                    "count": len(kepts)
                }))
            show_packages(kepts)

        if self._transaction.download:
            print(
                _("Need to get %sB of archives.") %
                client.get_size_string(self._transaction.download))
        if self._transaction.space > 0:
            print(
                _("After this operation, %sB of additional disk space "
                  "will be used.") %
                client.get_size_string(self._transaction.space))
        elif self._transaction.space < 0:
            print(
                _("After this operation, %sB of additional disk space "
                  "will be freed.") %
                client.get_size_string(self._transaction.space))
        if (self._transaction.space or self._transaction.download or installs
                or upgrades or downgrades or removals or kepts or reinstalls):
            try:
                if PY3K:
                    cont = input(_("Do you want to continue [Y/n]?"))
                else:
                    cont = raw_input(_("Do you want to continue [Y/n]?"))
            except EOFError:
                cont = "n"
            # FIXME: Listen to changed dependencies!
            if (not re.match(locale.nl_langinfo(locale.YESEXPR), cont)
                    and cont != ""):
                msg = enums.get_exit_string_from_enum(enums.EXIT_CANCELLED)
                self._update_custom_progress(msg, None, False)
                self._loop.quit()
                sys.exit(1)
        # TRANSLATORS: status message
        self._progress_id = GLib.timeout_add(250, self._update_custom_progress,
                                             _("Queuing"))
        self._transaction.run(
            error_handler=self._on_exception,
            reply_handler=lambda: self._stop_custom_progress())
Ejemplo n.º 57
0
def main():
    if locale.nl_langinfo(locale.CODESET).upper() not in ['US-ASCII', 'UTF-8']:
        print(
            "asciinema needs an ASCII or UTF-8 character encoding to run. Check the output of `locale` command."
        )
        sys.exit(1)

    try:
        cfg = config.load()
    except config.ConfigError as e:
        sys.stderr.write(str(e) + '\n')
        sys.exit(1)

    # create the top-level parser
    parser = argparse.ArgumentParser(
        description="Record and share your terminal sessions, the right way.",
        epilog="""example usage:
  Record terminal and upload it to asciinema.org:
    \x1b[1masciinema rec\x1b[0m
  Record terminal to local file:
    \x1b[1masciinema rec demo.cast\x1b[0m
  Record terminal and upload it to asciinema.org, specifying title:
    \x1b[1masciinema rec -t "My git tutorial"\x1b[0m
  Record terminal to local file, limiting idle time to max 2.5 sec:
    \x1b[1masciinema rec -i 2.5 demo.cast\x1b[0m
  Replay terminal recording from local file:
    \x1b[1masciinema play demo.cast\x1b[0m
  Replay terminal recording hosted on asciinema.org:
    \x1b[1masciinema play https://asciinema.org/a/difqlgx86ym6emrmd8u62yqu8\x1b[0m
  Print full output of recorded session:
    \x1b[1masciinema cat demo.cast\x1b[0m

For help on a specific command run:
  \x1b[1masciinema <command> -h\x1b[0m""",
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--version',
                        action='version',
                        version='asciinema %s' % __version__)

    subparsers = parser.add_subparsers()

    # create the parser for the "rec" command
    parser_rec = subparsers.add_parser('rec', help='Record terminal session')
    parser_rec.add_argument('--stdin',
                            help='enable stdin recording, disabled by default',
                            action='store_true',
                            default=cfg.record_stdin)
    parser_rec.add_argument('--append',
                            help='append to existing recording',
                            action='store_true',
                            default=False)
    parser_rec.add_argument('--raw',
                            help='save only raw stdout output',
                            action='store_true',
                            default=False)
    parser_rec.add_argument('--overwrite',
                            help='overwrite the file if it already exists',
                            action='store_true',
                            default=False)
    parser_rec.add_argument('-c',
                            '--command',
                            help='command to record, defaults to $SHELL',
                            default=cfg.record_command)
    parser_rec.add_argument(
        '-e',
        '--env',
        help='list of environment variables to capture, defaults to ' +
        config.DEFAULT_RECORD_ENV,
        default=cfg.record_env)
    parser_rec.add_argument('-t', '--title', help='title of the asciicast')
    parser_rec.add_argument(
        '-i',
        '--idle-time-limit',
        help='limit recorded idle time to given number of seconds',
        type=positive_float,
        default=maybe_str(cfg.record_idle_time_limit))
    parser_rec.add_argument(
        '-y',
        '--yes',
        help='answer "yes" to all prompts (e.g. upload confirmation)',
        action='store_true',
        default=cfg.record_yes)
    parser_rec.add_argument(
        '-q',
        '--quiet',
        help='be quiet, suppress all notices/warnings (implies -y)',
        action='store_true',
        default=cfg.record_quiet)
    parser_rec.add_argument('filename',
                            nargs='?',
                            default='',
                            help='filename/path to save the recording to')
    parser_rec.set_defaults(func=rec_command)

    # create the parser for the "play" command
    parser_play = subparsers.add_parser('play', help='Replay terminal session')
    parser_play.add_argument(
        '-i',
        '--idle-time-limit',
        help='limit idle time during playback to given number of seconds',
        type=positive_float,
        default=maybe_str(cfg.play_idle_time_limit))
    parser_play.add_argument('-s',
                             '--speed',
                             help='playback speedup (can be fractional)',
                             type=positive_float,
                             default=cfg.play_speed)
    parser_play.add_argument(
        'filename', help='local path, http/ipfs URL or "-" (read from stdin)')
    parser_play.set_defaults(func=play_command)

    # create the parser for the "cat" command
    parser_cat = subparsers.add_parser(
        'cat', help='Print full output of terminal session')
    parser_cat.add_argument(
        'filename', help='local path, http/ipfs URL or "-" (read from stdin)')
    parser_cat.set_defaults(func=cat_command)

    # create the parser for the "upload" command
    parser_upload = subparsers.add_parser(
        'upload',
        help='Upload locally saved terminal session to asciinema.org')
    parser_upload.add_argument('filename',
                               help='filename or path of local recording')
    parser_upload.set_defaults(func=upload_command)

    # create the parser for the "auth" command
    parser_auth = subparsers.add_parser(
        'auth', help='Manage recordings on asciinema.org account')
    parser_auth.set_defaults(func=auth_command)

    # parse the args and call whatever function was selected
    args = parser.parse_args()

    if hasattr(args, 'func'):
        command = args.func(args, cfg)
        code = command.execute()
        sys.exit(code)
    else:
        parser.print_help()
        sys.exit(1)
Ejemplo n.º 58
0
    def print_formatted(
        self,
        fp=sys.stdout,
        force_color=False,
        no_color=False,
        show_cmd=False,
        show_full_cmd=False,
        show_user=False,
        show_pid=False,
        show_power=None,
        show_fan_speed=None,
        gpuname_width=16,
        show_header=True,
        eol_char=os.linesep,
    ):
        # ANSI color configuration
        if force_color and no_color:
            raise ValueError("--color and --no_color can't"
                             " be used at the same time")

        if force_color:
            t_color = Terminal(kind='linux', force_styling=True)

            # workaround of issue #32 (watch doesn't recognize sgr0 characters)
            t_color.normal = u'\x1b[0;10m'
        elif no_color:
            t_color = Terminal(force_styling=None)
        else:
            t_color = Terminal()  # auto, depending on isatty

        # appearance settings
        entry_name_width = [len(g.entry['name']) for g in self]
        gpuname_width = max([gpuname_width or 0] + entry_name_width)

        # header
        if show_header:
            time_format = locale.nl_langinfo(locale.D_T_FMT)

            header_template = '{t.bold_white}{hostname:{width}}{t.normal}  '
            header_template += '{timestr}  '
            header_template += '{t.bold_black}{driver_version}{t.normal}'

            header_msg = header_template.format(
                hostname=self.hostname,
                width=gpuname_width + 3,  # len("[?]")
                timestr=self.query_time.strftime(time_format),
                driver_version=self.driver_version,
                t=t_color,
            )

            fp.write(header_msg.strip())
            fp.write(eol_char)

        # body
        for g in self:
            g.print_to(fp,
                       show_cmd=show_cmd,
                       show_full_cmd=show_full_cmd,
                       show_user=show_user,
                       show_pid=show_pid,
                       show_power=show_power,
                       show_fan_speed=show_fan_speed,
                       gpuname_width=gpuname_width,
                       term=t_color)
            fp.write(eol_char)

        fp.flush()
Ejemplo n.º 59
0
def __log_locale_settings(message=None):
    _setlocale_categories = {}
    for category in 'LC_ALL LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION'.split(
    ):
        try:
            _setlocale_categories[category] = getattr(locale, category)
        except Exception:
            _log.warning('this OS does not have locale.%s', category)
    _getlocale_categories = {}
    for category in 'LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION'.split(
    ):
        try:
            _getlocale_categories[category] = getattr(locale, category)
        except Exception:
            pass
    if message is not None:
        _log.debug(message)

    _log.debug('current locale settings:')
    _log.debug('locale.getlocale(): %s' % str(locale.getlocale()))
    for category in _getlocale_categories:
        _log.debug(
            'locale.getlocale(%s): %s' %
            (category, locale.getlocale(_getlocale_categories[category])))
    for category in _setlocale_categories:
        _log.debug(
            '(locale.setlocale(%s): %s)' %
            (category, locale.setlocale(_setlocale_categories[category])))
    try:
        _log.debug('locale.getdefaultlocale() - default (user) locale: %s' %
                   str(locale.getdefaultlocale()))
    except ValueError:
        _log.exception('the OS locale setup seems faulty')

    _log.debug(
        'encoding sanity check (also check "locale.nl_langinfo(CODESET)" below):'
    )
    pref_loc_enc = locale.getpreferredencoding(do_setlocale=False)
    loc_enc = locale.getlocale()[1]
    py_str_enc = sys.getdefaultencoding()
    sys_fs_enc = sys.getfilesystemencoding()
    _log.debug('sys.getdefaultencoding(): [%s]' % py_str_enc)
    _log.debug('locale.getpreferredencoding(): [%s]' % pref_loc_enc)
    _log.debug('locale.getlocale()[1]: [%s]' % loc_enc)
    _log.debug('sys.getfilesystemencoding(): [%s]' % sys_fs_enc)
    if loc_enc is not None:
        loc_enc = loc_enc.upper()
        loc_enc_compare = loc_enc.replace('-', '')
    else:
        loc_enc_compare = loc_enc
    if pref_loc_enc.upper().replace('-', '') != loc_enc_compare:
        _log.warning(
            'encoding suggested by locale (%s) does not match encoding currently set in locale (%s)'
            % (pref_loc_enc, loc_enc))
        _log.warning('this might lead to encoding errors')
    for enc in [pref_loc_enc, loc_enc, py_str_enc, sys_fs_enc]:
        if enc is not None:
            try:
                codecs.lookup(enc)
                _log.debug('<codecs> module CAN handle encoding [%s]' % enc)
            except LookupError:
                _log.warning('<codecs> module can NOT handle encoding [%s]' %
                             enc)
    _log.debug(
        'on Linux you can determine a likely candidate for the encoding by running "locale charmap"'
    )

    _log.debug(
        'locale related environment variables (${LANG} is typically used):')
    for var in 'LANGUAGE LC_ALL LC_CTYPE LANG'.split():
        try:
            _log.debug('${%s}=%s' % (var, os.environ[var]))
        except KeyError:
            _log.debug('${%s} not set' % (var))

    _log.debug('database of locale conventions:')
    data = locale.localeconv()
    for key in data:
        if loc_enc is None:
            _log.debug('locale.localeconv(%s): %s', key, data[key])
        else:
            try:
                _log.debug('locale.localeconv(%s): %s', key, str(data[key]))
            except UnicodeDecodeError:
                _log.debug('locale.localeconv(%s): %s', key,
                           str(data[key], loc_enc))
    _nl_langinfo_categories = {}
    for category in 'CODESET D_T_FMT D_FMT T_FMT T_FMT_AMPM RADIXCHAR THOUSEP YESEXPR NOEXPR CRNCYSTR ERA ERA_D_T_FMT ERA_D_FMT ALT_DIGITS'.split(
    ):
        try:
            _nl_langinfo_categories[category] = getattr(locale, category)
        except Exception:
            _log.warning(
                'this OS does not support nl_langinfo category locale.%s' %
                category)
    try:
        for category in _nl_langinfo_categories:
            if loc_enc is None:
                _log.debug(
                    'locale.nl_langinfo(%s): %s' %
                    (category,
                     locale.nl_langinfo(_nl_langinfo_categories[category])))
            else:
                try:
                    _log.debug(
                        'locale.nl_langinfo(%s): %s', category,
                        str(
                            locale.nl_langinfo(
                                _nl_langinfo_categories[category])))
                except UnicodeDecodeError:
                    _log.debug(
                        'locale.nl_langinfo(%s): %s', category,
                        str(
                            locale.nl_langinfo(
                                _nl_langinfo_categories[category]), loc_enc))
    except Exception:
        _log.exception('this OS does not support nl_langinfo')

    _log.debug('gmI18N.get_encoding(): %s', get_encoding())
Ejemplo n.º 60
0
    def load_lang(self, lang, lang_name=None):
        """ Create the given language if necessary, and make it active. """
        # if the language exists, simply make it active
        language = self.with_context(active_test=False).search(
            [('code', '=', lang)], limit=1)
        if language:
            language.write({'active': True})
            return language.id

        # create the language with locale information
        fail = True
        iso_lang = tools.get_iso_codes(lang)
        for ln in tools.get_locales(lang):
            try:
                locale.setlocale(locale.LC_ALL, str(ln))
                fail = False
                break
            except locale.Error:
                continue
        if fail:
            lc = locale.getdefaultlocale()[0]
            msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.'
            _logger.warning(msg, lang, lc)

        if not lang_name:
            lang_name = lang

        def fix_xa0(s):
            """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(),
               coercing to utf-8, as some platform seem to output localeconv() in their system
               encoding, e.g. Windows-1252"""
            if s == '\xa0':
                return '\xc2\xa0'
            return s

        def fix_datetime_format(format):
            """Python's strftime supports only the format directives
               that are available on the platform's libc, so in order to
               be 100% cross-platform we map to the directives required by
               the C standard (1989 version), always available on platforms
               with a C standard implementation."""
            # For some locales, nl_langinfo returns a D_FMT/T_FMT that contains
            # unsupported '%-' patterns, e.g. for cs_CZ
            format = format.replace('%-', '%')
            for pattern, replacement in tools.DATETIME_FORMATS_MAP.items():
                format = format.replace(pattern, replacement)
            return str(format)

        conv = locale.localeconv()
        lang_info = {
            'code': lang,
            'iso_code': iso_lang,
            'name': lang_name,
            'active': True,
            'date_format':
            fix_datetime_format(locale.nl_langinfo(locale.D_FMT)),
            'time_format':
            fix_datetime_format(locale.nl_langinfo(locale.T_FMT)),
            'decimal_point': fix_xa0(str(conv['decimal_point'])),
            'thousands_sep': fix_xa0(str(conv['thousands_sep'])),
            'grouping': str(conv.get('grouping', [])),
        }
        try:
            return self.create(lang_info).id
        finally:
            tools.resetlocale()