コード例 #1
0
ファイル: Filter.py プロジェクト: JPilarr/tapyr
    op_name = "and"
    quant = staticmethod(all_true)

    def __invert__(self):
        return Filter_Or(*self._inverted_predicate())

    # end def __invert__


# end class Filter_And


class Filter_Or(_Filter_Q_):
    """Return all items from an iterable which satisfy any of the predicates."""

    op_name = "or"
    quant = staticmethod(any_true)

    def __invert__(self):
        return Filter_And(*self._inverted_predicate())

    # end def __invert__


# end class Filter_Or

if __name__ != "__main__":
    TFL._Export("*", "_Filter_", "_Filter_Q_")
### __END__ TFL.Filter
コード例 #2
0
ファイル: __init__.py プロジェクト: xiaochang91/tapyr
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2010 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.Babel.__init__
#
# Purpose
#    Package for inetgration with the Babel i18n framework
#
# Revision Dates
#    21-Jan-2010 (MG) Creation
#    ««revision-date»»···
#--

from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

Babel = Package_Namespace()
TFL._Export("Babel")

del Package_Namespace

### __END__ TFL.Babel.__init__
コード例 #3
0
ファイル: Q_Result.py プロジェクト: Tapyr/tapyr
@Single_Dispatch
def fixed_order_by (x) :
    if hasattr (x, "__call__") :
        return x
    else :
        raise ValueError ("Cannot order by %s %r" % (x.__class__.__name__, x))
# end def fixed_order_by

@fixed_order_by.add_type (TFL.Sorted_By, TFL.Q_Exp.Base)
def _fixed_order_by_sorted_by_ (x) :
    return x
# end def _fixed_order_by_sorted_by_

@fixed_order_by.add_type (* pyk.string_types)
def _fixed_order_by_str_ (x) :
    return TFL.Sorted_By (x)
# end def _fixed_order_by_str_

@fixed_order_by.add_type (tuple)
def _fixed_order_by_tuple (xs) :
    if len (xs) == 1 :
        return fixed_order_by (xs [0])
    else :
        return TFL.Sorted_By (* tuple (fixed_order_by (x) for x in xs))
# end def _fixed_order_by_tuple

if __name__ != "__main__" :
    TFL._Export ("*", "_Q_Result_")
### __END__ TFL.Q_Result
コード例 #4
0
    def add_alias (self, alias_name, real_name) :
        self._alias_names [alias_name] = real_name
    # end def add_alias

    def copy (self, ** kw) :
        result = self.__class__ (self, ** kw)
        result._alias_names = dict (self._alias_names)
        return result
    # end def copy

    def get (self, key, default = None) :
        key = self._alias_names.get (key, key)
        return self.__super.get (key, default)
    # end def get

    def __contains__ (self, key) :
        key = self._alias_names.get (key, key)
        return self.__super.__contains__ (key)
    # end def __contains__

    def __getitem__ (self, key) :
        key = self._alias_names.get (key, key)
        return self.__super.__getitem__ (key)
    # end def __getitem__

# end class Alias_Dict

if __name__ != "__main__" :
    TFL._Export ("Alias_Dict")
### __END__ TFL.Alias_Dict
コード例 #5
0
ファイル: Filter.py プロジェクト: Tapyr/tapyr
# end class _Filter_Q_

class Filter_And (_Filter_Q_) :
    """Return all items from an iterable which satisfy all predicates."""

    op_name = "and"
    quant   = staticmethod (all_true)

    def __invert__ (self) :
        return Filter_Or (* self._inverted_predicate ())
    # end def __invert__

# end class Filter_And

class Filter_Or (_Filter_Q_) :
    """Return all items from an iterable which satisfy any of the predicates."""

    op_name = "or"
    quant   = staticmethod (any_true)

    def __invert__ (self) :
        return Filter_And (* self._inverted_predicate ())
    # end def __invert__

# end class Filter_Or

if __name__ != "__main__" :
    TFL._Export ("*", "_Filter_", "_Filter_Q_")
### __END__ TFL.Filter
コード例 #6
0
    >>> print (formatted_repr (Record (qux = 23)))
    Record (qux = 23)

    >>> thinr = Record (foo = 42, bar = u"wrzl", baz = "MadamImadam")
    >>> print (formatted_repr (thinr))
    Record
      ( bar = 'wrzl'
      , baz = 'MadamImadam'
      , foo = 42
      )

    >>> thinq = ["abc", "dfg", { 1 : "yxz" }, thinr]
    >>> print (formatted_repr (thinq))
    [ 'abc'
    , 'dfg'
    , {1 : 'yxz'}
    , Record
        ( bar = 'wrzl'
        , baz = 'MadamImadam'
        , foo = 42
        )
    ]

"""

__all__ = ("formatted_repr", "formatted_repr_compact")

if __name__ != "__main__" :
    TFL._Export (* __all__)
### __END__ TFL.formatted_repr
コード例 #7
0
ファイル: __init__.py プロジェクト: xiaochang91/tapyr
#
# Revision Dates
#    13-May-2002 (CT) Creation
#     2-Feb-2009 (CT) Documentation added
#     3-Feb-2009 (CT) Documentation added..
#     4-Feb-2009 (CT) Documentation added...
#    14-Oct-2013 (CT) Add `Single_Dispatch`
#     5-Aug-2015 (CT) Add `M_Auto_Update_Combined`
#    ««revision-date»»···
#--

from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

Meta = Package_Namespace()
TFL._Export("Meta")

del Package_Namespace

__doc__ = """
.. moduleauthor:: Christian Tanzer <*****@*****.**>

