Example #1
0
 def matching_keys (self, abbr) :
     """Returns a list of all keys matching `abbr` if any."""
     if abbr in self :
         return [abbr]
     elif isinstance (abbr, str) :
         return TFL.matches (TFL.sorted (pyk.iterkeys (self)), abbr)
     return []
Example #2
0
 def __init__ (self, fct, counter_name = None) :
     self.fct      = self.__func__ = fct
     self.__name__ = getattr (fct, "__name__", None)
     self.__doc__  = getattr (fct, "__doc__", None)
     self.changes  = TFL.defaultdict (lambda : -1)
     self.result   = TFL.defaultdict (lambda : None)
     if counter_name :
         self.counter_name = counter_name
Example #3
0
def Extract (dirname, template_file, config, cmd) :
    absname = os.path.abspath (dirname)
    po_file = TFL.Babel.PO_File \
        ( project            = cmd.project
        , version            = cmd.version
        , bugs_address       = cmd.bugs_address
        , copyright_holder   = cmd.copyright_holder
        , charset            = cmd.charset
        , width              = cmd.width
        , no_location        = cmd.no_location
        , omit_header        = cmd.omit_header
        , sort               = cmd.sort
        )
    keywords = Default_Keywords.copy ()
    keywords.update (dict (k, None) for k in cmd.keywords)
    for root, dirnames, filenames in os.walk (absname) :
        dirnames.sort  ()
        for filename in sorted (filenames) :
            filename = os.path.relpath \
                (os.path.join (root, filename).replace (os.sep, '/'), dirname)
            try :
                for method_name, pattern in config.patterns.items () :
                    if pathmatch (pattern, filename) :
                        for pattern in config.get_list \
                            ("ignore_patterns", method_name, set (), True) :
                            if pathmatch (pattern, filename) :
                                raise Skip
                        filepath = os.path.join (absname, filename)
                        rfp      = TFL.relative_to_python_path (filepath)
                        print ("Method `%-10s`: `%s" % (method_name, filename))
                        trans = config.get ("loaded_translations", method_name)
                        for lineno, message, comments, found_in in \
                                _extract_from_file    \
                                    ( method_name
                                    , filepath
                                    , config
                                    , cmd
                                    , keywords
                                    ) :
                            fn = rfp
                            if found_in :
                                fn = TFL.relative_to_python_path (found_in)
                            if message not in trans :
                                po_file.add \
                                    ( message, None, [(fn, lineno)]
                                    , auto_comments = comments
                                    )
                        break
            except Skip :
                print ("Ignore             : `%s" % (filename, ))
    print ("Create template file", template_file, file = sys.stderr)
    po_file.save (template_file)
Example #4
0
 def selected_type (self) :
     result = self._selected_type
     if TFL.is_undefined (result) :
         outer = self._outer
         if outer is not None :
             result = self._selected_type = outer.selected_type
     return result
Example #5
0
 def _e_type_attrs_q_able (self, ET) :
     attrs  = ET.q_able_no_edit
     _own   = ET._Attributes._own_names
     result = []
     if attrs :
         heading   = "Queryable attributes"
         leader    = None
         own_attrs = [a for a in attrs if a.name in _own]
         if len (attrs) > len (own_attrs) :
             def _gen_parents (ET) :
                 for p in ET.parents :
                     if p.q_able_no_edit :
                         ### filter out intermediate ancestors without
                         ### q_able_no_edit attributes of their own
                         ### --> refer to their parents instead
                         own = p._Attributes._own_names
                         if [a for a in p.q_able_no_edit if a.name in own] :
                             yield p
                         else :
                             for mp in _gen_parents (p) :
                                 yield mp
             parents = list (TFL.uniq (_gen_parents (ET)))
             if parents :
                 leader  = "For inherited %s see also %s" % \
                     ( heading.lower ()
                     , ", ".join
                         (   self._heading_ref (p, heading, p.type_name)
                         for p in parents
                         )
                     )
         result = self._e_type_attrs \
             ( ET, own_attrs if leader else attrs, heading, leader
             , electric = True
             )
     return result
