示例#1
0
def filter_include():
    filter_func = pycallgraph.GlobbingFilter(include=['*.secret_function', \
        'Banana.__init__'])
    pycallgraph.start_trace(filter_func=filter_func)
    banana = Banana()
    banana.eat()
    pycallgraph.make_dot_graph('filter-include.png')
示例#2
0
    def render (self, include=None, exclude=None, **kwargs): # {{{
        """
            Actually returns an image (as png), and will reset the trace if the
            include or exclude parameters are different.
        """
        
        inc = self.last_include
        exc = self.last_exclude

        if include or include == "":
            inc = include.split(',')

        if exclude or exclude == "":
            exc = exclude.split(',')

        if inc != self.last_include or exc != self.last_exclude:
            # New trace, resetting the old one.

            pycallgraph.stop_trace()
            pycallgraph.start_trace(filter_func = self.filter_func(inc, exc), reset=True)

        pycallgraph.make_dot_graph("." + self.image_file, stop=False)

        cherrypy.response.headers['Content-Type'] = "image/png"
        f = open("." + self.image_file, "r+b")
        return f.read()
示例#3
0
def main():

    # Do the trace, remember the values for later
    pycallgraph.start_trace()
    import HTMLParser
    pycallgraph.stop_trace()

    # Set the edge colour to black for all examples
    pycallgraph.settings['edge_colour'] = lambda a, b: 'black'

    # Default node colouring
    pycallgraph.make_dot_graph('colours-default.png')

    # Rainbow
    pycallgraph.settings['node_colour'] = rainbow
    pycallgraph.make_dot_graph('colours-rainbow.png')

    # Greyscale
    pycallgraph.settings['node_colour'] = greyscale
    pycallgraph.make_dot_graph('colours-greyscale.png')

    # Orange/Green
    pycallgraph.settings['node_colour'] = orange_green
    pycallgraph.make_dot_graph('colours-orange-green.png')

    # Random
    pycallgraph.settings['node_colour'] = rand
    pycallgraph.make_dot_graph('colours-random.png')
示例#4
0
def makeBatch(images, iGrid):
    '''
	makes a batch of sprites out of images depending on if they are
	visible or not
	'''
    import pycallgraph
    pycallgraph.start_trace()
    batch = pyglet.graphics.Batch()
    sprites = []
    tiles = []
    xS = []
    yS = []
    print "Making sprite batch"
    i = 0
    for image, coords in images:
        i += 1
        print "image", i, "of", len(images)
        x, y = coords
        key = str(x) + str(y)
        if visible(image, coords):
            iGrid[key][1] = True
            sprites.append(pyglet.sprite.Sprite(image, x=x, y=y, batch=batch))
        else:
            iGrid[key][1] = False
    pycallgraph.make_dot_graph(r'C:\C9\test2.png')
    print "callgraph saved"
    return batch, sprites, iGrid
示例#5
0
def filter_exclude():
    filter_func = pycallgraph.GlobbingFilter(exclude=['pycallgraph.*', \
        '*.secret_function'])
    pycallgraph.start_trace(filter_func=filter_func)
    banana = Banana()
    banana.eat()
    pycallgraph.make_dot_graph('filter-exclude.png')
示例#6
0
def main():

    # Do the trace, remember the values for later
    pycallgraph.start_trace()
    import HTMLParser
    pycallgraph.stop_trace()

    # Set the edge colour to black for all examples
    pycallgraph.settings['edge_colour'] = lambda a, b: 'black'

    # Default node colouring
    pycallgraph.make_dot_graph('colours-default.png')

    # Rainbow
    pycallgraph.settings['node_colour'] = rainbow
    pycallgraph.make_dot_graph('colours-rainbow.png')

    # Greyscale
    pycallgraph.settings['node_colour'] = greyscale
    pycallgraph.make_dot_graph('colours-greyscale.png')

    # Orange/Green
    pycallgraph.settings['node_colour'] = orange_green
    pycallgraph.make_dot_graph('colours-orange-green.png')

    # Random
    pycallgraph.settings['node_colour'] = rand
    pycallgraph.make_dot_graph('colours-random.png')
示例#7
0
 def callwrapper(*args, **kwargs):
     if not outfile: # allow deactivating
         return fn(*args, **kwargs)
     pycallgraph.start_trace()
     fn_output = fn(*args, **kwargs)
     pycallgraph.stop_trace()
     pycallgraph.make_dot_graph(outfile)
     return fn_output
示例#8
0
def main():
    pycallgraph.settings['dont_exclude_anything'] = True
    import_list = ['pickle', 'htmllib']

    for imp in import_list:
        pycallgraph.start_trace()
        __import__(imp)
        pycallgraph.make_dot_graph('import-%s.png' % imp)
示例#9
0
 def shutdown(self):
     fname = self._filename
     pycallgraph = self.pycallgraph
     if fname.endswith('.png'):
         logging.info("Saving the rendered callgraph to '%s'", fname)
         pycallgraph.make_dot_graph(fname)
     elif fname.endswith('.dot'):
         logging.info("Saving the raw callgraph to '%s'", fname)
         pycallgraph.save_dot(fname)
示例#10
0
 def shutdown(self):
     fname = self._filename
     pycallgraph = self.pycallgraph
     if fname.endswith('.png'):
         logging.info("Saving the rendered callgraph to '%s'", fname)
         pycallgraph.make_dot_graph(fname)
     elif fname.endswith('.dot'):
         logging.info("Saving the raw callgraph to '%s'", fname)
         pycallgraph.save_dot(fname)