`TFL.Meta` provides a generic base-class and various meta-classes and
property-helpers:

- New-style classes should be derived (directly or indirectly) from
  :class:`Object<_TFL._Meta.Object.Object>` instead of
  Python's builtin `object`.

- Classes derived from other builtin types (like `dict`, `list`,
  `set`, etc.) should declare their metaclass to be
コード例 #8
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
# Copyright (C) 2006-2016 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.DRA.__init__
#
# Purpose
#    Package for data reduction and analysis
#
# Revision Dates
#    15-Nov-2006 (CT) Creation
#     9-Oct-2016 (CT) Move to Package_Namespace `TFL`
#    ««revision-date»»···
#--

from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

DRA = Package_Namespace ()

TFL._Export ("DRA")

del Package_Namespace

### __END__ TFL.DRA.__init__
コード例 #9
0
        def unicode (obj, seen) :
            return repr (obj).lstrip ("u")
        # end def unicode
    else : ### Python version >= 3
        @generic_portable_repr.add_type (bytes)
        def bytes (obj, seen) :
            return repr (obj).lstrip ("b")
        # end def bytes

# end class _portable_repr_properties

_portable_repr_properties.update \
    (  (k, getattr (_portable_repr_properties ["call"], k))
    for k in ("add_type", "dispatch", "top_func")
    )

@Attributed (** _portable_repr_properties)
def portable_repr (obj) :
    """Return a portable canonical string representation of `obj`.

       For many object types, eval (portable_repr (object)) == object.
    """
    return portable_repr.call (obj, seen = set ())
# end def portable_repr

__all__ = ("portable_repr", )

if __name__ != "__main__" :
    TFL._Export (* __all__)
### __END__ TFL.portable_repr
コード例 #10
0
ファイル: Sync_File.py プロジェクト: Tapyr/tapyr
        try :
            file = db.open ()
        except Sync_Conflict as exc :
            ### traceback.print_exc ()
            print \
                ( "The %s `%s` was changed since you started to work on it"
                % (db.file_desc, db.file_name)
                )
            raise Sync_Error (db)
        except KeyboardInterrupt :
            raise
        except Exception as exc :
            ### traceback.print_exc ()
            print \
                ( "The %s `%s` couldn't be opened for writing "
                  "due to exception\n    `%s`"
                % (db.file_desc, db.file_name, str (exc))
                )
            raise
        try :
            self._save_data (file)
        finally :
            db.close ()
    # end def save

# end class Sync_DB_

if __name__ != "__main__" :
    TFL._Export ("*", "_Sync_File_", "_Open_Sync_Dir_")
### __END__ TFL.Sync_File
コード例 #11
0
ファイル: ui_display.py プロジェクト: JPilarr/tapyr
    >>> print (ui_display ("a"))
    a

    >>> print (ui_display (u"a"))
    a

For types with no specific implementation, ``ui_display`` returns the
``portable_repr``:

    >>> import datetime
    >>> d = datetime.date (2014, 2, 6)

    >>> print (ui_display (d))
    datetime.date(2014, 2, 6)

Adding an implementation for a specific type is easy enough, though::

    >>> @ui_display.add_type (datetime.date)
    ... def _ui_display_date (obj) :
    ...     return str (obj)

    >>> print (ui_display (d))
    2014-02-06

"""

if __name__ != "__main__":
    TFL._Export("ui_display")
### __END__ TFL.ui_display
コード例 #12
0
ファイル: Black_Hole.py プロジェクト: Tapyr/tapyr
       Don't try too apply `dir' to `black_hole' -- it will die slowly.

       `__coerce__' is needed to allow comparisons and the use of
       `black_hole' with unary and binary operators.

    """

    def __init__    (s, * args, ** kw) : pass
    def __call__    (s, * args, ** kw) : return s
    def __bool__    (s)                : return False
    def __coerce__  (s, o)             : return s, s
    def __eq__      (s, o)             : return False
    def __getattr__ (s, n)             : return s
    def __ge__      (s, o)             : return False
    def __gt__      (s, o)             : return False
    def __hash__    (s)                : return 0
    def __len__     (s)                : return 0
    def __le__      (s, o)             : return False
    def __lt__      (s, o)             : return False
    def __ne__      (s, o)             : return False
    def __repr__    (s)                : return "<_Black_Hole_ at %s>" % id (s)
    def __str__     (s)                : return ""

# end class _Black_Hole_

black_hole = _Black_Hole_ ()

if __name__ != "__main__" :
    TFL._Export ("black_hole", "_Black_Hole_")
### __END__ TFL.Black_Hole
コード例 #13
0
ファイル: import_module.py プロジェクト: Tapyr/tapyr
    ###
    ### When importing a module from a package, note that
    ### __import__('A.B', ...) returns package A when fromlist is empty,
    ### but its submodule B when fromlist is not empty.
    result = __import__ (module_name)
    for n in module_name.split (".") [1:] :
        ### This kind of importing is brittle because it fails if one tries to
        ### `import_module_brittle` a module inside a package while the module
        ### itself is still being imported (it is already in sys.modules but
        ### not yet in the `__dict__` of the containing package)
        try :
            result = getattr (result, n)
        except AttributeError as exc :
            raise ImportError ("%s: %s, %s" % (exc, module_name, result))
    return result
# end def import_module_brittle

def import_module (module_name) :
    """Returns the imported module named `module_name`. If `module_name` is
       naming a module living inside a package (e.g., `A.B.C`), the rightmost
       module (i.e., `C`) is returned.
    """
    __import__ (module_name)
    return sys.modules [module_name]