Example #6
0
 def attr_filters \
         ( soc, E_Type, request, data, scope
         , a_pat      = None
         , default_op = "EQ"
         ) :
     filters   = []
     filters_q = []
     map       = TFL.mm_dict_mm_list ()
     af_args   = ichain \
         ( soc.af_args_api (request.req_data_list, default_op)
         , soc.af_args_fif (data, a_pat, default_op)
         )
     for fn, name, typ, tail, op, value in af_args :
         if typ :
             map [name] [typ].append ((tail, op, value))
         else :
             f, fq = soc._setup_attr (E_Type, fn, name, op, value)
             filters.append   (f)
             filters_q.append (fq)
     for name, t_map in pyk.iteritems (map) :
         if len (t_map) > 1 :
             raise ValueError \
                 ( "Got types %s instead of exactly one type"
                 % (sorted (t_map), )
                 )
         typ    = first (t_map)
         nqr    = soc.nested (scope, scope [typ], t_map [typ])
         fs, fq = soc._setup_attr_pepk (E_Type, name, nqr)
         filters.extend   (fs)
         filters_q.append (fq)
     return tuple (filters), tuple (filters_q)
Example #7
0
 def templates_e (self) :
     def _gen () :
         yield self
         if self.extends :
             for e in self.extends.templates_e :
                 yield e
     return tuple (TFL.uniq (_gen ()))
Example #8
0
File: Store.py Project: Tapyr/tapyr
 def consume (self, e_iter, c_iter, chunk_size, db_meta_data) :
     assert sos.path.exists (self.x_uri.name), self.x_uri.name
     assert not self.info.commits
     assert not self.info.pending
     assert not self.info.stores
     db_uri  = self.db_uri
     x_name  = self.x_uri.name
     with TFL.lock_file (x_name) :
         info    = self.info
         stores  = info.stores  = []
         commits = info.commits = []
         for i, cargo in enumerate (sliced (e_iter, chunk_size)) :
             s_name  = TFL.Filename ("by_pid_%d" % i, self.x_uri)
             with open (s_name.name, "wb") as file :
                 pickle.dump (cargo, file, pyk.pickle_protocol)
             stores.append   (s_name.base_ext)
         for cargo in sliced (c_iter, chunk_size) :
             max_cid = cargo [-1] [1] ["cid"]
             c_name  = TFL.Filename ("%d.commit" % max_cid, self.x_uri)
             with open (c_name.name, "wb") as file :
                 pickle.dump (cargo, file, pyk.pickle_protocol)
             commits.append ((max_cid, c_name.base_ext))
         info.max_cid = db_meta_data.max_cid
         info.max_pid = db_meta_data.max_pid
         self._save_info (info)
Example #9
0
 def js (self) :
     """Combined Javascript code required by media fragments that can be
        loaded from a single file or included inline in a html <script>
        element.
     """
     env      = self.env
     encoding = env.encoding
     handler  = env.static_handler
     media    = self._Media_R
     if handler and media :
         def _gen (handler, encoding, scripts, media) :
             for s in sorted (scripts, key = TFL.Getter.rank) :
                 p = handler.get_path (s.src)
                 if p :
                     with open (p, "rb") as file :
                         yield file.read ().decode (encoding)
                 else :
                     try :
                         src, p, _ = env.loader.get_source (env, s.src)
                     except Exception :
                         pass
                     else :
                         if p :
                             yield src
             for s in sorted (media.script_files, key = TFL.Getter.rank) :
                 yield pyk.decoded (s.body, encoding)
         result = "\n\n".join \
             (TFL.uniq (_gen (handler, encoding, self.scripts_c, media)))
         return result
Example #10
0
 def _new_delivery_box(self, d, prefix):
     config = TFL.load_config_file(
         sos.path.join(d, ".config.py"), dict(Maildir_Type=PMA.Maildir, Maildir_kw={}, PMA=PMA)
     )
     result = config["Maildir_Type"](d, prefix=prefix, **config["Maildir_kw"])
     result.config = config
     return result
Example #11
0
 def row_as_pickle_cargo (self, row, db_attrs = None) :
     result = TFL.defaultdict (tuple)
     if db_attrs is None :
         db_attrs = self.db_attrs
     for name, kind_wrapper in pyk.iteritems (db_attrs) :
         result [name] = kind_wrapper.row_as_pickle_cargo (row)
     return result