示例#11
0
def cuba():
    eqs = '''
    dv/dt = (ge+gi-(v+49*mV))/(20*ms) : volt
    dge/dt = -ge/(5*ms) : volt
    dgi/dt = -gi/(10*ms) : volt
    '''
    eqs = Equations(eqs)
    pycallgraph.start_trace(filter_func=ff)
    eqs.prepare()
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-Equations.prepare.png')
示例#12
0
 def call_graph(fac, cmd='fac.query(1)'):
     import pycallgraph
     import Image
     iom = fac.hs.iom
     logmsg('Call Graph Command: ' + cmd)
     callgraph_fpath = iom.get_temp_fpath('callgraph' + cmd + '.png')
     pycallgraph.start_trace()
     eval(cmd)
     pycallgraph.stop_trace()
     pycallgraph.make_dot_graph(callgraph_fpath)
     Image.open(callgraph_fpath).show()
示例#13
0
 def call_graph(fac, cmd='fac.query(1)'):
     import pycallgraph
     import Image
     iom = fac.hs.iom
     logmsg('Call Graph Command: '+cmd)
     callgraph_fpath = iom.get_temp_fpath('callgraph'+cmd+'.png')
     pycallgraph.start_trace()
     eval(cmd)
     pycallgraph.stop_trace()
     pycallgraph.make_dot_graph(callgraph_fpath)
     Image.open(callgraph_fpath).show()
示例#14
0
def cuba():
    eqs = '''
    dv/dt = (ge+gi-(v+49*mV))/(20*ms) : volt
    dge/dt = -ge/(5*ms) : volt
    dgi/dt = -gi/(10*ms) : volt
    '''
    eqs = Equations(eqs)
    pycallgraph.start_trace(filter_func=ff)
    eqs.prepare()
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph(
        'callgraphs/cuba-bigcallgraph-Equations.prepare.png')
示例#15
0
def quit(signo, stackframe):
    """ Signal handler for aborting signals """
    global httpd, config
    logging.info("Thanks for using MoinMoin!")

    fname = config.pycallgraph_output
    if fname:
        import pycallgraph
        if fname.endswith('.png'):
            pycallgraph.make_dot_graph(fname)
        elif fname.endswith('.dot'):
            pycallgraph.save_dot(fname)

    if httpd:
        httpd.die()
示例#16
0
            def callgraphed_application(*args, **kwargs):
                ''' Start measuring the callgraph and dispatch. '''

                global _runcount

                # start tracing right before dispatch
                pycallgraph.start_trace()
                for chunk in app(*args, **kwargs):
                    yield chunk  # exhaust app generator

                # stop tracing after request is finished
                pycallgraph.stop_trace()
                _runcount = _runcount + 1
                pycallgraph.make_dot_graph('/'.join(
                    prefix +
                    ['.profile',
                     '%s-%s-callgraph.png' % (appname, _runcount)]))
                raise StopIteration()
示例#17
0
    def run(self):
        '''Main code runner for testing. To set a new test, update the self.callTest attribute in __init__(). 
        '''
        fp = environLocal.getTempFile('.png')
        gf = pycallgraph.GlobbingFilter(exclude=self.excludeList)
        # create instnace; will call setup routines
        ct = self.callTest()

        # start timer
        print('starting test')
        t = common.Timer()
        t.start()

        pycallgraph.start_trace(filter_func = gf)
        ct.testFocus() # run routine

        pycallgraph.stop_trace()
        pycallgraph.make_dot_graph(fp)

        print('elpased time: %s' % t)
        # open the completed file
        environLocal.launch('png', fp)
示例#18
0
def makeBatch(images,iGrid):
	'''
	makes a batch of sprites out of images depending on if they are
	visible or not
	'''
	if profile:
		import pycallgraph
		pycallgraph.start_trace()
	batch = pyglet.graphics.Batch()
	sprites = []
	tiles = []
	xS = []
	yS = []
	#print"Making sprite batch"
	i = 0
	for size,coords in images:
		i+=1
		#print"image",i,"of",len(images)
		x,y = coords
		h,w = size
		key = str(x) + str(y)
		if visible(size,coords):
			iGrid[key][1] = True
			image = MainImage.get_region(x,y,w,h)
			print"x,y",x,y
			print"size",image.width,image.height
			try:
				sprites.append(pyglet.sprite.Sprite(image,x=x,y=y,batch=batch))
			except:
				print"error"
		else:
			iGrid[key][1] = False
	if profile:
		pycallgraph.make_dot_graph(r'C:\C9\test.png')
		print "callgraph saved"
		sys.exit()
	return batch,sprites,iGrid