# end def import_module

if __name__ != "__main__" :
    from _TFL import TFL
    TFL._Export ("import_module")
### __END__ import_module
コード例 #14
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2010 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.FMW.__init__
#
# Purpose
#    Function/Method Wrapper package
#
# Revision Dates
#    22-Sep-2004 (CT) Creation
#    ««revision-date»»···
#--

from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

FMW = Package_Namespace ()
TFL._Export ("FMW")

del Package_Namespace

### __END__ TFL.FMW.__init__
コード例 #15
0
ファイル: Sphere.py プロジェクト: Tapyr/tapyr
        lng2 = math.radians (p2.lon)

        sin_lat1, cos_lat1 = math.sin (lat1), math.cos (lat1)
        sin_lat2, cos_lat2 = math.sin (lat2), math.cos (lat2)

        delta_lng            = lng2 - lng1
        cos_d_lng, sin_d_lng = math.cos (delta_lng), math.sin (delta_lng)

        # We're correcting from floating point rounding errors on very-near
        # and exact points here
        central_angle = math.acos \
            (min (1.0, sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_d_lng))

        d = math.atan2 \
            ( math.sqrt
                ( (cos_lat2 * sin_d_lng) ** 2
                + (cos_lat1 * sin_lat2 - sin_lat1 * cos_lat2 * cos_d_lng) ** 2
                )
            , sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_d_lng
            )
        return self.radius * d
    # end def distance

# end class Sphere

Earth = Sphere (6372795) ### Average radius of the earth in meters

if __name__ != "__main__" :
    TFL._Export ("Sphere", "Earth")
### __END__ TFL.Sphere
コード例 #16
0
ファイル: Sphere.py プロジェクト: JPilarr/tapyr
        lng2 = math.radians (p2.lon)

        sin_lat1, cos_lat1 = math.sin (lat1), math.cos (lat1)
        sin_lat2, cos_lat2 = math.sin (lat2), math.cos (lat2)

        delta_lng            = lng2 - lng1
        cos_d_lng, sin_d_lng = math.cos (delta_lng), math.sin (delta_lng)

        # We're correcting from floating point rounding errors on very-near
        # and exact points here
        central_angle = math.acos \
            (min (1.0, sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_d_lng))

        d = math.atan2 \
            ( math.sqrt
                ( (cos_lat2 * sin_d_lng) ** 2
                + (cos_lat1 * sin_lat2 - sin_lat1 * cos_lat2 * cos_d_lng) ** 2
                )
            , sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_d_lng
            )
        return self.radius * d
    # end def distance

# end class Sphere

Earth = Sphere (6372795) ### Average radius of the earth in meters

if __name__ != "__main__" :
    TFL._Export ("Sphere", "Earth")
### __END__ TFL.Sphere
コード例 #17
0
    def __repr__(self):
        return str(self.number)

    # end def __repr__

    def __eq__(self, other):
        if isinstance(other, _Divisor_Dag_):
            other = other.number
        return self.number == other

    # end def __eq__

    def __hash__(self):
        return hash(self.number)

    # end def divisors

    def __lt__(self, other):
        if isinstance(other, _Divisor_Dag_):
            other = other.number
        return self.number < other

    # end def __lt__


# end class _Divisor_Dag_

if __name__ != "__main__":
    TFL._Export("*", "_Divisor_Dag_")
### __END__ TFL.Divisor_Dag
コード例 #18
0
        print ("One of the options -AP_Closure or -Diff must be specified")
        raise SystemExit (9)
    packager = Plugin_Packager \
        (cmd.pi_root_name, ap_closure, import_path, cmd.target_root, ignore)
# end def _main

_Command = TFL.CAO.Cmd \
    ( handler       = _main
    , args          =
        ( "pi_root_name:S"
        , "target_root:S"
        , "import_path:P=./"
        )
    , opts          =
        ( "-AP_Closure:S"
              "?Name of file containing the import closure of application"
        , "-Diff:S"
              "?Name of python_module which import closure gets subtracted"
        , "-ignore:S,=U_Test?Ignore modules specified"
        , "-Pathsep:S=:?Path separator used by `import_path'"
        )
    , min_args      = 2
    , max_args      = 3
    )

if __name__ != "__main__":
    TFL._Export ("Plugin_Packager")
else :
    _Command ()
### __END__ TFL.Plugin_Packager
コード例 #19
0
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.SDG.__init__
#
# Purpose
#    Package modelling structured document generators
#
# Revision Dates
#    23-Jul-2004 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    26-Feb-2012 (MG) `__future__` imports added
#    ««revision-date»»···
#--

from __future__ import absolute_import, division, print_function, unicode_literals
from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

SDG = Package_Namespace()
TFL._Export("SDG")

del Package_Namespace

### __END__ TFL.SDG.__init__
コード例 #20
0
ファイル: Field_Reader.py プロジェクト: xiaochang91/tapyr
#    06-Aug-2007 (CED) Future import removed again
#    ««revision-date»»···
#--



import sys

class Field_Reader :
    """Read and convert fields from the next line of a file"""

    def __init__ (self, * field_types, ** kw) :
        self.field_types = field_types
        self._file       = kw.get ("file",      sys.stdin)
        splitargs        = kw.get ("splitargs", ())
        if isinstance (splitargs, str) :
            splitargs    = (splitargs, )
        self.splitargs   = splitargs
    # end def __init__

    def __call__ (self) :
        fields = self._file.readline ().split (* self.splitargs)
        return [c (f) for (c,f) in zip (self.field_types, fields)]
    # end def __call__