Example #12
0
def import_module (path) :
    fn = Filename (path)
    mn = fn.base
    md = fn.directory or "./"
    with TFL.Context.list_push (sys.path, md, 0) :
        result = TFL.import_module (mn)
        result.__App_Tests_Dir__ = md
        return result
Example #13
0
 def field_values (self, json) :
     result = dict (json ["field_values"])
     for e in self.elems :
         if e.id not in result :
             v = e.init
             if e.readonly and v is not None and not TFL.is_undefined (v) :
                 result [e.id] = v
     return result
Example #14
0
File: Store.py Project: Tapyr/tapyr
 def create (self) :
     assert not sos.path.exists (self.db_uri.name), self.db_uri.name
     assert not sos.path.exists (self.x_uri.name), self.x_uri.name
     x_name = self.x_uri.name
     with TFL.lock_file (x_name) :
         sos.mkdir  (x_name)
         sos.system ("chmod go= %s" % x_name)
         self._create_info ()
Example #15
0
 def js_on_ready (self) :
     """Combined Javascript code required by media fragments to be
        executed when document is ready.
     """
     media = self._Media
     if media :
         return sorted (TFL.uniq (media.js_on_ready), key = TFL.Getter.rank)
     return ()
Example #16
0
 def __init__ (self, markup, docstrings = True, * file_or_package_names) :
     self._markups         = markup
     self._mark_docstrings = docstrings
     self._translations    = TFL.defaultdict (list)
     for file in self._filenames (file_or_package_names) :
         for toknum, tokval, (sline, srow), (erow, ecol), line \
                                in tokenize.generate_tokens (file) :
             self._handle_tokens (toknum, tokval, sline)
Example #17
0
 def _get_name (self, pip) :
     try :
         sys_path = list (sys.path)
         sys.path [0:0] = self.import_path
         m = TFL.import_module ("%s.Version" % pip.pkg)
         return m.Version.productid
     finally :
         sys.path = sys_path
Example #18
0
 def scripts (self) :
     """Scripts required by media fragments that need to be put into
        separate <script src="..."> elements.
     """
     media = self._Media
     if media :
         return tuple (TFL.uniq (media.scripts))
     return ()
Example #19
0
File: Macro.py Project: Tapyr/tapyr
 def _explanation (self, ** kw) :
     if not self.explanation :
         yield ""
         return
     yield "\\item \\textbf{Description:} \\\\"
     format_prec = max (int (kw ["format_prec"]), 4)
     wrapper     = textwrap.TextWrapper (width = format_prec)
     for l in wrapper.wrap (TFL.tex_quoted (self.explanation)) :
         yield l
Example #20
0
 def entities_transitive (self, ems) :
     def _gen (self, ems) :
         for e in self.entities (ems) :
             yield e
             for iea in e.id_entity_attr :
                 v = iea.get_value (e)
                 if v is not None :
                     yield v
     return TFL.uniq (_gen (self, ems))
Example #21
0
File: Store.py Project: Tapyr/tapyr
 def load_changes (self) :
     assert sos.path.exists (self.x_uri.name), self.x_uri.name
     info  = self.info
     x_uri = self.x_uri
     with TFL.lock_file (x_uri.name) :
         for (cid, name) in info.commits :
             file_name = TFL.Filename (name, x_uri).name
             for c in self._loaded_changes (file_name) :
                 pass ### `_loaded_changes` adds the changes to `self.cm`
     self.cm.to_load = []
Example #22
0
File: Store.py Project: Tapyr/tapyr
 def produce_entities (self) :
     assert sos.path.exists (self.x_uri.name), self.x_uri.name
     assert not self.info.pending
     info  = self.info
     x_uri = self.x_uri
     with TFL.lock_file (x_uri.name) :
         for s in info.stores :
             with open (TFL.Filename (s, x_uri).name, "rb") as file :
                 for epc in pickle.load (file) :
                     yield epc
Example #23
0
File: Store.py Project: Tapyr/tapyr
 def _save_context (self, x_name, scope, info) :
     Version = self.Version
     with TFL.lock_file (x_name) :
         self._check_sync_ro (info)
         yield info
         ems            = scope.ems
         info.max_cid   = ems.max_cid
         info.max_pid   = ems.max_pid
         info.max_surrs = ems.max_surrs
         self._save_info (info)