示例#19
0
class UrlTest(unittest.TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.client = Client()
        self.user = User.objects.get(id=1)
        self.staff_client = TestClient()
        self.staff_client.login_user(self.user)

    def test_homepage(self):
        ''' Homepage: unit '''
        url = os.environ.get('URL', reverse('home'))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._is_rendered, True)
        if hasattr(self, 'n'):
            self.i += 1
            print_progress(self.i, self.n, "Homepage: benchmark ... ")

    def test_homepage_bench(self):
        ''' Homepage: benchmark '''
        n = os.environ.get('BENCHMARK')
        graph = os.environ.get('GRAPH')
        if not n:
            print 'no benchmark ',
            sys.stdout.flush()
            return
        try:
            self.n = int(n)
            self.i = 0
        except Exception, err:
            print err
        try:
            from compressor.storage import default_storage
            default_storage.entries
        except:
            pass
        if graph:
            try:
                import pycallgraph
                pycallgraph.start_trace(filter_func=pycall_django_filter)
            except:
                print "install pycallgraph to draw profiling graph"
                graph = None
        t = timeit.timeit(self.test_homepage, setup=self.setUp, number=self.n)
        if graph:
            pycallgraph.make_dot_graph('test_homepage_bench.png')
        print ' ... {0:.1f} ms/view '.format((t / self.n) * 1000),
        sys.stdout.flush()
示例#20
0
def cuba():
    N = 4000
    Ne = int(N * 0.8)
    Ni = N - Ne
    p = 80. / N

    eqs = '''
    dv/dt = (ge+gi-(v+49*mV))/(20*ms) : volt
    dge/dt = -ge/(5*ms) : volt
    dgi/dt = -gi/(10*ms) : volt
    '''

    pycallgraph.start_trace(filter_func=ff_nomagicstateupdater)
    P = NeuronGroup(N, eqs, threshold=-50 * mV, reset=-60 * mV)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph(
        'callgraphs/cuba-bigcallgraph-NeuronGroup.__init__.no_magic_state_updater.png'
    )

    P.v = -60 * mV + 10 * mV * rand(len(P))
    Pe = P.subgroup(Ne)
    Pi = P.subgroup(Ni)

    pycallgraph.start_trace(filter_func=ff)
    Ce = Connection(Pe, P, 'ge', weight=1.62 * mV, sparseness=p)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph(
        'callgraphs/cuba-bigcallgraph-Connection.__init__.png')

    Ci = Connection(Pi, P, 'gi', weight=-9 * mV, sparseness=p)

    pycallgraph.start_trace(filter_func=ff)
    M = SpikeMonitor(P)
    trace = StateMonitor(P, 'v', record=0)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph(
        'callgraphs/cuba-bigcallgraph-Monitors.__init__.png')

    pycallgraph.start_trace(filter_func=ff_prepare)
    run(.1 * ms)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-run-prepare.png')
示例#21
0
def cuba():
    N = 4000
    Ne = int(N * 0.8)
    Ni = N - Ne
    p = 80. / N

    eqs = '''
    dv/dt = (ge+gi-(v+49*mV))/(20*ms) : volt
    dge/dt = -ge/(5*ms) : volt
    dgi/dt = -gi/(10*ms) : volt
    '''

    pycallgraph.start_trace(filter_func=ff_nomagicstateupdater)
    P = NeuronGroup(N, eqs,
                  threshold= -50 * mV, reset= -60 * mV)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-NeuronGroup.__init__.no_magic_state_updater.png')

    P.v = -60 * mV + 10 * mV * rand(len(P))
    Pe = P.subgroup(Ne)
    Pi = P.subgroup(Ni)

    pycallgraph.start_trace(filter_func=ff)
    Ce = Connection(Pe, P, 'ge', weight=1.62 * mV, sparseness=p)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-Connection.__init__.png')

    Ci = Connection(Pi, P, 'gi', weight= -9 * mV, sparseness=p)

    pycallgraph.start_trace(filter_func=ff)
    M = SpikeMonitor(P)
    trace = StateMonitor(P, 'v', record=0)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-Monitors.__init__.png')

    pycallgraph.start_trace(filter_func=ff_prepare)
    run(.1 * ms)
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraphs/cuba-bigcallgraph-run-prepare.png')
示例#22
0
def callgraph():
	import pycallgraph
	l = prepare()
	l.reset()
	lx = l.lexicon
	gr = l.grammar
	prp = l.properties
	#Lexicon Compile
	pycallgraph.start_trace()
	lx.compile(prp, True)
	pycallgraph.make_dot_graph('lexicon_compile.png')
	#Grammar Compile
	pycallgraph.start_trace()
	gr.compile(True)
	pycallgraph.make_dot_graph('grammar_compile.png')
	#Read
	pycallgraph.start_trace()
	l.read(u"mi pona e ilo")
	pycallgraph.make_dot_graph('read.png')
示例#23
0
              #TODO:  
              elif signal == 'shutdown':
                s.send('shutdown')



              elif signal == 'sample':
                  import pycallgraph
                  pycallgraph.start_trace()
                  # TODO:
                  # import cProfile
                  # cProfile.run('foo()')


              elif signal == 'stop_sample':
                pycallgraph.make_dot_graph('images/sample.png')
                #TODO: check to see if you need to stop pycallgraph.start_trace()

              elif signal == 'mouseevent':
                screen.process(event)


              elif signal == 'turn_on_logging':
                logging.basicConfig(filename='log/client.log', filemode='w', level=logging.DEBUG)
                

              elif signal == 'turn_off_logging':
                logger.setLevel(logging.CRITICAL)


        #reset signal
示例#24
0
def demo():
    # Teach network XOR function
    pat = [
        [[0,0], [0]],
        [[0,1], [1]],
        [[1,0], [1]],
        [[1,1], [0]]
    ]
    
    #change the sequence for testing
    pat2 = [
        [[0,1], [1]],
        [[0,0], [0]],
        [[1,0], [1]],
        [[1,1], [0]]
    ]

    # create a network with two input, two hidden, and one output nodes
    n = NN(2, 2, 1)
    # train it with some patterns
    n.train(pat)
    # test it
    n.test(pat2)