# end class Field_Reader

from _TFL import TFL
TFL._Export ("Field_Reader")

### __END__ Field_Reader
コード例 #21
0
ファイル: predicate.py プロジェクト: xiaochang91/tapyr
       [0, 1, 2]
       >>> un_nested ([list (range (3))])
       [0, 1, 2]
       >>> un_nested ([list (range (3)), list (range (2))])
       [[0, 1, 2], [0, 1]]
    """
    if l and len(l) == 1 and isinstance(l[0], (list, tuple)):
        l = l[0]
    return l


# end def un_nested


def xored_string(source, salt="ß"):
    salt = ord(salt)
    return "".join(chr(ord(c) ^ salt) for c in source)


# end def xored_string

__doc__ = """

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__":
    TFL._Export("*", "sorted", "reversed")
### __END__ TFL.predicate
コード例 #22
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.Units.__init__
#
# Purpose
#    Package for measurement units
#
# Revision Dates
#     8-Aug-2004 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    ««revision-date»»···
#--



from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

Units = Package_Namespace ()
TFL._Export ("Units")

del Package_Namespace

### __END__ TFL.Units.__init__
コード例 #23
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    __init__
#
# Purpose
#    Package for 2D geometry
#
# Revision Dates
#    24-Jun-2002 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    ««revision-date»»···
#--



from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

D2 = Package_Namespace ()
TFL._Export ("D2")

del Package_Namespace

### __END__ __init__
コード例 #24
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2010 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.Babel.__init__
#
# Purpose
#    Package for inetgration with the Babel i18n framework
#
# Revision Dates
#    21-Jan-2010 (MG) Creation
#    ««revision-date»»···
#--

from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

Babel = Package_Namespace ()
TFL._Export ("Babel")

del Package_Namespace

### __END__ TFL.Babel.__init__
コード例 #25
0
ファイル: Undef.py プロジェクト: Tapyr/tapyr
    >>> undefined_foo = Undef ("foo")
    >>> bool (undefined_foo)
    False
    >>> undefined_foo
    <Undef/foo>

    >>> undefined_bar = Undef ("bar")
    >>> bool (undefined_bar)
    False
    >>> undefined_bar
    <Undef/bar>

    >>> undefined_foo == undefined_bar
    False
    >>> undefined_foo is undefined_bar
    False

    >>> undefined_foo == Undef ("foo")
    False
    >>> undefined_foo is Undef ("foo")
    False

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__" :
    TFL._Export ("Undef", "is_undefined")
### __END__ TFL.Undef
コード例 #26
0
ファイル: __init__.py プロジェクト: xiaochang91/tapyr
# Copyright (C) 2006-2016 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.DRA.__init__
#
# Purpose
#    Package for data reduction and analysis
#
# Revision Dates
#    15-Nov-2006 (CT) Creation
#     9-Oct-2016 (CT) Move to Package_Namespace `TFL`
#    ««revision-date»»···
#--

from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

DRA = Package_Namespace()

TFL._Export("DRA")

del Package_Namespace

### __END__ TFL.DRA.__init__
コード例 #27
0
        """
        if not hasattr(self, "ivn"):
            ### object still under construction -- don't prevent attribute
            ### settings or changes
            self.__dict__[name] = value
            return
        ### object fully constructed -- do what must be done
        if name in self.ivn:
            self.ivn[name].external_version = value
        elif name in self.__dict__:
            raise TypeError \
                ( "Attribute %s is readonly. Cannot change value from %s to %s"
                % (name, getattr (self, name), value)
                )
        else:
            self.__dict__[name] = value

    # end def __setattr__

    def __str__(self):
        return self.message

    # end def __str__


Product_Version = _TFL_Product_Version_  # end class

if __name__ != "__main__":
    TFL._Export("Product_Version", "Lic_Comp")
### __END__ TFL.Product_Version
コード例 #28
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.SDG.__init__
#
# Purpose
#    Package modelling structured document generators
#
# Revision Dates
#    23-Jul-2004 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    26-Feb-2012 (MG) `__future__` imports added
#    ««revision-date»»···
#--

from   __future__  import absolute_import, division, print_function, unicode_literals
from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

SDG = Package_Namespace ()
TFL._Export ("SDG")

del Package_Namespace

### __END__ TFL.SDG.__init__
コード例 #29
0
ファイル: Sync_File.py プロジェクト: xiaochang91/tapyr
        except Sync_Conflict as exc:
            ### traceback.print_exc ()
            print \
                ( "The %s `%s` was changed since you started to work on it"
                % (db.file_desc, db.file_name)
                )
            raise Sync_Error(db)
        except KeyboardInterrupt:
            raise
        except Exception as exc:
            ### traceback.print_exc ()
            print \
                ( "The %s `%s` couldn't be opened for writing "
                  "due to exception\n    `%s`"
                % (db.file_desc, db.file_name, str (exc))
                )
            raise
        try:
            self._save_data(file)
        finally:
            db.close()

    # end def save


# end class Sync_DB_

if __name__ != "__main__":
    TFL._Export("*", "_Sync_File_", "_Open_Sync_Dir_")
### __END__ TFL.Sync_File
コード例 #30
0
ファイル: __init__.py プロジェクト: xiaochang91/tapyr
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    __init__
#
# Purpose
#    Package for 2D geometry
#
# Revision Dates
#    24-Jun-2002 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    ««revision-date»»···
#--

from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

D2 = Package_Namespace()
TFL._Export("D2")

del Package_Namespace

### __END__ __init__
コード例 #31
0
ファイル: Angle.py プロジェクト: Tapyr/tapyr
    >>> a = Angle (405)
    >>> a
    Angle_D (45)

    >>> b = Angle (Angle_D (45))
    >>> a == b
    True

    >>> c = Angle (Angle_R (0.78539816339744828))
    >>> a == c
    True

    >>> d = Angle ((48, 30, 18))
    >>> d
    Angle_D (48.505)

    """
    if isinstance (angle, _Angle_) :
        result = angle
    else :
        if isinstance (angle, (list, tuple)) :
            angle = Angle_D (* angle)
        result = Angle_D.normalized (angle)
    return result