Example #24
0
File: Store.py Project: Tapyr/tapyr
 def load_info (self) :
     assert sos.path.exists (self.db_uri.name), self.db_uri.name
     x_name = self.x_uri.name
     with TFL.lock_file (x_name) :
         if not sos.path.exists (x_name) :
             sos.mkdir (x_name)
             sos.system ("chmod go= %s" % x_name)
             with contextlib.closing \
                      (self.ZF.ZipFile (self.db_uri.name, "r")) as zf :
                 zf.extractall (x_name)
         self.info = self._load_info ()
Example #25
0
File: Store.py Project: Tapyr/tapyr
 def load_objects (self) :
     assert sos.path.exists (self.x_uri.name), self.x_uri.name
     info  = self.info
     x_uri = self.x_uri
     with TFL.lock_file (x_uri.name) :
         self.scope.db_errors = []
         for s in info.stores :
             self._load_store   (TFL.Filename (s, x_uri).name)
         for (cid, name) in info.pending :
             self._load_pending (TFL.Filename (name, x_uri).name)
     self.cm.to_load  = [name for (cid, name) in info.commits]
Example #26
0
 def _temp_body (self) :
     if self._tfn is None or not sos.path.isfile (self._tfn) :
         dir = TFL.Filename \
             ( (self.filename or "").encode
                 (PMA.file_system_encoding, "ignore")
             ).directory
         with TFL.open_tempfile (dir = dir, auto_remove = False) as \
                  (f, result) :
             f.write (self.body)
             self._tfn = result
     return self._tfn
Example #27
0
 def _insert (self, other) :
     key = self.key (other)
     try :
         larger = TFL.first (it for it in self if it.key > key)
     except IndexError :
         prev = self.tail
     else :
         prev = larger.prev
     self.__super.insert (prev, other)
     if self.mark.key > key :
         self.rotate_prev (1)
Example #28
0
 def extends (self) :
     env    = self.env
     pat    = self._extend_pat
     source = self.source
     if source and pat.search (source) :
         try :
             path = TFL.r_eval (pat.name.strip (), ** self.env_globals)
         except Exception :
             pass
         else :
             return self.__class__ (env, path)
Example #29
0
 def _setup_lic_comps (self) :
     pns_name = self.productnick
     pkg_name = "_%s" % pns_name
     pkg      = sys.modules.get (pkg_name)
     if pkg :
         pns  = getattr (pkg, pns_name)
         try :
             lp_module = TFL.import_module ("%s.Lic_Comps" % pkg_name)
         except ImportError :
             pass
         else :
             self.lic_comps.extend (getattr (lp_module, "list"))
Example #30
0
 def _gen () :
     for match in pat.search_iter (source) :
         try:
             name   = match.group ("name").strip ()
             pathes = TFL.r_eval  (name, ** self.env_globals)
         except Exception :
             pass
         else :
             if isinstance (pathes, pyk.string_types) :
                 pathes = [pathes]
             for p in pathes :
                 yield self.__class__ (env, p)
Example #31
0
 def __init__ (self, file_name, ** kw) :
     self.__super.__init__ \
         ( file_name = file_name
         , name      = kw.pop ("name", None) or TFL.Filename (file_name).base
         , ** kw
         )
Example #32
0
 def max_surrs(self):
     return TFL.defaultdict(int)  ### XXX
Example #33
0
 def _as_template_elem(self, seen_etypes):
     result = dict(self._as_template_elem_inv, ui_name=self._ui_name_T)
     return TFL.Record(**result)
Example #34
0
        if self.can_eval:
            print(eval(self.code, glob_dct, loc_dct))
        else:
            exec(self.code, glob_dct, loc_dct)

    # end def __call__


# end class Pycode_Compiler


def complete_command(line, glob_dct, loc_dct=None):
    prefix, space, line = line.rpartition(" ")
    d = dict(glob_dct)
    d.update(loc_dct or {})
    c = rlcompleter.Completer(d)
    try:
        c.complete(line, 0)
    except Exception:
        return None, None
    match = "".join((prefix, space, common_head(c.matches)))
    cands = ", ".join(sorted(s.split(".")[-1] for s in set(c.matches)))
    return match, ("%s\n\n" % cands if cands else "")