if __name__ == '__main__':
    pycallgraph.start_trace()
    demo()
    pycallgraph.make_dot_graph('D:/IntelligentSystems/kaggle/cgTest.png')
示例#25
0
def filter_max_depth():
    filter_func = pycallgraph.GlobbingFilter(max_depth=1)
    pycallgraph.start_trace(filter_func=filter_func)
    banana = Banana()
    banana.eat()
    pycallgraph.make_dot_graph('filter-max-depth.png')
示例#26
0
    def run(self, runWithEnviron=False):
        '''Main code runner for testing. To set a new test, update the self.callTest attribute in __init__(). 
        '''
        suffix = '.svg'
        fmt = suffix[1:]
        _MOD = "test.timeGraphs.py"

        if runWithEnviron:
            from music21 import environment
            environLocal = environment.Environment(_MOD)
            fp = environLocal.getTempFile(suffix)
        # manually get a temporary file
        else:
            import tempfile
            import os
            import sys
            if os.name in ['nt'] or sys.platform.startswith('win'):
                platform = 'win'
            else:
                platform = 'other'
            
            tempdir = os.path.join(tempfile.gettempdir(), 'music21')
            if platform != 'win':
                fd, fp = tempfile.mkstemp(dir=tempdir, suffix=suffix)
                if isinstance(fd, int):
                # on MacOS, fd returns an int, like 3, when this is called
                # in some context (specifically, programmatically in a 
                # TestExternal class. the fp is still valid and works
                # TODO: this did not work on MacOS 10.6.8 w/ py 2.7
                    pass
                else:
                    fd.close() 
            else:
                tf = tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix)
                fp = tf.name
                tf.close()

 
        if self.includeList is not None:
            gf = pycallgraph.GlobbingFilter(include=self.includeList, exclude=self.excludeList)
        else:
            gf = pycallgraph.GlobbingFilter(exclude=self.excludeList)
        # create instance; will call setup routines
        ct = self.callTest()

        # start timer
        print('%s starting test' % _MOD)
        t = Timer()
        t.start()

        pycallgraph.start_trace(filter_func = gf)
        ct.testFocus() # run routine

        pycallgraph.stop_trace()
        pycallgraph.make_dot_graph(fp, format=fmt, tool='/usr/local/bin/dot')
        print('elapsed time: %s' % t)
        # open the completed file
        print('file path: ' + fp)
        try:
            environLocal = environment.Environment(_MOD)
            environLocal.launch(format, fp)
        except NameError:
            pass
示例#27
0
 def wrapper(*args, **kwargs):
     pycallgraph.start_trace()
     func(*args, **kwargs)
     pycallgraph.save_dot('callgraph.log')
     pycallgraph.make_dot_graph('callgraph.png')
示例#28
0
 def generate_callgraph(self, output_filename):
     pycallgraph.make_dot_graph(output_filename)
示例#29
0
def main():
    pycallgraph.start_trace()
    for a in xrange(1, 10):
        factorial(a)

    pycallgraph.make_dot_graph('recursive.png')
示例#30
0
print "Network construction time:", time.time() - start_time, "seconds"
print len(P), "neurons in the network"
print "Simulation running..."

if use_synapses:
    net = Network(P, Se, Si, Me, Mi, M)#, M0)
else:
    net = Network(P, Ce, Ci, Me, Mi, M)#, M0)
net.run(100 * msecond)
#M0.plot()
#show()
#exit()

start_time = time.time()
if do_callgraph:
    pycallgraph.start_trace(filter_func=ff(cg_func))

net.run(1 * second)

duration = time.time() - start_time
if do_callgraph:
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('cuba-callgraph.png')

print "Simulation time:", duration, "seconds"
print Me.nspikes, "excitatory spikes"
print Mi.nspikes, "inhibitory spikes"

