home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1874 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  20.6 KB  |  511 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __docformat__ = 'restructuredtext en'
  5. import sys
  6. import cPickle as pickle
  7. from types import FunctionType
  8. import linecache
  9. import warnings
  10. from twisted.internet import reactor
  11. from twisted.python import components, log
  12. from twisted.python.failure import Failure
  13. from zope.interface import Interface, implements, Attribute
  14. from IPython.ColorANSI import TermColors
  15. from IPython.kernel.twistedutil import blockingCallFromThread
  16. from IPython.kernel import error
  17. from IPython.kernel.parallelfunction import ParallelFunction
  18. from IPython.kernel.mapper import MultiEngineMapper, IMultiEngineMapperFactory, IMapper
  19. from IPython.kernel import map as Map
  20. from IPython.kernel import multiengine as me
  21. from IPython.kernel.multiengine import IFullMultiEngine, IFullSynchronousMultiEngine
  22.  
  23. class IPendingResult(Interface):
  24.     result_id = Attribute('ID of the deferred on the other side')
  25.     client = Attribute('A client that I came from')
  26.     r = Attribute('An attribute that is a property that calls and returns get_result')
  27.     
  28.     def get_result(default = None, block = True):
  29.         pass
  30.  
  31.     
  32.     def add_callback(f, *args, **kwargs):
  33.         pass
  34.  
  35.  
  36.  
  37. class PendingResult(object):
  38.     
  39.     def __init__(self, client, result_id):
  40.         self.client = client
  41.         self.result_id = result_id
  42.         self.called = False
  43.         self.raised = False
  44.         self.callbacks = []
  45.  
  46.     
  47.     def get_result(self, default = None, block = True):
  48.         if self.called:
  49.             if self.raised:
  50.                 raise self.result[0], self.result[1], self.result[2]
  51.             self.raised
  52.             return self.result
  53.         self.called
  54.         
  55.         try:
  56.             result = self.client.get_pending_deferred(self.result_id, block)
  57.         except error.ResultNotCompleted:
  58.             return default
  59.             self.result = sys.exc_info()
  60.             self.called = True
  61.             self.raised = True
  62.             raise 
  63.  
  64.         for cb in self.callbacks:
  65.             result = cb[0](result, *cb[1], **cb[2])
  66.         
  67.         self.result = result
  68.         self.called = True
  69.         return result
  70.  
  71.     
  72.     def add_callback(self, f, *args, **kwargs):
  73.         self.callbacks.append((f, args, kwargs))
  74.  
  75.     
  76.     def __cmp__(self, other):
  77.         if self.result_id < other.result_id:
  78.             return -1
  79.         return 1
  80.  
  81.     
  82.     def _get_r(self):
  83.         return self.get_result(block = True)
  84.  
  85.     r = property(_get_r)
  86.  
  87.  
  88. class ResultList(list):
  89.     
  90.     def __repr__(self):
  91.         output = []
  92.         if sys.platform == 'win32':
  93.             blue = normal = red = green = ''
  94.         else:
  95.             blue = TermColors.Blue
  96.             normal = TermColors.Normal
  97.             red = TermColors.Red
  98.             green = TermColors.Green
  99.         output.append('<Results List>\n')
  100.         for cmd in self:
  101.             if isinstance(cmd, Failure):
  102.                 output.append(cmd)
  103.                 continue
  104.             target = cmd.get('id', None)
  105.             cmd_num = cmd.get('number', None)
  106.             cmd_stdin = cmd.get('input', { }).get('translated', 'No Input')
  107.             cmd_stdout = cmd.get('stdout', None)
  108.             cmd_stderr = cmd.get('stderr', None)
  109.             output.append('%s[%i]%s In [%i]:%s %s\n' % (green, target, blue, cmd_num, normal, cmd_stdin))
  110.             if cmd_stdout:
  111.                 output.append('%s[%i]%s Out[%i]:%s %s\n' % (green, target, red, cmd_num, normal, cmd_stdout))
  112.             
  113.             if cmd_stderr:
  114.                 output.append('%s[%i]%s Err[%i]:\n%s %s' % (green, target, red, cmd_num, normal, cmd_stderr))
  115.                 continue
  116.         
  117.         return ''.join(output)
  118.  
  119.  
  120.  
  121. def wrapResultList(result):
  122.     if len(result) == 0:
  123.         result = [
  124.             result]
  125.     
  126.     return ResultList(result)
  127.  
  128.  
  129. class QueueStatusList(list):
  130.     
  131.     def __repr__(self):
  132.         output = []
  133.         output.append('<Queue Status List>\n')
  134.         for e in self:
  135.             output.append('Engine: %s\n' % repr(e[0]))
  136.             output.append('    Pending: %s\n' % repr(e[1]['pending']))
  137.             for q in e[1]['queue']:
  138.                 output.append('    Command: %s\n' % repr(q))
  139.             
  140.         
  141.         return ''.join(output)
  142.  
  143.  
  144.  
  145. class InteractiveMultiEngineClient(object):
  146.     
  147.     def activate(self):
  148.         
  149.         try:
  150.             __IPYTHON__.activeController = self
  151.         except NameError:
  152.             print 'The IPython Controller magics only work within IPython.'
  153.  
  154.  
  155.     
  156.     def __setitem__(self, key, value):
  157.         (targets, block) = self._findTargetsAndBlock()
  158.         return self.push({
  159.             key: value }, targets = targets, block = block)
  160.  
  161.     
  162.     def __getitem__(self, key):
  163.         if isinstance(key, str):
  164.             (targets, block) = self._findTargetsAndBlock()
  165.             return self.pull(key, targets = targets, block = block)
  166.         raise TypeError('__getitem__ only takes strs')
  167.  
  168.     
  169.     def __len__(self):
  170.         return len(self.get_ids())
  171.  
  172.     
  173.     def findsource_file(self, f):
  174.         linecache.checkcache()
  175.         s = findsource(f.f_code)
  176.         lnum = f.f_lineno
  177.         wsource = s[0][f.f_lineno:]
  178.         return strip_whitespace(wsource)
  179.  
  180.     
  181.     def findsource_ipython(self, f):
  182.         ipapi = ipapi
  183.         import IPython
  184.         self.ip = ipapi.get()
  185.         wsource = [ l + '\n' for l in self.ip.IP.input_hist_raw[-1].splitlines()[1:] ]
  186.         return strip_whitespace(wsource)
  187.  
  188.     
  189.     def __enter__(self):
  190.         f = sys._getframe(1)
  191.         local_ns = f.f_locals
  192.         global_ns = f.f_globals
  193.         if f.f_code.co_filename == '<ipython console>':
  194.             s = self.findsource_ipython(f)
  195.         else:
  196.             s = self.findsource_file(f)
  197.         self._with_context_result = self.execute(s)
  198.  
  199.     
  200.     def __exit__(self, etype, value, tb):
  201.         if issubclass(etype, error.StopLocalExecution):
  202.             return True
  203.  
  204.  
  205.  
  206. def remote():
  207.     m = 'Special exception to stop local execution of parallel code.'
  208.     raise error.StopLocalExecution(m)
  209.  
  210.  
  211. def strip_whitespace(source):
  212.     wsource = [ l.expandtabs(4) for l in source ]
  213.     done = False
  214.     for line in wsource:
  215.         for col, char in enumerate(line):
  216.             if char != ' ':
  217.                 done = True
  218.                 break
  219.                 continue
  220.             None if line.isspace() else []
  221.         
  222.         if done:
  223.             break
  224.             continue
  225.     
  226.     for lno, line in enumerate(wsource):
  227.         lead = line[:col]
  228.         if lead.isspace():
  229.             continue
  230.             continue
  231.         if not lead.lstrip().startswith('#'):
  232.             break
  233.             continue
  234.     
  235.     src_lines = [ l[col:] for l in wsource[:lno + 1] ]
  236.     for nline, line in enumerate(src_lines):
  237.         if 'remote()' in line:
  238.             break
  239.             continue
  240.         None if line.isspace() or line.startswith('#') else []
  241.         raise ValueError('remote() call missing at the start of code')
  242.     
  243.     src = ''.join(src_lines[nline + 1:])
  244.     return src
  245.  
  246. _prop_warn = '\nWe are currently refactoring the task dependency system.  This might\ninvolve the removal of this method and other methods related to engine\nproperties.  Please see the docstrings for IPython.kernel.TaskRejectError \nfor more information.'
  247.  
  248. class IFullBlockingMultiEngineClient(Interface):
  249.     pass
  250.  
  251.  
  252. class FullBlockingMultiEngineClient(InteractiveMultiEngineClient):
  253.     implements(IFullBlockingMultiEngineClient, IMultiEngineMapperFactory, IMapper)
  254.     
  255.     def __init__(self, smultiengine):
  256.         self.smultiengine = smultiengine
  257.         self.block = True
  258.         self.targets = 'all'
  259.  
  260.     
  261.     def _findBlock(self, block = None):
  262.         if block is None:
  263.             return self.block
  264.         if block in (True, False):
  265.             return block
  266.         raise ValueError('block must be True or False')
  267.  
  268.     
  269.     def _findTargets(self, targets = None):
  270.         if targets is None:
  271.             return self.targets
  272.         if not isinstance(targets, (str, list, tuple, int)):
  273.             raise ValueError('targets must be a str, list, tuple or int')
  274.         isinstance(targets, (str, list, tuple, int))
  275.         return targets
  276.  
  277.     
  278.     def _findTargetsAndBlock(self, targets = None, block = None):
  279.         return (self._findTargets(targets), self._findBlock(block))
  280.  
  281.     
  282.     def _blockFromThread(self, function, *args, **kwargs):
  283.         block = kwargs.get('block', None)
  284.         if block is None:
  285.             raise error.MissingBlockArgument("'block' keyword argument is missing")
  286.         block is None
  287.         result = blockingCallFromThread(function, *args, **kwargs)
  288.         if not block:
  289.             result = PendingResult(self, result)
  290.         
  291.         return result
  292.  
  293.     
  294.     def get_pending_deferred(self, deferredID, block):
  295.         return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block)
  296.  
  297.     
  298.     def barrier(self, pendingResults):
  299.         prList = list(pendingResults)
  300.         for pr in prList:
  301.             if not isinstance(pr, PendingResult):
  302.                 raise error.NotAPendingResult('Objects passed to barrier must be PendingResult instances')
  303.             isinstance(pr, PendingResult)
  304.         
  305.         prList.sort()
  306.         for pr in prList:
  307.             
  308.             try:
  309.                 result = pr.get_result(block = True)
  310.             continue
  311.             except Exception:
  312.                 continue
  313.             
  314.  
  315.         
  316.  
  317.     
  318.     def flush(self):
  319.         r = blockingCallFromThread(self.smultiengine.clear_pending_deferreds)
  320.         return r
  321.  
  322.     clear_pending_results = flush
  323.     
  324.     def execute(self, lines, targets = None, block = None):
  325.         (targets, block) = self._findTargetsAndBlock(targets, block)
  326.         result = blockingCallFromThread(self.smultiengine.execute, lines, targets = targets, block = block)
  327.         if block:
  328.             result = ResultList(result)
  329.         else:
  330.             result = PendingResult(self, result)
  331.             result.add_callback(wrapResultList)
  332.         return result
  333.  
  334.     
  335.     def push(self, namespace, targets = None, block = None):
  336.         (targets, block) = self._findTargetsAndBlock(targets, block)
  337.         return self._blockFromThread(self.smultiengine.push, namespace, targets = targets, block = block)
  338.  
  339.     
  340.     def pull(self, keys, targets = None, block = None):
  341.         (targets, block) = self._findTargetsAndBlock(targets, block)
  342.         return self._blockFromThread(self.smultiengine.pull, keys, targets = targets, block = block)
  343.  
  344.     
  345.     def push_function(self, namespace, targets = None, block = None):
  346.         (targets, block) = self._findTargetsAndBlock(targets, block)
  347.         return self._blockFromThread(self.smultiengine.push_function, namespace, targets = targets, block = block)
  348.  
  349.     
  350.     def pull_function(self, keys, targets = None, block = None):
  351.         (targets, block) = self._findTargetsAndBlock(targets, block)
  352.         return self._blockFromThread(self.smultiengine.pull_function, keys, targets = targets, block = block)
  353.  
  354.     
  355.     def push_serialized(self, namespace, targets = None, block = None):
  356.         (targets, block) = self._findTargetsAndBlock(targets, block)
  357.         return self._blockFromThread(self.smultiengine.push_serialized, namespace, targets = targets, block = block)
  358.  
  359.     
  360.     def pull_serialized(self, keys, targets = None, block = None):
  361.         (targets, block) = self._findTargetsAndBlock(targets, block)
  362.         return self._blockFromThread(self.smultiengine.pull_serialized, keys, targets = targets, block = block)
  363.  
  364.     
  365.     def get_result(self, i = None, targets = None, block = None):
  366.         (targets, block) = self._findTargetsAndBlock(targets, block)
  367.         result = blockingCallFromThread(self.smultiengine.get_result, i, targets = targets, block = block)
  368.         if block:
  369.             result = ResultList(result)
  370.         else:
  371.             result = PendingResult(self, result)
  372.             result.add_callback(wrapResultList)
  373.         return result
  374.  
  375.     
  376.     def reset(self, targets = None, block = None):
  377.         (targets, block) = self._findTargetsAndBlock(targets, block)
  378.         return self._blockFromThread(self.smultiengine.reset, targets = targets, block = block)
  379.  
  380.     
  381.     def keys(self, targets = None, block = None):
  382.         (targets, block) = self._findTargetsAndBlock(targets, block)
  383.         return self._blockFromThread(self.smultiengine.keys, targets = targets, block = block)
  384.  
  385.     
  386.     def kill(self, controller = False, targets = None, block = None):
  387.         (targets, block) = self._findTargetsAndBlock(targets, block)
  388.         return self._blockFromThread(self.smultiengine.kill, controller, targets = targets, block = block)
  389.  
  390.     
  391.     def clear_queue(self, targets = None, block = None):
  392.         (targets, block) = self._findTargetsAndBlock(targets, block)
  393.         return self._blockFromThread(self.smultiengine.clear_queue, targets = targets, block = block)
  394.  
  395.     
  396.     def queue_status(self, targets = None, block = None):
  397.         (targets, block) = self._findTargetsAndBlock(targets, block)
  398.         return self._blockFromThread(self.smultiengine.queue_status, targets = targets, block = block)
  399.  
  400.     
  401.     def set_properties(self, properties, targets = None, block = None):
  402.         warnings.warn(_prop_warn)
  403.         (targets, block) = self._findTargetsAndBlock(targets, block)
  404.         return self._blockFromThread(self.smultiengine.set_properties, properties, targets = targets, block = block)
  405.  
  406.     
  407.     def get_properties(self, keys = None, targets = None, block = None):
  408.         warnings.warn(_prop_warn)
  409.         (targets, block) = self._findTargetsAndBlock(targets, block)
  410.         return self._blockFromThread(self.smultiengine.get_properties, keys, targets = targets, block = block)
  411.  
  412.     
  413.     def has_properties(self, keys, targets = None, block = None):
  414.         warnings.warn(_prop_warn)
  415.         (targets, block) = self._findTargetsAndBlock(targets, block)
  416.         return self._blockFromThread(self.smultiengine.has_properties, keys, targets = targets, block = block)
  417.  
  418.     
  419.     def del_properties(self, keys, targets = None, block = None):
  420.         warnings.warn(_prop_warn)
  421.         (targets, block) = self._findTargetsAndBlock(targets, block)
  422.         return self._blockFromThread(self.smultiengine.del_properties, keys, targets = targets, block = block)
  423.  
  424.     
  425.     def clear_properties(self, targets = None, block = None):
  426.         warnings.warn(_prop_warn)
  427.         (targets, block) = self._findTargetsAndBlock(targets, block)
  428.         return self._blockFromThread(self.smultiengine.clear_properties, targets = targets, block = block)
  429.  
  430.     
  431.     def get_ids(self):
  432.         result = blockingCallFromThread(self.smultiengine.get_ids)
  433.         return result
  434.  
  435.     
  436.     def scatter(self, key, seq, dist = 'b', flatten = False, targets = None, block = None):
  437.         (targets, block) = self._findTargetsAndBlock(targets, block)
  438.         return self._blockFromThread(self.smultiengine.scatter, key, seq, dist, flatten, targets = targets, block = block)
  439.  
  440.     
  441.     def gather(self, key, dist = 'b', targets = None, block = None):
  442.         (targets, block) = self._findTargetsAndBlock(targets, block)
  443.         return self._blockFromThread(self.smultiengine.gather, key, dist, targets = targets, block = block)
  444.  
  445.     
  446.     def raw_map(self, func, seq, dist = 'b', targets = None, block = None):
  447.         (targets, block) = self._findTargetsAndBlock(targets, block)
  448.         return self._blockFromThread(self.smultiengine.raw_map, func, seq, dist, targets = targets, block = block)
  449.  
  450.     
  451.     def map(self, func, *sequences):
  452.         return self.mapper().map(func, *sequences)
  453.  
  454.     
  455.     def mapper(self, dist = 'b', targets = 'all', block = None):
  456.         return MultiEngineMapper(self, dist, targets, block)
  457.  
  458.     
  459.     def parallel(self, dist = 'b', targets = None, block = None):
  460.         (targets, block) = self._findTargetsAndBlock(targets, block)
  461.         mapper = self.mapper(dist, targets, block)
  462.         pf = ParallelFunction(mapper)
  463.         return pf
  464.  
  465.     
  466.     def zip_pull(self, keys, targets = None, block = None):
  467.         (targets, block) = self._findTargetsAndBlock(targets, block)
  468.         return self._blockFromThread(self.smultiengine.zip_pull, keys, targets = targets, block = block)
  469.  
  470.     
  471.     def run(self, filename, targets = None, block = None):
  472.         (targets, block) = self._findTargetsAndBlock(targets, block)
  473.         return self._blockFromThread(self.smultiengine.run, filename, targets = targets, block = block)
  474.  
  475.     
  476.     def benchmark(self, push_size = 10000):
  477.         import timeit
  478.         import __builtin__
  479.         __builtin__._mec_self = self
  480.         benchmarks = { }
  481.         repeat = 3
  482.         count = 10
  483.         timer = timeit.Timer('_mec_self.execute("pass",0)')
  484.         result = 1000 * min(timer.repeat(repeat, count)) / count
  485.         benchmarks['single_engine_latency'] = (result, 'msec')
  486.         timer = timeit.Timer('_mec_self.execute("pass")')
  487.         result = 1000 * min(timer.repeat(repeat, count)) / count
  488.         benchmarks['all_engine_latency'] = (result, 'msec')
  489.         
  490.         try:
  491.             import numpy as np
  492.         except:
  493.             pass
  494.  
  495.         timer = timeit.Timer('_mec_self.push(d)', "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size)
  496.         result = min(timer.repeat(repeat, count)) / count
  497.         benchmarks['all_engine_push'] = (1e-06 * push_size * 8 / result, 'MB/sec')
  498.         
  499.         try:
  500.             import numpy as np
  501.         except:
  502.             pass
  503.  
  504.         timer = timeit.Timer('_mec_self.push(d,0)', "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size)
  505.         result = min(timer.repeat(repeat, count)) / count
  506.         benchmarks['single_engine_push'] = (1e-06 * push_size * 8 / result, 'MB/sec')
  507.         return benchmarks
  508.  
  509.  
  510. components.registerAdapter(FullBlockingMultiEngineClient, IFullSynchronousMultiEngine, IFullBlockingMultiEngineClient)
  511.