# end def complete_command

if __name__ != "__main__":
    TFL._Export("*")
### __END__ Py_Interpreter
Example #35
0
        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
Example #36
0
 def __init__(self, *iv_list):
     self.iv_map = TFL.sorted(iv_list)
Example #37
0
 def __init__(self, directories, lang=None, suffix=""):
     self.languages = set()
     self.directories = set()
     self.files_per_language = TFL.defaultdict(list)
     for d in directories:
         self._add_languages(d, set(lang), suffix)
Example #38
0
 def __init__ (cls, name, bases, dict) :
     cls.__m_super.__init__ (name, bases, dict)
     if not hasattr (cls, "_") :
         cls._ = TFL.Record ()
Example #39
0
 def change_info(self):
     return TFL.Record(etag=self.top.App_Type.db_version_hash)
Example #40
0
from Media_Parameters import Media_Parameters

Media_Parameters = Media_Parameters()

src_dir = sos.path.dirname(__file__)
web_root_dir = "//ffm.funkfeuer.at"
web_src_root = sos.path.abspath(src_dir)

base_template_dir = sos.path.dirname(_JNJ.__file__)
template_dirs = [src_dir, base_template_dir]

web_links = \
    [ TFL.Record
        ( href        = "http://guifi.net/en/"
        , title       = "Spanish open wireless network"
        , short_title = "Guifi.net"
        )
    , TFL.Record
        ( href        = "http://wlan-si.net/"
        , title       = "Slovenian open wireless network"
        , short_title = "wlan-si"
        )
    ]


def root_kw_args(cmd, **kw):
    return dict \
        ( console_context   = dict
            ( FFM           = FFM
            , GTW           = GTW
Example #41
0
 def __init__(self, scope, db_url):
     self.__super.__init__(scope, db_url)
     self._counts = TFL.defaultdict(int)
     self.max_surrs = TFL.defaultdict(int)
     self._r_map = TFL.defaultdict(lambda: TFL.defaultdict(set))
     self._tables = TFL.defaultdict(dict)
Example #42
0
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))
Example #43
0
            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
Example #44
0
 def __init__(self, e_type):
     self.__super.__init__(e_type)
     self._attr_map = TFL.defaultdict(list)
     self.uniqueness = e_type.P_uniqueness + e_type.P_exclusion
Example #45
0
 def file_name (self, cao, ext) :
     fn = TFL.Filename ("." + ext, cao.name, default_dir = cao.dir)
     return fn.name
Example #46
0

# end def ungettext


def use(*lang):
    Config.choice = (l, v) = choose(*lang)
    Config.current = Config.Languages[l]


# end def use

_ = mark


def _T(s):
    if s:
        return ugettext(s)
    return s


# end def _T

_Tn = ungettext

Name = _Name_()

if __name__ != "__main__":
    TFL._Export_Module()
### __END__ TFL.I18N
Example #47
0
 def _sort_properties (self, e_type) :
     for pk in pyk.itervalues (self._prop_kind) :
         pk.sort (key = TFL.Sorted_By ("rank", "name"))
Example #48
0
 def __init__(self, source):
     self.source = source = iter(source)
     self._sentinel = self._succ = TFL.Undef("sentinel")
Example #49
0
import _GTW._RST.Resource
import _GTW._RST.HTTP_Method
import _GTW._RST._MOM.Mixin

from   _MOM.import_MOM          import MOM, Q

from   _TFL._Meta.Once_Property import Once_Property
from   _TFL.Decorator           import getattr_safe
from   _TFL.pyk                 import pyk

import _TFL._Meta.Object
import _TFL.Undef

from   posixpath                import join as pp_join

_undef_arg = TFL.Undef ("arg")

