home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / util / primitives / funcs.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  15.2 KB  |  552 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from __future__ import with_statement
  5. from functional import ObjectList
  6. from refs import stupidref, better_ref
  7. from collections import defaultdict
  8. from error_handling import traceguard
  9. import functools
  10. import operator
  11. import pprint
  12. import sys
  13. import traceback
  14.  
  15. try:
  16.     sentinel
  17. except NameError:
  18.     sentinel = object()
  19.  
  20.  
  21. def get(obj, key, default = sentinel):
  22.     
  23.     try:
  24.         return obj[key]
  25.     except (IndexError, KeyError):
  26.         if default is sentinel:
  27.             raise 
  28.         else:
  29.             return default
  30.     except TypeError:
  31.         
  32.         try:
  33.             return getattr(obj, key)
  34.         except AttributeError:
  35.             if default is sentinel:
  36.                 raise 
  37.             else:
  38.                 return default
  39.         except:
  40.             default is sentinel
  41.         
  42.  
  43.         None<EXCEPTION MATCH>AttributeError
  44.  
  45.  
  46.  
  47. def ischeck(f):
  48.     
  49.     def checker(v):
  50.         
  51.         try:
  52.             r = f(v)
  53.         except:
  54.             return False
  55.  
  56.         if type(r) is bool:
  57.             return r
  58.         else:
  59.             return True
  60.  
  61.     return checker
  62.  
  63.  
  64. def itercheck(x, exclude = (basestring,)):
  65.     
  66.     try:
  67.         iter(x)
  68.     except:
  69.         return False
  70.  
  71.     if not isinstance(x, exclude):
  72.         return True
  73.     else:
  74.         return False
  75.  
  76. isint = ischeck(int)
  77. isiterable = ischeck(itercheck)
  78. isnumber = ischeck(float)
  79.  
  80. def make_first(seq, item):
  81.     
  82.     try:
  83.         idx = seq.index(item)
  84.         seq.pop(idx)
  85.     except ValueError:
  86.         pass
  87.  
  88.     seq.insert(0, item)
  89.  
  90.  
  91. def do(seq_or_func, seq = None):
  92.     if seq is None:
  93.         for x in seq_or_func:
  94.             pass
  95.         
  96.     else:
  97.         for x in seq:
  98.             seq_or_func(x)
  99.         
  100.  
  101.  
  102. def find(seq, item):
  103.     
  104.     try:
  105.         return seq.index(item)
  106.     except ValueError:
  107.         return -1
  108.  
  109.  
  110.  
  111. def groupby(seq, key = (lambda x: x)):
  112.     res = defaultdict(list)
  113.     for item in seq:
  114.         res[key(item)].append(item)
  115.     
  116.     for k in res:
  117.         yield (k, res[k])
  118.     
  119.  
  120.  
  121. class Delegate(ObjectList):
  122.     VETO = object()
  123.     
  124.     def __init__(self, iterable = [], ignore_exceptions = None, collect_values = False):
  125.         list.__init__(self, iterable)
  126.         self.__dict__['collect_values'] = collect_values
  127.         None(object.__setattr__, self, 'ignore_exceptions' if ignore_exceptions is not None else tuple())
  128.  
  129.     
  130.     def __iadd__(self, f):
  131.         if isinstance(f, list):
  132.             for thing in f:
  133.                 self.__iadd__(thing)
  134.             
  135.         else:
  136.             self.append(f)
  137.         return self
  138.  
  139.     
  140.     def __isub__(self, f):
  141.         if not isiterable(f):
  142.             f = (f,)
  143.         
  144.         for x in f:
  145.             self.remove(x)
  146.         
  147.         return self
  148.  
  149.     
  150.     def __ipow__(self, d):
  151.         self(**d)
  152.         return self
  153.  
  154.     
  155.     def __imul__(self, a):
  156.         self(*a)
  157.         return self
  158.  
  159.     
  160.     def __idiv__(self, tup):
  161.         (a, k) = tup
  162.         self(*a, **k)
  163.         return self
  164.  
  165.     
  166.     def __call__(self, *a, **k):
  167.         result = [
  168.             None]
  169.         for call in self:
  170.             
  171.             try:
  172.                 result.append(call(*a, **k))
  173.             except self.ignore_exceptions:
  174.                 self.remove(call)
  175.             except Exception:
  176.                 traceback.print_exc()
  177.  
  178.             if result[-1] is self.VETO:
  179.                 break
  180.             
  181.             if not self.collect_values:
  182.                 result = result[-1:]
  183.                 continue
  184.         
  185.         if self.collect_values:
  186.             result.pop(0)
  187.         else:
  188.             result = result[-1]
  189.         return result
  190.  
  191.     
  192.     def call_and_clear(self):
  193.         result = self()
  194.         self[:] = []
  195.         return result
  196.  
  197.     
  198.     def __repr__(self):
  199.         funcinfo = funcinfo
  200.         import util
  201.         return '<%s: [%s]>' % (type(self).__name__, (', '.join,)((lambda .0: for f in .0:
  202. funcinfo(f))(self)))
  203.  
  204.     
  205.     def add_unique(self, cb):
  206.         if cb not in self:
  207.             self.append(cb)
  208.         
  209.  
  210.     
  211.     def remove_maybe(self, cb):
  212.         if cb in self:
  213.             self.remove(cb)
  214.         
  215.  
  216.  
  217. objset = object.__setattr__
  218.  
  219. class PausableDelegate(Delegate):
  220.     
  221.     def __init__(self):
  222.         Delegate.__init__(self)
  223.         objset(self, 'paused', False)
  224.  
  225.     
  226.     def __call__(self, *a, **k):
  227.         if self.paused:
  228.             (None, None, self.paused_calls.append)((lambda : Delegate.__call__(self, *a, **k)))
  229.             return None
  230.         else:
  231.             return Delegate.__call__(self, *a, **k)
  232.  
  233.     
  234.     def pause(self):
  235.         if not self.paused:
  236.             objset(self, 'paused', True)
  237.             objset(self, 'paused_calls', [])
  238.             return True
  239.         
  240.         return False
  241.  
  242.     
  243.     def unpause(self):
  244.         if self.paused:
  245.             objset(self, 'paused', False)
  246.             if self.paused_calls:
  247.                 for call in self.paused_calls:
  248.                     traceguard.__enter__()
  249.                     
  250.                     try:
  251.                         call()
  252.                     finally:
  253.                         pass
  254.  
  255.                 
  256.                 del self.paused_calls[:]
  257.             
  258.             return True
  259.         
  260.         return False
  261.  
  262.  
  263.  
  264. class WeakDelegate(object):
  265.     
  266.     def __init__(self):
  267.         self.cbs = []
  268.  
  269.     
  270.     def append(self, cb, obj = None):
  271.         self.cbs.append(better_ref(cb, obj = obj))
  272.  
  273.     
  274.     def __iadd__(self, cb):
  275.         self.cbs.append(better_ref(cb))
  276.         return self
  277.  
  278.     
  279.     def __isub__(self, cb):
  280.         new_cbs = []
  281.         for cbref in self.cbs:
  282.             callback = cbref()
  283.             if cb is not callback:
  284.                 new_cbs.append(cb)
  285.                 continue
  286.         
  287.         self.cbs = new_cbs
  288.         return self
  289.  
  290.     
  291.     def __call__(self, *a, **k):
  292.         new_cbs = []
  293.         cbs = self.cbs[:]
  294.         self.cbs[:] = []
  295.         for cbref in cbs:
  296.             callback = cbref()
  297.             if callback is not None:
  298.                 new_cbs.append(cbref)
  299.                 
  300.                 try:
  301.                     callback(*a, **k)
  302.                 except Exception:
  303.                     traceback.print_exc()
  304.                 except:
  305.                     None<EXCEPTION MATCH>Exception
  306.                 
  307.  
  308.             None<EXCEPTION MATCH>Exception
  309.         
  310.         self.cbs[:] = new_cbs
  311.  
  312.  
  313.  
  314. def autoassign(self, locals):
  315.     for key, value in locals.iteritems():
  316.         if key == 'self':
  317.             continue
  318.         
  319.         setattr(self, key, value)
  320.     
  321.  
  322.  
  323. def flatten(seq):
  324.     lst = []
  325.     for el in seq:
  326.         if isinstance(el, (list, tuple)):
  327.             lst.extend(flatten(el))
  328.             continue
  329.         lst.append(el)
  330.     
  331.     return lst
  332.  
  333.  
  334. def dictargs(**argmap):
  335.     
  336.     def decorator(func):
  337.         
  338.         def newf(self, response):
  339.             
  340.             try:
  341.                 args = _[1]
  342.             except KeyError:
  343.                 print >>sys.stderr, 'Error matching argument for', func.__name__
  344.                 raise 
  345.  
  346.             return func(self, *args)
  347.  
  348.         newf = (None, functools.wraps(func))(newf)
  349.         return newf
  350.  
  351.     return decorator
  352.  
  353.  
  354. def dictargcall(func, argdict, argmapping):
  355.     argdict = argdict.copy()
  356.     args = []
  357.     kwargs = { }
  358.     code = func.func_code
  359.     argcount = code.co_argcount
  360.     argnames = code.co_varnames[:argcount]
  361.     if not func.func_defaults:
  362.         pass
  363.     defaults = ()
  364.     _takes_args = bool(code.co_flags & 4)
  365.     takes_kwargs = bool(code.co_flags & 8)
  366.     if argnames and argnames[0] == 'self':
  367.         argnames = argnames[1:]
  368.         argcount -= 1
  369.     
  370.     for argname in argnames[:argcount - len(defaults)]:
  371.         if argname not in argmapping:
  372.             raise ValueError('required argument %s is not in mapping\ngiven mapping: %s' % (argname, pprint.pformat(argmapping)))
  373.         
  374.         real_name = argmapping[argname]
  375.         if real_name not in argdict:
  376.             raise ValueError('required argument "%s" (%s) is not in argument dictionary\ngiven arguments: %s' % (argname, real_name, pprint.pformat(argdict)))
  377.         
  378.         args.append(argdict[real_name])
  379.         del argdict[real_name]
  380.     
  381.     default_index = 0
  382.     for argname in argnames[argcount - len(defaults):]:
  383.         if argname not in argmapping or argmapping[argname] not in argdict:
  384.             args.append(defaults[default_index])
  385.         else:
  386.             args.append(argdict[argmapping[argname]])
  387.             del argdict[argmapping[argname]]
  388.         default_index += 1
  389.     
  390.     if takes_kwargs:
  391.         for k, v in argdict.iteritems():
  392.             if k in argmapping:
  393.                 kwargs[argmapping[k]] = v
  394.                 continue
  395.             kwargs[str(k)] = v
  396.         
  397.     
  398.     if not takes_kwargs:
  399.         return func(*args)
  400.     else:
  401.         return func(*args, **kwargs)
  402.  
  403.  
  404. def funcToMethod(func, clas, method_name = None):
  405.     func.im_class = clas
  406.     func.im_func = func
  407.     func.im_self = None
  408.     if not method_name:
  409.         method_name = func.__name__
  410.     
  411.     clas.__dict__[method_name] = func
  412.  
  413.  
  414. def attach_method(obj, func, name = None):
  415.     if not name:
  416.         pass
  417.     name = func.__name__
  418.     cls = obj.__class__
  419.     cls.temp_foo = func
  420.     obj.__setattr__(name, cls.temp_foo)
  421.     del cls.temp_foo
  422.  
  423.  
  424. class InheritableProperty(object):
  425.     
  426.     def __init__(self, fget = None, fset = None, fdel = None, doc = None):
  427.         self.fget = fget
  428.         self.fset = fset
  429.         self.fdel = fdel
  430.         self.__doc__ = doc
  431.  
  432.     
  433.     def __get__(self, obj, objtype = None):
  434.         if obj is None:
  435.             return self
  436.         
  437.         if callable(self.fget):
  438.             return self.fget(obj)
  439.         
  440.         if isinstance(self.fget, basestring):
  441.             return getattr(obj, self.fget)()
  442.         
  443.         raise AttributeError('unreadable attribute')
  444.  
  445.     
  446.     def __set__(self, obj, value):
  447.         if callable(self.fset):
  448.             return self.fset(obj, value)
  449.         
  450.         if isinstance(self.fset, basestring):
  451.             return getattr(obj, self.fset)(value)
  452.         
  453.         raise AttributeError("can't set attribute")
  454.  
  455.     
  456.     def __delete__(self, obj):
  457.         if callable(self.fdel):
  458.             return self.fdel(obj)
  459.         
  460.         if isinstance(self.fdel, basestring):
  461.             return getattr(obj, self.fdel)()
  462.         
  463.         raise AttributeError("can't delete attribute")
  464.  
  465.  
  466. iproperty = InheritableProperty
  467.  
  468. def gen_sequence(func):
  469.     cannotcompile = cannotcompile
  470.     import util.introspect
  471.     
  472.     def wrapper(*args, **kwargs):
  473.         gen = func(*args, **kwargs)
  474.         val = gen.next()
  475.         
  476.         try:
  477.             gen.send(stupidref(gen))
  478.         except StopIteration:
  479.             pass
  480.  
  481.         return val
  482.  
  483.     wrapper = cannotcompile((functools.wraps(func),)(wrapper))
  484.     return wrapper
  485.  
  486.  
  487. def removedupes(seq, key = (lambda x: x)):
  488.     s = set()
  489.     uniqueseq = []
  490.     for elem in seq:
  491.         if key(elem) not in s:
  492.             uniqueseq.append(elem)
  493.             s.add(key(elem))
  494.             continue
  495.     
  496.     return uniqueseq
  497.  
  498.  
  499. def lispify(*args):
  500.     
  501.     try:
  502.         iter(args[0])
  503.     except:
  504.         pass
  505.  
  506.     args = args[0]
  507.     return reduce((lambda x, y: (lambda : x(y(*a, **k)))
  508. ), args)
  509.  
  510.  
  511. class CallCounter(object):
  512.     
  513.     def __init__(self, trigger, func, *args, **kwargs):
  514.         self._count = -1
  515.         self._trigger = trigger
  516.         self._func = func
  517.         self._args = args
  518.         self._kwargs = kwargs
  519.         self()
  520.  
  521.     
  522.     def __call__(self):
  523.         self._count += 1
  524.         if self._count == self._trigger:
  525.             self._func(*self._args, **self._kwargs)
  526.         
  527.  
  528.     
  529.     def func_code(self):
  530.         return self._func.func_code
  531.  
  532.     func_code = property(func_code)
  533.  
  534.  
  535. def readonly(attr):
  536.     return property(operator.attrgetter(attr))
  537.  
  538.  
  539. def takemany(n, iterable):
  540.     while n > 0:
  541.         yield iterable.next()
  542.         n -= 1
  543.  
  544.  
  545. def boolify(s):
  546.     return s.lower() in ('yes', 'true', '1')
  547.  
  548. if __name__ == '__main__':
  549.     import doctest
  550.     doctest.testmod(verbose = True)
  551.  
  552.