# end def Angle

if __name__ == "__main__" :
    TFL._Export ("*", "_Angle_")
### __END__ TFL.Angle
コード例 #32
0
ファイル: Accessor.py プロジェクト: Tapyr/tapyr
        callbacks).

       >>> lower = Method.lower
       >>> print (lower ("abCDe"))
       abcde
       >>> with expect_except (AttributeError) :
       ...     lower (1)
       AttributeError: 'int' object has no attribute 'lower'
    """

    def __getattr__ (self, name) :
        def _ (this, * args, ** kw) :
            return getattr (this, name) (* args, ** kw)
        _.__name__ = name
        return _
    # end def __getattr__

# end class _Method_

Getter = _Getter_ ()
Method = _Method_ ()

__doc__ = """
.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__" :
    TFL._Export ("Getter", "Method")
### __END__ TFL.Accessor
コード例 #33
0
ファイル: ulid.py プロジェクト: Tapyr/tapyr
        """Return an integer with `k` random bytes based on `os.urandom`.

           In Python 3.6, calls to `os.urandom` can block if there isn't
           enough entropy available.
        """
        return int (codecs.encode (os.urandom (k), "hex"), 16)
    # end def get_random_cu

# end class Ulid

ulid_48  = Ulid (t_factor =    1000, t_length = 10, r_bytes  = 10)
ulid_64  = Ulid (t_factor = 1000000, t_length = 13, r_bytes  =  8)

ulid_48_secure   = Ulid \
    ( t_factor   = 1000
    , t_length   = 10
    , r_bytes    = 10
    , get_random = Ulid.get_random_cu
    )

ulid_64_secure   = Ulid \
    ( t_factor   = 1000000
    , t_length   = 13
    , r_bytes    = 8
    , get_random = Ulid.get_random_cu
    )

if __name__ != "__main__" :
    TFL._Export ("ulid_48", "ulid_64", "ulid_48_secure", "ulid_64_secure")
### __END__ TFL.ulid
コード例 #34
0
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
#    TFL.Units.__init__
#
# Purpose
#    Package for measurement units
#
# Revision Dates
#     8-Aug-2004 (CT) Creation
#    23-Jul-2007 (CED) Activated absolute_import
#    06-Aug-2007 (CED) Future import removed again
#    ««revision-date»»···
#--

from _TFL import TFL
from _TFL.Package_Namespace import Package_Namespace

Units = Package_Namespace()
TFL._Export("Units")

del Package_Namespace