@TFL.Add_Method (MOM.Attr._A_Id_Entity_)
def as_rest_cargo_raw \
        (self, obj, method, resource, request, response, seen, getter, a_name) :
    result = self.kind.get_value (obj)
    if result is not None :
        res_vet = resource.resource_from_e_type (result.type_name)
        url     = res_vet.href_obj (result)
        if (   request.has_option ("closure")
           and result.pid not in seen
           and res_vet.allow_method (method, request.user)
           ) :
            result = method._response_obj \
                ( resource, request, response, result, result.edit_attr, seen
                , getter, a_name
Example #50
0
    class _SRM_Year_ (GTW.RST.TOP.MOM.Renderer_Mixin, _Ancestor.Year) :

        _real_name          = "Year"

        dir_template_name   = "regatta_calendar"
        Entity              = Regatta_Event
        head_line_format    = _ ("Regatta Events %(year)s")
        list_display        = \
            ( "ui_date_short"
            , "regatta_kinds"
            , "regatta_classes"
            , "event_link"
            )
        regattas            = Alias_Property ("object_entries")
        skip_etag           = True
        sort_key            = TFL.Sorted_By ("date.start", "perma_name")

        _field_class_map    = dict \
            ( ui_date_short     = "align-right"
            )

        _field_type_map     = dict \
            ( event_link            = Q.Field_Event_Link
            , regatta_classes       = Q.Field_Regatta_Classes
            , regatta_kinds         = Q.Field_Regatta_Kinds
            )

        class Field_Event_Link (GTW.RST.TOP.MOM.Field.HTML_Link) :

            attr_name = "desc"

            @property ### depends on currently selected language (I18N/L10N)
            @getattr_safe
            def ui_name (self) :
                return _T ("Regatta")
            # end def ui_name

            def _as_html_href (self, o, renderer) :
                resource = self.resource
                href     = resource.href_display (o)
                return href
            # end def _as_html_href

            def _as_html_value (self, o, renderer) :
                return o.desc
            # end def _as_html_value

        # end class Field_Event_Link

        class Field_Regatta_Classes (GTW.RST.TOP.MOM.Field.HTML_Link_Set) :

            attr_name = "regattas"

            @property ### depends on currently selected language (I18N/L10N)
            @getattr_safe
            def ui_name (self) :
                return _T ("Class")
            # end def ui_name

            def _as_html_href (self, o, renderer) :
                resource = self.resource
                regatta  = self._value_getter (o)
                href     = resource.href_regatta (regatta) \
                    if not regatta.is_cancelled else ""
                return href
            # end def _as_html_href

            def _as_html_value (self, o, renderer) :
                regatta  = self._value_getter (o)
                return regatta.name.replace (" ", " ")
            # end def _as_html_value

        # end class Field_Regatta_Classes

        class Field_Regatta_Kinds (GTW.RST.TOP.MOM.Field.AQ) :

            attr_name = "regattas"

            @property ### depends on currently selected language (I18N/L10N)
            @getattr_safe
            def ui_name (self) :
                return _T ("Kind")
            # end def ui_name

            def as_html (self, o, renderer) :
                regattas = sorted (self._value_getter (o), key = Q.name)
                canc     = _T ("Is cancelled")
                return "<br>".join \
                    ((r.kind if not r.is_cancelled else canc) for r in regattas)
            # end def as_html

        # end class Field_Regatta_Kinds

        class _SRM_Year_Renderer_ (GTW.RST.TOP.MOM.Renderer.E_Type) :

            _real_name          = "Renderer"
            template_module     = "ETR_table_regatta"

        Renderer = _SRM_Year_Renderer_ # end class

        @property ### depends on currently selected language (I18N/L10N)
        def head_line (self) :
            return self.head_line_format % TFL.Caller.Object_Scope (self)
Example #51
0
class UI_Spec(object):
    """UI specification for E_Types defined by GTW.OMP.PAP"""

    property_include_rev_refs = \
        ("persons", "companies", "associations")

    subject_include_rev_refs  = \
        ("addresses", "emails", "phones")

    Address              = dict \
        ( list_display   = ("zip", "city", "street", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = ("gps", ) + property_include_rev_refs
            )
        , sort_key       = TFL.Sorted_By ( "zip", "street")
        )

    Adhoc_Group          = dict \
        (
        )

    Association          = dict \
        ( list_display   = ("name", "short_name", "lifetime")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = subject_include_rev_refs
            )
        )

    Company              = dict \
        ( list_display   = ("name", "short_name", "lifetime")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = subject_include_rev_refs
            )
        )

    Company_1P           = dict \
        ( list_display   =
            ( "ui_display", "short_name", "lifetime")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = subject_include_rev_refs
            )
        )

    Email                = dict \
        ( list_display   = ("ui_display", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = property_include_rev_refs
            )
        )

    IM_Handle            = dict \
        ( list_display   = ("ui_display", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = property_include_rev_refs
            )
        )

    Nickname             = dict \
        ( list_display   = ("ui_display", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = property_include_rev_refs
            )
        )

    Person               = dict \
        ( list_display   =
            ( "last_name", "first_name", "middle_name", "title"
            , "lifetime", "sex"
            )
        , MF3_Form_Spec  = dict
            ( include_rev_refs =
                (subject_include_rev_refs + ("im_handles", "accounts"))
            )
        )

    Phone                = dict \
        ( list_display   = ("ui_display", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = property_include_rev_refs
            )
        )

    Url                  = dict \
        ( list_display   = ("ui_display", "desc")
        , MF3_Form_Spec  = dict
            ( include_rev_refs = property_include_rev_refs
            )
        )

    Address_Position     = dict \
        (
        )

    Company_has_Address  = dict \
        (
        )

    Company_has_Email    = dict \
        (
        )

    Company_has_Phone    = dict \
        (
        )

    Company_has_Url      = dict \
        (
        )

    Company_has_VAT_IDN  = dict \
        ( list_display   = ("left.ui_display", "vin")
        )

    Id_Entity_permits_Group = dict \
        (
        )

    Person_has_Account   = dict \
        (
        )

    Person_has_Address   = dict \
        (
        )

    Person_has_Email     = dict \
        (
        )

    Person_has_IM_Handle = dict \
        (
        )

    Person_has_Nickname  = dict \
        (
        )

    Person_has_Phone     = dict \
        (
        )

    Person_has_Url       = dict \
        (
        )

    Person_has_VAT_IDN   = dict \
        ( list_display   = ("left.ui_display", "vin")
        )

    Person_in_Group      = dict \
        ( sort_key       = TFL.Sorted_By ("pid") ### XXX remove this
        )

    Subject_has_Property = dict \
        (
        )