#plot(M.times / ms, M.smooth_rate(2 * ms, 'gaussian'))
#show()
示例#31
0
def run_tests(test_labels,
              verbosity=1,
              interactive=True,
              extra_tests=[],
              nodatabase=False,
              xml_out=False,
              callgraph=False):
    """
    Test runner which displays a code coverage report at the end of the
    run.
    """
    cov = coverage.coverage()
    cov.erase()
    cov.use_cache(0)

    test_labels = test_labels or getattr(settings, "TEST_APPS", None)
    cover_branch = getattr(settings, "COVERAGE_BRANCH_COVERAGE", False)
    cov = coverage.coverage(branch=cover_branch, cover_pylib=False)
    cov.use_cache(0)

    coverage_modules = []
    if test_labels:
        for label in test_labels:
            # Don't report coverage if you're only running a single
            # test case.
            if '.' not in label:
                app = get_app(label)
                coverage_modules.extend(get_all_coverage_modules(app))
    else:
        for app in get_apps():
            coverage_modules.extend(get_all_coverage_modules(app))

    morfs = filter(is_wanted_module, coverage_modules)

    if callgraph:
        try:
            import pycallgraph
            #_include = [i.__name__ for i in coverage_modules]
            _included = getattr(settings, "COVERAGE_INCLUDE_MODULES", [])
            _excluded = getattr(settings, "COVERAGE_EXCLUDE_MODULES", [])

            _included = [i.strip('*') + '*' for i in _included]
            _excluded = [i.strip('*') + '*' for i in _included]

            _filter_func = pycallgraph.GlobbingFilter(
                include=_included or ['*'],
                #include=['lotericas.*'],
                #exclude=[],
                #max_depth=options.max_depth,
            )

            pycallgraph_enabled = True
        except ImportError:
            pycallgraph_enabled = False
    else:
        pycallgraph_enabled = False

    cov.start()

    if pycallgraph_enabled:
        pycallgraph.start_trace(filter_func=_filter_func)

    if nodatabase:
        results = nodatabase_run_tests(test_labels, verbosity, interactive,
                                       extra_tests)
    else:
        results = django_test_runner(test_labels, verbosity, interactive,
                                     extra_tests)

    if callgraph and pycallgraph_enabled:
        pycallgraph.stop_trace()

    cov.stop()

    report_methd = cov.report
    if getattr(settings, "COVERAGE_HTML_REPORT", False) or \
            os.environ.get("COVERAGE_HTML_REPORT"):
        output_dir = getattr(settings, "COVERAGE_HTML_DIRECTORY", "covhtml")
        report_method = curry(cov.html_report, directory=output_dir)
        if callgraph and pycallgraph_enabled:
            callgraph_path = output_dir + '/' + 'callgraph.png'
            pycallgraph.make_dot_graph(callgraph_path)

        print >> sys.stdout
        print >> sys.stdout, "Coverage HTML reports were output to '%s'" % output_dir
        if callgraph:
            if pycallgraph_enabled:
                print >> sys.stdout, "Call graph was output to '%s'" % callgraph_path
            else:
                print >> sys.stdout, "Call graph was not generated: Install 'pycallgraph' module to do so"

    else:
        report_method = cov.report

    if coverage_modules:
        if xml_out:
            # using the same output directory as the --xml function uses for testing
            if not os.path.isdir(os.path.join("temp", "xml")):
                os.makedirs(os.path.join("temp", "xml"))
            output_filename = 'temp/xml/coverage_output.xml'
            cov.xml_report(morfs=coverage_modules, outfile=output_filename)

        cov.report(coverage_modules, show_missing=1)

    return results
示例#32
0
 def wrapper(*args, **kwargs):
     pycallgraph.start_trace()
     func(*args, **kwargs)
     pycallgraph.save_dot('callgraph.log')
     pycallgraph.make_dot_graph('callgraph.png')
示例#33
0
from brian import *
set_global_preferences(useweave=True)
import cuba_runopts
cuba_runopts.duration = 100 * ms
import pycallgraph
from cuba import *

cg_func = 'Connection.do_propagate'

def ff(pat):
    def f(call_stack, module_name, class_name, func_name, full_name):
        if not 'brian' in module_name: return False
        for n in call_stack + [full_name]:
            if pat in n:
                return True
        return False
    return f

def cuba(P, Pe, Pi, Ce, Ci, M, net):
    net.run(duration)

c = cubanetwork(4000)
pycallgraph.start_trace(filter_func=ff(cg_func))
cuba(*c)
pycallgraph.stop_trace()
pycallgraph.make_dot_graph('callgraphs/cuba-callgraph-' + cg_func + '.png')
示例#34
0
def main():
    pycallgraph.start_trace()
    re.search('(hel[j-s]o).*(th[^e]*ere)', 'hello there')
    pycallgraph.make_dot_graph('regexp.png')
示例#35
0
                log.warning("No input files %s" % traceback.format_exc())
        if False:
            if useTK and currentReductionNum == numReductions:
                try:
                    cw.done()
                    cw.mainWindow.after_cancel(cw.pcqid)
                    if True: #cw.killed == True:
                        raw_input("Press Enter to Close Monitor Windows:")
                    # After ID print cw.pcqid
                    cw.mainWindow.quit()
                except:
                    cw.mainWindow.quit()    
                    raise

            if (generate_pycallgraphs):
                pycallgraph.make_dot_graph("recipman-callgraph.png")

            while (False):
                from time import sleep
                for th in threading.enumerate():
                    print str(th)
                #sleep(5.)
            # print co.report_history()
            # main()
            # don't leave the terminal in another color/mode, that's rude
except SystemExit:
    log.error("SYSTEM EXIT: see log for more information")
    raise