### __END__ TFL.Units.__init__
コード例 #35
0
ファイル: predicate.py プロジェクト: Tapyr/tapyr
       This is handy if you want to support the passing of a list to a `*
       args' argument without using `apply`.

       >>> un_nested (list (range (3)))
       [0, 1, 2]
       >>> un_nested ([list (range (3))])
       [0, 1, 2]
       >>> un_nested ([list (range (3)), list (range (2))])
       [[0, 1, 2], [0, 1]]
    """
    if l and len (l) == 1 and isinstance (l [0], (list, tuple)) :
        l = l [0]
    return l
# end def un_nested

def xored_string (source, salt = "ß") :
    salt = ord (salt)
    return "".join (chr (ord (c) ^ salt) for c in source)
# end def xored_string

__doc__ = """

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__" :
    TFL._Export ("*", "sorted", "reversed")
### __END__ TFL.predicate
コード例 #36
0
_Command = TFL.CAO.Cmd \
    ( handler       = _main
    , args          =
        ( "python_module:S"
        , "import_path:P=./"
        , "separator:S= "
        )
    , opts          =
        ( "-as_code:B?Print import closure as executable python code"
        , "-debug:I=0"
        , "-Diff:S"
              "?Name of python_module which import closure gets subtracted"
        , "-files:B?Show all files in import closure"
        , "-ignore:S,=U_Test?Ignore modules specified"
        , "-packages:B?Show all packages in import closure"
        , "-Pathsep:S=:?Path separator used by `import_path`"
        , "-toplevels:B?Show all toplevel packages in import closure"
        , "-script_code:B?Add imports following the "
          "__name__ == '__main__' line"
        )
    , min_args      = 1
    , max_args      = 3
    )

if __name__ != "__main__":
    TFL._Export ("Import_Closure", "Derived_PNS_Finder")
else :
    _Command ()
### __END__ TFL.Import_Closure
コード例 #37
0
        else :
            exc_name = exc_type
        res = []
        for tb_line in traceback.extract_tb (exc_tb) :
            res.append (self._one_tb_line (tb_line))
        res.append ("\n%s: %s\n" % (exc_name, exc_value))
        return "\n".join (res)
    # end def as_string

    def _cut (self, s) :
        """returns `s`, reduced by the first match of the cutter"""
        if self.cutter :
            s = self.cutter.sub ("", s)
        return s
    # end def _cut

    def _one_tb_line (self, line) :
        """generate one traceback line (apply format string)"""
        fn, number, function, text = line
        fn = self._cut (fn)
        return self.format_str % locals ()
    # end def _one_tb_line

# end class _Traceback_Printer_

Traceback_Printer = _Traceback_Printer_ ()

if __name__ != "__main__" :
    TFL._Export ("_Traceback_Printer_", "Traceback_Printer")
### __END__ TFL.Traceback_Printer
コード例 #38
0
ファイル: Password_Hasher.py プロジェクト: JPilarr/tapyr
        @classmethod
        def hashed(cls, clear_password, salt=None):
            """Hashed value of `clear_password` using `salt`"""
            if salt is None:
                salt = bcrypt.gensalt(cls.default_rounds)
            else:
                salt = pyk.encoded(salt)
            result = bcrypt.hashpw(pyk.encoded(clear_password, "ascii"), salt)
            return pyk.decoded(result, "ascii")

        # end def hashed

        @classmethod
        def verify(cls, clear_password, hashed_password):
            """True if `clear_password` and `hashed_password` match"""
            try:
                cp = pyk.encoded(clear_password, "ascii")
                hp = pyk.encoded(hashed_password, "ascii")
                return bcrypt.checkpw(cp, hp)
            except Exception:
                return False

        # end def verify

    # end class Bcrypt

if __name__ != "__main__":
    TFL._Export("Password_Hasher")
### __END__ TFL.Password_Hasher
コード例 #39
0
            print ("%-40s: %d pattern occurrences replaced" % (fn, n))
    if not cmd.quiet :
        print \
            ( "%-40s: %d pattern occurrences replaced in %d files"
            % ("Total", t_n, t_f)
            )
# end def _main

__doc__ = """

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__" :
    TFL._Export ("*", "re")
else :
    import _TFL.CAO

    _Command = TFL.CAO.Cmd \
        ( handler       = _main
        , args          =
            ( TFL.CAO.Arg.Re_Replacer
                ( "replace"
                , description = "Regular expression to replace"
                )
            , "file:P?File(s) to replace regular expression(s) in"
            )
        , opts          =
            ( TFL.CAO.Arg.Re_Replacer
                ( "additional_replace"
コード例 #40
0
ファイル: Q_Exp.py プロジェクト: Tapyr/tapyr
    >>> Q.foo.bar.OR (Q.baz, Q.qux) > 23
    <Filter_Or [Q.foo.bar.baz > 23, Q.foo.bar.qux > 23]>

    >>> r1
    Record (bar = 137, baz = 11, foo = 42)

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 42) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 137) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 11) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 23) (r1)
    False

"""

__test__ = dict \
    ( test_doc = __doc__
    , test_q   = _test_q
    )

if __name__ != "__main__" :
    TFL._Export ("Q")
    TFL._Export_Module ()
### __END__ TFL.Q_Exp
コード例 #41
0
ファイル: ulid.py プロジェクト: JPilarr/tapyr
           In Python 3.6, calls to `os.urandom` can block if there isn't
           enough entropy available.
        """
        return int(codecs.encode(os.urandom(k), "hex"), 16)

    # end def get_random_cu


# end class Ulid

ulid_48 = Ulid(t_factor=1000, t_length=10, r_bytes=10)
ulid_64 = Ulid(t_factor=1000000, t_length=13, r_bytes=8)

ulid_48_secure   = Ulid \
    ( t_factor   = 1000
    , t_length   = 10
    , r_bytes    = 10
    , get_random = Ulid.get_random_cu
    )

ulid_64_secure   = Ulid \
    ( t_factor   = 1000000
    , t_length   = 13
    , r_bytes    = 8
    , get_random = Ulid.get_random_cu
    )

if __name__ != "__main__":
    TFL._Export("ulid_48", "ulid_64", "ulid_48_secure", "ulid_64_secure")
### __END__ TFL.ulid
コード例 #42
0

# end def tex_quoted


def tex_quoted_no_underscore(s):
    """Same as tex_quoted but does NOT quote underscores.
    """
    if isinstance(s, pyk.string_types):
        s = _tex_pi_symbols.sub(_tex_subs_pi_symbols, s)
        s = _tex_to_quote.sub(_tex_subs_to_quote, s)
        s = _tex_tt_symbols.sub(_tex_subs_tt_symbols, s)
        s = _tex_diacritics.sub(_tex_subs_diacritics, s)
    return s


# end def tex_quoted_no_underscore


def tex_quoted_underscore_word_with_path(s):
    if isinstance(s, pyk.string_types):
        s = _tex_path_text.sub(_tex_subs_to_path, s)
    return s


# end def tex_quoted_underscore_word_with_path

if __name__ != "__main__":
    TFL._Export("tex_quoted")
### __END__ TFL.tex_quoted
コード例 #43
0
ファイル: __init__.py プロジェクト: Tapyr/tapyr
#
# Revision Dates
#    13-May-2002 (CT) Creation
#     2-Feb-2009 (CT) Documentation added
#     3-Feb-2009 (CT) Documentation added..
#     4-Feb-2009 (CT) Documentation added...
#    14-Oct-2013 (CT) Add `Single_Dispatch`
#     5-Aug-2015 (CT) Add `M_Auto_Update_Combined`
#    ««revision-date»»···
#--

from   _TFL                   import TFL
from   _TFL.Package_Namespace import Package_Namespace

Meta = Package_Namespace ()
TFL._Export ("Meta")

del Package_Namespace

__doc__ = """
.. moduleauthor:: Christian Tanzer <*****@*****.**>

`TFL.Meta` provides a generic base-class and various meta-classes and
property-helpers:

- New-style classes should be derived (directly or indirectly) from
  :class:`Object<_TFL._Meta.Object.Object>` instead of
  Python's builtin `object`.

- Classes derived from other builtin types (like `dict`, `list`,
  `set`, etc.) should declare their metaclass to be
コード例 #44
0
ファイル: UCD.py プロジェクト: JPilarr/tapyr
_Command = TFL.CAO.Cmd \
    ( args          =
        ( TFL.CAO.Cmd_Choice
            ( "command"
            , _Command_by_code
            , _Command_by_id
            , _Command_create_map
            , _Command_table
            , _Command_ucd_category
            )
        ,
        )
    , description   = """
The display commands (by_code, by_id, table) need to be used in conjunction
with a font containing glyphs for the various unicode characters.

One font supporting many glyphs is `DejaVuSansMono.ttf`.

For instance::

    python -m _TFL.UCD table | python -m _TFL.text_to_pdf -landscape -Display -purge -Font DejaVuSansMono.ttf -vt_limit=17 STDIN
    """
    , min_args      = 1
    )

if __name__ != "__main__" :
    TFL._Export ("UCD")
if __name__ == "__main__" :
    _Command ()
### __END__ TFL.UCD
コード例 #45
0
    def __hash__(s):
        return 0

    def __len__(s):
        return 0

    def __le__(s, o):
        return False

    def __lt__(s, o):
        return False

    def __ne__(s, o):
        return False

    def __repr__(s):
        return "<_Black_Hole_ at %s>" % id(s)

    def __str__(s):
        return ""


# end class _Black_Hole_

black_hole = _Black_Hole_()

if __name__ != "__main__":
    TFL._Export("black_hole", "_Black_Hole_")
### __END__ TFL.Black_Hole
コード例 #46
0
ファイル: Product_Version.py プロジェクト: Tapyr/tapyr
        """Prevent the changing of attributes other than entries of `ivn'.

           Once an attribute is set, it cannot be changed to another value.
        """
        if not hasattr (self, "ivn") :
            ### object still under construction -- don't prevent attribute
            ### settings or changes
            self.__dict__ [name] = value
            return
        ### object fully constructed -- do what must be done
        if name in self.ivn :
            self.ivn [name].external_version = value
        elif name in self.__dict__ :
            raise TypeError \
                ( "Attribute %s is readonly. Cannot change value from %s to %s"
                % (name, getattr (self, name), value)
                )
        else :
            self.__dict__ [name] = value
    # end def __setattr__

    def __str__ (self) :
        return self.message
    # end def __str__

Product_Version = _TFL_Product_Version_ # end class

if __name__ != "__main__" :
    TFL._Export ("Product_Version", "Lic_Comp")
### __END__ TFL.Product_Version
コード例 #47
0
    if rest :
        indent = 0
        for line in rest :
            contents = line.lstrip ()
            if contents :
                indent = len (line) - len (contents)
                break
        if indent :
            lines = [head] + [line [indent:] for line in rest]
    return "\n".join (lines)
# end def _normalized_indent

try :
    from textwrap import dedent as _dedent
except ImportError :
    normalized_indent = _normalized_indent
else :
    def normalized_indent (text) :
        """Returns `text` with normalized indentation."""
        lines  = text.strip ().split ("\n", 1)
        result = lines [0]
        rest   = lines [1:]
        if rest :
            result = "\n".join ((result, _dedent (rest [0])))
        return result
    # end def normalized_indent

if __name__ != "__main__" :
    TFL._Export ("normalized_indent")
### __END__ normalized_indent
コード例 #48
0
ファイル: ui_display.py プロジェクト: Tapyr/tapyr
    >>> print (ui_display ("a"))
    a

    >>> print (ui_display (u"a"))
    a

For types with no specific implementation, ``ui_display`` returns the
``portable_repr``:

    >>> import datetime
    >>> d = datetime.date (2014, 2, 6)

    >>> print (ui_display (d))
    datetime.date(2014, 2, 6)

Adding an implementation for a specific type is easy enough, though::

    >>> @ui_display.add_type (datetime.date)
    ... def _ui_display_date (obj) :
    ...     return pyk.text_type (obj)

    >>> print (ui_display (d))
    2014-02-06

"""