Example #52
0
    class Field__Crew_Club (GTW.RST.TOP.MOM.Field.Id_Entity_Set) :

        attr_name  = "_crew"
        attr_names = ("club", )
        sort_key   = TFL.Sorted_By ("key", "pid")
Example #53
0
                orig_f.is_classmethod = cors is classmethod
            wrapper = decorator(orig_f)
            decorated = cors(wrapper)
            _update_wrapper(wrapper, orig_f)
        else:
            decorated = decorator(f)
            _update_wrapper(decorated, f)
        return decorated

    _update_wrapper(wrapper, decorator)
    return wrapper


# end def Decorator

_AR_undefined = TFL.Undef("return-value")


def Annotated(RETURN=_AR_undefined, **kw):
    """Add dictionary `func_annotations` containing elements of `kw` and
       value of `RETURN` bound to key `return` as proposed by
       http://www.python.org/dev/peps/pep-3107/.

       Each key of `kw` must be the name of an argument of the function to be
       annotated::

           >>> from _TFL.portable_repr import portable_repr
           >>> @TFL.Annotated (bar = "Arg 1", baz = 42)
           ... def foo (bar, baz) : pass
           ...
           >>> portable_repr (foo.func_annotations)
Example #54
0
    class Field__Crew_MNA_Number (GTW.RST.TOP.MOM.Field.Id_Entity_Set) :

        attr_name  = "_crew"
        attr_names = ("mna_number", )
        sort_key   = TFL.Sorted_By ("key", "pid")
Example #55
0
def load_entries (file_name) :
    with open (file_name) as f :
         return TFL.r_eval (f.read (), ** eval_scope ())
Example #56
0
    class Field__Crew_Person (GTW.RST.TOP.MOM.Field.Id_Entity_Set) :

        attr_name  = "_crew"
        attr_names = ("_crew_person_set", )
        sort_key   = TFL.Sorted_By ("key", "pid")
Example #57
0
       >>> 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
Example #58
0
 def E_Type (self) :
     result = self.scope.SRM.Boat_in_Regatta.E_Type
     ### XXX change MOM rev-ref autogeneration to do this automatically
     result.attr_prop ("race_results").attr.sort_key = TFL.Sorted_By ("race")
     return result
Example #59
0
    >>> 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
Example #60
0
class Aggregator (GTW.RST.MOM.Mixin, _Ancestor) :
    """Page aggregating the most recent instances of one or more E_Types."""

    css_class             = "news-clip"
    page_template_name    = "e_type_aggregator"
    query_limit           = 25
    sort_key              = TFL.Sorted_By ("-date.start", "-prio")
    static_p              = True

    _exclude_robots       = False
    _old_objects          = None

    class Aggregator_GET (_Ancestor.GET) :

        _real_name             = "GET"

        def _render_context (self, resource, request, response, ** kw) :
            return self.__super._render_context \
                ( resource, request, response
                , calendar       = resource.calendar
                , clips          = resource.clips
                , random_picture = None
                    if resource.clips else resource.random_picture
                , ** kw
                )
        # end def _render_context

    GET = Aggregator_GET # end class

    class Instance (TFL.Meta.Object) :

        def __init__ (self, obj, parent) :
            self.obj    = obj
            self.parent = parent
            self.top    = parent.top
            self.FO     = GTW.FO (obj, parent.top.encoding)
        # end def __init__

        def __getattr__ (self, name) :
            if name.startswith ("__") and name.endswith ("__") :
                ### Placate inspect.unwrap of Python 3.5,
                ### which accesses `__wrapped__` and eventually throws
                ### `ValueError`
                return getattr (self.__super, name)
            if name == "link_to" :
                top    = self.top
                result = getattr (self.obj, name, None)
                if not result :
                    left = getattr (self.obj, "left", None)
                    if left is not None :
                        result = top.obj_href (left)
                if result :
                    page   = top.resource_from_href (result)
                    result = page.permalink
            else :
                result = getattr (self.FO, name)
            return result
        # end def __getattr__

    # end class Instance

    def __init__ (self, ** kw) :
        kw ["_ETMS"] = kw.pop ("ETMS")
        self.__super.__init__ (** kw)
    # end def __init__

    @Once_Property
    @getattr_safe
    def calendar (self) :
        return getattr (self.top.SC, "Cal", None)
    # end def calendar

    @Once_Property
    @getattr_safe
    def change_query_filters (self) :
        return (Q.type_name.IN (sorted (self.change_query_types)), )
    # end def change_query_filters

    @Once_Property
    @getattr_safe
    def change_query_types (self) :
        result = set ()
        for ETM in self.ETMS :
            E_Type = ETM.E_Type
            result.update (self._change_query_types (E_Type))
        return result
    # end def change_query_types

    @property
    @getattr_safe
    def clips (self) :
        objects = self.objects
        if self._old_objects is not objects :
            self._clips = \
                [self.Instance (obj = o, parent = self) for o in objects]
            if objects :
                self._old_objects = objects
        return self._clips
    # end def clips

    @Once_Property
    @getattr_safe
    def ETMS (self) :
        result = []
        for etm in self._kw ["_ETMS"] :
            if isinstance (etm, pyk.string_types) :
                etm = self.top.scope [etm]
            result.append (etm)
        return result
    # end def ETMS

    @Once_Property
    @getattr_safe
    def query_filters_s (self) :
        return self.__super.query_filters_s + (Q.date.alive, )
    # end def query_filters_s

    @Once_Property
    @getattr_safe
    def Random_Picture (self) :
        return getattr (self.top.SC, "Random_Picture", None)
    # end def Random_Picture

    @property
    @getattr_safe
    def random_picture (self) :
        RP = self.Random_Picture
        if RP is not None :
            return RP.picture.left
    # end def random_picture

    def query (self) :
        qs = []
        ql = self.query_limit
        sk = self.sort_key
        for ETM in self.ETMS :
            q = ETM.query (* self.query_filters, sort_key = sk)
            if ql :
                q = q.limit (ql)
            qs.append (q)
        result = TFL.Q_Result_Composite (qs, order_by = sk)
        if ql :
            result.limit (ql)
        return result