Esempio n. 1
0
    def __call__(cls, *args, **kwargs):
        obj = cls.__new__(cls)
        if ('locale' in kwargs) and (kwargs['locale'] is not None):
            obj._locale = kwargs['locale']
        else:
            obj._locale = get_locale()

        if 'session' in kwargs:
            obj._session = kwargs['session']
        else:
            obj._session = get_session()

        obj._data = {}
        if 'raw' in kwargs:
            # if 'raw' keyword is supplied, create populate object manually
            if len(args) != 0:
                raise TypeError('__init__() takes exactly 2 arguments (1 given)')
            obj._populate.apply(kwargs['raw'], False)
        else:
            # if not, the number of input arguments must exactly match that
            # defined by the Data definitions
            if len(args) != len(cls._InitArgs):
                raise TypeError('__init__() takes exactly {0} arguments ({1} given)'\
                            .format(len(cls._InitArgs)+1, len(args)+1))
            for a,v in zip(cls._InitArgs, args):
                setattr(obj, a, v)

        obj.__init__()
        return obj
Esempio n. 2
0
 def fromIMDB(cls, imdbid, locale=None):
     try:
         # assume string
         if not imdbid.startswith('tt'):
             imdbid = "tt{0:0>7}".format(imdbid)
     except AttributeError:
         # assume integer
         imdbid = "tt{0:0>7}".format(imdbid)
     if locale is None:
         locale = get_locale()
     movie = cls(imdbid, locale=locale)
     movie._populate()
     return movie
Esempio n. 3
0
    def __init__(self, url, **kwargs):
        """Return a request object, using specified API path and arguments."""
        kwargs["api_key"] = self.api_key
        self._url = url.lstrip("/")
        self._kwargs = dict([(kwa, kwv) for kwa, kwv in kwargs.items() if kwv is not None])

        locale = get_locale()
        kwargs = {}
        for k, v in self._kwargs.items():
            kwargs[k] = locale.encode(v)
        url = "{0}{1}?{2}".format(self._base_url, self._url, urlencode(kwargs))

        urllib2.Request.__init__(self, url)
        self.add_header("Accept", "application/json")
        self.lifetime = 3600  # 1hr
    def __init__(self, url, **kwargs):
        """
        Return a request object, using specified API path and
        arguments.
        """
        kwargs['api_key'] = self.api_key
        self._url = url.lstrip('/')
        self._kwargs = dict([(kwa, kwv) for kwa, kwv in kwargs.items()
                                        if kwv is not None])

        locale = get_locale()
        kwargs = {}
        for k, v in self._kwargs.items():
            if isinstance(v, unicode):
                kwargs[k] = v.encode('utf-8')
            else:
                kwargs[k] = str(v)
        url = '{0}{1}?{2}'.format(self._base_url, self._url, urlencode(kwargs))

        urllib2.Request.__init__(self, url)
        self.add_header('Accept', 'application/json')
        self.lifetime = 3600  # 1hr
Esempio n. 5
0
 def __init__(self, request, locale=None):
     if locale is None:
         locale = get_locale()
     super(CollectionSearchResult, self).__init__(
                 request.new(language=locale.language),
                 lambda x: Collection(raw=x, locale=locale))
Esempio n. 6
0
 def locale(self):
     return get_locale(self.language, self.country)
Esempio n. 7
0
 def __init__(self, request, locale=None):
     if locale is None:
         locale = get_locale()
     super(SeriesSearchResult, self).__init__(
                 request.new(language=locale.language),
                 lambda x: Series(raw=x, locale=locale))
Esempio n. 8
0
 def locale(self):
     return get_locale(self.language, self.country)
Esempio n. 9
0
 def __init__(self, request, locale=None):
     if locale is None:
         locale = get_locale()
     super(CollectionSearchResult,
           self).__init__(request.new(language='fr'),
                          lambda x: Collection(raw=x, locale=locale))
Esempio n. 10
0
    # Instead it is a special "windows/cp" encoding
    # We need to run and check the output of the "chcp" windows command to
    # check for the current encoding
    """
    FIXME: Is this really necessary when we get the current character encoding
           from the call to the "locale.getdefaultlocale()" method above?
    """
    import subprocess
    # We need to split the output by ": " and choosing the last/second part.
    # Then, we appends the returned number to the "cp" prefix (could as well
    # have used "windows-" as prefix)
    current_coding = "cp" + subprocess.check_output(
        "chcp", shell=True).split(": ")[1].strip()