if __name__ != "__main__" :
    TFL._Export ("ui_display")
### __END__ TFL.ui_display
コード例 #49
0
    # end def __eq__

    def __hash__ (self) :
        return hash (self.number)
    # end def divisors

    def __lt__ (self, other) :
        if isinstance (other, _Divisor_Dag_) :
            other = other.number
        return self.number < other
    # end def __lt__

# end class _Divisor_Dag_

if __name__ != "__main__" :
    TFL._Export ("*", "_Divisor_Dag_")
else :
    from time import time
    from _TFL.Command_Line import Command_Line
    cmd = Command_Line \
        ( option_spec =
            ( "-iterations:I=50?Number of iterations per number looked at"
            , "-limit:I=1000?Largest number to look at"
            )
        )
    iterations = cmd.iterations
    limit      = cmd.limit
    def test_time (number, iterations) :
        d                   = Divisor_Dag (number)
        table               = _Divisor_Dag_.Table.copy ()
        _Divisor_Dag_.Table = {}
コード例 #50
0
@fixed_order_by.add_type(TFL.Sorted_By, TFL.Q_Exp.Base)
def _fixed_order_by_sorted_by_(x):
    return x


# end def _fixed_order_by_sorted_by_


@fixed_order_by.add_type(*pyk.string_types)
def _fixed_order_by_str_(x):
    return TFL.Sorted_By(x)