except:
    import traceback as tb
    log.error("UNHANDLED ERROR, closing down reduce, traceback:\n"
示例#36
0
def filter_module():
    filter_func = pycallgraph.GlobbingFilter(include=['sre_parse.*'])
    pycallgraph.start_trace(time_filter_func=filter_func)
    for a in xrange(100):
        re.compile('test3-%i' % a)
    pycallgraph.make_dot_graph('filter-time-module.png')
def run_tests(test_labels, verbosity=1, interactive=True,
        extra_tests=[], nodatabase=False, xml_out=False, callgraph=False, html_only=False):
    """
    Test runner which displays a code coverage report at the end of the
    run.
    """
    cov = coverage.coverage()
    cov.erase()
    cov.use_cache(0)

    test_labels = test_labels or getattr(settings, "TEST_APPS", None)
    cover_branch = getattr(settings, "COVERAGE_BRANCH_COVERAGE", False)
    cov = coverage.coverage(branch=cover_branch, cover_pylib=False)
    cov.use_cache(0)

    coverage_modules = []
    if test_labels:
        for label in test_labels:
            # Don't report coverage if you're only running a single
            # test case.
            if '.' not in label:
                app = get_app(label)
                coverage_modules.extend(get_all_coverage_modules(app))
    else:
        for app in get_apps():
            coverage_modules.extend(get_all_coverage_modules(app))

    morfs = filter(is_wanted_module, coverage_modules)

    if callgraph:
        try:
            import pycallgraph
            #_include = [i.__name__ for i in coverage_modules]
            _included = getattr(settings, "COVERAGE_INCLUDE_MODULES", [])
            _excluded = getattr(settings, "COVERAGE_EXCLUDE_MODULES", [])

            _included = [i.strip('*')+'*' for i in _included]
            _excluded = [i.strip('*')+'*' for i in _included]

            _filter_func = pycallgraph.GlobbingFilter(
                include=_included or ['*'],
                #include=['lotericas.*'],
                #exclude=[],
                #max_depth=options.max_depth,
            )

            pycallgraph_enabled = True
        except ImportError:
            pycallgraph_enabled = False
    else:
        pycallgraph_enabled = False

    cov.start()

    if pycallgraph_enabled:
        pycallgraph.start_trace(filter_func=_filter_func)

    if nodatabase:
        results = nodatabase_run_tests(test_labels, verbosity, interactive,
            extra_tests)
    else:
        tr = django_test_runner(verbosity, interactive)
        results = tr.run_tests(test_labels, extra_tests)
        #results = django_test_runner(test_labels, verbosity, interactive,
        #    extra_tests)

    if callgraph and pycallgraph_enabled:
        pycallgraph.stop_trace()

    cov.stop()

    if getattr(settings, "COVERAGE_HTML_REPORT", False) or \
            os.environ.get("COVERAGE_HTML_REPORT"):
        output_dir = getattr(settings, "COVERAGE_HTML_DIRECTORY", "covhtml")
        report_method = curry(cov.html_report, directory=output_dir)
        if callgraph and pycallgraph_enabled:
            callgraph_path = output_dir + '/' + 'callgraph.png'
            pycallgraph.make_dot_graph(callgraph_path)

        print >>sys.stdout
        print >>sys.stdout, "Coverage HTML reports were output to '%s'" %output_dir
        if callgraph:
            if pycallgraph_enabled:
                print >>sys.stdout, "Call graph was output to '%s'" %callgraph_path
            else:
                print >>sys.stdout, "Call graph was not generated: Install 'pycallgraph' module to do so"

    else:
        report_method = cov.report

    if coverage_modules:
        if xml_out:
            # using the same output directory as the --xml function uses for testing
            if not os.path.isdir(os.path.join("temp", "xml")):
                os.makedirs(os.path.join("temp", "xml"))
            output_filename = 'temp/xml/coverage_output.xml'
            cov.xml_report(morfs=coverage_modules, outfile=output_filename)

        if not html_only:
            cov.report(coverage_modules, show_missing=1)

    return results
示例#38
0
 def process_response(self, request, response):
     if settings.DEBUG and 'graph' in request.GET:
         pycallgraph.make_dot_graph('callgraph-' + str(time.time()) + '.png')
     return response
示例#39
0
    if opts.debug:
        log.setLevel(logging.DEBUG)

    try:
        cmd = args.pop()
        assert cmd in commands.map
    except (IndexError,AssertionError):
        op.error("missing or invalid command")
        
    start_cpu = time.clock()
    start_real = time.time()        
    
    if opts.profile:
        import profile
        profile.run("%s(opts)" % cmd, "profile.out")
    else:
        if opts.pygraph:
            import pycallgraph
            pycallgraph.start_trace()

        commands.map[cmd](opts)

        if opts.pygraph: 
            pycallgraph.make_dot_graph('profile.png')
    
    end_cpu = time.clock()
    end_real = time.time()
    
    print "Real Seconds: %f" % (end_real - start_real)
    print "CPU Seconds: %f" % (end_cpu - start_cpu)
示例#40
0
def filter_none():
    pycallgraph.start_trace()
    for a in xrange(100):
        re.compile('test1-%i' % a)
    pycallgraph.make_dot_graph('filter-time-none.png')
示例#41
0
        log.setLevel(logging.DEBUG)

    try:
        cmd = args.pop()
        assert cmd in commands.map
    except (IndexError, AssertionError):
        op.error("missing or invalid command")

    start_cpu = time.clock()
    start_real = time.time()

    if opts.profile:
        import profile
        profile.run("%s(opts)" % cmd, "profile.out")
    else:
        if opts.pygraph:
            import pycallgraph
            pycallgraph.start_trace()

        print opts
        commands.map[cmd](opts)

        if opts.pygraph:
            pycallgraph.make_dot_graph('profile.png')

    end_cpu = time.clock()
    end_real = time.time()

    print "Real Seconds: %f" % (end_real - start_real)
    print "CPU Seconds: %f" % (end_cpu - start_cpu)
示例#42
0
def main():
    pycallgraph.start_trace()
    banana = Banana()
    banana.eat()
    pycallgraph.make_dot_graph('basic.png')
示例#43
0
if profile:
    pr = cProfile.Profile()
    pr.enable()

if graph:
    pycallgraph.start_trace()

if timer:
    for name, t in (("Python", runitp), ("cython", runit)):
        res = timeit.Timer(t).repeat(sample, number)
        min_run = min(res)
        per_loop = min_run/number

        print u'{}'.format(name)
        print u'{} total run'.format(format_time(min_run))
        print u'{} per/loop'.format(format_time(per_loop))
        #print u'{} per/friend'.format(format_time(per_loop/friends_cnt))
else:
    for j in xrange(number):
        runit()

if graph:
    pycallgraph.make_dot_graph('example.png')

if profile:
    pr.disable()
    ps = pstats.Stats(pr)
    sort_by = 'cumulative'
    ps.strip_dirs().sort_stats(sort_by).print_stats(20)
示例#44
0
if profile:
    pr = cProfile.Profile()
    pr.enable()

if graph:
    pycallgraph.start_trace()

if timer:
    for name, t in (("Python", runitp), ("cython", runit)):
        res = timeit.Timer(t).repeat(sample, number)
        min_run = min(res)
        per_loop = min_run / number

        print u'{}'.format(name)
        print u'{} total run'.format(format_time(min_run))
        print u'{} per/loop'.format(format_time(per_loop))
        #print u'{} per/friend'.format(format_time(per_loop/friends_cnt))
else:
    for j in xrange(number):
        runit()

if graph:
    pycallgraph.make_dot_graph('example.png')

if profile:
    pr.disable()
    ps = pstats.Stats(pr)
    sort_by = 'cumulative'
    ps.strip_dirs().sort_stats(sort_by).print_stats(20)
示例#45
0
M = SpikeMonitor(P)

net = MagicNetwork()

start = time.time()
net.prepare()
net.run(1 * ms)
print 'Preparation time:', time.time() - start

if do_callgraph:
    import pycallgraph

    def ff(call_stack, module_name, class_name, func_name, full_name):
        if not 'brian' in module_name: return False
        return True

    pycallgraph.start_trace(filter_func=ff)

start = time.time()
net.run(1 * second)
print 'Run time:', time.time() - start

if do_callgraph:
    pycallgraph.stop_trace()
    pycallgraph.make_dot_graph('callgraph.png')

if plot_output:
    raster_plot(M)
    show()
示例#46
0
def main():
    pycallgraph.start_trace()
    import urllib
    from xml.dom.minidom import parse, parseString
    parseString(urllib.urlopen('http://w3.org/').read())
    pycallgraph.make_dot_graph('large.png')
示例#47
0
def filter_none():
    pycallgraph.start_trace()
    for a in xrange(100):
        re.compile('test1-%i' % a)
    pycallgraph.make_dot_graph('filter-time-none.png')
示例#48
0
from brian import *
set_global_preferences(useweave=True)
import cuba_runopts
cuba_runopts.duration = 100 * ms
import pycallgraph
from cuba import *

cg_func = 'Connection.do_propagate'


def ff(pat):
    def f(call_stack, module_name, class_name, func_name, full_name):
        if not 'brian' in module_name: return False
        for n in call_stack + [full_name]:
            if pat in n:
                return True
        return False

    return f


def cuba(P, Pe, Pi, Ce, Ci, M, net):
    net.run(duration)


c = cubanetwork(4000)
pycallgraph.start_trace(filter_func=ff(cg_func))
cuba(*c)
pycallgraph.stop_trace()
pycallgraph.make_dot_graph('callgraphs/cuba-callgraph-' + cg_func + '.png')
示例#49
0
def timeHumdrum():
    masterStream = music21.humdrum.parseData(htf.mazurka6).stream

def timeMozart():
    a = music21.converter.parse(music21.corpus.getWork('k155')[0])
#    ls = music21.lily.LilyString("{" + a[0].lily + "}")
#    ls.showPNG()
#    a = music21.converter.parse(mxtf.ALL[1])

def timeCapua():
    c1 = music21.trecento.capua.Test()
    c1.testRunPiece()

def timeCapua2():
    music21.trecento.capua.ruleFrequency()

excludeList =  ['pycallgraph.*','re.*','sre_*', 'copy*', '*xlrd*',]
excludeList += ['*meter*', 'encodings*', '*isClass*', '*duration.Duration*']

gf = pycallgraph.GlobbingFilter(exclude=excludeList)

print(time.ctime())

pycallgraph.start_trace(filter_func = gf)

timeCapua2()

pycallgraph.make_dot_graph('d:\\desktop\\test1.png')

print(time.ctime())
示例#50
0
def filter_min_depth():
    filter_func = pycallgraph.GlobbingFilter(min_depth=7)
    pycallgraph.start_trace(time_filter_func=filter_func)
    for a in xrange(100):
        re.compile('test2-%i' % a)
    pycallgraph.make_dot_graph('filter-time-min-depth.png')
示例#51
0
def main():
    pycallgraph.start_trace()
    import urllib
    from xml.dom.minidom import parse, parseString
    parseString(urllib.urlopen('http://w3.org/').read())
    pycallgraph.make_dot_graph('large.png')
示例#52
0
def filter_module():
    filter_func = pycallgraph.GlobbingFilter(include=['sre_parse.*'])
    pycallgraph.start_trace(time_filter_func=filter_func)
    for a in xrange(100):
        re.compile('test3-%i' % a)
    pycallgraph.make_dot_graph('filter-time-module.png')
示例#53
0
worldIndex = [
    {'code':"000001", 'yahoo':"000001.SS",'name':{'chinese':u"中国上证指数", 'english':"CHINA SHANGHAI COMPOSITE INDEX"}},
    {'code':"399001", 'yahoo':"399001.SZ",'name':{'chinese':u"中国深证成指", 'english':"SZSE COMPONENT INDEX"}},
    {'code':"DJI", 'yahoo':"^DJI",'name':{'chinese':u"美国道琼斯工业平均指数", 'english':"Dow Jones Industrial Average"}},
    {'code':"IXIC", 'yahoo':"^IXIC",'name':{'chinese':u"美国纳斯达克综合指数", 'english':"NASDAQ Composite"},},
    {'code':"GSPC", 'yahoo':"^GSPC",'name':{'chinese':u"美国标准普尔500指数", 'english':"S&P 500"}},
    {'code':"N225", 'yahoo':"^N225",'name':{'chinese':u"日本日经225指数", 'english':"NIKKEI 225"}},
    {'code':"TWII", 'yahoo':"^TWII",'name':{'chinese':u"台湾台北加权指数", 'english':"TSEC weighted index"}},
    {'code':"HSI", 'yahoo':"^HSI",'name':{'chinese':u"香港恒生指数", 'english':"HANG SENG INDEX"}},
    {'code':"FCHI", 'yahoo':"^FCHI",'name':{'chinese':u"法国CAC40指数", 'english':"CAC 40"}},
    {'code':"FTSE", 'yahoo':"^FTSE",'name':{'chinese':u"英国富时100指数", 'english':"FTSE 100"}},
    {'code':"GDAXI", 'yahoo':"^GDAXI",'name':{'chinese':u"德国法兰克福DAX指数", 'english':"DAX"} }
]
chinaStock = [
    "000063", #  中兴通讯
    "600036", #  招商银行
]

def main():
    "main function"
    print "test world stock index:" 
    for stockDict in worldIndex:
        print get_yahoo_daily(stockDict)


if __name__ == '__main__':
    import pycallgraph 
    pycallgraph.start_trace()
    main()
    pycallgraph.make_dot_graph('r.png')
        newNetworkDirectory = mFPH.getDirectory('networkXmlFileXXXDirectory',
                                                newNetworkName, "xxx", 'read')
        newTruncateFile = ''.join([newNetworkDirectory, '/', 'truncate.txt'])

        shutil.copyfile(truncateFile, newTruncateFile)


#     if save:
#         string1 = ' '.join(['/usr/bin/python',cur+'/Main.py','-f',newNetworkName, '-n',dataNumber, '-d', simulationDescription])
#         print "gonna run new network"
#         print string1
#         subprocess.Popen(string1, shell = True )

if __name__ == '__main__':

    profiling = False
    callGraph = False

    if profiling == True:
        import cProfile
        cProfile.run('main()')

    elif callGraph == True:
        import pycallgraph
        pycallgraph.start_trace()
        main()
        pycallgraph.make_dot_graph('STARFiSh-CallGraph.png')
    else:
        main()
示例#55
0
    def run(self, runWithEnviron=True):
        '''
        Main code runner for testing. To set a new test, update the self.callTest attribute in __init__(). 
        
        Note that the default of runWithEnviron imports music21.environment.  That might
        skew results
        '''
        suffix = '.svg'
        outputFormat = suffix[1:]
        _MOD = "test.timeGraphs.py"

        if runWithEnviron:
            from music21 import environment
            environLocal = environment.Environment(_MOD)
            fp = environLocal.getTempFile(suffix)
        # manually get a temporary file
        else:
            import tempfile
            import os
            import sys
            if os.name in ['nt'] or sys.platform.startswith('win'):
                platform = 'win'
            else:
                platform = 'other'

            tempdir = os.path.join(tempfile.gettempdir(), 'music21')
            if platform != 'win':
                fd, fp = tempfile.mkstemp(dir=tempdir, suffix=suffix)
                if isinstance(fd, int):
                    # on MacOS, fd returns an int, like 3, when this is called
                    # in some context (specifically, programmatically in a
                    # TestExternal class. the fp is still valid and works
                    # TODO: this did not work on MacOS 10.6.8 w/ py 2.7
                    pass
                else:
                    fd.close()
            else:
                tf = tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix)
                fp = tf.name
                tf.close()

        if self.includeList is not None:
            gf = pycallgraph.GlobbingFilter(include=self.includeList,
                                            exclude=self.excludeList)
        else:
            gf = pycallgraph.GlobbingFilter(exclude=self.excludeList)
        # create instance; will call setup routines
        ct = self.callTest()

        # start timer
        print('%s starting test' % _MOD)
        t = Timer()
        t.start()

        pycallgraph.start_trace(filter_func=gf)
        ct.testFocus()  # run routine

        pycallgraph.stop_trace()
        pycallgraph.make_dot_graph(fp,
                                   format=outputFormat,
                                   tool='/usr/local/bin/dot')
        print('elapsed time: %s' % t)
        # open the completed file
        print('file path: ' + fp)
        try:
            environLocal = environment.Environment(_MOD)
            environLocal.launch(outputFormat, fp)
        except NameError:
            pass
示例#56
0
def filter_min_depth():
    filter_func = pycallgraph.GlobbingFilter(min_depth=7)
    pycallgraph.start_trace(time_filter_func=filter_func)
    for a in xrange(100):
        re.compile('test2-%i' % a)
    pycallgraph.make_dot_graph('filter-time-min-depth.png')