print current_coding

localized_strings = locales.get_locale(current_locale)
print localized_strings

# Create a thread pool to keep the number of running threads to a minimum
thread_pool = ThreadPool(4)


@atexit.register
def clean_up():
    frontend.stop()
    active_channel = 0
    if p is not None and p.player:
        active_channel = p.active_channel
        p.player.stop()
    config.save_last_state(last_radio_station=active_channel,
                           last_page=gui.current_page)
Esempio n. 11
0
    def humanize(self, other=None, locale='en_us'):
        ''' Returns a localized, humanized representation of a relative difference in time.

        :param other: (optional) an :class:`Arrow <arrow.arrow.Arrow>` or ``datetime`` object.
            Defaults to now in the current :class:`Arrow <arrow.arrow.Arrow>` object's timezone.
        :param locale: (optional) a ``str`` specifying a locale.  Defaults to 'en_us'.

        Usage::

            >>> earlier = arrow.utcnow().replace(hours=-2)
            >>> earlier.humanize()
            '2 hours ago'

            >>> later = later = earlier.replace(hours=4)
            >>> later.humanize(earlier)
            'in 4 hours'

        '''

        locale = locales.get_locale(locale)

        if other is None:
            utc = datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc())
            dt = utc.astimezone(self._datetime.tzinfo)

        elif isinstance(other, Arrow):
            dt = other._datetime

        elif isinstance(other, datetime):
            if other.tzinfo is None:
                dt = other.replace(tzinfo=self._datetime.tzinfo)
            else:
                dt = other.astimezone(self._datetime.tzinfo)

        else:
            raise TypeError()

        delta = int(util.total_seconds(self._datetime - dt))
        sign = -1 if delta < 0 else 1
        diff = abs(delta)
        delta = diff

        if diff < 10:
            return locale.describe('now')

        if diff < 45:
            return locale.describe('seconds', sign)

        elif diff < 90:
            return locale.describe('minute', sign)
        elif diff < 2700:
            minutes = sign * int(max(delta / 60, 2))
            return locale.describe('minutes', minutes)

        elif diff < 5400:
            return locale.describe('hour', sign)
        elif diff < 79200:
            hours = sign * int(max(delta / 3600, 2))
            return locale.describe('hours', hours)

        elif diff < 129600:
            return locale.describe('day', sign)
        elif diff < 2160000:
            days = sign * int(max(delta / 86400, 2))
            return locale.describe('days', days)

        elif diff < 3888000:
            return locale.describe('month', sign)
        elif diff < 29808000:
            self_months = self._datetime.year * 12 + self._datetime.month
            other_months = dt.year * 12 + dt.month
            months = sign * abs(other_months - self_months)

            return locale.describe('months', months)

        elif diff < 47260800:
            return locale.describe('year', sign)
        else:
            years = sign * int(max(delta / 31536000, 2))
            return locale.describe('years', years)
Esempio n. 12
0
 def __init__(self, request, locale=None):
     if locale is None:
         locale = get_locale()
     super(MovieSearchResult, self).__init__(
                             request.new(language='fr'),
                             lambda x: Movie(raw=x, locale=locale))
Esempio n. 13
0
    # On windows platforms, current character encoding is never "utf-8".
    # Instead it is a special "windows/cp" encoding
    # We need to run and check the output of the "chcp" windows command to
    # check for the current encoding
    """
    FIXME: Is this really necessary when we get the current character encoding
           from the call to the "locale.getdefaultlocale()" method above?
    """
    import subprocess
    # We need to split the output by ": " and choosing the last/second part.
    # Then, we appends the returned number to the "cp" prefix (could as well
    # have used "windows-" as prefix)
    current_coding = "cp" + subprocess.check_output("chcp", shell=True).split(": ")[1].strip()
print current_coding

localized_strings = locales.get_locale(current_locale)
print localized_strings

# Create a thread pool to keep the number of running threads to a minimum
thread_pool = ThreadPool(4)

@atexit.register
def clean_up():
    frontend.stop()
    active_channel = 0
    if p is not None and p.player:
        active_channel = p.active_channel
        p.player.stop()
    config.save_last_state(
        last_radio_station=active_channel, 
        last_page=gui.current_page