# end def _fixed_order_by_str_


@fixed_order_by.add_type(tuple)
def _fixed_order_by_tuple(xs):
    if len(xs) == 1:
        return fixed_order_by(xs[0])
    else:
        return TFL.Sorted_By(*tuple(fixed_order_by(x) for x in xs))


# end def _fixed_order_by_tuple

if __name__ != "__main__":
    TFL._Export("*", "_Q_Result_")
### __END__ TFL.Q_Result
コード例 #51
0
ファイル: Undef.py プロジェクト: JPilarr/tapyr
    >>> undefined_foo = Undef ("foo")
    >>> bool (undefined_foo)
    False
    >>> undefined_foo
    <Undef/foo>

    >>> undefined_bar = Undef ("bar")
    >>> bool (undefined_bar)
    False
    >>> undefined_bar
    <Undef/bar>

    >>> undefined_foo == undefined_bar
    False
    >>> undefined_foo is undefined_bar
    False

    >>> undefined_foo == Undef ("foo")
    False
    >>> undefined_foo is Undef ("foo")
    False

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__":
    TFL._Export("Undef", "is_undefined")
### __END__ TFL.Undef
コード例 #52
0
ファイル: Q_Exp.py プロジェクト: JPilarr/tapyr
    >>> Q.foo.bar.OR (Q.baz, Q.qux) > 23
    <Filter_Or [Q.foo.bar.baz > 23, Q.foo.bar.qux > 23]>

    >>> r1
    Record (bar = 137, baz = 11, foo = 42)

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 42) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 137) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 11) (r1)
    True

    >>> (Q.OR (Q.foo, Q.bar, Q.baz) == 23) (r1)
    False

"""

__test__ = dict \
    ( test_doc = __doc__
    , test_q   = _test_q
    )

if __name__ != "__main__" :
    TFL._Export ("Q")
    TFL._Export_Module ()
### __END__ TFL.Q_Exp
コード例 #53
0
ファイル: PMPP.py プロジェクト: Tapyr/tapyr
                    ### return untagged text unchanged
                    yield l
            else :
                l = next (source)
                if comment_pat.match (l) :
                    comment = comment_pat.comment
                while not (else_tag.match (l) or tail_tag.match (l)) :
                    ### return text between start-tag and else- or tail-tag
                    ### without the leading comment
                    yield l.replace (comment, "", 1)
                    l = next (source)
                if else_tag.match (l) :
                    ### skip over text between else- and tail-tag
                    while not tail_tag.match (l) :
                        l = next (source)
    # end def __call__

# end class PMPP

"""
Usage examples:
    Demoize  = PMPP ("DEMOVERSION")
    makedemo = Demoize.rewrite

    TMCoize  = PMPP ("TMCVERSION")
"""

if __name__ != "__main__" :
    TFL._Export ("*")
### __END__ TFL.PMPP
コード例 #54
0
ファイル: Regexp.py プロジェクト: Tapyr/tapyr
class Multi_Re_Replacer (TFL.Meta.Object) :
    """Wrap multiple `Re_Replacer` instances and apply them in sequence"""

    def __init__ (self, * rerep) :
        self.rereps = list (rerep)
    # end def __init__

    def __call__ (self, text, count = 0) :
        result = text
        for rerep in self.rereps :
            result = rerep (result, count)
        return result
    # end def __call__

    def add (self, * rereps) :
        self.rereps.extend (rereps)
    # end def add

# end class Multi_Re_Replacer

__doc__ = """

.. moduleauthor:: Christian Tanzer <*****@*****.**>

"""

if __name__ != "__main__" :
    TFL._Export ("*", "re")
### __END__ TFL.Regexp
コード例 #55
0
ファイル: Record.py プロジェクト: JPilarr/tapyr
@portable_repr.add_type(Record)
@portable_repr.recurses
def _portable_repr_Record(obj, seen):
    return "%s (%s)" % (obj.__class__.__name__, obj._formatted_kw(seen))


# end def _portable_repr_Record


@portable_repr.recursion_repr.add_type(Record)
def _recursion_repr_Record(obj):
    return "%s (...)" % (obj.__class__.__name__, )


# end def _recursion_repr_Record


@TFL._Add_Import_Callback("_TFL.json_dump")
def _import_cb_json_dump(module):
    @module.default.add_type(Record)
    def json_encode_record(o):
        return o._kw


# end def _import_cb_json_dump

if __name__ != "__main__":
    TFL._Export("*")
### __END__ TFL.Record
コード例 #56
0
ファイル: normalized_indent.py プロジェクト: Tapyr/tapyr
            if contents:
                indent = len(line) - len(contents)
                break
        if indent:
            lines = [head] + [line[indent:] for line in rest]
    return "\n".join(lines)


# end def _normalized_indent

try:
    from textwrap import dedent as _dedent
except ImportError:
    normalized_indent = _normalized_indent
else:

    def normalized_indent(text):
        """Returns `text` with normalized indentation."""
        lines = text.strip().split("\n", 1)
        result = lines[0]
        rest = lines[1:]
        if rest:
            result = "\n".join((result, _dedent(rest[0])))
        return result

    # end def normalized_indent

if __name__ != "__main__":
    TFL._Export("normalized_indent")
### __END__ normalized_indent