code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
# snippet to change the LookupTables (colourmaps) of the selected objects
# this should be run in the introspection context of a slice3dVWR
# $Id$
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
# find all polydata objects
so = obj._tdObjects._getSelectedObjects()
polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
pd.GetClassName() == 'vtkPolyData']
# now find their Mappers
objectsDict = obj._tdObjects._tdObjectsDict
actors = [objectsDict[pd]['vtkActor'] for pd in polyDatas]
mappers = [a.GetMapper() for a in actors]
for mapper in mappers:
lut = mapper.GetLookupTable()
lut.SetScaleToLog10()
#lut.SetScaleToLinear()
srange = mapper.GetInput().GetScalarRange()
lut.SetTableRange(srange)
lut.SetSaturationRange(1.0,1.0)
lut.SetValueRange(1.0, 1.0)
lut.SetHueRange(0.1, 1.0)
lut.Build()
else:
print "This snippet must be run from a slice3dVWR introspection window."
| [
[
1,
0,
0.1351,
0.027,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1622,
0.027,
0,
0.66,
0.25,
516,
0,
1,
0,
0,
516,
0,
0
],
[
1,
0,
0.1892,
0.027,
0,
0.66,... | [
"import os",
"import tempfile",
"import vtk",
"className = obj.__class__.__name__",
"if className == 'slice3dVWR':\n\n # find all polydata objects\n so = obj._tdObjects._getSelectedObjects()\n polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and\n pd.GetClassName() == 'vt... |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
# square figure and square axes looks better for polar plots
numpy_test_figure = obj.mpl_new_figure(figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')
# following example from http://matplotlib.sourceforge.net/screenshots/polar_demo.py
# radar green, solid grid lines
rc('grid', color='#316931', linewidth=1, linestyle='-')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
r = arange(0,1,0.001)
theta = 2*2*pi*r
polar(theta, r, color='#ee8d18', lw=3)
setp(ax.thetagridlabels, y=1.075) # the radius of the grid labels
title("And there was much rejoicing!", fontsize=20)
| [
[
1,
0,
0.1071,
0.0357,
0,
0.66,
0,
735,
0,
1,
0,
0,
735,
0,
0
],
[
7,
0,
0.2679,
0.1429,
0,
0.66,
0.0909,
0,
0,
1,
0,
0,
0,
0,
1
],
[
8,
1,
0.25,
0.0357,
1,
0.64,
... | [
"from pylab import *",
"try:\n obj.mpl_close_figure(numpy_test_figure)\nexcept NameError:\n pass",
" obj.mpl_close_figure(numpy_test_figure)",
"numpy_test_figure = obj.mpl_new_figure(figsize=(8,8))",
"ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')",
"rc('grid', color='#316931', lin... |
# snippet that illustrates programmatic setting of Window/Level
# in the slice3dVWR introspection interface
W = 500
L = 1000
sds = obj.sliceDirections._sliceDirectionsDict.values()
for sd in sds:
ipw = sd._ipws[0]
ipw.SetWindowLevel(W, L, 0)
| [
[
14,
0,
0.4,
0.1,
0,
0.66,
0,
94,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.5,
0.1,
0,
0.66,
0.3333,
714,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.7,
0.1,
0,
0.66,
0.6667,
... | [
"W = 500",
"L = 1000",
"sds = obj.sliceDirections._sliceDirectionsDict.values()",
"for sd in sds:\n ipw = sd._ipws[0]\n ipw.SetWindowLevel(W, L, 0)",
" ipw = sd._ipws[0]",
" ipw.SetWindowLevel(W, L, 0)"
] |
# this snippet will rotate the camera in the slice3dVWR that you have
# selected and dump every frame as a PNG to the temporary directory
# you can modify this snippet if you want to make movies of for instance
# deforming surfaces and whatnot
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. do the same for your superQuadric (select 'superQuadric' as index name)
# 5. execute this snippet
import os
import tempfile
import vtk
import wx
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
#sq = devideApp.ModuleManager.getMarkedModule('superQuadric')
if sv and sq:
# bring the window to the front
sv.view()
# make sure it actually happens
wx.Yield()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(sv._threedRenderer.GetRenderWindow())
pngWriter = vtk.vtkPNGWriter()
pngWriter.SetInput(w2i.GetOutput())
tempdir = tempfile.gettempdir()
fprefix = os.path.join(tempdir, 'devideFrame')
camera = sv._threedRenderer.GetActiveCamera()
for i in range(2 * 36):
sq._superquadricSource.SetPhiRoundness(i / 36.0)
camera.Azimuth(10)
sv.render3D()
# make sure w2i knows it's a new image
w2i.Modified()
pngWriter.SetFileName('%s%03d.png' % (fprefix, i))
pngWriter.Write()
print "The frames have been written as %s*.png." % (fprefix,)
else:
print "You have to mark a slice3dVWR module and a superQuadric module!"
| [
[
1,
0,
0.2449,
0.0204,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2653,
0.0204,
0,
0.66,
0.2,
516,
0,
1,
0,
0,
516,
0,
0
],
[
1,
0,
0.2857,
0.0204,
0,
0.6... | [
"import os",
"import tempfile",
"import vtk",
"import wx",
"sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')",
"if sv and sq:\n # bring the window to the front\n sv.view()\n # make sure it actually happens\n wx.Yield()\n \n w2i = vtk.vtkWindowToImageFilter()\n w2i.SetInput(s... |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
numpy_test_figure = obj.mpl_new_figure()
# this example from http://matplotlib.sourceforge.net/screenshots/log_shot.py
dt = 0.01
t = arange(dt, 20.0, dt)
subplot(211)
semilogx(t, sin(2*pi*t))
ylabel('semilog')
xticks([])
setp(gca(), 'xticklabels', [])
grid(True)
subplot(212)
loglog(t, 20*exp(-t/10.0), basey=4)
grid(True)
gca().xaxis.grid(True, which='minor') # minor grid on too
xlabel('time (s)')
ylabel('loglog')
| [
[
1,
0,
0.1034,
0.0345,
0,
0.66,
0,
735,
0,
1,
0,
0,
735,
0,
0
],
[
7,
0,
0.2586,
0.1379,
0,
0.66,
0.0625,
0,
0,
1,
0,
0,
0,
0,
1
],
[
8,
1,
0.2414,
0.0345,
1,
0.07... | [
"from pylab import *",
"try:\n obj.mpl_close_figure(numpy_test_figure)\nexcept NameError:\n pass",
" obj.mpl_close_figure(numpy_test_figure)",
"numpy_test_figure = obj.mpl_new_figure()",
"dt = 0.01",
"t = arange(dt, 20.0, dt)",
"subplot(211)",
"semilogx(t, sin(2*pi*t))",
"ylabel('semilog')"... |
# link cameras of all selected slice3dVWRs
# after having run this, all selected slice3dVWRs will have linked
# cameras, so if you change the view in anyone, all will follow.
# 1. run this in the main DeVIDE introspection window after having
# selected a number of slice3dVWRs
# 2. to unlink views, type unlink_slice3dVWRs() in the bottom
# interpreter window.
def observer_istyle(s3d, s3ds):
cam = s3d._threedRenderer.GetActiveCamera()
pos = cam.GetPosition()
fp = cam.GetFocalPoint()
vu = cam.GetViewUp()
for other_s3d in s3ds:
if not other_s3d is s3d:
other_ren = other_s3d._threedRenderer
other_cam = other_ren.GetActiveCamera()
other_cam.SetPosition(pos)
other_cam.SetFocalPoint(fp)
other_cam.SetViewUp(vu)
other_ren.UpdateLightsGeometryToFollowCamera()
other_ren.ResetCameraClippingRange()
other_s3d.render3D()
def unlink_slice3dVWRs():
for s3d in s3ds:
istyle = s3d.threedFrame.threedRWI.GetInteractorStyle()
istyle.RemoveObservers('InteractionEvent') # more or less safe
iface = devide_app.get_interface()
sg = iface._graph_editor._selected_glyphs.getSelectedGlyphs()
s3ds = [i.module_instance for i in sg if i.module_instance.__class__.__name__ == 'slice3dVWR']
unlink_slice3dVWRs()
for s3d in s3ds:
ren = s3d._threedRenderer
istyle = s3d.threedFrame.threedRWI.GetInteractorStyle()
istyle.AddObserver('InteractionEvent', lambda o,e,s3d=s3d: observer_istyle(s3d,s3ds))
| [
[
2,
0,
0.3936,
0.3404,
0,
0.66,
0,
99,
0,
2,
0,
0,
0,
0,
11
],
[
14,
1,
0.2553,
0.0213,
1,
0.09,
0,
155,
3,
0,
0,
0,
427,
10,
1
],
[
14,
1,
0.2766,
0.0213,
1,
0.09... | [
"def observer_istyle(s3d, s3ds):\n cam = s3d._threedRenderer.GetActiveCamera()\n pos = cam.GetPosition()\n fp = cam.GetFocalPoint()\n vu = cam.GetViewUp()\n\n for other_s3d in s3ds:\n if not other_s3d is s3d:",
" cam = s3d._threedRenderer.GetActiveCamera()",
" pos = cam.GetPosition()... |
import vtk
import wx
def makeBorderPD(ipw):
# setup source
ps = vtk.vtkPlaneSource()
ps.SetOrigin(ipw.GetOrigin())
ps.SetPoint1(ipw.GetPoint1())
ps.SetPoint2(ipw.GetPoint2())
fe = vtk.vtkFeatureEdges()
fe.SetInput(ps.GetOutput())
tubef = vtk.vtkTubeFilter()
tubef.SetNumberOfSides(12)
tubef.SetRadius(0.5)
tubef.SetInput(fe.GetOutput())
return tubef.GetOutput()
className = obj.__class__.__name__
if className == 'slice3dVWR':
sds = obj.sliceDirections.getSelectedSliceDirections()
if len(sds) > 0:
apd = vtk.vtkAppendPolyData()
for sd in sds:
for ipw in sd._ipws:
apd.AddInput(makeBorderPD(ipw))
mapper = vtk.vtkPolyDataMapper()
mapper.ScalarVisibilityOff()
mapper.SetInput(apd.GetOutput())
actor = vtk.vtkActor()
actor.GetProperty().SetColor(0.0, 0.0, 1.0)
actor.SetMapper(mapper)
if hasattr(obj._threedRenderer, 'addBorderToSlicesActor'):
obj._threedRenderer.RemoveProp(
obj._threedRenderer.addBorderToSlicesActor)
obj._threedRenderer.AddProp(actor)
obj._threedRenderer.addBorderToSlicesActor = actor
else:
print "Please select the slices whose opacity you want to set."
else:
print "You have to run this from a slice3dVWR introspect window."
| [
[
1,
0,
0.0182,
0.0182,
0,
0.66,
0,
665,
0,
1,
0,
0,
665,
0,
0
],
[
1,
0,
0.0364,
0.0182,
0,
0.66,
0.25,
666,
0,
1,
0,
0,
666,
0,
0
],
[
2,
0,
0.2182,
0.3091,
0,
0.... | [
"import vtk",
"import wx",
"def makeBorderPD(ipw):\n\n # setup source\n ps = vtk.vtkPlaneSource()\n ps.SetOrigin(ipw.GetOrigin())\n ps.SetPoint1(ipw.GetPoint1())\n ps.SetPoint2(ipw.GetPoint2())",
" ps = vtk.vtkPlaneSource()",
" ps.SetOrigin(ipw.GetOrigin())",
" ps.SetPoint1(ipw.Get... |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
numpy_test_figure = obj.mpl_new_figure()
a = arange(-30, 30, 0.01)
plot(a, sin(a) / a, label='sinc(x)')
plot(a, cos(a), label='cos(x)')
legend()
grid()
xlabel('x')
ylabel('f(x)')
| [
[
1,
0,
0.1429,
0.0476,
0,
0.66,
0,
735,
0,
1,
0,
0,
735,
0,
0
],
[
7,
0,
0.3571,
0.1905,
0,
0.66,
0.1111,
0,
0,
1,
0,
0,
0,
0,
1
],
[
8,
1,
0.3333,
0.0476,
1,
0.44... | [
"from pylab import *",
"try:\n obj.mpl_close_figure(numpy_test_figure)\nexcept NameError:\n pass",
" obj.mpl_close_figure(numpy_test_figure)",
"numpy_test_figure = obj.mpl_new_figure()",
"a = arange(-30, 30, 0.01)",
"plot(a, sin(a) / a, label='sinc(x)')",
"plot(a, cos(a), label='cos(x)')",
"l... |
# this DeVIDE snippet will determine the surface area of all selected
# 3D objects in a marked slice3dVWR
# in short:
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. execute this snippet
import vtk
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
if sv:
so = sv._tdObjects._getSelectedObjects()
polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
pd.GetClassName() == 'vtkPolyData']
tf = vtk.vtkTriangleFilter()
mp = vtk.vtkMassProperties()
mp.SetInput(tf.GetOutput())
for pd in polyDatas:
tf.SetInput(pd)
mp.Update()
print "AREA == %f" % (mp.GetSurfaceArea(),)
if len(polyDatas) == 0:
print "You haven't selected any objects for me to work with!"
else:
print "You have to mark a slice3dVWR module!"
| [
[
1,
0,
0.2857,
0.0286,
0,
0.66,
0,
665,
0,
1,
0,
0,
665,
0,
0
],
[
14,
0,
0.3714,
0.0286,
0,
0.66,
0.5,
868,
3,
1,
0,
0,
685,
10,
1
],
[
4,
0,
0.6857,
0.5429,
0,
0... | [
"import vtk",
"sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')",
"if sv:\n so = sv._tdObjects._getSelectedObjects()\n polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and\n pd.GetClassName() == 'vtkPolyData']\n \n tf = vtk.vtkTriangleFilter()\n mp = vtk.vtkMa... |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# I could have done this with just a module variable, but I found this
# Borg thingy too nice not to use. See:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
class CounterBorg:
"""Borg-pattern (similar to a Singleton) for maintaining a
monotonically increasing counter.
Instantiate this anywhere, and call get() to return and increment
the increasing counter. DeVIDE uses this to stamp modified and
execute times of modules.
"""
# we start with 1, so that client code can init to 0 and guarantee
# an initial invalid state. The counter is explicitly long, this
# gives us unlimited precision (up to your memory limits, YEAH!)
__shared_state = {'counter' : 1L}
def __init__(self):
self.__dict__ = self.__shared_state
def get(self):
c = self.counter
self.counter += 1
return c
def counter():
return CounterBorg().get()
| [
[
3,
0,
0.5781,
0.625,
0,
0.66,
0,
359,
0,
2,
0,
0,
0,
0,
0
],
[
8,
1,
0.4062,
0.2188,
1,
0.92,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
1,
0.7031,
0.0625,
1,
0.92,
0.... | [
"class CounterBorg:\n \"\"\"Borg-pattern (similar to a Singleton) for maintaining a\n monotonically increasing counter.\n\n Instantiate this anywhere, and call get() to return and increment\n the increasing counter. DeVIDE uses this to stamp modified and\n execute times of modules.\n \"\"\"",
"... |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""itk_kit package driver file.
Inserts the following modules in sys.modules: itk, InsightToolkit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
VERSION = ''
def setDLFlags():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols when
# importing a module, if called as sys.setdlopenflags(0) To share
# symbols across extension modules, call as
#
# sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
#
# GCC 3.x depends on proper merging of symbols for RTTI:
# http://gcc.gnu.org/faq.html#dso
#
try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# if we're frozen, make sure we grab the wrapitk contained in this kit
p1 = os.path.dirname(__file__)
p2 = os.path.join(p1, os.path.join('wrapitk', 'python'))
p3 = os.path.join(p1, os.path.join('wrapitk', 'lib'))
sys.path.insert(0, p2)
sys.path.insert(0, p3)
# and now the LD_LIBRARY_PATH / PATH
if sys.platform == 'win32':
so_path_key = 'PATH'
else:
so_path_key = 'LD_LIBRARY_PATH'
# this doesn't work on Linux in anycase
if so_path_key in os.environ:
os.environ[so_path_key] = '%s%s%s' % \
(p3, os.pathsep, os.environ[so_path_key])
else:
os.environ[so_path_key] = p3
# with WrapITK, this takes almost no time
import itk
theModuleManager.setProgress(5, 'Initialising ITK: start')
# let's get the version (which will bring in VXLNumerics and Base)
# setup the kit version
global VERSION
isv = itk.Version.GetITKSourceVersion()
ind = re.match('.*Date: ([0-9]+-[0-9]+-[0-9]+).*', isv).group(1)
VERSION = '%s (%s)' % (itk.Version.GetITKVersion(), ind)
theModuleManager.setProgress(45, 'Initialising ITK: VXLNumerics, Base')
if pre_import:
# then ItkVtkGlue (at the moment this is fine, VTK is always there;
# keep in mind for later when we allow VTK-less startups)
a = itk.VTKImageToImageFilter
theModuleManager.setProgress(
75,
'Initialising ITK: BaseTransforms, SimpleFilters, ItkVtkGlue')
# user can address this as module_kits.itk_kit.utils.blaat()
import module_kits.itk_kit.utils as utils
theModuleManager.setProgress(100, 'Initialising ITK: DONE')
| [
[
8,
0,
0.067,
0.0536,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1071,
0.0089,
0,
0.66,
0.1429,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1161,
0.0089,
0,
0.66,... | [
"\"\"\"itk_kit package driver file.\n\nInserts the following modules in sys.modules: itk, InsightToolkit.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import os",
"import re",
"import sys",
"VERSION = ''",
"def setDLFlags():\n # brought over from ITK Wrapping/CSwig/Python\n\n # Python... |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""matplotlib_kit package driver file.
Inserts the following modules in sys.modules: matplotlib, pylab.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# matplotlib supports py2exe by checking for matplotlibdata in the appdir
# but this is only done on windows (and therefore works for our windows
# installer builds). On non-windows, we have to stick it in the env
# to make sure that MPL finds its datadir (only if we're frozen)
mpldir = os.path.join(theModuleManager.get_appdir(), 'matplotlibdata')
os.environ['MATPLOTLIBDATA'] = mpldir
# import the main module itself
# this doesn't import numerix yet...
global matplotlib
import matplotlib
# use WX + Agg backend (slower, but nicer that WX)
matplotlib.use('WXAgg')
# interactive mode: user can use pylab commands from any introspection
# interface, changes will be made immediately and matplotlib cooperates
# nicely with main WX event loop
matplotlib.interactive(True)
# with matplotlib 1.0.1 we can't do this anymore.
# makes sure we use the numpy backend
#from matplotlib import rcParams
#rcParams['numerix'] = 'numpy'
theModuleManager.setProgress(25, 'Initialising matplotlib_kit: config')
# @PATCH:
# this is for the combination numpy 1.0.4 and matplotlib 0.91.2
# matplotlib/numerix/ma/__init__.py:
# . normal installation fails on "from numpy.ma import *", so "from
# numpy.core.ma import *" is done, thus bringing in e.g. getmask
# . pyinstaller binaries for some or other reason succeed on
# "from numpy.ma import *" (no exception raised), therefore do
# not do "from numpy.core.ma import *", and therefore things like
# getmask are not imported.
# solution:
# we make sure that "from numpy.ma import *" actually brings in
# numpy.core.ma by importing that and associating the module
# binding to the global numpy.ma.
#if hasattr(sys, 'frozen') and sys.frozen:
# import numpy.core.ma
# sys.modules['numpy.ma'] = sys.modules['numpy.core.ma']
# import the pylab interface, make sure it's available from this namespace
global pylab
import pylab
theModuleManager.setProgress(90, 'Initialising matplotlib_kit: pylab')
# build up VERSION
global VERSION
VERSION = '%s' % (matplotlib.__version__,)
theModuleManager.setProgress(100, 'Initialising matplotlib_kit: complete')
| [
[
8,
0,
0.1159,
0.0732,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1707,
0.0122,
0,
0.66,
0.1667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1829,
0.0122,
0,
0.66... | [
"\"\"\"matplotlib_kit package driver file.\n\nInserts the following modules in sys.modules: matplotlib, pylab.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import os",
"import re",
"import sys",
"import types",
"VERSION = ''",
"def init(theModuleManager, pre_import=True):\n\n if hasatt... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import gdcm
def sort_ipp(filenames):
"""STOP PRESS. This is currently incomplete. I'm waiting to see
what's going to happen with the IPPSorter in GDCM.
Given a list of filenames, make use of the gdcm scanner to sort
them all according to IPP.
@param filenames: list of full pathnames that you want to have
sorted.
@returns: tuple with (average z space,
"""
s = gdcm.Scanner()
# we need the IOP and the IPP tags
iop_tag = gdcm.Tag(0x0020, 0x0037)
s.AddTag(iop_tag)
ipp_tag = gdcm.Tag(0x0020, 0x0032)
s.AddTag(ipp_tag)
ret = s.Scan(filenames)
if not ret:
return (0, [])
for f in filenames:
mapping = s.GetMapping(f)
pttv = gdcm.PythonTagToValue(mapping)
pttv.Start()
while not pttv.IsAtEnd():
tag = pttv.GetCurrentTag()
val = pttv.GetCurrentValue()
| [
[
1,
0,
0.1316,
0.0263,
0,
0.66,
0,
188,
0,
1,
0,
0,
188,
0,
0
],
[
2,
0,
0.5921,
0.8421,
0,
0.66,
1,
450,
0,
1,
1,
0,
0,
0,
12
],
[
8,
1,
0.3289,
0.2632,
1,
0.74,
... | [
"import gdcm",
"def sort_ipp(filenames):\n \"\"\"STOP PRESS. This is currently incomplete. I'm waiting to see\n what's going to happen with the IPPSorter in GDCM.\n \n Given a list of filenames, make use of the gdcm scanner to sort\n them all according to IPP.\n\n @param filenames: list of ful... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
"""gdcm_kit driver module.
This pre-loads GDCM2, the second generation Grass Roots Dicom library,
used since 2008 by DeVIDE for improved DICOM loading / saving support.
"""
import os
import sys
VERSION = ''
def init(module_manager, pre_import=True):
# as of 20080628, the order of importing vtkgdcm and gdcm IS
# important on Linux. vtkgdcm needs to go before gdcm, else very
# strange things happen due to the dl (dynamic loading) switches.
global vtkgdcm
import vtkgdcm
global gdcm
import gdcm
# since 2.0.9, we do the following to locate part3.xml:
if hasattr(sys, 'frozen') and sys.frozen:
g = gdcm.Global.GetInstance()
# devide.spec puts Part3.xml in devide_dir/gdcmdata/XML/
g.Prepend(os.path.join(
module_manager.get_appdir(), 'gdcmdata','XML'))
if not g.LoadResourcesFiles():
raise RuntimeError('Could not setup GDCM resource files.')
# will be available as module_kits.gdcm_kit.utils after the client
# programmer has done module_kits.gdcm_kit
import module_kits.gdcm_kit.utils
global VERSION
VERSION = gdcm.Version.GetVersion()
module_manager.set_progress(100, 'Initialising gdcm_kit: complete.')
| [
[
8,
0,
0.1667,
0.1042,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.25,
0.0208,
0,
0.66,
0.25,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2708,
0.0208,
0,
0.66,
... | [
"\"\"\"gdcm_kit driver module.\n\nThis pre-loads GDCM2, the second generation Grass Roots Dicom library,\nused since 2008 by DeVIDE for improved DICOM loading / saving support.\n\"\"\"",
"import os",
"import sys",
"VERSION = ''",
"def init(module_manager, pre_import=True):\n # as of 20080628, the order o... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
class MedicalMetaData:
def __init__(self):
self.medical_image_properties = None
self.direction_cosines = None
def close(self):
del self.medical_image_properties
del self.direction_cosines
def deep_copy(self, source_mmd):
"""Given another MedicalMetaData instance source_mmd, copy its
contents to this instance.
"""
if not source_mmd is None:
self.medical_image_properties.DeepCopy(
source_mmd.medical_image_properties)
self.direction_cosines.DeepCopy(
source_mmd.direction_cosines)
| [
[
3,
0,
0.5833,
0.7917,
0,
0.66,
0,
29,
0,
3,
0,
0,
0,
0,
2
],
[
2,
1,
0.2917,
0.125,
1,
0.19,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.2917,
0.0417,
2,
0.92,
... | [
"class MedicalMetaData:\n def __init__(self):\n self.medical_image_properties = None\n self.direction_cosines = None\n\n def close(self):\n del self.medical_image_properties\n del self.direction_cosines",
" def __init__(self):\n self.medical_image_properties = None\n ... |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class SubjectMixin(object):
def __init__(self):
# dictionary mapping from event name to list of observer
# callables
self._observers = {}
def add_observer(self, event_name, observer):
"""Add an observer to this subject.
observer is a function that takes the subject instance as parameter.
"""
try:
if not observer in self._observers[event_name]:
self._observers[event_name].append(observer)
except KeyError:
self._observers[event_name] = [observer]
def close(self):
del self._observers
def notify(self, event_name):
try:
for observer in self._observers[event_name]:
if callable(observer):
# call observer with the observed subject as param
observer(self)
except KeyError:
# it could be that there are no observers for this event,
# in which case we just shut up
pass
def remove_observer(self, event_name, observer):
self._observers[event_name].remove(observer)
| [
[
3,
0,
0.5366,
0.8537,
0,
0.66,
0,
779,
0,
5,
0,
0,
186,
0,
4
],
[
2,
1,
0.2073,
0.0976,
1,
0,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.2439,
0.0244,
2,
0.76,
... | [
"class SubjectMixin(object):\n\n def __init__(self):\n # dictionary mapping from event name to list of observer\n # callables\n self._observers = {}\n\n def add_observer(self, event_name, observer):",
" def __init__(self):\n # dictionary mapping from event name to list of obse... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import sys
VERSION = 'INTEGRATED'
# debug print command: if DEBUG is true, outputs to stdout, if not
# then outputs nothing.
# import with: from module_kits.misc_kit import dprint
DEBUG=False
if DEBUG:
def dprint(*msg):
print msg
else:
def dprint(*msg):
pass
def init(module_manager, pre_import=True):
global misc_utils
import misc_utils
global mixins
import mixins
global types
module_manager.set_progress(100, 'Initialising misc_kit: complete.')
| [
[
1,
0,
0.1613,
0.0323,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.2258,
0.0323,
0,
0.66,
0.25,
557,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.3871,
0.0323,
0,
0.... | [
"import sys",
"VERSION = 'INTEGRATED'",
"DEBUG=False",
"if DEBUG:\n def dprint(*msg):\n print(msg)\nelse:\n def dprint(*msg):\n pass",
" def dprint(*msg):\n print(msg)",
" print(msg)",
" def dprint(*msg):\n pass",
"def init(module_manager, pre_import=True... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import wx
from wx import py
from wx import stc
class DVEditWindow(py.editwindow.EditWindow):
"""DeVIDE EditWindow.
This fixes all of the py screwups by providing a re-usable Python
EditWindow component. The Py components are useful, they've just been put
together in a really unfortunate way. Poor Orbtech.
Note: SaveFile/LoadFile.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):
py.editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
self._setup_folding_and_numbers()
self.interp = None
self.observer_modified = None
# we only want insertions and deletions of text to be detected
# by self._handler_modified
self.SetModEventMask(stc.STC_MOD_INSERTTEXT |
stc.STC_MOD_DELETETEXT)
# Assign handlers for keyboard events.
self.Bind(wx.EVT_CHAR, self._handler_char)
self.Bind(stc.EVT_STC_MARGINCLICK, self._handler_marginclick)
self.Bind(stc.EVT_STC_MODIFIED, self._handler_modified)
def _handler_char(self, event):
"""Keypress event handler.
Only receives an event if OnKeyDown calls event.Skip() for the
corresponding event."""
# in wxPython this used to be KeyCode(). In 2.8 it's an ivar.
key = event.KeyCode
if self.interp is None:
event.Skip()
return
if key in self.interp.getAutoCompleteKeys():
# Usually the dot (period) key activates auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText(chr(key))
text, pos = self.GetCurLine()
text = text[:pos]
if self.autoComplete:
self.autoCompleteShow(text)
elif key == ord('('):
# The left paren activates a call tip and cancels an
# active auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText('(')
text, pos = self.GetCurLine()
text = text[:pos]
self.autoCallTipShow(text)
else:
# Allow the normal event handling to take place.
event.Skip()
def _handler_marginclick(self, evt):
# fold and unfold as needed
if evt.GetMargin() == 2:
if evt.GetShift() and evt.GetControl():
self._fold_all()
else:
lineClicked = self.LineFromPosition(evt.GetPosition())
if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
if evt.GetShift():
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 1)
elif evt.GetControl():
if self.GetFoldExpanded(lineClicked):
self.SetFoldExpanded(lineClicked, False)
self._fold_expand(lineClicked, False, True, 0)
else:
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 100)
else:
self.ToggleFold(lineClicked)
def _handler_modified(self, evt):
if callable(self.observer_modified):
self.observer_modified(self)
def _fold_all(self):
lineCount = self.GetLineCount()
expanding = True
# find out if we are folding or unfolding
for lineNum in range(lineCount):
if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
expanding = not self.GetFoldExpanded(lineNum)
break
lineNum = 0
while lineNum < lineCount:
level = self.GetFoldLevel(lineNum)
if level & stc.STC_FOLDLEVELHEADERFLAG and \
(level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
if expanding:
self.SetFoldExpanded(lineNum, True)
lineNum = self._fold_expand(lineNum, True)
lineNum = lineNum - 1
else:
lastChild = self.GetLastChild(lineNum, -1)
self.SetFoldExpanded(lineNum, False)
if lastChild > lineNum:
self.HideLines(lineNum+1, lastChild)
lineNum = lineNum + 1
def _fold_expand(self, line, doExpand, force=False, visLevels=0, level=-1):
lastChild = self.GetLastChild(line, level)
line = line + 1
while line <= lastChild:
if force:
if visLevels > 0:
self.ShowLines(line, line)
else:
self.HideLines(line, line)
else:
if doExpand:
self.ShowLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
if visLevels > 1:
self.SetFoldExpanded(line, True)
else:
self.SetFoldExpanded(line, False)
line = self._fold_expand(line, doExpand, force, visLevels-1)
else:
if doExpand and self.GetFoldExpanded(line):
line = self._fold_expand(line, True, force, visLevels-1)
else:
line = self._fold_expand(
line, False, force, visLevels-1)
else:
line = line + 1
return line
def _setup_folding_and_numbers(self):
# from our direct ancestor
self.setDisplayLineNumbers(True)
# the rest is from the wxPython StyledControl_2 demo
self.SetProperty("fold", "1")
self.SetMargins(0,0)
self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
self.SetEdgeColumn(78)
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
# Like a flattened tree control using circular headers and curved joins
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN,
stc.STC_MARK_CIRCLEMINUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER,
stc.STC_MARK_CIRCLEPLUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB,
stc.STC_MARK_VLINE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL,
stc.STC_MARK_LCORNERCURVE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND,
stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID,
stc.STC_MARK_CIRCLEMINUSCONNECTED, "white",
"#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL,
stc.STC_MARK_TCORNERCURVE, "white", "#404040")
def set_interp(self, interp):
"""Assign new py.Interpreter instance to this EditWindow.
This instance will be used for autocompletion. This is often a
py.Shell's interp instance.
"""
self.interp = interp
def autoCallTipShow(self, command):
"""Display argument spec and docstring in a popup window."""
if self.interp is None:
return
if self.CallTipActive():
self.CallTipCancel()
(name, argspec, tip) = self.interp.getCallTip(command)
# if tip:
# dispatcher.send(signal='Shell.calltip', sender=self,
# calltip=tip)
if not self.autoCallTip:
return
if argspec:
startpos = self.GetCurrentPos()
self.AddText(argspec + ')')
endpos = self.GetCurrentPos()
self.SetSelection(endpos, startpos)
if tip:
curpos = self.GetCurrentPos()
size = len(name)
tippos = curpos - (size + 1)
fallback = curpos - self.GetColumn(curpos)
# In case there isn't enough room, only go back to the
# fallback.
tippos = max(tippos, fallback)
self.CallTipShow(tippos, tip)
self.CallTipSetHighlight(0, size)
def autoCompleteShow(self, command):
"""Display auto-completion popup list."""
if self.interp is None:
return
list = self.interp.getAutoCompleteList(
command,
includeMagic=self.autoCompleteIncludeMagic,
includeSingle=self.autoCompleteIncludeSingle,
includeDouble=self.autoCompleteIncludeDouble)
if list:
options = ' '.join(list)
offset = 0
self.AutoCompShow(offset, options)
| [
[
1,
0,
0.0181,
0.0036,
0,
0.66,
0,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0217,
0.0036,
0,
0.66,
0.3333,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0253,
0.0036,
0,
... | [
"import wx",
"from wx import py",
"from wx import stc",
"class DVEditWindow(py.editwindow.EditWindow):\n\n \"\"\"DeVIDE EditWindow.\n\n This fixes all of the py screwups by providing a re-usable Python\n EditWindow component. The Py components are useful, they've just been put\n together in a rea... |
import wx
from wx import py
class DVShell(py.shell.Shell):
"""DeVIDE shell.
Once again, PyCrust makes some pretty bad calls here and there. With this
override we fix some of them.
1. passing locals=None will result in shell.Shell setting locals to
__main__.__dict__ (!!) in contrast to the default behaviour of the Python
code.InteractiveInterpreter , which is what we do here.
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CLIP_CHILDREN,
introText='', locals=None, InterpClass=None,
startupScript=None, execStartupScript=False,
*args, **kwds):
# default behaviour for InteractiveInterpreter
if locals is None:
locals = {"__name__": "__console__", "__doc__": None}
py.shell.Shell.__init__(self, parent, id, pos,
size, style,
introText, locals, InterpClass,
startupScript, execStartupScript,
*args, **kwds)
| [
[
1,
0,
0.0345,
0.0345,
0,
0.66,
0,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.069,
0.0345,
0,
0.66,
0.5,
666,
0,
1,
0,
0,
666,
0,
0
],
[
3,
0,
0.569,
0.8966,
0,
0.66,... | [
"import wx",
"from wx import py",
"class DVShell(py.shell.Shell):\n \"\"\"DeVIDE shell.\n\n Once again, PyCrust makes some pretty bad calls here and there. With this\n override we fix some of them.\n\n 1. passing locals=None will result in shell.Shell setting locals to\n __main__.__dict__ (!!) i... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import wx
def get_system_font_size():
# wx.SYS_ANSI_FIXED_FONT seems to return reliable settings under
# Windows and Linux. SYS_SYSTEM_FONT doesn't do so well on Win.
ft = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
return ft.GetPointSize()
def create_html_font_size_array():
"""Based on the system font size, return a 7-element font-size
array that can be used to SetFont() on a wxHtml.
For system font size 8, this should be:
[4,6,8,10,12,14,16]
corresponding with HTML sizes -2 to +4
Currently used to set font sizes on the module documentation
window. Would have liked to use on the module list box as well,
but we can't get to the underlying wxHTML to set it, so we're
forced to use font size=-1 in that case.
"""
sfs = get_system_font_size()
fsa = [0,0,0,0,0,0,0]
for i in range(7):
fsa[i] = sfs + (i-2)*2
return fsa
| [
[
1,
0,
0.1471,
0.0294,
0,
0.66,
0,
666,
0,
1,
0,
0,
666,
0,
0
],
[
2,
0,
0.2647,
0.1471,
0,
0.66,
0.5,
265,
0,
0,
1,
0,
0,
0,
2
],
[
14,
1,
0.2941,
0.0294,
1,
0.73... | [
"import wx",
"def get_system_font_size():\n # wx.SYS_ANSI_FIXED_FONT seems to return reliable settings under\n # Windows and Linux. SYS_SYSTEM_FONT doesn't do so well on Win.\n ft = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)\n return ft.GetPointSize()",
" ft = wx.SystemSettings.GetFont(wx... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""wxpython_kit package driver file.
Inserts the following modules in sys.modules: wx.
@author: Charl P. Botha <http://cpbotha.net/>
"""
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
# import the main module itself
global wx
import wx
import dvedit_window
import dvshell
import python_shell_mixin
import python_shell
import utils
# build up VERSION
global VERSION
VERSION = wx.VERSION_STRING
theModuleManager.setProgress(100, 'Initialising wx_kit')
| [
[
8,
0,
0.3382,
0.1765,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5,
0.0294,
0,
0.66,
0.5,
557,
1,
0,
0,
0,
0,
3,
0
],
[
2,
0,
0.7794,
0.4706,
0,
0.66,
1... | [
"\"\"\"wxpython_kit package driver file.\n\nInserts the following modules in sys.modules: wx.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"VERSION = ''",
"def init(theModuleManager, pre_import=True):\n # import the main module itself\n global wx\n import wx\n\n import dvedit_window\n ... |
medical_image_properties_keywords = [
'PatientName',
'PatientID',
'PatientAge',
'PatientSex',
'PatientBirthDate',
'ImageDate',
'ImageTime',
'ImageNumber',
'StudyDescription',
'StudyID',
'StudyDate',
'AcquisitionDate',
'SeriesNumber',
'SeriesDescription',
'Modality',
'ManufacturerModelName',
'Manufacturer',
'StationName',
'InstitutionName',
'ConvolutionKernel',
'SliceThickness',
'KVP',
'GantryTilt',
'EchoTime',
'EchoTrainLength',
'RepetitionTime',
'ExposureTime',
'XRayTubeCurrent'
]
| [
[
14,
0,
0.5,
0.9677,
0,
0.66,
0,
738,
0,
0,
0,
0,
0,
5,
0
]
] | [
"medical_image_properties_keywords = [\n 'PatientName',\n 'PatientID',\n 'PatientAge',\n 'PatientSex',\n 'PatientBirthDate',\n 'ImageDate',\n 'ImageTime',"
] |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""Utility methods for vtk_kit module kit.
@author Charl P. Botha <http://cpbotha.net/>
"""
import vtk
class DVOrientationWidget:
"""Convenience class for embedding orientation widget in any
renderwindowinteractor. If the data has DeVIDE style orientation
metadata, this class will show the little LRHFAP block, otherwise
x-y-z cursor.
"""
def __init__(self, rwi):
self._orientation_widget = vtk.vtkOrientationMarkerWidget()
self._orientation_widget.SetInteractor(rwi)
# we'll use this if there is no orientation metadata
# just a thingy with x-y-z indicators
self._axes_actor = vtk.vtkAxesActor()
# we'll use this if there is orientation metadata
self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
# configure the thing with better colours and no stupid edges
#aca.TextEdgesOff()
aca.GetXMinusFaceProperty().SetColor(1,0,0)
aca.GetXPlusFaceProperty().SetColor(1,0,0)
aca.GetYMinusFaceProperty().SetColor(0,1,0)
aca.GetYPlusFaceProperty().SetColor(0,1,0)
aca.GetZMinusFaceProperty().SetColor(0,0,1)
aca.GetZPlusFaceProperty().SetColor(0,0,1)
def close(self):
self.set_input(None)
self._orientation_widget.SetInteractor(None)
def set_input(self, input_data):
if input_data is None:
self._orientation_widget.Off()
return
ala = input_data.GetFieldData().GetArray('axis_labels_array')
if ala:
lut = list('LRPAFH')
labels = []
for i in range(6):
labels.append(lut[ala.GetValue(i)])
self._set_annotated_cube_actor_labels(labels)
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._annotated_cube_actor)
self._orientation_widget.On()
else:
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._axes_actor)
self._orientation_widget.On()
def _set_annotated_cube_actor_labels(self, labels):
aca = self._annotated_cube_actor
aca.SetXMinusFaceText(labels[0])
aca.SetXPlusFaceText(labels[1])
aca.SetYMinusFaceText(labels[2])
aca.SetYPlusFaceText(labels[3])
aca.SetZMinusFaceText(labels[4])
aca.SetZPlusFaceText(labels[5])
###########################################################################
def vtkmip_copy(src, dst):
"""Given two vtkMedicalImageProperties instances, copy all
attributes from the one to the other.
Rather use vtkMedicalImageProperties.DeepCopy.
"""
import module_kits.vtk_kit as vk
mip_kw = vk.constants.medical_image_properties_keywords
for kw in mip_kw:
# get method objects for the getter and the setter
gmo = getattr(src, 'Get%s' % (kw,))
smo = getattr(dst, 'Set%s' % (kw,))
# from the get to the set!
smo(gmo())
def setup_renderers(renwin, fg_ren, bg_ren):
"""Utility method to configure foreground and background renderer
and insert them into different layers of the renderenwinindow.
Use this if you want an incredibly cool gradient background!
"""
# bit of code thanks to
# http://www.bioengineering-research.com/vtk/BackgroundGradient.tcl
# had to change approach though to using background renderer,
# else transparent objects don't appear, and adding flat
# shaded objects breaks the background gradient.
# =================================================================
qpts = vtk.vtkPoints()
qpts.SetNumberOfPoints(4)
qpts.InsertPoint(0, 0, 0, 0)
qpts.InsertPoint(1, 1, 0, 0)
qpts.InsertPoint(2, 1, 1, 0)
qpts.InsertPoint(3, 0, 1, 0)
quad = vtk.vtkQuad()
quad.GetPointIds().SetId(0,0)
quad.GetPointIds().SetId(1,1)
quad.GetPointIds().SetId(2,2)
quad.GetPointIds().SetId(3,3)
uc = vtk.vtkUnsignedCharArray()
uc.SetNumberOfComponents(4)
uc.SetNumberOfTuples(4)
uc.SetTuple4(0, 128, 128, 128, 255) # bottom left RGBA
uc.SetTuple4(1, 128, 128, 128, 255) # bottom right RGBA
uc.SetTuple4(2, 255, 255, 255, 255) # top right RGBA
uc.SetTuple4(3, 255, 255, 255, 255) # tob left RGBA
dta = vtk.vtkPolyData()
dta.Allocate(1,1)
dta.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
dta.SetPoints(qpts)
dta.GetPointData().SetScalars(uc)
coord = vtk.vtkCoordinate()
coord.SetCoordinateSystemToNormalizedDisplay()
mapper2d = vtk.vtkPolyDataMapper2D()
mapper2d.SetInput(dta)
mapper2d.SetTransformCoordinate(coord)
actor2d = vtk.vtkActor2D()
actor2d.SetMapper(mapper2d)
actor2d.GetProperty().SetDisplayLocationToBackground()
bg_ren.AddActor(actor2d)
bg_ren.SetLayer(0) # seems to be background
bg_ren.SetInteractive(0)
fg_ren.SetLayer(1) # and foreground
renwin.SetNumberOfLayers(2)
renwin.AddRenderer(fg_ren)
renwin.AddRenderer(bg_ren)
| [
[
8,
0,
0.0406,
0.025,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0625,
0.0063,
0,
0.66,
0.25,
665,
0,
1,
0,
0,
665,
0,
0
],
[
3,
0,
0.2812,
0.4188,
0,
0.66,
... | [
"\"\"\"Utility methods for vtk_kit module kit.\n\n@author Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import vtk",
"class DVOrientationWidget:\n \"\"\"Convenience class for embedding orientation widget in any\n renderwindowinteractor. If the data has DeVIDE style orientation\n metadata, this class... |
# $Id$
"""Mixins that are useful for classes using vtk_kit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj
from external.vtkPipeline.vtkMethodParser import VtkMethodParser
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin # temporary
import module_utils # temporary, most of this should be in utils.
import re
import types
import utils
#########################################################################
class PickleVTKObjectsModuleMixin(object):
"""This mixin will pickle the state of all vtk objects whose binding
attribute names have been added to self._vtkObjects, e.g. if you have
a self._imageMath, '_imageMath' should be in the list.
Your module has to derive from module_base as well so that it has a
self._config!
Remember to call the __init__ of this class with the list of attribute
strings representing vtk objects that you want pickled. All the objects
have to exist and be initially configured by then.
Remember to call close() when your child class close()s.
"""
def __init__(self, vtkObjectNames):
# you have to add the NAMES of the objects that you want pickled
# to this list.
self._vtkObjectNames = vtkObjectNames
self.statePattern = re.compile ("To[A-Z0-9]")
# make sure that the state of the vtkObjectNames objects is
# encapsulated in the initial _config
self.logic_to_config()
def close(self):
# make sure we get rid of these bindings as well
del self._vtkObjectNames
def logic_to_config(self):
parser = VtkMethodParser()
for vtkObjName in self._vtkObjectNames:
# pickled data: a list with toggle_methods, state_methods and
# get_set_methods as returned by the vtkMethodParser. Each of
# these is a list of tuples with the name of the method (as
# returned by the vtkMethodParser) and the value; in the case
# of the stateMethods, we use the whole stateGroup instead of
# just a single name
vtkObjPD = [[], [], []]
vtkObj = getattr(self, vtkObjName)
parser.parse_methods(vtkObj)
# parser now has toggle_methods(), state_methods() and
# get_set_methods();
# toggle_methods: ['BlaatOn', 'AbortExecuteOn']
# state_methods: [['SetBlaatToOne', 'SetBlaatToTwo'],
# ['SetMaatToThree', 'SetMaatToFive']]
# get_set_methods: ['NumberOfThreads', 'Progress']
for method in parser.toggle_methods():
# if you query ReleaseDataFlag on a filter with 0 outputs,
# VTK yields an error
if vtkObj.GetNumberOfOutputPorts() == 0 and \
method == 'ReleaseDataFlagOn':
continue
# we need to snip the 'On' off
val = eval("vtkObj.Get%s()" % (method[:-2],))
vtkObjPD[0].append((method, val))
for stateGroup in parser.state_methods():
# we search up to the To
end = self.statePattern.search (stateGroup[0]).start ()
# so we turn SetBlaatToOne to GetBlaat
get_m = 'G'+stateGroup[0][1:end]
# we're going to have to be more clever when we set_config...
# use a similar trick to get_state in vtkMethodParser
val = eval('vtkObj.%s()' % (get_m,))
vtkObjPD[1].append((stateGroup, val))
for method in parser.get_set_methods():
val = eval('vtkObj.Get%s()' % (method,))
vtkObjPD[2].append((method, val))
# finally set the pickle data in the correct position
setattr(self._config, vtkObjName, vtkObjPD)
def config_to_logic(self):
# go through at least the attributes in self._vtkObjectNames
for vtkObjName in self._vtkObjectNames:
try:
vtkObjPD = getattr(self._config, vtkObjName)
vtkObj = getattr(self, vtkObjName)
except AttributeError:
print "PickleVTKObjectsModuleMixin: %s not available " \
"in self._config OR in self. Skipping." % (vtkObjName,)
else:
for method, val in vtkObjPD[0]:
if val:
eval('vtkObj.%s()' % (method,))
else:
# snip off the On
eval('vtkObj.%sOff()' % (method[:-2],))
for stateGroup, val in vtkObjPD[1]:
# keep on calling the methods in stategroup until
# the getter returns a value == val.
end = self.statePattern.search(stateGroup[0]).start()
getMethod = 'G'+stateGroup[0][1:end]
for i in range(len(stateGroup)):
m = stateGroup[i]
eval('vtkObj.%s()' % (m,))
tempVal = eval('vtkObj.%s()' % (getMethod,))
if tempVal == val:
# success! break out of the for loop
break
for method, val in vtkObjPD[2]:
try:
eval('vtkObj.Set%s(val)' % (method,))
except TypeError:
if type(val) in [types.TupleType, types.ListType]:
# sometimes VTK wants the separate elements
# and not the tuple / list
eval("vtkObj.Set%s(*val)"%(method,))
else:
# re-raise the exception if it wasn't a
# tuple/list
raise
#########################################################################
# note that the pickle mixin comes first, as its config_to_logic/logic_to_config
# should be chosen over that of noConfig
class SimpleVTKClassModuleBase(PickleVTKObjectsModuleMixin,
IntrospectModuleMixin,
ModuleBase):
"""Use this base to make a DeVIDE module that wraps a single VTK
object. The state of the VTK object will be saved when the network
is.
You only have to override the __init__ method and call the __init__
of this class with the desired parameters.
The __doc__ string of your module class will be replaced with the
__doc__ string of the encapsulated VTK class (and will thus be
shown if the user requests module help). If you don't want this,
call the ctor with replaceDoc=False.
inputFunctions is a list of the complete methods that have to be called
on the encapsulated VTK class, e.g. ['SetInput1(inputStream)',
'SetInput1(inputStream)']. The same goes for outputFunctions, except that
there's no inputStream involved. Use None in both cases if you want
the default to be used (SetInput(), GetOutput()).
"""
def __init__(self, module_manager, vtkObjectBinding, progressText,
inputDescriptions, outputDescriptions,
replaceDoc=True,
inputFunctions=None, outputFunctions=None):
self._viewFrame = None
self._configVtkObj = None
# first these two mixins
ModuleBase.__init__(self, module_manager)
self._theFilter = vtkObjectBinding
if replaceDoc:
myMessage = "<em>"\
"This is a special DeVIDE module that very simply " \
"wraps a single VTK class. In general, the " \
"complete state of the class will be saved along " \
"with the rest of the network. The documentation " \
"below is that of the wrapped VTK class:</em>"
self.__doc__ = '%s\n\n%s' % (myMessage, self._theFilter.__doc__)
# now that we have the object, init the pickle mixin so
# that the state of this object will be saved
PickleVTKObjectsModuleMixin.__init__(self, ['_theFilter'])
# make progress hooks for the object
module_utils.setup_vtk_object_progress(self, self._theFilter,
progressText)
self._inputDescriptions = inputDescriptions
self._outputDescriptions = outputDescriptions
self._inputFunctions = inputFunctions
self._outputFunctions = outputFunctions
def _createViewFrame(self):
parentWindow = self._module_manager.get_module_view_parent_window()
import resources.python.defaultModuleViewFrame
reload(resources.python.defaultModuleViewFrame)
dMVF = resources.python.defaultModuleViewFrame.defaultModuleViewFrame
viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, dMVF)
# ConfigVtkObj parent not important, we're passing frame + panel
# this should populate the sizer with a new sizer7
# params: noParent, noRenwin, vtk_obj, frame, panel
self._configVtkObj = ConfigVtkObj(None, None,
self._theFilter,
viewFrame, viewFrame.viewFramePanel)
module_utils.create_standard_object_introspection(
self, viewFrame, viewFrame.viewFramePanel,
{'Module (self)' : self}, None)
# we don't want the Execute button to be default... else stuff gets
# executed with every enter in the command window (at least in Doze)
module_utils.create_eoca_buttons(self, viewFrame,
viewFrame.viewFramePanel,
False)
self._viewFrame = viewFrame
return viewFrame
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
PickleVTKObjectsModuleMixin.close(self)
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
self._configVtkObj.close()
self._viewFrame.Destroy()
ModuleBase.close(self)
# get rid of our binding to the vtkObject
del self._theFilter
def get_output_descriptions(self):
return self._outputDescriptions
def get_output(self, idx):
# this will only every be invoked if your get_output_descriptions has
# 1 or more elements
if self._outputFunctions:
return eval('self._theFilter.%s' % (self._outputFunctions[idx],))
else:
return self._theFilter.GetOutput()
def get_input_descriptions(self):
return self._inputDescriptions
def set_input(self, idx, inputStream):
# this will only be called for a certain idx if you've specified that
# many elements in your get_input_descriptions
if self._inputFunctions:
exec('self._theFilter.%s' %
(self._inputFunctions[idx]))
else:
if idx == 0:
self._theFilter.SetInput(inputStream)
else:
self._theFilter.SetInput(idx, inputStream)
def execute_module(self):
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def streaming_execute_module(self):
"""All VTK classes should be streamable.
"""
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def view(self):
if self._viewFrame is None:
# we have an initial config populated with stuff and in sync
# with theFilter. The viewFrame will also be in sync with the
# filter
self._viewFrame = self._createViewFrame()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def config_to_view(self):
# the pickleVTKObjectsModuleMixin does logic <-> config
# so when the user clicks "sync", logic_to_config is called
# which transfers picklable state from the LOGIC to the CONFIG
# then we do double the work and call update_gui, which transfers
# the same state from the LOGIC straight up to the VIEW
self._configVtkObj.update_gui()
def view_to_config(self):
# same thing here: user clicks "apply", view_to_config is called which
# zaps UI changes straight to the LOGIC. Then we have to call
# logic_to_config explicitly which brings the info back up to the
# config... i.e. view -> logic -> config
# after that, config_to_logic is called which transfers all state AGAIN
# from the config to the logic
self._configVtkObj.apply_changes()
self.logic_to_config()
#########################################################################
| [
[
8,
0,
0.0134,
0.0119,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0239,
0.003,
0,
0.66,
0.1,
101,
0,
1,
0,
0,
101,
0,
0
],
[
1,
0,
0.0269,
0.003,
0,
0.66,
... | [
"\"\"\"Mixins that are useful for classes using vtk_kit.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj",
"from external.vtkPipeline.vtkMethodParser import VtkMethodParser",
"from module_base import ModuleBase",
"from module_mixins impo... |
# perceptually linear colour scales based on those published by Haim
# Levkowitz at http://www.cs.uml.edu/~haim/ColorCenter/
# code by Peter R. Krekel (c) 2009
# modified by Charl Botha to cache lookuptable per range
import vtk
class ColorScales():
def __init__(self):
self.BlueToYellow = {}
self.Linear_Heat = {}
self.Linear_BlackToWhite = {}
self.Linear_BlueToYellow = {}
def LUT_BlueToYellow(self, LUrange):
key = tuple(LUrange)
try:
return self.BlueToYellow[key]
except KeyError:
pass
differencetable = vtk.vtkLookupTable()
differencetable.SetNumberOfColors(50)
differencetable.SetRange(LUrange[0], LUrange[1])
i=0.0
while i<50:
differencetable.SetTableValue( int(i), (i/50.0, i/50.0, 1-(i/50.0) ,1.0))
i=i+1
differencetable.Build()
self.BlueToYellow[key] = differencetable
return self.BlueToYellow[key]
def LUT_Linear_Heat(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_Heat[key]
except KeyError:
pass
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 3 , ( 0.004 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 4 , ( 0.008 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 5 , ( 0.008 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 6 , ( 0.012 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 7 , ( 0.012 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 8 , ( 0.016 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 9 , ( 0.020 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 10 , ( 0.020 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 11 , ( 0.024 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 12 , ( 0.027 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 13 , ( 0.027 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 14 , ( 0.031 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 15 , ( 0.035 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 16 , ( 0.035 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 17 , ( 0.039 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 18 , ( 0.043 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 19 , ( 0.047 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 20 , ( 0.051 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 21 , ( 0.055 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 22 , ( 0.059 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 23 , ( 0.063 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 24 , ( 0.067 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 25 , ( 0.071 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 26 , ( 0.075 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 27 , ( 0.078 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 28 , ( 0.082 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 29 , ( 0.086 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 30 , ( 0.090 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 31 , ( 0.098 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 32 , ( 0.102 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 33 , ( 0.106 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 34 , ( 0.110 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 35 , ( 0.118 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 36 , ( 0.122 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 37 , ( 0.129 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 38 , ( 0.133 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 39 , ( 0.137 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 40 , ( 0.145 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 41 , ( 0.153 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 42 , ( 0.157 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 43 , ( 0.169 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 44 , ( 0.176 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 45 , ( 0.180 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 46 , ( 0.192 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 47 , ( 0.200 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 48 , ( 0.208 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 49 , ( 0.212 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 50 , ( 0.220 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 51 , ( 0.227 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 52 , ( 0.235 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 53 , ( 0.243 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 54 , ( 0.251 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 55 , ( 0.263 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 56 , ( 0.271 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 57 , ( 0.278 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 58 , ( 0.290 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 59 , ( 0.298 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 60 , ( 0.314 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 61 , ( 0.318 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 62 , ( 0.329 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 63 , ( 0.337 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 64 , ( 0.349 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 65 , ( 0.361 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 66 , ( 0.369 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 67 , ( 0.380 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 68 , ( 0.392 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 69 , ( 0.404 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 70 , ( 0.416 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 71 , ( 0.427 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 72 , ( 0.439 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 73 , ( 0.451 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 74 , ( 0.459 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 75 , ( 0.478 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 76 , ( 0.494 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 77 , ( 0.502 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 78 , ( 0.514 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 79 , ( 0.529 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 80 , ( 0.529 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 81 , ( 0.529 , 0.004 , 0.000 ,1.0))
L1table.SetTableValue( 82 , ( 0.529 , 0.008 , 0.000 ,1.0))
L1table.SetTableValue( 83 , ( 0.529 , 0.012 , 0.000 ,1.0))
L1table.SetTableValue( 84 , ( 0.529 , 0.016 , 0.000 ,1.0))
L1table.SetTableValue( 85 , ( 0.529 , 0.024 , 0.000 ,1.0))
L1table.SetTableValue( 86 , ( 0.529 , 0.024 , 0.000 ,1.0))
L1table.SetTableValue( 87 , ( 0.529 , 0.031 , 0.000 ,1.0))
L1table.SetTableValue( 88 , ( 0.529 , 0.035 , 0.000 ,1.0))
L1table.SetTableValue( 89 , ( 0.529 , 0.039 , 0.000 ,1.0))
L1table.SetTableValue( 90 , ( 0.529 , 0.043 , 0.000 ,1.0))
L1table.SetTableValue( 91 , ( 0.529 , 0.051 , 0.000 ,1.0))
L1table.SetTableValue( 92 , ( 0.529 , 0.051 , 0.000 ,1.0))
L1table.SetTableValue( 93 , ( 0.529 , 0.059 , 0.000 ,1.0))
L1table.SetTableValue( 94 , ( 0.529 , 0.067 , 0.000 ,1.0))
L1table.SetTableValue( 95 , ( 0.529 , 0.067 , 0.000 ,1.0))
L1table.SetTableValue( 96 , ( 0.529 , 0.075 , 0.000 ,1.0))
L1table.SetTableValue( 97 , ( 0.529 , 0.082 , 0.000 ,1.0))
L1table.SetTableValue( 98 , ( 0.529 , 0.086 , 0.000 ,1.0))
L1table.SetTableValue( 99 , ( 0.529 , 0.090 , 0.000 ,1.0))
L1table.SetTableValue( 100 , ( 0.529 , 0.098 , 0.000 ,1.0))
L1table.SetTableValue( 101 , ( 0.529 , 0.102 , 0.000 ,1.0))
L1table.SetTableValue( 102 , ( 0.529 , 0.106 , 0.000 ,1.0))
L1table.SetTableValue( 103 , ( 0.529 , 0.114 , 0.000 ,1.0))
L1table.SetTableValue( 104 , ( 0.529 , 0.122 , 0.000 ,1.0))
L1table.SetTableValue( 105 , ( 0.529 , 0.125 , 0.000 ,1.0))
L1table.SetTableValue( 106 , ( 0.529 , 0.129 , 0.000 ,1.0))
L1table.SetTableValue( 107 , ( 0.529 , 0.137 , 0.000 ,1.0))
L1table.SetTableValue( 108 , ( 0.529 , 0.141 , 0.000 ,1.0))
L1table.SetTableValue( 109 , ( 0.529 , 0.149 , 0.000 ,1.0))
L1table.SetTableValue( 110 , ( 0.529 , 0.157 , 0.000 ,1.0))
L1table.SetTableValue( 111 , ( 0.529 , 0.165 , 0.000 ,1.0))
L1table.SetTableValue( 112 , ( 0.529 , 0.173 , 0.000 ,1.0))
L1table.SetTableValue( 113 , ( 0.529 , 0.180 , 0.000 ,1.0))
L1table.SetTableValue( 114 , ( 0.529 , 0.184 , 0.000 ,1.0))
L1table.SetTableValue( 115 , ( 0.529 , 0.192 , 0.000 ,1.0))
L1table.SetTableValue( 116 , ( 0.529 , 0.200 , 0.000 ,1.0))
L1table.SetTableValue( 117 , ( 0.529 , 0.204 , 0.000 ,1.0))
L1table.SetTableValue( 118 , ( 0.529 , 0.212 , 0.000 ,1.0))
L1table.SetTableValue( 119 , ( 0.529 , 0.220 , 0.000 ,1.0))
L1table.SetTableValue( 120 , ( 0.529 , 0.224 , 0.000 ,1.0))
L1table.SetTableValue( 121 , ( 0.529 , 0.231 , 0.000 ,1.0))
L1table.SetTableValue( 122 , ( 0.529 , 0.243 , 0.000 ,1.0))
L1table.SetTableValue( 123 , ( 0.529 , 0.247 , 0.000 ,1.0))
L1table.SetTableValue( 124 , ( 0.529 , 0.255 , 0.000 ,1.0))
L1table.SetTableValue( 125 , ( 0.529 , 0.263 , 0.000 ,1.0))
L1table.SetTableValue( 126 , ( 0.529 , 0.271 , 0.000 ,1.0))
L1table.SetTableValue( 127 , ( 0.529 , 0.282 , 0.000 ,1.0))
L1table.SetTableValue( 128 , ( 0.529 , 0.286 , 0.000 ,1.0))
L1table.SetTableValue( 129 , ( 0.529 , 0.298 , 0.000 ,1.0))
L1table.SetTableValue( 130 , ( 0.529 , 0.306 , 0.000 ,1.0))
L1table.SetTableValue( 131 , ( 0.529 , 0.314 , 0.000 ,1.0))
L1table.SetTableValue( 132 , ( 0.529 , 0.322 , 0.000 ,1.0))
L1table.SetTableValue( 133 , ( 0.529 , 0.329 , 0.000 ,1.0))
L1table.SetTableValue( 134 , ( 0.529 , 0.341 , 0.000 ,1.0))
L1table.SetTableValue( 135 , ( 0.529 , 0.345 , 0.000 ,1.0))
L1table.SetTableValue( 136 , ( 0.529 , 0.353 , 0.000 ,1.0))
L1table.SetTableValue( 137 , ( 0.529 , 0.365 , 0.000 ,1.0))
L1table.SetTableValue( 138 , ( 0.529 , 0.373 , 0.000 ,1.0))
L1table.SetTableValue( 139 , ( 0.529 , 0.384 , 0.000 ,1.0))
L1table.SetTableValue( 140 , ( 0.529 , 0.396 , 0.000 ,1.0))
L1table.SetTableValue( 141 , ( 0.529 , 0.404 , 0.000 ,1.0))
L1table.SetTableValue( 142 , ( 0.529 , 0.416 , 0.000 ,1.0))
L1table.SetTableValue( 143 , ( 0.529 , 0.420 , 0.000 ,1.0))
L1table.SetTableValue( 144 , ( 0.529 , 0.431 , 0.000 ,1.0))
L1table.SetTableValue( 145 , ( 0.529 , 0.443 , 0.000 ,1.0))
L1table.SetTableValue( 146 , ( 0.529 , 0.451 , 0.000 ,1.0))
L1table.SetTableValue( 147 , ( 0.529 , 0.463 , 0.000 ,1.0))
L1table.SetTableValue( 148 , ( 0.529 , 0.475 , 0.000 ,1.0))
L1table.SetTableValue( 149 , ( 0.529 , 0.486 , 0.000 ,1.0))
L1table.SetTableValue( 150 , ( 0.529 , 0.498 , 0.000 ,1.0))
L1table.SetTableValue( 151 , ( 0.529 , 0.506 , 0.000 ,1.0))
L1table.SetTableValue( 152 , ( 0.529 , 0.522 , 0.000 ,1.0))
L1table.SetTableValue( 153 , ( 0.529 , 0.529 , 0.000 ,1.0))
L1table.SetTableValue( 154 , ( 0.529 , 0.541 , 0.000 ,1.0))
L1table.SetTableValue( 155 , ( 0.529 , 0.553 , 0.000 ,1.0))
L1table.SetTableValue( 156 , ( 0.529 , 0.565 , 0.000 ,1.0))
L1table.SetTableValue( 157 , ( 0.529 , 0.580 , 0.000 ,1.0))
L1table.SetTableValue( 158 , ( 0.529 , 0.588 , 0.000 ,1.0))
L1table.SetTableValue( 159 , ( 0.529 , 0.608 , 0.000 ,1.0))
L1table.SetTableValue( 160 , ( 0.529 , 0.616 , 0.000 ,1.0))
L1table.SetTableValue( 161 , ( 0.529 , 0.627 , 0.000 ,1.0))
L1table.SetTableValue( 162 , ( 0.529 , 0.639 , 0.000 ,1.0))
L1table.SetTableValue( 163 , ( 0.529 , 0.651 , 0.000 ,1.0))
L1table.SetTableValue( 164 , ( 0.529 , 0.667 , 0.000 ,1.0))
L1table.SetTableValue( 165 , ( 0.529 , 0.682 , 0.000 ,1.0))
L1table.SetTableValue( 166 , ( 0.529 , 0.694 , 0.000 ,1.0))
L1table.SetTableValue( 167 , ( 0.529 , 0.706 , 0.000 ,1.0))
L1table.SetTableValue( 168 , ( 0.529 , 0.722 , 0.000 ,1.0))
L1table.SetTableValue( 169 , ( 0.529 , 0.737 , 0.000 ,1.0))
L1table.SetTableValue( 170 , ( 0.529 , 0.753 , 0.000 ,1.0))
L1table.SetTableValue( 171 , ( 0.529 , 0.765 , 0.000 ,1.0))
L1table.SetTableValue( 172 , ( 0.529 , 0.784 , 0.000 ,1.0))
L1table.SetTableValue( 173 , ( 0.529 , 0.796 , 0.000 ,1.0))
L1table.SetTableValue( 174 , ( 0.529 , 0.804 , 0.000 ,1.0))
L1table.SetTableValue( 175 , ( 0.529 , 0.824 , 0.000 ,1.0))
L1table.SetTableValue( 176 , ( 0.529 , 0.839 , 0.000 ,1.0))
L1table.SetTableValue( 177 , ( 0.529 , 0.855 , 0.000 ,1.0))
L1table.SetTableValue( 178 , ( 0.529 , 0.871 , 0.000 ,1.0))
L1table.SetTableValue( 179 , ( 0.529 , 0.886 , 0.000 ,1.0))
L1table.SetTableValue( 180 , ( 0.529 , 0.906 , 0.000 ,1.0))
L1table.SetTableValue( 181 , ( 0.529 , 0.925 , 0.000 ,1.0))
L1table.SetTableValue( 182 , ( 0.529 , 0.937 , 0.000 ,1.0))
L1table.SetTableValue( 183 , ( 0.529 , 0.957 , 0.000 ,1.0))
L1table.SetTableValue( 184 , ( 0.529 , 0.976 , 0.000 ,1.0))
L1table.SetTableValue( 185 , ( 0.529 , 0.996 , 0.000 ,1.0))
L1table.SetTableValue( 186 , ( 0.529 , 1.000 , 0.004 ,1.0))
L1table.SetTableValue( 187 , ( 0.529 , 1.000 , 0.020 ,1.0))
L1table.SetTableValue( 188 , ( 0.529 , 1.000 , 0.039 ,1.0))
L1table.SetTableValue( 189 , ( 0.529 , 1.000 , 0.059 ,1.0))
L1table.SetTableValue( 190 , ( 0.529 , 1.000 , 0.078 ,1.0))
L1table.SetTableValue( 191 , ( 0.529 , 1.000 , 0.090 ,1.0))
L1table.SetTableValue( 192 , ( 0.529 , 1.000 , 0.110 ,1.0))
L1table.SetTableValue( 193 , ( 0.529 , 1.000 , 0.129 ,1.0))
L1table.SetTableValue( 194 , ( 0.529 , 1.000 , 0.149 ,1.0))
L1table.SetTableValue( 195 , ( 0.529 , 1.000 , 0.169 ,1.0))
L1table.SetTableValue( 196 , ( 0.529 , 1.000 , 0.176 ,1.0))
L1table.SetTableValue( 197 , ( 0.529 , 1.000 , 0.192 ,1.0))
L1table.SetTableValue( 198 , ( 0.529 , 1.000 , 0.212 ,1.0))
L1table.SetTableValue( 199 , ( 0.529 , 1.000 , 0.231 ,1.0))
L1table.SetTableValue( 200 , ( 0.529 , 1.000 , 0.255 ,1.0))
L1table.SetTableValue( 201 , ( 0.529 , 1.000 , 0.275 ,1.0))
L1table.SetTableValue( 202 , ( 0.529 , 1.000 , 0.290 ,1.0))
L1table.SetTableValue( 203 , ( 0.529 , 1.000 , 0.314 ,1.0))
L1table.SetTableValue( 204 , ( 0.529 , 1.000 , 0.329 ,1.0))
L1table.SetTableValue( 205 , ( 0.529 , 1.000 , 0.353 ,1.0))
L1table.SetTableValue( 206 , ( 0.529 , 1.000 , 0.373 ,1.0))
L1table.SetTableValue( 207 , ( 0.529 , 1.000 , 0.384 ,1.0))
L1table.SetTableValue( 208 , ( 0.529 , 1.000 , 0.408 ,1.0))
L1table.SetTableValue( 209 , ( 0.529 , 1.000 , 0.431 ,1.0))
L1table.SetTableValue( 210 , ( 0.529 , 1.000 , 0.455 ,1.0))
L1table.SetTableValue( 211 , ( 0.529 , 1.000 , 0.471 ,1.0))
L1table.SetTableValue( 212 , ( 0.529 , 1.000 , 0.490 ,1.0))
L1table.SetTableValue( 213 , ( 0.529 , 1.000 , 0.514 ,1.0))
L1table.SetTableValue( 214 , ( 0.529 , 1.000 , 0.537 ,1.0))
L1table.SetTableValue( 215 , ( 0.529 , 1.000 , 0.565 ,1.0))
L1table.SetTableValue( 216 , ( 0.529 , 1.000 , 0.584 ,1.0))
L1table.SetTableValue( 217 , ( 0.529 , 1.000 , 0.604 ,1.0))
L1table.SetTableValue( 218 , ( 0.529 , 1.000 , 0.620 ,1.0))
L1table.SetTableValue( 219 , ( 0.529 , 1.000 , 0.647 ,1.0))
L1table.SetTableValue( 220 , ( 0.529 , 1.000 , 0.675 ,1.0))
L1table.SetTableValue( 221 , ( 0.529 , 1.000 , 0.702 ,1.0))
L1table.SetTableValue( 222 , ( 0.529 , 1.000 , 0.729 ,1.0))
L1table.SetTableValue( 223 , ( 0.529 , 1.000 , 0.749 ,1.0))
L1table.SetTableValue( 224 , ( 0.529 , 1.000 , 0.776 ,1.0))
L1table.SetTableValue( 225 , ( 0.529 , 1.000 , 0.796 ,1.0))
L1table.SetTableValue( 226 , ( 0.529 , 1.000 , 0.827 ,1.0))
L1table.SetTableValue( 227 , ( 0.529 , 1.000 , 0.847 ,1.0))
L1table.SetTableValue( 228 , ( 0.529 , 1.000 , 0.878 ,1.0))
L1table.SetTableValue( 229 , ( 0.529 , 1.000 , 0.910 ,1.0))
L1table.SetTableValue( 230 , ( 0.529 , 1.000 , 0.941 ,1.0))
L1table.SetTableValue( 231 , ( 0.529 , 1.000 , 0.973 ,1.0))
L1table.SetTableValue( 232 , ( 0.529 , 1.000 , 0.996 ,1.0))
L1table.SetTableValue( 233 , ( 0.529 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 234 , ( 0.549 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 235 , ( 0.573 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 236 , ( 0.600 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 237 , ( 0.612 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 238 , ( 0.631 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 239 , ( 0.659 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 240 , ( 0.675 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 241 , ( 0.694 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 242 , ( 0.714 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 243 , ( 0.741 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 244 , ( 0.753 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 245 , ( 0.780 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 246 , ( 0.800 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 247 , ( 0.824 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 248 , ( 0.843 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 249 , ( 0.863 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 250 , ( 0.882 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 251 , ( 0.910 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 252 , ( 0.925 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 253 , ( 0.941 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 254 , ( 0.973 , 1.000 , 1.000 ,1.0))
L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0))
L1table.Build()
self.Linear_Heat[key] = L1table
return self.Linear_Heat[key]
def LUT_Linear_BlackToWhite(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_BlackToWhite[key]
except KeyError:
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 3 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 4 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 5 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 6 , ( 0.000 , 0.000 , 0.000 ,1.0))
L1table.SetTableValue( 7 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 8 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 9 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 10 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 11 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 12 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 13 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 14 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 15 , ( 0.004 , 0.004 , 0.004 ,1.0))
L1table.SetTableValue( 16 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 17 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 18 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 19 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 20 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 21 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 22 , ( 0.008 , 0.008 , 0.008 ,1.0))
L1table.SetTableValue( 23 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 24 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 25 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 26 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 27 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 28 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 29 , ( 0.012 , 0.012 , 0.012 ,1.0))
L1table.SetTableValue( 30 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 31 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 32 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 33 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 34 , ( 0.016 , 0.016 , 0.016 ,1.0))
L1table.SetTableValue( 35 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 36 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 37 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 38 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 39 , ( 0.020 , 0.020 , 0.020 ,1.0))
L1table.SetTableValue( 40 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 41 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 42 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 43 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 44 , ( 0.024 , 0.024 , 0.024 ,1.0))
L1table.SetTableValue( 45 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 46 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 47 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 48 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 49 , ( 0.027 , 0.027 , 0.027 ,1.0))
L1table.SetTableValue( 50 , ( 0.031 , 0.031 , 0.031 ,1.0))
L1table.SetTableValue( 51 , ( 0.031 , 0.031 , 0.031 ,1.0))
L1table.SetTableValue( 52 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 53 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 54 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 55 , ( 0.035 , 0.035 , 0.035 ,1.0))
L1table.SetTableValue( 56 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 57 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 58 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 59 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 60 , ( 0.039 , 0.039 , 0.039 ,1.0))
L1table.SetTableValue( 61 , ( 0.043 , 0.043 , 0.043 ,1.0))
L1table.SetTableValue( 62 , ( 0.043 , 0.043 , 0.043 ,1.0))
L1table.SetTableValue( 63 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 64 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 65 , ( 0.047 , 0.047 , 0.047 ,1.0))
L1table.SetTableValue( 66 , ( 0.051 , 0.051 , 0.051 ,1.0))
L1table.SetTableValue( 67 , ( 0.051 , 0.051 , 0.051 ,1.0))
L1table.SetTableValue( 68 , ( 0.055 , 0.055 , 0.055 ,1.0))
L1table.SetTableValue( 69 , ( 0.055 , 0.055 , 0.055 ,1.0))
L1table.SetTableValue( 70 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 71 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 72 , ( 0.059 , 0.059 , 0.059 ,1.0))
L1table.SetTableValue( 73 , ( 0.063 , 0.063 , 0.063 ,1.0))
L1table.SetTableValue( 74 , ( 0.063 , 0.063 , 0.063 ,1.0))
L1table.SetTableValue( 75 , ( 0.067 , 0.067 , 0.067 ,1.0))
L1table.SetTableValue( 76 , ( 0.067 , 0.067 , 0.067 ,1.0))
L1table.SetTableValue( 77 , ( 0.071 , 0.071 , 0.071 ,1.0))
L1table.SetTableValue( 78 , ( 0.071 , 0.071 , 0.071 ,1.0))
L1table.SetTableValue( 79 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 80 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 81 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 82 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 83 , ( 0.075 , 0.075 , 0.075 ,1.0))
L1table.SetTableValue( 84 , ( 0.078 , 0.078 , 0.078 ,1.0))
L1table.SetTableValue( 85 , ( 0.078 , 0.078 , 0.078 ,1.0))
L1table.SetTableValue( 86 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 87 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 88 , ( 0.086 , 0.086 , 0.086 ,1.0))
L1table.SetTableValue( 89 , ( 0.090 , 0.090 , 0.090 ,1.0))
L1table.SetTableValue( 90 , ( 0.090 , 0.090 , 0.090 ,1.0))
L1table.SetTableValue( 91 , ( 0.094 , 0.094 , 0.094 ,1.0))
L1table.SetTableValue( 92 , ( 0.094 , 0.094 , 0.094 ,1.0))
L1table.SetTableValue( 93 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 94 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 95 , ( 0.102 , 0.102 , 0.102 ,1.0))
L1table.SetTableValue( 96 , ( 0.106 , 0.106 , 0.106 ,1.0))
L1table.SetTableValue( 97 , ( 0.106 , 0.106 , 0.106 ,1.0))
L1table.SetTableValue( 98 , ( 0.114 , 0.114 , 0.114 ,1.0))
L1table.SetTableValue( 99 , ( 0.114 , 0.114 , 0.114 ,1.0))
L1table.SetTableValue( 100 , ( 0.118 , 0.118 , 0.118 ,1.0))
L1table.SetTableValue( 101 , ( 0.118 , 0.118 , 0.118 ,1.0))
L1table.SetTableValue( 102 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 103 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 104 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 105 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 106 , ( 0.125 , 0.125 , 0.125 ,1.0))
L1table.SetTableValue( 107 , ( 0.133 , 0.133 , 0.133 ,1.0))
L1table.SetTableValue( 108 , ( 0.133 , 0.133 , 0.133 ,1.0))
L1table.SetTableValue( 109 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 110 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 111 , ( 0.137 , 0.137 , 0.137 ,1.0))
L1table.SetTableValue( 112 , ( 0.145 , 0.145 , 0.145 ,1.0))
L1table.SetTableValue( 113 , ( 0.145 , 0.145 , 0.145 ,1.0))
L1table.SetTableValue( 114 , ( 0.153 , 0.153 , 0.153 ,1.0))
L1table.SetTableValue( 115 , ( 0.153 , 0.153 , 0.153 ,1.0))
L1table.SetTableValue( 116 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 117 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 118 , ( 0.161 , 0.161 , 0.161 ,1.0))
L1table.SetTableValue( 119 , ( 0.169 , 0.169 , 0.169 ,1.0))
L1table.SetTableValue( 120 , ( 0.169 , 0.169 , 0.169 ,1.0))
L1table.SetTableValue( 121 , ( 0.176 , 0.176 , 0.176 ,1.0))
L1table.SetTableValue( 122 , ( 0.176 , 0.176 , 0.176 ,1.0))
L1table.SetTableValue( 123 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 124 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 125 , ( 0.180 , 0.180 , 0.180 ,1.0))
L1table.SetTableValue( 126 , ( 0.184 , 0.184 , 0.184 ,1.0))
L1table.SetTableValue( 127 , ( 0.184 , 0.184 , 0.184 ,1.0))
L1table.SetTableValue( 128 , ( 0.192 , 0.192 , 0.192 ,1.0))
L1table.SetTableValue( 129 , ( 0.192 , 0.192 , 0.192 ,1.0))
L1table.SetTableValue( 130 , ( 0.200 , 0.200 , 0.200 ,1.0))
L1table.SetTableValue( 131 , ( 0.200 , 0.200 , 0.200 ,1.0))
L1table.SetTableValue( 132 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 133 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 134 , ( 0.204 , 0.204 , 0.204 ,1.0))
L1table.SetTableValue( 135 , ( 0.212 , 0.212 , 0.212 ,1.0))
L1table.SetTableValue( 136 , ( 0.212 , 0.212 , 0.212 ,1.0))
L1table.SetTableValue( 137 , ( 0.220 , 0.220 , 0.220 ,1.0))
L1table.SetTableValue( 138 , ( 0.220 , 0.220 , 0.220 ,1.0))
L1table.SetTableValue( 139 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 140 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 141 , ( 0.231 , 0.231 , 0.231 ,1.0))
L1table.SetTableValue( 142 , ( 0.239 , 0.239 , 0.239 ,1.0))
L1table.SetTableValue( 143 , ( 0.239 , 0.239 , 0.239 ,1.0))
L1table.SetTableValue( 144 , ( 0.251 , 0.251 , 0.251 ,1.0))
L1table.SetTableValue( 145 , ( 0.251 , 0.251 , 0.251 ,1.0))
L1table.SetTableValue( 146 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 147 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 148 , ( 0.263 , 0.263 , 0.263 ,1.0))
L1table.SetTableValue( 149 , ( 0.271 , 0.271 , 0.271 ,1.0))
L1table.SetTableValue( 150 , ( 0.271 , 0.271 , 0.271 ,1.0))
L1table.SetTableValue( 151 , ( 0.282 , 0.282 , 0.282 ,1.0))
L1table.SetTableValue( 152 , ( 0.282 , 0.282 , 0.282 ,1.0))
L1table.SetTableValue( 153 , ( 0.294 , 0.294 , 0.294 ,1.0))
L1table.SetTableValue( 154 , ( 0.294 , 0.294 , 0.294 ,1.0))
L1table.SetTableValue( 155 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 156 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 157 , ( 0.298 , 0.298 , 0.298 ,1.0))
L1table.SetTableValue( 158 , ( 0.306 , 0.306 , 0.306 ,1.0))
L1table.SetTableValue( 159 , ( 0.306 , 0.306 , 0.306 ,1.0))
L1table.SetTableValue( 160 , ( 0.318 , 0.318 , 0.318 ,1.0))
L1table.SetTableValue( 161 , ( 0.318 , 0.318 , 0.318 ,1.0))
L1table.SetTableValue( 162 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 163 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 164 , ( 0.329 , 0.329 , 0.329 ,1.0))
L1table.SetTableValue( 165 , ( 0.341 , 0.341 , 0.341 ,1.0))
L1table.SetTableValue( 166 , ( 0.341 , 0.341 , 0.341 ,1.0))
L1table.SetTableValue( 167 , ( 0.357 , 0.357 , 0.357 ,1.0))
L1table.SetTableValue( 168 , ( 0.357 , 0.357 , 0.357 ,1.0))
L1table.SetTableValue( 169 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 170 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 171 , ( 0.369 , 0.369 , 0.369 ,1.0))
L1table.SetTableValue( 172 , ( 0.380 , 0.380 , 0.380 ,1.0))
L1table.SetTableValue( 173 , ( 0.380 , 0.380 , 0.380 ,1.0))
L1table.SetTableValue( 174 , ( 0.396 , 0.396 , 0.396 ,1.0))
L1table.SetTableValue( 175 , ( 0.396 , 0.396 , 0.396 ,1.0))
L1table.SetTableValue( 176 , ( 0.408 , 0.408 , 0.408 ,1.0))
L1table.SetTableValue( 177 , ( 0.408 , 0.408 , 0.408 ,1.0))
L1table.SetTableValue( 178 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 179 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 180 , ( 0.420 , 0.420 , 0.420 ,1.0))
L1table.SetTableValue( 181 , ( 0.424 , 0.424 , 0.424 ,1.0))
L1table.SetTableValue( 182 , ( 0.424 , 0.424 , 0.424 ,1.0))
L1table.SetTableValue( 183 , ( 0.439 , 0.439 , 0.439 ,1.0))
L1table.SetTableValue( 184 , ( 0.439 , 0.439 , 0.439 ,1.0))
L1table.SetTableValue( 185 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 186 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 187 , ( 0.455 , 0.455 , 0.455 ,1.0))
L1table.SetTableValue( 188 , ( 0.471 , 0.471 , 0.471 ,1.0))
L1table.SetTableValue( 189 , ( 0.471 , 0.471 , 0.471 ,1.0))
L1table.SetTableValue( 190 , ( 0.486 , 0.486 , 0.486 ,1.0))
L1table.SetTableValue( 191 , ( 0.486 , 0.486 , 0.486 ,1.0))
L1table.SetTableValue( 192 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 193 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 194 , ( 0.502 , 0.502 , 0.502 ,1.0))
L1table.SetTableValue( 195 , ( 0.518 , 0.518 , 0.518 ,1.0))
L1table.SetTableValue( 196 , ( 0.518 , 0.518 , 0.518 ,1.0))
L1table.SetTableValue( 197 , ( 0.533 , 0.533 , 0.533 ,1.0))
L1table.SetTableValue( 198 , ( 0.533 , 0.533 , 0.533 ,1.0))
L1table.SetTableValue( 199 , ( 0.553 , 0.553 , 0.553 ,1.0))
L1table.SetTableValue( 200 , ( 0.553 , 0.553 , 0.553 ,1.0))
L1table.SetTableValue( 201 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 202 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 203 , ( 0.569 , 0.569 , 0.569 ,1.0))
L1table.SetTableValue( 204 , ( 0.576 , 0.576 , 0.576 ,1.0))
L1table.SetTableValue( 205 , ( 0.576 , 0.576 , 0.576 ,1.0))
L1table.SetTableValue( 206 , ( 0.588 , 0.588 , 0.588 ,1.0))
L1table.SetTableValue( 207 , ( 0.588 , 0.588 , 0.588 ,1.0))
L1table.SetTableValue( 208 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 209 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 210 , ( 0.604 , 0.604 , 0.604 ,1.0))
L1table.SetTableValue( 211 , ( 0.624 , 0.624 , 0.624 ,1.0))
L1table.SetTableValue( 212 , ( 0.624 , 0.624 , 0.624 ,1.0))
L1table.SetTableValue( 213 , ( 0.643 , 0.643 , 0.643 ,1.0))
L1table.SetTableValue( 214 , ( 0.643 , 0.643 , 0.643 ,1.0))
L1table.SetTableValue( 215 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 216 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 217 , ( 0.663 , 0.663 , 0.663 ,1.0))
L1table.SetTableValue( 218 , ( 0.682 , 0.682 , 0.682 ,1.0))
L1table.SetTableValue( 219 , ( 0.682 , 0.682 , 0.682 ,1.0))
L1table.SetTableValue( 220 , ( 0.702 , 0.702 , 0.702 ,1.0))
L1table.SetTableValue( 221 , ( 0.702 , 0.702 , 0.702 ,1.0))
L1table.SetTableValue( 222 , ( 0.725 , 0.725 , 0.725 ,1.0))
L1table.SetTableValue( 223 , ( 0.725 , 0.725 , 0.725 ,1.0))
L1table.SetTableValue( 224 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 225 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 226 , ( 0.745 , 0.745 , 0.745 ,1.0))
L1table.SetTableValue( 227 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 228 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 229 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 230 , ( 0.765 , 0.765 , 0.765 ,1.0))
L1table.SetTableValue( 231 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 232 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 233 , ( 0.788 , 0.788 , 0.788 ,1.0))
L1table.SetTableValue( 234 , ( 0.812 , 0.812 , 0.812 ,1.0))
L1table.SetTableValue( 235 , ( 0.812 , 0.812 , 0.812 ,1.0))
L1table.SetTableValue( 236 , ( 0.831 , 0.831 , 0.831 ,1.0))
L1table.SetTableValue( 237 , ( 0.831 , 0.831 , 0.831 ,1.0))
L1table.SetTableValue( 238 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 239 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 240 , ( 0.855 , 0.855 , 0.855 ,1.0))
L1table.SetTableValue( 241 , ( 0.878 , 0.878 , 0.878 ,1.0))
L1table.SetTableValue( 242 , ( 0.878 , 0.878 , 0.878 ,1.0))
L1table.SetTableValue( 243 , ( 0.902 , 0.902 , 0.902 ,1.0))
L1table.SetTableValue( 244 , ( 0.902 , 0.902 , 0.902 ,1.0))
L1table.SetTableValue( 245 , ( 0.929 , 0.929 , 0.929 ,1.0))
L1table.SetTableValue( 246 , ( 0.929 , 0.929 , 0.929 ,1.0))
L1table.SetTableValue( 247 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 248 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 249 , ( 0.953 , 0.953 , 0.953 ,1.0))
L1table.SetTableValue( 250 , ( 0.976 , 0.976 , 0.976 ,1.0))
L1table.SetTableValue( 251 , ( 0.976 , 0.976 , 0.976 ,1.0))
L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 253 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 254 , ( 0.988 , 0.988 , 0.988 ,1.0))
L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0))
L1table.Build()
self.Linear_BlackToWhite[key] = L1table
return self.Linear_BlackToWhite[key]
def LUT_Linear_BlueToYellow(self, LUrange):
key = tuple(LUrange)
try:
return self.Linear_BlueToYellow[key]
except KeyError:
L1table = vtk.vtkLookupTable()
L1table.SetRange(LUrange[0], LUrange[1])
L1table.SetNumberOfColors(256)
L1table.SetTableValue( 0 , ( 0.027 , 0.027 , 0.996 ,1.0))
L1table.SetTableValue( 1 , ( 0.090 , 0.090 , 0.988 ,1.0))
L1table.SetTableValue( 2 , ( 0.118 , 0.118 , 0.980 ,1.0))
L1table.SetTableValue( 3 , ( 0.141 , 0.141 , 0.973 ,1.0))
L1table.SetTableValue( 4 , ( 0.157 , 0.157 , 0.969 ,1.0))
L1table.SetTableValue( 5 , ( 0.173 , 0.173 , 0.961 ,1.0))
L1table.SetTableValue( 6 , ( 0.184 , 0.184 , 0.953 ,1.0))
L1table.SetTableValue( 7 , ( 0.196 , 0.196 , 0.949 ,1.0))
L1table.SetTableValue( 8 , ( 0.204 , 0.204 , 0.941 ,1.0))
L1table.SetTableValue( 9 , ( 0.216 , 0.216 , 0.937 ,1.0))
L1table.SetTableValue( 10 , ( 0.224 , 0.224 , 0.933 ,1.0))
L1table.SetTableValue( 11 , ( 0.231 , 0.231 , 0.925 ,1.0))
L1table.SetTableValue( 12 , ( 0.239 , 0.239 , 0.922 ,1.0))
L1table.SetTableValue( 13 , ( 0.247 , 0.247 , 0.918 ,1.0))
L1table.SetTableValue( 14 , ( 0.255 , 0.255 , 0.914 ,1.0))
L1table.SetTableValue( 15 , ( 0.259 , 0.259 , 0.906 ,1.0))
L1table.SetTableValue( 16 , ( 0.267 , 0.267 , 0.902 ,1.0))
L1table.SetTableValue( 17 , ( 0.271 , 0.271 , 0.898 ,1.0))
L1table.SetTableValue( 18 , ( 0.278 , 0.278 , 0.894 ,1.0))
L1table.SetTableValue( 19 , ( 0.282 , 0.282 , 0.890 ,1.0))
L1table.SetTableValue( 20 , ( 0.290 , 0.290 , 0.886 ,1.0))
L1table.SetTableValue( 21 , ( 0.294 , 0.294 , 0.882 ,1.0))
L1table.SetTableValue( 22 , ( 0.298 , 0.298 , 0.882 ,1.0))
L1table.SetTableValue( 23 , ( 0.306 , 0.306 , 0.878 ,1.0))
L1table.SetTableValue( 24 , ( 0.310 , 0.310 , 0.875 ,1.0))
L1table.SetTableValue( 25 , ( 0.314 , 0.314 , 0.871 ,1.0))
L1table.SetTableValue( 26 , ( 0.318 , 0.318 , 0.867 ,1.0))
L1table.SetTableValue( 27 , ( 0.322 , 0.322 , 0.867 ,1.0))
L1table.SetTableValue( 28 , ( 0.329 , 0.329 , 0.863 ,1.0))
L1table.SetTableValue( 29 , ( 0.333 , 0.333 , 0.859 ,1.0))
L1table.SetTableValue( 30 , ( 0.337 , 0.337 , 0.855 ,1.0))
L1table.SetTableValue( 31 , ( 0.341 , 0.341 , 0.855 ,1.0))
L1table.SetTableValue( 32 , ( 0.345 , 0.345 , 0.851 ,1.0))
L1table.SetTableValue( 33 , ( 0.349 , 0.349 , 0.847 ,1.0))
L1table.SetTableValue( 34 , ( 0.353 , 0.353 , 0.847 ,1.0))
L1table.SetTableValue( 35 , ( 0.357 , 0.357 , 0.843 ,1.0))
L1table.SetTableValue( 36 , ( 0.361 , 0.361 , 0.839 ,1.0))
L1table.SetTableValue( 37 , ( 0.365 , 0.365 , 0.839 ,1.0))
L1table.SetTableValue( 38 , ( 0.369 , 0.369 , 0.835 ,1.0))
L1table.SetTableValue( 39 , ( 0.373 , 0.373 , 0.835 ,1.0))
L1table.SetTableValue( 40 , ( 0.376 , 0.376 , 0.831 ,1.0))
L1table.SetTableValue( 41 , ( 0.380 , 0.380 , 0.831 ,1.0))
L1table.SetTableValue( 42 , ( 0.384 , 0.384 , 0.827 ,1.0))
L1table.SetTableValue( 43 , ( 0.384 , 0.384 , 0.824 ,1.0))
L1table.SetTableValue( 44 , ( 0.388 , 0.388 , 0.824 ,1.0))
L1table.SetTableValue( 45 , ( 0.392 , 0.392 , 0.820 ,1.0))
L1table.SetTableValue( 46 , ( 0.396 , 0.396 , 0.820 ,1.0))
L1table.SetTableValue( 47 , ( 0.400 , 0.400 , 0.816 ,1.0))
L1table.SetTableValue( 48 , ( 0.404 , 0.404 , 0.816 ,1.0))
L1table.SetTableValue( 49 , ( 0.408 , 0.408 , 0.816 ,1.0))
L1table.SetTableValue( 50 , ( 0.412 , 0.412 , 0.812 ,1.0))
L1table.SetTableValue( 51 , ( 0.412 , 0.412 , 0.812 ,1.0))
L1table.SetTableValue( 52 , ( 0.416 , 0.416 , 0.808 ,1.0))
L1table.SetTableValue( 53 , ( 0.420 , 0.420 , 0.808 ,1.0))
L1table.SetTableValue( 54 , ( 0.424 , 0.424 , 0.804 ,1.0))
L1table.SetTableValue( 55 , ( 0.427 , 0.427 , 0.804 ,1.0))
L1table.SetTableValue( 56 , ( 0.431 , 0.431 , 0.800 ,1.0))
L1table.SetTableValue( 57 , ( 0.431 , 0.431 , 0.800 ,1.0))
L1table.SetTableValue( 58 , ( 0.435 , 0.435 , 0.800 ,1.0))
L1table.SetTableValue( 59 , ( 0.439 , 0.439 , 0.796 ,1.0))
L1table.SetTableValue( 60 , ( 0.443 , 0.443 , 0.796 ,1.0))
L1table.SetTableValue( 61 , ( 0.447 , 0.447 , 0.792 ,1.0))
L1table.SetTableValue( 62 , ( 0.447 , 0.447 , 0.792 ,1.0))
L1table.SetTableValue( 63 , ( 0.451 , 0.451 , 0.792 ,1.0))
L1table.SetTableValue( 64 , ( 0.455 , 0.455 , 0.788 ,1.0))
L1table.SetTableValue( 65 , ( 0.459 , 0.459 , 0.788 ,1.0))
L1table.SetTableValue( 66 , ( 0.463 , 0.463 , 0.784 ,1.0))
L1table.SetTableValue( 67 , ( 0.463 , 0.463 , 0.784 ,1.0))
L1table.SetTableValue( 68 , ( 0.467 , 0.467 , 0.784 ,1.0))
L1table.SetTableValue( 69 , ( 0.471 , 0.471 , 0.780 ,1.0))
L1table.SetTableValue( 70 , ( 0.475 , 0.475 , 0.780 ,1.0))
L1table.SetTableValue( 71 , ( 0.475 , 0.475 , 0.780 ,1.0))
L1table.SetTableValue( 72 , ( 0.478 , 0.478 , 0.776 ,1.0))
L1table.SetTableValue( 73 , ( 0.482 , 0.482 , 0.776 ,1.0))
L1table.SetTableValue( 74 , ( 0.486 , 0.486 , 0.776 ,1.0))
L1table.SetTableValue( 75 , ( 0.486 , 0.486 , 0.773 ,1.0))
L1table.SetTableValue( 76 , ( 0.490 , 0.490 , 0.773 ,1.0))
L1table.SetTableValue( 77 , ( 0.494 , 0.494 , 0.773 ,1.0))
L1table.SetTableValue( 78 , ( 0.498 , 0.498 , 0.769 ,1.0))
L1table.SetTableValue( 79 , ( 0.502 , 0.502 , 0.769 ,1.0))
L1table.SetTableValue( 80 , ( 0.502 , 0.502 , 0.765 ,1.0))
L1table.SetTableValue( 81 , ( 0.506 , 0.506 , 0.765 ,1.0))
L1table.SetTableValue( 82 , ( 0.510 , 0.510 , 0.765 ,1.0))
L1table.SetTableValue( 83 , ( 0.510 , 0.510 , 0.761 ,1.0))
L1table.SetTableValue( 84 , ( 0.514 , 0.514 , 0.761 ,1.0))
L1table.SetTableValue( 85 , ( 0.518 , 0.518 , 0.761 ,1.0))
L1table.SetTableValue( 86 , ( 0.522 , 0.522 , 0.757 ,1.0))
L1table.SetTableValue( 87 , ( 0.522 , 0.522 , 0.757 ,1.0))
L1table.SetTableValue( 88 , ( 0.525 , 0.525 , 0.757 ,1.0))
L1table.SetTableValue( 89 , ( 0.529 , 0.529 , 0.753 ,1.0))
L1table.SetTableValue( 90 , ( 0.533 , 0.533 , 0.753 ,1.0))
L1table.SetTableValue( 91 , ( 0.533 , 0.533 , 0.753 ,1.0))
L1table.SetTableValue( 92 , ( 0.537 , 0.537 , 0.749 ,1.0))
L1table.SetTableValue( 93 , ( 0.541 , 0.541 , 0.749 ,1.0))
L1table.SetTableValue( 94 , ( 0.545 , 0.545 , 0.749 ,1.0))
L1table.SetTableValue( 95 , ( 0.545 , 0.545 , 0.745 ,1.0))
L1table.SetTableValue( 96 , ( 0.549 , 0.549 , 0.745 ,1.0))
L1table.SetTableValue( 97 , ( 0.553 , 0.553 , 0.745 ,1.0))
L1table.SetTableValue( 98 , ( 0.557 , 0.557 , 0.741 ,1.0))
L1table.SetTableValue( 99 , ( 0.557 , 0.557 , 0.741 ,1.0))
L1table.SetTableValue( 100 , ( 0.561 , 0.561 , 0.741 ,1.0))
L1table.SetTableValue( 101 , ( 0.565 , 0.565 , 0.737 ,1.0))
L1table.SetTableValue( 102 , ( 0.565 , 0.565 , 0.737 ,1.0))
L1table.SetTableValue( 103 , ( 0.569 , 0.569 , 0.737 ,1.0))
L1table.SetTableValue( 104 , ( 0.573 , 0.573 , 0.733 ,1.0))
L1table.SetTableValue( 105 , ( 0.576 , 0.576 , 0.733 ,1.0))
L1table.SetTableValue( 106 , ( 0.576 , 0.576 , 0.733 ,1.0))
L1table.SetTableValue( 107 , ( 0.580 , 0.580 , 0.729 ,1.0))
L1table.SetTableValue( 108 , ( 0.584 , 0.584 , 0.729 ,1.0))
L1table.SetTableValue( 109 , ( 0.584 , 0.584 , 0.729 ,1.0))
L1table.SetTableValue( 110 , ( 0.588 , 0.588 , 0.725 ,1.0))
L1table.SetTableValue( 111 , ( 0.592 , 0.592 , 0.725 ,1.0))
L1table.SetTableValue( 112 , ( 0.596 , 0.596 , 0.725 ,1.0))
L1table.SetTableValue( 113 , ( 0.596 , 0.596 , 0.722 ,1.0))
L1table.SetTableValue( 114 , ( 0.600 , 0.600 , 0.722 ,1.0))
L1table.SetTableValue( 115 , ( 0.604 , 0.604 , 0.722 ,1.0))
L1table.SetTableValue( 116 , ( 0.604 , 0.604 , 0.718 ,1.0))
L1table.SetTableValue( 117 , ( 0.608 , 0.608 , 0.718 ,1.0))
L1table.SetTableValue( 118 , ( 0.612 , 0.612 , 0.714 ,1.0))
L1table.SetTableValue( 119 , ( 0.616 , 0.616 , 0.714 ,1.0))
L1table.SetTableValue( 120 , ( 0.616 , 0.616 , 0.714 ,1.0))
L1table.SetTableValue( 121 , ( 0.620 , 0.620 , 0.710 ,1.0))
L1table.SetTableValue( 122 , ( 0.624 , 0.624 , 0.710 ,1.0))
L1table.SetTableValue( 123 , ( 0.624 , 0.624 , 0.710 ,1.0))
L1table.SetTableValue( 124 , ( 0.627 , 0.627 , 0.706 ,1.0))
L1table.SetTableValue( 125 , ( 0.631 , 0.631 , 0.706 ,1.0))
L1table.SetTableValue( 126 , ( 0.635 , 0.635 , 0.706 ,1.0))
L1table.SetTableValue( 127 , ( 0.635 , 0.635 , 0.702 ,1.0))
L1table.SetTableValue( 128 , ( 0.639 , 0.639 , 0.702 ,1.0))
L1table.SetTableValue( 129 , ( 0.643 , 0.643 , 0.698 ,1.0))
L1table.SetTableValue( 130 , ( 0.643 , 0.643 , 0.698 ,1.0))
L1table.SetTableValue( 131 , ( 0.647 , 0.647 , 0.698 ,1.0))
L1table.SetTableValue( 132 , ( 0.651 , 0.651 , 0.694 ,1.0))
L1table.SetTableValue( 133 , ( 0.655 , 0.655 , 0.694 ,1.0))
L1table.SetTableValue( 134 , ( 0.655 , 0.655 , 0.690 ,1.0))
L1table.SetTableValue( 135 , ( 0.659 , 0.659 , 0.690 ,1.0))
L1table.SetTableValue( 136 , ( 0.663 , 0.663 , 0.690 ,1.0))
L1table.SetTableValue( 137 , ( 0.663 , 0.663 , 0.686 ,1.0))
L1table.SetTableValue( 138 , ( 0.667 , 0.667 , 0.686 ,1.0))
L1table.SetTableValue( 139 , ( 0.671 , 0.671 , 0.682 ,1.0))
L1table.SetTableValue( 140 , ( 0.675 , 0.675 , 0.682 ,1.0))
L1table.SetTableValue( 141 , ( 0.675 , 0.675 , 0.678 ,1.0))
L1table.SetTableValue( 142 , ( 0.678 , 0.678 , 0.678 ,1.0))
L1table.SetTableValue( 143 , ( 0.682 , 0.682 , 0.678 ,1.0))
L1table.SetTableValue( 144 , ( 0.682 , 0.682 , 0.675 ,1.0))
L1table.SetTableValue( 145 , ( 0.686 , 0.686 , 0.675 ,1.0))
L1table.SetTableValue( 146 , ( 0.690 , 0.690 , 0.671 ,1.0))
L1table.SetTableValue( 147 , ( 0.694 , 0.694 , 0.671 ,1.0))
L1table.SetTableValue( 148 , ( 0.694 , 0.694 , 0.667 ,1.0))
L1table.SetTableValue( 149 , ( 0.698 , 0.698 , 0.667 ,1.0))
L1table.SetTableValue( 150 , ( 0.702 , 0.702 , 0.663 ,1.0))
L1table.SetTableValue( 151 , ( 0.702 , 0.702 , 0.663 ,1.0))
L1table.SetTableValue( 152 , ( 0.706 , 0.706 , 0.659 ,1.0))
L1table.SetTableValue( 153 , ( 0.710 , 0.710 , 0.659 ,1.0))
L1table.SetTableValue( 154 , ( 0.710 , 0.710 , 0.655 ,1.0))
L1table.SetTableValue( 155 , ( 0.714 , 0.714 , 0.655 ,1.0))
L1table.SetTableValue( 156 , ( 0.718 , 0.718 , 0.651 ,1.0))
L1table.SetTableValue( 157 , ( 0.722 , 0.722 , 0.651 ,1.0))
L1table.SetTableValue( 158 , ( 0.722 , 0.722 , 0.647 ,1.0))
L1table.SetTableValue( 159 , ( 0.725 , 0.725 , 0.647 ,1.0))
L1table.SetTableValue( 160 , ( 0.729 , 0.729 , 0.643 ,1.0))
L1table.SetTableValue( 161 , ( 0.729 , 0.729 , 0.643 ,1.0))
L1table.SetTableValue( 162 , ( 0.733 , 0.733 , 0.639 ,1.0))
L1table.SetTableValue( 163 , ( 0.737 , 0.737 , 0.639 ,1.0))
L1table.SetTableValue( 164 , ( 0.741 , 0.741 , 0.635 ,1.0))
L1table.SetTableValue( 165 , ( 0.741 , 0.741 , 0.635 ,1.0))
L1table.SetTableValue( 166 , ( 0.745 , 0.745 , 0.631 ,1.0))
L1table.SetTableValue( 167 , ( 0.749 , 0.749 , 0.631 ,1.0))
L1table.SetTableValue( 168 , ( 0.749 , 0.749 , 0.627 ,1.0))
L1table.SetTableValue( 169 , ( 0.753 , 0.753 , 0.624 ,1.0))
L1table.SetTableValue( 170 , ( 0.757 , 0.757 , 0.624 ,1.0))
L1table.SetTableValue( 171 , ( 0.761 , 0.761 , 0.620 ,1.0))
L1table.SetTableValue( 172 , ( 0.761 , 0.761 , 0.620 ,1.0))
L1table.SetTableValue( 173 , ( 0.765 , 0.765 , 0.616 ,1.0))
L1table.SetTableValue( 174 , ( 0.769 , 0.769 , 0.616 ,1.0))
L1table.SetTableValue( 175 , ( 0.769 , 0.769 , 0.612 ,1.0))
L1table.SetTableValue( 176 , ( 0.773 , 0.773 , 0.608 ,1.0))
L1table.SetTableValue( 177 , ( 0.776 , 0.776 , 0.608 ,1.0))
L1table.SetTableValue( 178 , ( 0.780 , 0.780 , 0.604 ,1.0))
L1table.SetTableValue( 179 , ( 0.780 , 0.780 , 0.600 ,1.0))
L1table.SetTableValue( 180 , ( 0.784 , 0.784 , 0.600 ,1.0))
L1table.SetTableValue( 181 , ( 0.788 , 0.788 , 0.596 ,1.0))
L1table.SetTableValue( 182 , ( 0.788 , 0.788 , 0.592 ,1.0))
L1table.SetTableValue( 183 , ( 0.792 , 0.792 , 0.592 ,1.0))
L1table.SetTableValue( 184 , ( 0.796 , 0.796 , 0.588 ,1.0))
L1table.SetTableValue( 185 , ( 0.800 , 0.800 , 0.584 ,1.0))
L1table.SetTableValue( 186 , ( 0.800 , 0.800 , 0.584 ,1.0))
L1table.SetTableValue( 187 , ( 0.804 , 0.804 , 0.580 ,1.0))
L1table.SetTableValue( 188 , ( 0.808 , 0.808 , 0.576 ,1.0))
L1table.SetTableValue( 189 , ( 0.808 , 0.808 , 0.573 ,1.0))
L1table.SetTableValue( 190 , ( 0.812 , 0.812 , 0.573 ,1.0))
L1table.SetTableValue( 191 , ( 0.816 , 0.816 , 0.569 ,1.0))
L1table.SetTableValue( 192 , ( 0.820 , 0.820 , 0.565 ,1.0))
L1table.SetTableValue( 193 , ( 0.820 , 0.820 , 0.561 ,1.0))
L1table.SetTableValue( 194 , ( 0.824 , 0.824 , 0.561 ,1.0))
L1table.SetTableValue( 195 , ( 0.827 , 0.827 , 0.557 ,1.0))
L1table.SetTableValue( 196 , ( 0.827 , 0.827 , 0.553 ,1.0))
L1table.SetTableValue( 197 , ( 0.831 , 0.831 , 0.549 ,1.0))
L1table.SetTableValue( 198 , ( 0.835 , 0.835 , 0.545 ,1.0))
L1table.SetTableValue( 199 , ( 0.839 , 0.839 , 0.541 ,1.0))
L1table.SetTableValue( 200 , ( 0.839 , 0.839 , 0.541 ,1.0))
L1table.SetTableValue( 201 , ( 0.843 , 0.843 , 0.537 ,1.0))
L1table.SetTableValue( 202 , ( 0.847 , 0.847 , 0.533 ,1.0))
L1table.SetTableValue( 203 , ( 0.847 , 0.847 , 0.529 ,1.0))
L1table.SetTableValue( 204 , ( 0.851 , 0.851 , 0.525 ,1.0))
L1table.SetTableValue( 205 , ( 0.855 , 0.855 , 0.522 ,1.0))
L1table.SetTableValue( 206 , ( 0.859 , 0.859 , 0.518 ,1.0))
L1table.SetTableValue( 207 , ( 0.859 , 0.859 , 0.514 ,1.0))
L1table.SetTableValue( 208 , ( 0.863 , 0.863 , 0.510 ,1.0))
L1table.SetTableValue( 209 , ( 0.867 , 0.867 , 0.506 ,1.0))
L1table.SetTableValue( 210 , ( 0.867 , 0.867 , 0.502 ,1.0))
L1table.SetTableValue( 211 , ( 0.871 , 0.871 , 0.498 ,1.0))
L1table.SetTableValue( 212 , ( 0.875 , 0.875 , 0.494 ,1.0))
L1table.SetTableValue( 213 , ( 0.878 , 0.878 , 0.490 ,1.0))
L1table.SetTableValue( 214 , ( 0.878 , 0.878 , 0.486 ,1.0))
L1table.SetTableValue( 215 , ( 0.882 , 0.882 , 0.482 ,1.0))
L1table.SetTableValue( 216 , ( 0.886 , 0.886 , 0.478 ,1.0))
L1table.SetTableValue( 217 , ( 0.886 , 0.886 , 0.475 ,1.0))
L1table.SetTableValue( 218 , ( 0.890 , 0.890 , 0.467 ,1.0))
L1table.SetTableValue( 219 , ( 0.894 , 0.894 , 0.463 ,1.0))
L1table.SetTableValue( 220 , ( 0.898 , 0.898 , 0.459 ,1.0))
L1table.SetTableValue( 221 , ( 0.898 , 0.898 , 0.455 ,1.0))
L1table.SetTableValue( 222 , ( 0.902 , 0.902 , 0.447 ,1.0))
L1table.SetTableValue( 223 , ( 0.906 , 0.906 , 0.443 ,1.0))
L1table.SetTableValue( 224 , ( 0.910 , 0.910 , 0.439 ,1.0))
L1table.SetTableValue( 225 , ( 0.910 , 0.910 , 0.431 ,1.0))
L1table.SetTableValue( 226 , ( 0.914 , 0.914 , 0.427 ,1.0))
L1table.SetTableValue( 227 , ( 0.918 , 0.918 , 0.420 ,1.0))
L1table.SetTableValue( 228 , ( 0.918 , 0.918 , 0.416 ,1.0))
L1table.SetTableValue( 229 , ( 0.922 , 0.922 , 0.408 ,1.0))
L1table.SetTableValue( 230 , ( 0.925 , 0.925 , 0.404 ,1.0))
L1table.SetTableValue( 231 , ( 0.929 , 0.929 , 0.396 ,1.0))
L1table.SetTableValue( 232 , ( 0.929 , 0.929 , 0.392 ,1.0))
L1table.SetTableValue( 233 , ( 0.933 , 0.933 , 0.384 ,1.0))
L1table.SetTableValue( 234 , ( 0.937 , 0.937 , 0.376 ,1.0))
L1table.SetTableValue( 235 , ( 0.937 , 0.937 , 0.369 ,1.0))
L1table.SetTableValue( 236 , ( 0.941 , 0.941 , 0.361 ,1.0))
L1table.SetTableValue( 237 , ( 0.945 , 0.945 , 0.357 ,1.0))
L1table.SetTableValue( 238 , ( 0.949 , 0.949 , 0.349 ,1.0))
L1table.SetTableValue( 239 , ( 0.949 , 0.949 , 0.337 ,1.0))
L1table.SetTableValue( 240 , ( 0.953 , 0.953 , 0.329 ,1.0))
L1table.SetTableValue( 241 , ( 0.957 , 0.957 , 0.322 ,1.0))
L1table.SetTableValue( 242 , ( 0.961 , 0.961 , 0.314 ,1.0))
L1table.SetTableValue( 243 , ( 0.961 , 0.961 , 0.302 ,1.0))
L1table.SetTableValue( 244 , ( 0.965 , 0.965 , 0.290 ,1.0))
L1table.SetTableValue( 245 , ( 0.969 , 0.969 , 0.282 ,1.0))
L1table.SetTableValue( 246 , ( 0.969 , 0.969 , 0.271 ,1.0))
L1table.SetTableValue( 247 , ( 0.973 , 0.973 , 0.255 ,1.0))
L1table.SetTableValue( 248 , ( 0.976 , 0.976 , 0.243 ,1.0))
L1table.SetTableValue( 249 , ( 0.980 , 0.980 , 0.227 ,1.0))
L1table.SetTableValue( 250 , ( 0.980 , 0.980 , 0.212 ,1.0))
L1table.SetTableValue( 251 , ( 0.984 , 0.984 , 0.192 ,1.0))
L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.173 ,1.0))
L1table.SetTableValue( 253 , ( 0.992 , 0.992 , 0.145 ,1.0))
L1table.SetTableValue( 254 , ( 0.992 , 0.992 , 0.110 ,1.0))
L1table.SetTableValue( 255 , ( 0.996 , 0.996 , 0.051 ,1.0))
L1table.Build()
self.Linear_BlueToYellow[key] = L1table
return self.Linear_BlueToYellow[key]
| [
[
1,
0,
0.0071,
0.0012,
0,
0.66,
0,
665,
0,
1,
0,
0,
665,
0,
0
],
[
3,
0,
0.5035,
0.9894,
0,
0.66,
1,
18,
0,
5,
0,
0,
0,
0,
99
],
[
2,
1,
0.013,
0.0059,
1,
0.52,
... | [
"import vtk",
"class ColorScales():\n def __init__(self):\n self.BlueToYellow = {}\n self.Linear_Heat = {}\n self.Linear_BlackToWhite = {}\n self.Linear_BlueToYellow = {}\n\n def LUT_BlueToYellow(self, LUrange):",
" def __init__(self):\n self.BlueToYellow = {}\n ... |
# $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK classes have ErrorEvent handlers that report back to
the ModuleManager.
Inserts the following modules in sys.modules: vtk, vtkdevide.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import traceback
import types
VERSION = ''
def preImportVTK(progressMethod):
vtkImportList = [('vtk.common', 'VTK Common.'),
('vtk.filtering', 'VTK Filtering.'),
('vtk.io', 'VTK IO.'),
('vtk.imaging', 'VTK Imaging.'),
('vtk.graphics', 'VTK Graphics.'),
('vtk.rendering', 'VTK Rendering.'),
('vtk.hybrid', 'VTK Hybrid.'),
#('vtk.patented', 'VTK Patented.'),
('vtk', 'Other VTK symbols')]
# set the dynamic loading flags. If we don't do this, we get strange
# errors on 64 bit machines. To see this happen, comment this statement
# and then run the VTK->ITK connection test case.
oldflags = setDLFlags()
percentStep = 100.0 / len(vtkImportList)
currentPercent = 0.0
# do the imports
for module, message in vtkImportList:
currentPercent += percentStep
progressMethod(currentPercent, 'Initialising vtk_kit: %s' % (message,),
noTime=True)
exec('import %s' % (module,))
# restore previous dynamic loading flags
resetDLFlags(oldflags)
def setDLFlags():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols when
# importing a module, if called as sys.setdlopenflags(0) To share
# symbols across extension modules, call as
#
# sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
#
# GCC 3.x depends on proper merging of symbols for RTTI:
# http://gcc.gnu.org/faq.html#dso
#
try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(module_manager, pre_import=True):
# first do the VTK pre-imports: this is here ONLY to keep the user happy
# it's not necessary for normal functioning
if pre_import:
preImportVTK(module_manager.setProgress)
# import the main module itself
# the global is so that users can also do:
# from module_kits import vtk_kit
# vtk_kit.vtk.vtkSomeFilter()
global vtk
import vtk
# and do the same for vtkdevide
global vtkdevide
import vtkdevide
# load up some generic functions into this namespace
# user can, after import of module_kits.vtk_kit, address these as
# module_kits.vtk_kit.blaat. In this case we don't need "global",
# as these are modules directly in this package.
import module_kits.vtk_kit.misc as misc
import module_kits.vtk_kit.mixins as mixins
import module_kits.vtk_kit.utils as utils
import module_kits.vtk_kit.constants as constants
import module_kits.vtk_kit.color_scales as color_scales
# setup the kit version
global VERSION
VERSION = '%s' % (vtk.vtkVersion.GetVTKVersion(),)
| [
[
8,
0,
0.0906,
0.0787,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1417,
0.0079,
0,
0.66,
0.1111,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.1496,
0.0079,
0,
0.66... | [
"\"\"\"vtk_kit package driver file.\n\nThis performs all initialisation necessary to use VTK from DeVIDE. Makes\nsure that all VTK classes have ErrorEvent handlers that report back to\nthe ModuleManager.\n\nInserts the following modules in sys.modules: vtk, vtkdevide.",
"import re",
"import sys",
"import tra... |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""numpy_kit package driver file.
Inserts the following modules in sys.modules: numpy.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
theModuleManager.setProgress(5, 'Initialising numpy_kit: start')
# import numpy into the global namespace
global numpy
import numpy
# we add this so that modules using "import Numeric" will probably also
# work (such as the FloatCanvas)
sys.modules['Numeric'] = numpy
sys.modules['numarray'] = numpy
theModuleManager.setProgress(95, 'Initialising numpy_kit: import done')
# build up VERSION
global VERSION
VERSION = '%s' % (numpy.version.version,)
theModuleManager.setProgress(100, 'Initialising numpy_kit: complete')
| [
[
8,
0,
0.2209,
0.1395,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3256,
0.0233,
0,
0.66,
0.1667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3488,
0.0233,
0,
0.66... | [
"\"\"\"numpy_kit package driver file.\n\nInserts the following modules in sys.modules: numpy.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import os",
"import re",
"import sys",
"import types",
"VERSION = ''",
"def init(theModuleManager, pre_import=True):\n theModuleManager.setProgress... |
import math
import numpy
epsilon = 1e-12
def abs(v1):
return numpy.absolute(v1)
def norm(v1):
"""Given vector v1, return its norm.
"""
v1a = numpy.array(v1)
norm = numpy.sqrt(numpy.sum(v1a * v1a))
return norm
def normalise_line(p1, p2):
"""Given two points, return normal vector, magnitude and original
line vector.
Example: normal_vec, mag, line_vec = normalize_line(p1_tuple, p2_tuple)
"""
line_vector = numpy.array(p2) - numpy.array(p1)
squared_norm = numpy.sum(line_vector * line_vector)
norm = numpy.sqrt(squared_norm)
if norm != 0.0:
unit_vec = line_vector / norm
else:
unit_vec = line_vector
return (unit_vec, norm, line_vector)
def points_to_vector(p1, p2):
v = numpy.array(p2) - numpy.array(p1)
return v
def dot(v1, v2):
"""Return dot-product between vectors v1 and v2.
"""
dot_product = numpy.sum(numpy.array(v1) * numpy.array(v2))
return dot_product
def move_line_to_target_along_normal(p1, p2, n, target):
"""Move the line (p1,p2) along normal vector n until it intersects
with target.
@returns: Adjusted p1,p2
"""
# n has to be a normal vector, mmmkay?
if norm(n) - 1.0 > epsilon:
raise RuntimeError('normal vector not unit size.')
p1a = numpy.array(p1)
p2a = numpy.array(p2)
ta = numpy.array(target)
# see how far p2a is from ta measured along n
dp = dot(p2a - ta, n)
# better to use an epsilon?
if numpy.absolute(dp) > epsilon:
# calculate vector needed to correct along n
dvec = - dp * n
p1a = p1a + dvec
p2a = p2a + dvec
return (p1a, p2a)
def intersect_line_sphere(p1, p2, sc, r):
"""Calculates intersection between line going through p1 and p2 and
sphere determined by centre sc and radius r.
Requires numpy.
@param p1: tuple, or 1D matrix, or 1D array with first point defining line.
@param p2: tuple, or 1D matrix, or 1D array with second point defining line.
See http://local.wasp.uwa.edu.au/~pbourke/geometry/sphereline/source.cpp
"""
# a is squared distance between the two points defining line
p_diff = numpy.array(p2) - numpy.array(p1)
a = numpy.sum(numpy.multiply(p_diff, p_diff))
b = 2 * ( (p2[0] - p1[0]) * (p1[0] - sc[0]) + \
(p2[1] - p1[1]) * (p1[1] - sc[1]) + \
(p2[2] - p1[2]) * (p1[2] - sc[2]) )
c = sc[0] ** 2 + sc[1] ** 2 + \
sc[2] ** 2 + p1[0] ** 2 + \
p1[1] ** 2 + p1[2] ** 2 - \
2 * (sc[0] * p1[0] + sc[1] * p1[1] + sc[2]*p1[2]) - r ** 2
i = b * b - 4 * a * c
if (i < 0.0):
# no intersections
return []
if (i == 0.0):
# one intersection
mu = -b / (2 * a)
return [ (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2])) ]
if (i > 0.0):
# two intersections
mu = (-b + math.sqrt( b ** 2 - 4*a*c )) / (2*a)
i1 = (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2]))
mu = (-b - math.sqrt( b ** 2 - 4*a*c )) / (2*a)
i2 = (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2]))
# in the case of two intersections, we want to make sure
# that the vector i1,i2 has the same orientation as vector p1,p2
i_diff = numpy.array(i2) - numpy.array(i1)
if numpy.dot(p_diff, i_diff) < 0:
return [i2, i1]
else:
return [i1, i2]
def intersect_line_ellipsoid(p1, p2, ec, radius_vectors):
"""Determine intersection points between line defined by p1 and p2,
and ellipsoid defined by centre ec and three radius vectors (tuple
of tuples, each inner tuple is a radius vector).
This requires numpy.
"""
# create transformation matrix that has the radius_vectors
# as its columns (hence the transpose)
rv = numpy.transpose(numpy.matrix(radius_vectors))
# calculate its inverse
rv_inv = numpy.linalg.pinv(rv)
# now transform the two points
# all points have to be relative to ellipsoid centre
# the [0] at the end and the numpy.array at the start is to make sure
# we pass a row vector (array) to the line_sphere_intersection
p1_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p1) - numpy.array(ec)))[0]
p2_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p2) - numpy.array(ec)))[0]
# now we only have to determine the intersection between the points
# (now transformed to ellipsoid space) with the unit sphere centred at 0
isects_e = intersect_line_sphere(p1_e, p2_e, (0.0,0.0,0.0), 1.0)
# transform intersections back to "normal" space
isects = []
for i in isects_e:
# numpy.array(...)[0] is for returning only row of matrix as array
itemp = numpy.array(numpy.matrixmultiply(rv, numpy.array(i)))[0]
isects.append(itemp + numpy.array(ec))
return isects
def intersect_line_mask(p1, p2, mask, incr):
"""Calculate FIRST intersection of line (p1,p2) with mask, as we walk
from p1 to p2 with increments == incr.
"""
p1 = numpy.array(p1)
p2 = numpy.array(p2)
origin = numpy.array(mask.GetOrigin())
spacing = numpy.array(mask.GetSpacing())
incr = float(incr)
line_vector = p2 - p1
squared_norm = numpy.sum(line_vector * line_vector)
norm = numpy.sqrt(squared_norm)
unit_vec = line_vector / norm
curp = p1
intersect = False
end_of_line = False
i_point = numpy.array((), float) # empty array
while not intersect and not end_of_line:
# get voxel coords
voxc = (curp - origin) / spacing
e = mask.GetExtent()
if voxc[0] >= e[0] and voxc[0] <= e[1] and \
voxc[1] >= e[2] and voxc[1] <= e[3] and \
voxc[2] >= e[4] and voxc[2] <= e[5]:
val = mask.GetScalarComponentAsDouble(
voxc[0], voxc[1], voxc[2], 0)
else:
val = 0.0
if val > 0.0:
intersect = True
i_point = curp
else:
curp = curp + unit_vec * incr
cur_squared_norm = numpy.sum(numpy.square(curp - p1))
if cur_squared_norm > squared_norm:
end_of_line = True
if end_of_line:
return None
else:
return i_point
| [
[
1,
0,
0.0046,
0.0046,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.0091,
0.0046,
0,
0.66,
0.0909,
954,
0,
1,
0,
0,
954,
0,
0
],
[
14,
0,
0.0183,
0.0046,
0,
... | [
"import math",
"import numpy",
"epsilon = 1e-12",
"def abs(v1):\n return numpy.absolute(v1)",
" return numpy.absolute(v1)",
"def norm(v1):\n \"\"\"Given vector v1, return its norm.\n \"\"\"\n\n v1a = numpy.array(v1)\n norm = numpy.sqrt(numpy.sum(v1a * v1a))\n return norm",
" \"\"... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""geometry_kit package driver file.
Inserts the following modules in sys.modules: geometry.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import sys
# you have to define this
VERSION = 'INTEGRATED'
def init(module_manager, pre_import=True):
global geometry
import geometry
# if we don't do this, the module will be in sys.modules as
# module_kits.stats_kit.stats because it's not in the sys.path.
# iow. if a module is in sys.path, "import module" will put 'module' in
# sys.modules. if a module isn't, "import module" will put
# 'relative.path.to.module' in sys.path.
sys.modules['geometry'] = geometry
module_manager.set_progress(100, 'Initialising geometry_kit: complete.')
def refresh():
# we have none of our own packages yet...
global geometry
reload(geometry)
| [
[
8,
0,
0.2875,
0.15,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4,
0.025,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.475,
0.025,
0,
0.66,
0.5... | [
"\"\"\"geometry_kit package driver file.\n\nInserts the following modules in sys.modules: geometry.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import sys",
"VERSION = 'INTEGRATED'",
"def init(module_manager, pre_import=True):\n global geometry\n import geometry\n\n # if we don't do t... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
"""sqlite_kit package driver file.
With this we make sure that sqlite3 is always packaged.
"""
VERSION = ''
def init(module_manager, pre_import=True):
global sqlite3
import sqlite3
global VERSION
VERSION = '%s (sqlite %s)' % (sqlite3.version,
sqlite3.sqlite_version)
| [
[
8,
0,
0.3421,
0.2105,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5263,
0.0526,
0,
0.66,
0.5,
557,
1,
0,
0,
0,
0,
3,
0
],
[
2,
0,
0.7895,
0.3684,
0,
0.66,
... | [
"\"\"\"sqlite_kit package driver file.\n\nWith this we make sure that sqlite3 is always packaged.\n\"\"\"",
"VERSION = ''",
"def init(module_manager, pre_import=True):\n global sqlite3\n import sqlite3\n\n global VERSION\n VERSION = '%s (sqlite %s)' % (sqlite3.version,\n sqlite3.sqlite_ve... |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtktudoss_kit package driver file.
Inserts the following modules in sys.modules: vtktudoss.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import types
# you have to define this
VERSION = 'SVN'
def init(theModuleManager, pre_import=True):
# import the main module itself
import vtktudoss
# I added the version variable on 20070802
try:
global VERSION
VERSION = vtktudoss.version
except AttributeError:
pass
theModuleManager.setProgress(100, 'Initialising vtktudoss_kit')
| [
[
8,
0,
0.2879,
0.1818,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4242,
0.0303,
0,
0.66,
0.2,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.4545,
0.0303,
0,
0.66,
... | [
"\"\"\"vtktudoss_kit package driver file.\n\nInserts the following modules in sys.modules: vtktudoss.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import re",
"import sys",
"import types",
"VERSION = 'SVN'",
"def init(theModuleManager, pre_import=True):\n # import the main module itself\... |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""itktudoss_kit package driver file.
This driver makes sure that itktudoss has been integrated with the main WrapITK
instalation.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import re
import sys
import types
# you have to define this
VERSION = 'SVN'
def init(theModuleManager, pre_import=True):
theModuleManager.setProgress(80, 'Initialising itktudoss_kit: TPGAC')
import itk # this will have been pre-imported by the itk_kit
a = itk.TPGACLevelSetImageFilter
theModuleManager.setProgress(100, 'Initialising itktudoss_kit: DONE')
| [
[
8,
0,
0.3704,
0.2593,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5556,
0.037,
0,
0.66,
0.2,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.5926,
0.037,
0,
0.66,
... | [
"\"\"\"itktudoss_kit package driver file.\n\nThis driver makes sure that itktudoss has been integrated with the main WrapITK\ninstalation.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import re",
"import sys",
"import types",
"VERSION = 'SVN'",
"def init(theModuleManager, pre_import=True):\... |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""stats_kit package driver file.
Inserts the following modules in sys.modules: stats.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import sys
# you have to define this
VERSION = 'Strangman - May 10, 2002'
def init(theModuleManager, pre_import=True):
# import the main module itself
global stats
import stats
# if we don't do this, the module will be in sys.modules as
# module_kits.stats_kit.stats because it's not in the sys.path.
# iow. if a module is in sys.path, "import module" will put 'module' in
# sys.modules. if a module isn't, "import module" will put
# 'relative.path.to.module' in sys.path.
sys.modules['stats'] = stats
theModuleManager.setProgress(100, 'Initialising stats_kit: complete.')
def refresh():
reload(stats)
| [
[
8,
0,
0.2714,
0.1714,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4,
0.0286,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4857,
0.0286,
0,
0.66,
... | [
"\"\"\"stats_kit package driver file.\n\nInserts the following modules in sys.modules: stats.\n\n@author: Charl P. Botha <http://cpbotha.net/>\n\"\"\"",
"import sys",
"VERSION = 'Strangman - May 10, 2002'",
"def init(theModuleManager, pre_import=True):\n # import the main module itself\n global stats\n ... |
# $Id: module_index.py 2790 2008-02-29 08:33:14Z cpbotha $
class emp_test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = \
"""Module to test DeVIDE extra-module-paths functionality.
"""
| [
[
3,
0,
0.4615,
0.5385,
0,
0.66,
0,
657,
0,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.3077,
0.0769,
1,
0.79,
0,
190,
0,
0,
0,
0,
0,
5,
0
],
[
14,
1,
0.3846,
0.0769,
1,
0.79,
... | [
"class emp_test:\n kits = ['vtk_kit']\n cats = ['Tests']\n keywords = ['test', 'tests', 'testing']\n help = \\\n \"\"\"Module to test DeVIDE extra-module-paths functionality.\n \"\"\"",
" kits = ['vtk_kit']",
" cats = ['Tests']",
" keywords = ['test', 'tests', 'testing']",
" he... |
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class emp_test(SimpleVTKClassModuleBase):
"""This is the minimum you need to wrap a single VTK object. This
__doc__ string will be replaced by the __doc__ string of the encapsulated
VTK object, i.e. vtkStripper in this case.
With these few lines, we have error handling, progress reporting, module
help and also: the complete state of the underlying VTK object is also
pickled, i.e. when you save and restore a network, any changes you've
made to the vtkObject will be restored.
"""
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkStripper(), 'Stripping polydata.',
('vtkPolyData',), ('Stripped vtkPolyData',))
| [
[
1,
0,
0.0455,
0.0455,
0,
0.66,
0,
67,
0,
1,
0,
0,
67,
0,
0
],
[
1,
0,
0.0909,
0.0455,
0,
0.66,
0.5,
665,
0,
1,
0,
0,
665,
0,
0
],
[
3,
0,
0.5227,
0.7273,
0,
0.66,... | [
"from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase",
"import vtk",
"class emp_test(SimpleVTKClassModuleBase):\n \"\"\"This is the minimum you need to wrap a single VTK object. This\n __doc__ string will be replaced by the __doc__ string of the encapsulated\n VTK object, i.e. vtkStripper ... |
"""Module to test basic matplotlib functionality.
"""
import os
import unittest
import tempfile
class MPLTest(unittest.TestCase):
def test_figure_output(self):
"""Test if matplotlib figure can be generated and wrote to disc.
"""
# make sure the pythonshell is running
self._devide_app.get_interface()._handler_menu_python_shell(None)
# create new figure
python_shell = self._devide_app.get_interface()._python_shell
f = python_shell.mpl_new_figure()
import pylab
# unfortunately, it's almost impossible to get pixel-identical
# rendering on all platforms, so we can only check that the plot
# itself is correct (all font-rendering is disabled)
# make sure we hardcode the font! (previous experiment)
#pylab.rcParams['font.sans-serif'] = ['Bitstream Vera Sans']
#pylab.rc('font', family='sans-serif')
from pylab import arange, plot, sin, cos, legend, grid, xlabel, ylabel
a = arange(-30, 30, 0.01)
plot(a, sin(a) / a, label='sinc(x)')
plot(a, cos(a), label='cos(x)')
#legend()
grid()
#xlabel('x')
#ylabel('f(x)')
# disable x and y ticks (no fonts allowed, remember)
pylab.xticks([])
pylab.yticks([])
# width and height in inches
f.set_figwidth(7.9)
f.set_figheight(5.28)
# and save it to disc
filename1 = tempfile.mktemp(suffix='.png', prefix='tmp', dir=None)
f.savefig(filename1, dpi=100)
# get rid of the figure
python_shell.mpl_close_figure(f)
# now compare the bugger
test_fn = os.path.join(self._devide_testing.get_images_dir(),
'mpl_test_figure_output.png')
err = self._devide_testing.compare_png_images(test_fn, filename1)
self.failUnless(err == 0, '%s differs from %s, err = %.2f' %
(filename1, test_fn, err))
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
# both of these tests require wx
mm = devide_app.get_module_manager()
mpl_suite = unittest.TestSuite()
if 'matplotlib_kit' in mm.module_kits.module_kit_list:
t = MPLTest('test_figure_output')
t._devide_app = devide_app
t._devide_testing = devide_testing
mpl_suite.addTest(t)
return mpl_suite
| [
[
8,
0,
0.0185,
0.0247,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0617,
0.0123,
0,
0.66,
... | [
"\"\"\"Module to test basic matplotlib functionality.\n\"\"\"",
"import os",
"import unittest",
"import tempfile",
"class MPLTest(unittest.TestCase):\n def test_figure_output(self):\n \"\"\"Test if matplotlib figure can be generated and wrote to disc.\n \"\"\"\n\n # make sure the pyt... |
"""Module to test basic DeVIDE functionality.
"""
import unittest
class BasicMiscTest(unittest.TestCase):
def test_sqlite3(self):
"""Test if sqlite3 is available.
"""
import sqlite3
v = sqlite3.version
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('create table stuff (some text)')
cur.execute('insert into stuff values (?)', (v,))
cur.close()
cur = conn.cursor()
cur.execute('select some from stuff')
# cur.fetchall() returns a list of tuples: we get the first
# item in the list, then the first element in that tuple, this
# should be the version we inserted.
self.failUnless(cur.fetchall()[0][0] == v)
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
mm = devide_app.get_module_manager()
misc_suite = unittest.TestSuite()
t = BasicMiscTest('test_sqlite3')
misc_suite.addTest(t)
return misc_suite
| [
[
8,
0,
0.0357,
0.0476,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0.3333,
88,
0,
1,
0,
0,
88,
0,
0
],
[
3,
0,
0.381,
0.5,
0,
0.66,
... | [
"\"\"\"Module to test basic DeVIDE functionality.\n\"\"\"",
"import unittest",
"class BasicMiscTest(unittest.TestCase):\n def test_sqlite3(self):\n \"\"\"Test if sqlite3 is available.\n \"\"\"\n\n import sqlite3\n \n v = sqlite3.version",
" def test_sqlite3(self):\n ... |
# testing.__init__.py copyright 2006 by Charl P. Botha http://cpbotha.net/
# $Id$
# this drives the devide unit testing. neat huh?
import os
import time
import unittest
from testing import misc
from testing import basic_vtk
from testing import basic_wx
from testing import graph_editor
from testing import numpy_tests
from testing import matplotlib_tests
module_list = [misc, basic_vtk, basic_wx, graph_editor,
numpy_tests, matplotlib_tests]
for m in module_list:
reload(m)
# ----------------------------------------------------------------------------
class DeVIDETesting:
def __init__(self, devide_app):
self.devide_app = devide_app
suite_list = [misc.get_suite(self),
basic_vtk.get_suite(self),
basic_wx.get_suite(self),
graph_editor.get_suite(self),
numpy_tests.get_suite(self),
matplotlib_tests.get_suite(self)
]
self.main_suite = unittest.TestSuite(tuple(suite_list))
def runAllTests(self):
runner = unittest.TextTestRunner(verbosity=2)
runner.run(self.main_suite)
print "Complete suite consists of 19 (multi-part) tests on "
print "lin32, lin64, win32, win64."
def runSomeTest(self):
#some_suite = misc.get_suite(self)
#some_suite = basic_vtk.get_suite(self)
#some_suite = basic_wx.get_suite(self)
some_suite = graph_editor.get_some_suite(self)
#some_suite = numpy_tests.get_suite(self)
#some_suite = matplotlib_tests.get_suite(self)
runner = unittest.TextTestRunner()
runner.run(some_suite)
def get_images_dir(self):
"""Return full path of directory with test images.
"""
return os.path.join(os.path.dirname(__file__), 'images')
def get_networks_dir(self):
"""Return full path of directory with test networks.
"""
return os.path.join(os.path.dirname(__file__), 'networks')
def compare_png_images(self, image1_filename, image2_filename,
threshold=16, allow_shift=False):
"""Compare two PNG images on disc. No two pixels may differ with more
than the default threshold.
"""
import vtk
r1 = vtk.vtkPNGReader()
r1.SetFileName(image1_filename)
r1.Update()
r2 = vtk.vtkPNGReader()
r2.SetFileName(image2_filename)
r2.Update()
# there's a bug in VTK 5.0.1 where input images of unequal size
# (depending on which input is larger) will cause a segfault
# see http://www.vtk.org/Bug/bug.php?op=show&bugid=3586
# se we check for that situation and bail if it's the case
if r1.GetOutput().GetDimensions() != r2.GetOutput().GetDimensions():
em = 'Input images %s and %s are not of equal size.' % \
(image1_filename, image2_filename)
raise RuntimeError, em
# sometimes PNG files have an ALPHA component we have to chuck away
# do this for both images
ec1 = vtk.vtkImageExtractComponents()
ec1.SetComponents(0,1,2)
ec1.SetInput(r1.GetOutput())
ec2 = vtk.vtkImageExtractComponents()
ec2.SetComponents(0,1,2)
ec2.SetInput(r2.GetOutput())
idiff = vtk.vtkImageDifference()
idiff.SetThreshold(threshold)
if allow_shift:
idiff.AllowShiftOn()
else:
idiff.AllowShiftOff()
idiff.SetImage(ec1.GetOutput())
idiff.SetInputConnection(ec2.GetOutputPort())
idiff.Update()
return idiff.GetThresholdedError()
| [
[
1,
0,
0.042,
0.0084,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0504,
0.0084,
0,
0.66,
0.0909,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0588,
0.0084,
0,
0... | [
"import os",
"import time",
"import unittest",
"from testing import misc",
"from testing import basic_vtk",
"from testing import basic_wx",
"from testing import graph_editor",
"from testing import numpy_tests",
"from testing import matplotlib_tests",
"module_list = [misc, basic_vtk, basic_wx, grap... |
"""Module to test basic DeVIDE functionality.
"""
import unittest
class PythonShellTest(unittest.TestCase):
def test_python_shell(self):
"""Test if PythonShell can be opened successfully.
"""
iface = self._devide_app.get_interface()
iface._handler_menu_python_shell(None)
self.failUnless(iface._python_shell._frame.IsShown())
iface._python_shell._frame.Show(False)
class HelpContentsTest(unittest.TestCase):
def test_help_contents(self):
"""Test if Help Contents can be opened successfully.
"""
import webbrowser
try:
self._devide_app.get_interface()._handlerHelpContents(None)
except webbrowser.Error:
self.fail()
def get_suite(devide_testing):
devide_app = devide_testing.devide_app
# both of these tests require wx
mm = devide_app.get_module_manager()
basic_suite = unittest.TestSuite()
if 'wx_kit' in mm.module_kits.module_kit_list:
t = PythonShellTest('test_python_shell')
t._devide_app = devide_app
basic_suite.addTest(t)
t = HelpContentsTest('test_help_contents')
t._devide_app = devide_app
basic_suite.addTest(t)
return basic_suite
| [
[
8,
0,
0.0312,
0.0417,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0833,
0.0208,
0,
0.66,
0.25,
88,
0,
1,
0,
0,
88,
0,
0
],
[
3,
0,
0.1979,
0.1667,
0,
0.66,
... | [
"\"\"\"Module to test basic DeVIDE functionality.\n\"\"\"",
"import unittest",
"class PythonShellTest(unittest.TestCase):\n def test_python_shell(self):\n \"\"\"Test if PythonShell can be opened successfully.\n \"\"\"\n iface = self._devide_app.get_interface()\n iface._handler_men... |
hiddenimports = ['matplotlib.numerix',
'matplotlib.numerix.fft',
'matplotlib.numerix.linear_algebra',
'matplotlib.numerix.ma',
'matplotlib.numerix.mlab',
'matplotlib.numerix.npyma',
'matplotlib.numerix.random_array',
'matplotlib.backends.backend_wxagg']
print "[*] hook-matplotlib.py - HIDDENIMPORTS"
print hiddenimports
| [
[
14,
0,
0.4091,
0.7273,
0,
0.66,
0,
892,
0,
0,
0,
0,
0,
5,
0
],
[
8,
0,
0.9091,
0.0909,
0,
0.66,
0.5,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.0909,
0,
0.66,
1... | [
"hiddenimports = ['matplotlib.numerix', \n 'matplotlib.numerix.fft',\n 'matplotlib.numerix.linear_algebra',\n 'matplotlib.numerix.ma',\n 'matplotlib.numerix.mlab',\n 'matplotlib.numerix.npyma',\n 'matplotlib.numerix.random_array',\n 'matplotlib.backends.backend_wxagg... |
# this hook is responsible for including everything that the DeVIDE
# modules could need. The top-level spec file explicitly excludes
# them.
import os
import sys
# normalize path of this file, get dirname
hookDir = os.path.dirname(os.path.normpath(__file__))
# split dirname, select everything except the ending "installer/hooks"
dd = hookDir.split(os.sep)[0:-2]
# we have to do this trick, since on windows os.path.join('c:', 'blaat')
# yields 'c:blaat', i.e. relative to current dir, and we know it's absolute
dd[0] = '%s%s' % (dd[0], os.sep)
# turn that into a path again by making use of join (the normpath will take
# care of redundant slashes on *ix due to the above windows trick)
devideDir = os.path.normpath(os.path.join(*dd))
# now we've inserted the devideDir into the module path, so
# import modules should work
sys.path.insert(0, devideDir)
import module_kits
# now also parse config file
import ConfigParser
config_defaults = {'nokits': ''}
cp = ConfigParser.ConfigParser(config_defaults)
cp.read(os.path.join(devideDir, 'devide.cfg'))
nokits = [i.strip() for i in cp.get('DEFAULT', 'nokits').split(',')]
module_kits_dir = os.path.join(devideDir, 'module_kits')
mkds = module_kits.get_sorted_mkds(module_kits_dir)
# 1. remove the no_kits
# 2. explicitly remove itk_kit, it's handled completely separately by
# the makePackage.sh script file
mkl = [i.name for i in mkds if i.name not in nokits and i.name not in
['itk_kit','itktudoss_kit']]
# other imports
other_imports = ['genMixins', 'gen_utils', 'ModuleBase', 'module_mixins',
'module_utils',
'modules.viewers.DICOMBrowser',
'modules.viewers.slice3dVWR',
'modules.viewers.histogram1D',
'modules.viewers.TransferFunctionEditor']
# seems on Linux we have to make sure readline comes along (else
# vtkObject introspection windows complain)
try:
import readline
except ImportError:
pass
else:
other_imports.append('readline')
hiddenimports = ['module_kits.%s' % (i,) for i in mkl] + other_imports
print "[*] hook-ModuleManager.py - HIDDENIMPORTS"
print hiddenimports
| [
[
1,
0,
0.0806,
0.0161,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0968,
0.0161,
0,
0.66,
0.05,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.1452,
0.0161,
0,
0... | [
"import os",
"import sys",
"hookDir = os.path.dirname(os.path.normpath(__file__))",
"dd = hookDir.split(os.sep)[0:-2]",
"dd[0] = '%s%s' % (dd[0], os.sep)",
"devideDir = os.path.normpath(os.path.join(*dd))",
"sys.path.insert(0, devideDir)",
"import module_kits",
"import ConfigParser",
"config_defau... |
# so vtktudoss.py uses a list of names to construct the various imports
# at runtime, installer doesn't see this. :(
import os
if os.name == 'posix':
hiddenimports = [
'libvtktudossGraphicsPython',
'libvtktudossWidgetsPython',
'libvtktudossSTLibPython']
else:
hiddenimports = [
'vtktudossGraphicsPython',
'vtktudossWidgetsPython',
'vtktudossSTLibPython']
print "[*] hook-vtktudoss.py - HIDDENIMPORTS"
print hiddenimports
| [
[
1,
0,
0.2222,
0.0556,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
4,
0,
0.5833,
0.5556,
0,
0.66,
0.3333,
0,
0,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.4722,
0.2222,
1,
0.9... | [
"import os",
"if os.name == 'posix':\n hiddenimports = [\n 'libvtktudossGraphicsPython',\n 'libvtktudossWidgetsPython',\n 'libvtktudossSTLibPython']\nelse:\n hiddenimports = [\n 'vtktudossGraphicsPython',",
" hiddenimports = [\n 'libvtktudossGraphi... |
# miscellaneous imports used by snippets
hiddenimports = ['tempfile']
| [
[
14,
0,
1,
0.3333,
0,
0.66,
0,
892,
0,
0,
0,
0,
0,
5,
0
]
] | [
"hiddenimports = ['tempfile']"
] |
hiddenimports = ['wx.aui', 'wx.lib.mixins']
print "[*] hook-wx.py - HIDDENIMPORTS"
print hiddenimports
| [
[
14,
0,
0.25,
0.25,
0,
0.66,
0,
892,
0,
0,
0,
0,
0,
5,
0
],
[
8,
0,
0.75,
0.25,
0,
0.66,
0.5,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.25,
0,
0.66,
1,
535,... | [
"hiddenimports = ['wx.aui', 'wx.lib.mixins']",
"print(\"[*] hook-wx.py - HIDDENIMPORTS\")",
"print(hiddenimports)"
] |
# so vtktud.py uses a list of names to construct the various imports
# at runtime, installer doesn't see this. :(
import os
if os.name == 'posix':
hiddenimports = ['libvtktudCommonPython',
'libvtktudImagingPython', 'libvtktudGraphicsPython',
'libvtktudWidgetsPython']
else:
hiddenimports = ['vtktudCommonPython',
'vtktudImagingPython', 'vtktudGraphicsPython',
'vtktudWidgetsPython']
print "[*] hook-vtktud.py - HIDDENIMPORTS"
print hiddenimports
| [
[
1,
0,
0.25,
0.0625,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
4,
0,
0.5938,
0.5,
0,
0.66,
0.3333,
0,
0,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.5,
0.1875,
1,
0.75,
0... | [
"import os",
"if os.name == 'posix':\n hiddenimports = ['libvtktudCommonPython',\n 'libvtktudImagingPython', 'libvtktudGraphicsPython',\n 'libvtktudWidgetsPython']\nelse:\n hiddenimports = ['vtktudCommonPython',\n 'vtktudImagingPython', 'vtktudGraphicsPython',\n '... |
"""Module for independently packaging up whole WrapITK tree.
"""
import itkConfig
import glob
import os
import shutil
import sys
# customise the following variables
if os.name == 'nt':
SO_EXT = 'dll'
SO_GLOB = '*.%s' % (SO_EXT,)
PYE_GLOB = '*.pyd'
# this should be c:/opt/ITK/bin
ITK_SO_DIR = os.path.normpath(
os.path.join(itkConfig.swig_lib, '../../../../bin'))
else:
SO_EXT = 'so'
SO_GLOB = '*.%s.*' % (SO_EXT,)
PYE_GLOB = '*.so'
curdir = os.path.abspath(os.curdir)
# first go down to Insight/lib/InsightToolkit/WrapITK/lib
os.chdir(itkConfig.swig_lib)
# then go up twice
os.chdir(os.path.join('..', '..'))
# then find the curdir
ITK_SO_DIR = os.path.abspath(os.curdir)
# change back to where we started
os.chdir(curdir)
# we want:
# itk_kit/wrapitk/py (*.py and Configuration and itkExtras subdirs from
# WrapITK/Python)
# itk_kit/wrapitk/lib (*.py and *.so from WrapITK/lib)
def get_wrapitk_tree():
"""Return tree relative to itk_kit/wrapitk top.
"""
# WrapITK/lib -> itk_kit/wrapitk/lib (py files, so/dll files)
lib_files = glob.glob('%s/*.py' % (itkConfig.swig_lib,))
# on linux there are Python SO files, on Windows they're actually
# all PYDs (and not DLLs) - these are ALL python extension modules
lib_files.extend(glob.glob('%s/%s' % (itkConfig.swig_lib, PYE_GLOB)))
# on Windows we also need the SwigRuntime.dll in c:/opt/WrapITK/bin!
# the files above on Windows are in:
# C:\\opt\\WrapITK\\lib\\InsightToolkit\\WrapITK\\lib
if os.name == 'nt':
lib_files.extend(glob.glob('%s/%s' % (ITK_SO_DIR, SO_GLOB)))
wrapitk_lib = [('lib/%s' %
(os.path.basename(i),), i) for i in lib_files]
# WrapITK/Python -> itk_kit/wrapitk/python (py files)
py_path = os.path.normpath(os.path.join(itkConfig.config_py, '..'))
py_files = glob.glob('%s/*.py' % (py_path,))
wrapitk_py = [('python/%s' %
(os.path.basename(i),), i) for i in py_files]
# WrapITK/Python/Configuration -> itk_kit/wrapitk/python/Configuration
config_files = glob.glob('%s/*.py' %
(os.path.join(py_path,'Configuration'),))
wrapitk_config = [('python/Configuration/%s' %
(os.path.basename(i),), i)
for i in config_files]
# itkExtras
extra_files = glob.glob('%s/*.py' % (os.path.join(py_path, 'itkExtras'),))
wrapitk_extra = [('python/itkExtras/%s' %
(os.path.basename(i),), i) for i in extra_files]
# complete tree
wrapitk_tree = wrapitk_lib + wrapitk_py + wrapitk_config + wrapitk_extra
return wrapitk_tree
def get_itk_so_tree():
"""Get the ITK DLLs themselves.
Return tree relative to itk_kit/wrapitk top.
"""
so_files = glob.glob('%s/%s' % (ITK_SO_DIR, SO_GLOB))
itk_so_tree = [('lib/%s' % (os.path.basename(i),), i) for i in so_files]
return itk_so_tree
def copy3(src, dst):
"""Same as shutil.copy2, but copies symlinks as they are, i.e. equivalent
to --no-dereference parameter of cp.
"""
dirname = os.path.dirname(dst)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if os.path.islink(src):
linkto = os.readlink(src)
os.symlink(linkto, dst)
else:
shutil.copy2(src, dst)
def install(devide_app_dir):
"""Install a self-contained wrapitk installation in itk_kit_dir.
"""
itk_kit_dir = os.path.join(devide_app_dir, 'module_kits/itk_kit')
print "Deleting existing wrapitk dir."
sys.stdout.flush()
witk_dest_dir = os.path.join(itk_kit_dir, 'wrapitk')
if os.path.exists(witk_dest_dir):
shutil.rmtree(witk_dest_dir)
print "Creating list of WrapITK files..."
sys.stdout.flush()
wrapitk_tree = get_wrapitk_tree()
print "Copying WrapITK files..."
sys.stdout.flush()
for f in wrapitk_tree:
copy3(f[1], os.path.join(witk_dest_dir, f[0]))
print "Creating list of ITK shared objects..."
sys.stdout.flush()
itk_so_tree = get_itk_so_tree()
print "Copying ITK shared objects..."
sys.stdout.flush()
for f in itk_so_tree:
copy3(f[1], os.path.join(witk_dest_dir, f[0]))
if os.name == 'nt':
# on Windows, it's not easy setting the DLL load path in a running
# application. You could try SetDllDirectory, but that only works
# since XP SP1. You could also change the current dir, but our DLLs
# are lazy loaded, so no go. An invoking batchfile is out of the
# question.
print "Moving all SOs back to main DeVIDE dir [WINDOWS] ..."
lib_path = os.path.join(witk_dest_dir, 'lib')
so_files = glob.glob(os.path.join(lib_path, SO_GLOB))
so_files.extend(glob.glob(os.path.join(lib_path, PYE_GLOB)))
for so_file in so_files:
shutil.move(so_file, devide_app_dir)
#also write list of DLLs that were moved to lib_path/moved_dlls.txt
f = file(os.path.join(lib_path, 'moved_dlls.txt'), 'w')
f.writelines(['%s\n' % (os.path.basename(fn),) for fn in so_files])
f.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Specify devide app dir as argument."
else:
install(sys.argv[1])
| [
[
8,
0,
0.009,
0.012,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0241,
0.006,
0,
0.66,
0.0909,
41,
0,
1,
0,
0,
41,
0,
0
],
[
1,
0,
0.0301,
0.006,
0,
0.66,
... | [
"\"\"\"Module for independently packaging up whole WrapITK tree.\n\"\"\"",
"import itkConfig",
"import glob",
"import os",
"import shutil",
"import sys",
"if os.name == 'nt':\n SO_EXT = 'dll'\n SO_GLOB = '*.%s' % (SO_EXT,)\n PYE_GLOB = '*.pyd'\n # this should be c:/opt/ITK/bin\n ITK_SO_DI... |
# example driver script for offline / command-line processing with DeVIDE
# the following variables are magically set in this script:
# interface - instance of ScriptInterface, with the following calls:
# meta_modules = load_and_realise_network()
# execute_network(self, meta_modules)
# clear_network(self)
# instance = get_module_instance(self, module_name)
# config = get_module_config(self, module_name)
# set_module_config(self, module_name, config)
# See devide/interfaces/simple_api_mixin.py for details.
# start the script with:
# dre devide --interface script --script example_offline_driver.py --script-params 0.0,100.0
def main():
# script_params is everything that gets passed on the DeVIDE
# commandline after --script-params
# first get the two strings split by a comma
l,u = script_params.split(',')
# then cast to float
LOWER = float(l)
UPPER = float(u)
print "offline_driver.py starting"
# load the DVN that you prepared
# load_and_realise_network returns module dictionary + connections
mdict,conn = interface.load_and_realise_network(
'BatchModeWithoutUI-ex.dvn')
# parameter is the module name that you assigned in DeVIDE
# using right-click on the module, then "Rename"
thresh_conf = interface.get_module_config('threshold')
# what's returned is module_instance._config (try this in the
# devide module introspection interface by introspecting "Module
# (self)" and then typing "dir(obj._config)"
thresh_conf.lowerThreshold = LOWER
thresh_conf.upperThreshold = UPPER
# set module config back again
interface.set_module_config('threshold', thresh_conf)
# get, change and set writer config to change filename
writer_conf = interface.get_module_config('vtp_wrt')
writer_conf.filename = 'result_%s-%s.vtp' % (str(LOWER),str(UPPER))
interface.set_module_config('vtp_wrt', writer_conf)
# run the network
interface.execute_network(mdict.values())
print "offline_driver.py done."
main()
| [
[
2,
0,
0.6321,
0.6792,
0,
0.66,
0,
624,
0,
0,
0,
0,
0,
0,
14
],
[
14,
1,
0.3774,
0.0189,
1,
0.52,
0,
962,
3,
1,
0,
0,
908,
10,
1
],
[
14,
1,
0.4151,
0.0189,
1,
0.5... | [
"def main():\n # script_params is everything that gets passed on the DeVIDE\n # commandline after --script-params\n # first get the two strings split by a comma\n l,u = script_params.split(',')\n # then cast to float\n LOWER = float(l)\n UPPER = float(u)",
" l,u = script_params.split(',')"... |
# dummy
| [] | [] |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import wx # todo: this should go away...
import string
import sys
import traceback
# todo: remove all VTK dependencies from this file!!
def clampVariable(v, min, max):
"""Make sure variable is on the range [min,max]. Return clamped variable.
"""
if v < min:
v = min
elif v > max:
v = max
return v
def exceptionToMsgs():
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
return dmsgs
def logError_DEPRECATED(msg):
"""DEPRECATED. Rather use devide_app.log_error().
"""
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
# we can't disable the timestamp yet
# wxLog_SetTimestamp()
# set the detail message
for dmsg in dmsgs:
wx.LogError(dmsg)
# then the most recent
wx.LogError(msg)
print msg
# and flush... the last message will be the actual error
# message, what we did before will add to it to become the
# detail message
wx.Log_FlushActive()
def logWarning_DEPRECATED(msg):
"""DEPRECATED. Rather use devide_app.logWarning().
"""
# create nice formatted string with tracebacks and all
ei = sys.exc_info()
#dmsg = \
# string.join(traceback.format_exception(ei[0],
# ei[1],
# ei[2]))
dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])
# we can't disable the timestamp yet
# wxLog_SetTimestamp()
# set the detail message
for dmsg in dmsgs:
wx.LogWarning(dmsg)
# then the most recent
wx.LogWarning(msg)
# and flush... the last message will be the actual error
# message, what we did before will add to it to become the
# detail message
wx.Log_FlushActive()
def setGridCellYesNo(grid, row, col, yes=True):
if yes:
colour = wx.Colour(0,255,0)
text = '1'
else:
colour = wx.Colour(255,0,0)
text = '0'
grid.SetCellValue(row, col, text)
grid.SetCellBackgroundColour(row, col, colour)
def textToFloat(text, defaultFloat):
"""Converts text to a float by using an eval and returns the float.
If something goes wrong, returns defaultFloat.
"""
try:
returnFloat = float(text)
except Exception:
returnFloat = defaultFloat
return returnFloat
def textToInt(text, defaultInt):
"""Converts text to an integer by using an eval and returns the integer.
If something goes wrong, returns default Int.
"""
try:
returnInt = int(text)
except Exception:
returnInt = defaultInt
return returnInt
def textToTuple(text, defaultTuple):
"""This will convert the text representation of a tuple into a real
tuple. No checking for type or number of elements is done. See
textToTypeTuple for that.
"""
# first make sure that the text starts and ends with brackets
text = text.strip()
if text[0] != '(':
text = '(%s' % (text,)
if text[-1] != ')':
text = '%s)' % (text,)
try:
returnTuple = eval('tuple(%s)' % (text,))
except Exception:
returnTuple = defaultTuple
return returnTuple
def textToTypeTuple(text, defaultTuple, numberOfElements, aType):
"""This will convert the text representation of a tuple into a real
tuple with numberOfElements elements, all of type aType. If the required
number of elements isn't available, or they can't all be casted to the
correct type, the defaultTuple will be returned.
"""
aTuple = textToTuple(text, defaultTuple)
if len(aTuple) != numberOfElements:
returnTuple = defaultTuple
else:
try:
returnTuple = tuple([aType(e) for e in aTuple])
except ValueError:
returnTuple = defaultTuple
return returnTuple
| [
[
1,
0,
0.0303,
0.0061,
0,
0.66,
0,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0364,
0.0061,
0,
0.66,
0.0833,
890,
0,
1,
0,
0,
890,
0,
0
],
[
1,
0,
0.0424,
0.0061,
0,
... | [
"import wx # todo: this should go away...",
"import string",
"import sys",
"import traceback",
"def clampVariable(v, min, max):\n \"\"\"Make sure variable is on the range [min,max]. Return clamped variable.\n \"\"\"\n if v < min:\n v = min\n elif v > max:\n v = max",
" \"\"\"... |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import vtk
from module_kits.misc_kit.mixins import SubjectMixin
from devide_canvas_object import DeVIDECanvasGlyph
import operator
import wx # we're going to use this for event handling
from module_kits.misc_kit import dprint
# think about turning this into a singleton.
class DeVIDECanvasEvent:
def __init__(self):
# last event information ############
self.wx_event = None
self.name = None
# pos is in wx-coords, i.e. top-left is 0,0
self.pos = (0,0)
# last_pos and pos_delta follow same convention
self.last_pos = (0,0)
self.pos_delta = (0,0)
# disp_pos is in VTK display coords: bottom-left is 0,0
self.disp_pos = (0,0)
self.world_pos = (0,0,0)
# state information #################
self.left_button = False
self.middle_button = False
self.right_button = False
self.clicked_object = None
# which cobject has the mouse
self.picked_cobject = None
self.picked_sub_prop = None
class DeVIDECanvas(SubjectMixin):
"""Give me a vtkRenderWindowInteractor with a Renderer, and I'll
do the rest. YEAH.
"""
def __init__(self, renderwindowinteractor, renderer):
self._rwi = renderwindowinteractor
self._ren = renderer
# need this to do same mouse capturing as original RWI under Win
self._rwi_use_capture = \
vtk.wx.wxVTKRenderWindowInteractor._useCapture
# we can't switch on Line/Point/Polygon smoothing here,
# because the renderwindow has already been initialised
# we do it in main_frame.py right after we create the RWI
# parent 2 ctor
SubjectMixin.__init__(self)
self._cobjects = []
# dict for mapping from prop back to cobject
self.prop_to_glyph = {}
self._previousRealCoords = None
self._potentiallyDraggedObject = None
self._draggedObject = None
self._ren.SetBackground(1.0,1.0,1.0)
self._ren.GetActiveCamera().SetParallelProjection(1)
# set a sensible initial zoom
self._zoom(0.004)
istyle = vtk.vtkInteractorStyleUser()
#istyle = vtk.vtkInteractorStyleImage()
self._rwi.SetInteractorStyle(istyle)
self._rwi.Bind(wx.EVT_RIGHT_DOWN, self._handler_rd)
self._rwi.Bind(wx.EVT_RIGHT_UP, self._handler_ru)
self._rwi.Bind(wx.EVT_LEFT_DOWN, self._handler_ld)
self._rwi.Bind(wx.EVT_LEFT_UP, self._handler_lu)
self._rwi.Bind(wx.EVT_MIDDLE_DOWN, self._handler_md)
self._rwi.Bind(wx.EVT_MIDDLE_UP, self._handler_mu)
self._rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_wheel)
self._rwi.Bind(wx.EVT_MOTION, self._handler_motion)
self._rwi.Bind(wx.EVT_LEFT_DCLICK, self._handler_ldc)
#self._rwi.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
#self._rwi.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
# If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions
# of all characters are always returned. EVT_CHAR also performs
# other necessary keyboard-dependent translations.
# * we unbind the char handler added by the wxRWI (else alt-w
# for example gets interpreted as w for wireframe e.g.)
self._rwi.Unbind(wx.EVT_CHAR)
self._rwi.Bind(wx.EVT_CHAR, self._handler_char)
#self._rwi.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self._observer_ids = []
self.event = DeVIDECanvasEvent()
# do initial drawing here.
def close(self):
# first remove all objects
# (we could do this more quickly, but we're opting for neatly)
for i in range(len(self._cobjects)-1,-1,-1):
cobj = self._cobjects[i]
self.remove_object(cobj)
for i in self._observer_ids:
self._rwi.RemoveObserver(i)
del self._rwi
del self._ren
# nuke this function, replace with display_to_world.
# events are in display, everything else in world.
# go back to graph_editor
def eventToRealCoords_DEPRECATED(self, ex, ey):
"""Convert window event coordinates to canvas relative coordinates.
"""
# get canvas parameters
vsx, vsy = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
# calculate REAL coords
rx = ex + vsx * dx
ry = ey + vsy * dy
return (rx, ry)
def display_to_world(self, dpt):
"""Takes 3-D display point as input, returns 3-D world point.
"""
# make sure we have 3 elements
if len(dpt) < 3:
dpt = tuple(dpt) + (0.0,)
elif len(dpt) > 3:
dpt = tuple(dpt[0:3])
self._ren.SetDisplayPoint(dpt)
self._ren.DisplayToWorld()
return self._ren.GetWorldPoint()[0:3]
def world_to_display(self, wpt):
"""Takes 3-D world point as input, returns 3-D display point.
"""
self._ren.SetWorldPoint(tuple(wpt) + (0.0,)) # this takes 4-vec
self._ren.WorldToDisplay()
return self._ren.GetDisplayPoint()
def flip_y(self, y):
return self._rwi.GetSize()[1] - y - 1
def wx_to_world(self, wx_x, wx_y):
disp_x = wx_x
disp_y = self.flip_y(wx_y)
world_depth = 0.0
disp_z = self.world_to_display((0.0,0.0, world_depth))[2]
wex, wey, wez = self.display_to_world((disp_x,disp_y,disp_z))
return (wex, wey, wez)
def _helper_handler_capture_release(self, button):
"""Helper method to be called directly after preamble
helper in button up handlers in order to release mouse.
@param button Text description of which button was pressed,
e.g. 'left'
"""
# if the same button is released that captured the mouse,
# and we have the mouse, release it. (we need to get rid
# of this as soon as possible; if we don't and one of the
# event handlers raises an exception, mouse is never
# released.)
if self._rwi_use_capture and self._rwi._own_mouse and \
button==self._rwi._mouse_capture_button:
self._rwi.ReleaseMouse()
self._rwi._own_mouse = False
def _helper_handler_capture(self, button):
"""Helper method to be called at end after button down
helpers.
@param button Text description of button that was pressed,
e.g. 'left'.
"""
# save the button and capture mouse until the button is
# released we only capture the mouse if it hasn't already
# been captured
if self._rwi_use_capture and not self._rwi._own_mouse:
self._rwi._own_mouse = True
self._rwi._mouse_capture_button = button
self._rwi.CaptureMouse()
def _helper_handler_preamble(self, e, focus=True):
e.Skip(False)
# Skip(False) won't search for other event
# handlers
self.event.wx_event = e
if focus:
# we need to take focus... else some other subwindow keeps it
# once we've been there to select a module for example
self._rwi.SetFocus()
def _helper_glyph_button_down(self, event_name):
ex, ey = self.event.disp_pos
ret = self._pick_glyph(ex,ey)
if ret:
pc, psp = ret
self.event.clicked_object = pc
self.event.name = event_name
pc.notify(event_name)
else:
self.event.clicked_object = None
# we only give the canvas the event if the glyph didn't
# take it
self.event.name = event_name
self.notify(event_name)
def _helper_glyph_button_up(self, event_name):
ex, ey = self.event.disp_pos
ret = self._pick_glyph(ex,ey)
if ret:
pc, psp = ret
self.event.name = event_name
pc.notify(event_name)
else:
self.event.name = event_name
self.notify(event_name)
# button goes up, object is not clicked anymore
self.event.clicked_object = None
def _handler_char(self, e):
# we're disabling all VTK. if we don't, the standard
# VTK keys such as 'r' (reset), '3' (stereo) and especially
# 'f' (fly to) can screw up things quite badly.
# if ctrl, shift or alt is involved, we should pass it on to
# wx (could be menu keys for example).
# if not, we just eat up the event.
if e.ControlDown() or e.ShiftDown() or e.AltDown():
e.Skip()
def _handler_ld(self, e):
self._helper_handler_preamble(e)
#ctrl, shift = event.ControlDown(), event.ShiftDown()
#self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
# ctrl, shift, chr(0), 0, None)
self.event.left_button = True
self._helper_glyph_button_down('left_button_down')
self._helper_handler_capture('l')
def _handler_lu(self, e):
dprint("_handler_lu::")
self._helper_handler_preamble(e, focus=False)
self._helper_handler_capture_release('l')
self.event.left_button = False
self._helper_glyph_button_up('left_button_up')
def _handler_ldc(self, e):
self._helper_handler_preamble(e)
self._helper_glyph_button_down('left_button_dclick')
def _handler_md(self, e):
self._helper_handler_preamble(e)
self.event.middle_button = True
self._helper_glyph_button_down('middle_button_down')
def _handler_mu(self, e):
self._helper_handler_preamble(e, focus=False)
self.event.middle_button = False
self._helper_glyph_button_up('middle_button_up')
def _handler_rd(self, e):
self._helper_handler_preamble(e)
if e.Dragging():
return
self.event.right_button = True
self._helper_glyph_button_down('right_button_down')
def _handler_ru(self, e):
self._helper_handler_preamble(e, focus=False)
if e.Dragging():
return
self.event.right_button = False
self._helper_glyph_button_up('right_button_up')
def _pick_glyph(self, ex, ey):
"""Give current VTK display position.
"""
p = vtk.vtkPicker()
p.SetTolerance(0.00001) # this is perhaps still too large
for i in self._cobjects:
if isinstance(i, DeVIDECanvasGlyph):
for prop in i.props:
p.AddPickList(prop)
p.PickFromListOn()
ret = p.Pick((ex, ey, 0), self._ren)
if ret:
#pc = p.GetProp3Ds()
#pc.InitTraversal()
#prop = pc.GetNextItemAsObject()
prop = p.GetAssembly() # for now we only want this.
try:
picked_cobject = self.prop_to_glyph[prop]
except KeyError:
dprint("_pick_glyph:: couldn't find prop in p2g dict")
return None
else:
# need to find out WHICH sub-actor was picked.
if p.GetPath().GetNumberOfItems() == 2:
sub_prop = \
p.GetPath().GetItemAsObject(1).GetViewProp()
else:
sub_prop = None
# our assembly is one level deep, so 1 is the one we
# want (actor at leaf node)
return (picked_cobject, sub_prop)
return None
def _zoom(self, amount):
cam = self._ren.GetActiveCamera()
if cam.GetParallelProjection():
cam.SetParallelScale(cam.GetParallelScale() / amount)
else:
self._ren.GetActiveCamera().Dolly(amount)
self._ren.ResetCameraClippingRange()
self._ren.UpdateLightsGeometryToFollowCamera()
self.redraw()
def _handler_wheel(self, event):
# wheel forward = zoom in
# wheel backward = zoom out
factor = [-2.0, 2.0][event.GetWheelRotation() > 0.0]
self._zoom(1.1 ** factor)
#event.GetWheelDelta()
def get_top_left_world(self):
"""Return top-left of canvas (0,0 in wx) in world coords.
In world coordinates, top_y > bottom_y.
"""
return self.wx_to_world(0,0)
def get_bottom_right_world(self):
"""Return bottom-right of canvas (sizex, sizey in wx) in world
coords.
In world coordinates, bottom_y < top_y.
"""
x,y = self._rwi.GetSize()
return self.wx_to_world(x-1, y-1)
def get_wh_world(self):
"""Return width and height of visible canvas in world
coordinates.
"""
tl = self.get_top_left_world()
br = self.get_bottom_right_world()
return br[0] - tl[0], tl[1] - br[1]
def get_motion_vector_world(self, world_depth):
"""Calculate motion vector in world space represented by last
mouse delta.
"""
c = self._ren.GetActiveCamera()
display_depth = self.world_to_display((0.0,0.0, world_depth))[2]
new_pick_pt = self.display_to_world(self.event.disp_pos +
(display_depth,))
fy = self.flip_y(self.event.last_pos[1])
old_pick_pt = self.display_to_world((self.event.last_pos[0], fy,
display_depth))
# old_pick_pt - new_pick_pt (reverse of camera!)
motion_vector = map(operator.sub, new_pick_pt,
old_pick_pt)
return motion_vector
def _handler_motion(self, event):
"""MouseMoveEvent observer for RWI.
o contains a binding to the RWI.
"""
#self._helper_handler_preamble(event)
self.event.wx_event = event
# event position is viewport relative (i.e. in pixels,
# top-left is 0,0)
ex, ey = event.GetX(), event.GetY()
# we need to flip Y to get VTK display coords
self.event.disp_pos = ex, self._rwi.GetSize()[1] - ey - 1
# before setting the new pos, record the delta
self.event.pos_delta = (ex - self.event.pos[0],
ey - self.event.pos[1])
self.event.last_pos = self.event.pos
self.event.pos = ex, ey
wex, wey, wez = self.display_to_world(self.event.disp_pos)
self.event.world_pos = wex, wey, wez
# add the "real" coords to the event structure
self.event.realX = wex
self.event.realY = wey
self.event.realZ = wez
# dragging gets preference...
if event.Dragging() and event.MiddleIsDown() and event.ShiftDown():
centre = self._ren.GetCenter()
# drag up = zoom in
# drag down = zoom out
dyf = - 10.0 * self.event.pos_delta[1] / centre[1]
self._zoom(1.1 ** dyf)
elif event.Dragging() and event.MiddleIsDown():
# move camera, according to self.event.pos_delta
c = self._ren.GetActiveCamera()
cfp = list(c.GetFocalPoint())
cp = list(c.GetPosition())
focal_depth = self.world_to_display(cfp)[2]
new_pick_pt = self.display_to_world(self.event.disp_pos +
(focal_depth,))
fy = self.flip_y(self.event.last_pos[1])
old_pick_pt = self.display_to_world((self.event.last_pos[0], fy,
focal_depth))
# old_pick_pt - new_pick_pt (reverse of camera!)
motion_vector = map(operator.sub, old_pick_pt,
new_pick_pt)
new_cfp = map(operator.add, cfp, motion_vector)
new_cp = map(operator.add, cp, motion_vector)
c.SetFocalPoint(new_cfp)
c.SetPosition(new_cp)
self.redraw()
else: # none of the preference events want this...
pg_ret = self._pick_glyph(ex, self.flip_y(ey))
if pg_ret:
picked_cobject, self.event.picked_sub_prop = pg_ret
if self.event.left_button and event.Dragging() and \
self.event.clicked_object == picked_cobject:
# left dragging on a glyph only works if THAT
# glyph was clicked (and the mouse button is still
# down)
self.event.name = 'dragging'
if self._draggedObject is None:
self._draggedObject = picked_cobject
# the actual event will be fired further below
if not picked_cobject is self.event.picked_cobject:
self.event.picked_cobject = picked_cobject
self.event.name = 'enter'
picked_cobject.notify('enter')
else:
self.event.name = 'motion'
picked_cobject.notify('motion')
else:
# nothing under the mouse...
if self.event.picked_cobject:
self.event.name = 'exit'
self.event.picked_cobject.notify('exit')
self.event.picked_cobject = None
if event.Dragging() and self._draggedObject:
# so we are Dragging() and there is a draggedObject...
# whether draggedObject was set above, or in a
# previous call of this event handler, we have to keep
# on firing these drag events until draggedObject is
# canceled.
self.event.name = 'dragging'
self._draggedObject.notify('dragging')
if event.Dragging and not self._draggedObject:
# user is dragging on canvas (no draggedObject!)
self.event.name = 'dragging'
self.notify(self.event.name)
if not event.Dragging():
# when user stops dragging the mouse, lose the object
if not self._draggedObject is None:
dprint("_handler_motion:: dragging -> off")
self._draggedObject.draggedPort = None
self._draggedObject = None
def add_object(self, cobj):
if cobj and cobj not in self._cobjects:
cobj.canvas = self
self._cobjects.append(cobj)
for prop in cobj.props:
self._ren.AddViewProp(prop)
# we only add prop to cobject if it's a glyph
if isinstance(cobj, DeVIDECanvasGlyph):
self.prop_to_glyph[prop] = cobj
cobj.__hasMouse = False
def redraw(self):
"""Redraw the whole scene.
"""
self._rwi.Render()
def update_all_geometry(self):
"""Update all geometry.
This is useful if many of the objects states have been changed
(e.g. new connections) and the connection visual states have
to be updated.
"""
for o in self._cobjects:
o.update_geometry()
def update_picked_cobject_at_drop(self, ex, ey):
"""Method to be used in the GraphEditor DropTarget
(geCanvasDropTarget) to make sure that the correct glyph is
selected.
Problem is that the application gets blocked during
wxDropSource.DoDragDrop(), so that if the user drags things
from for example the DICOMBrowser to a DICOMReader on the
canvas, the canvas doesn't know that the DICOMReader has been
picked.
If this method is called at drop time, all is well.
"""
pg_ret = self._pick_glyph(ex, self.flip_y(ey))
if pg_ret:
self.event.picked_cobject, self.event.picked_sub_prop = pg_ret
def remove_object(self, cobj):
if cobj and cobj in self._cobjects:
for prop in cobj.props:
self._ren.RemoveViewProp(prop)
# it's only in here if it's a glyph
if isinstance(cobj, DeVIDECanvasGlyph):
del self.prop_to_glyph[prop]
cobj.canvas = None
if self._draggedObject == cobj:
self._draggedObject = None
del self._cobjects[self._cobjects.index(cobj)]
def reset_view(self):
"""Make sure that all actors (glyphs, connections, etc.) are
visible.
"""
self._ren.ResetCamera()
self.redraw()
def getDraggedObject(self):
return self._draggedObject
def getObjectsOfClass(self, classt):
return [i for i in self._cobjects if isinstance(i, classt)]
def getObjectWithMouse(self):
"""Return object currently containing mouse, None if no object has
the mouse.
"""
for cobject in self._cobjects:
if cobject.__hasMouse:
return cobject
return None
def drag_object(self, cobj, delta):
"""Move object with delta in world space.
"""
cpos = cobj.get_position() # this gives us 2D in world space
npos = (cpos[0] + delta[0], cpos[1] + delta[1])
cobj.set_position(npos)
cobj.update_geometry()
def pan_canvas_world(self, delta_x, delta_y):
c = self._ren.GetActiveCamera()
cfp = list(c.GetFocalPoint())
cfp[0] += delta_x
cfp[1] += delta_y
c.SetFocalPoint(cfp)
cp = list(c.GetPosition())
cp[0] += delta_x
cp[1] += delta_y
c.SetPosition(cp)
self.redraw()
| [
[
1,
0,
0.0076,
0.0015,
0,
0.66,
0,
665,
0,
1,
0,
0,
665,
0,
0
],
[
1,
0,
0.0091,
0.0015,
0,
0.66,
0.1429,
313,
0,
1,
0,
0,
313,
0,
0
],
[
1,
0,
0.0106,
0.0015,
0,
... | [
"import vtk",
"from module_kits.misc_kit.mixins import SubjectMixin",
"from devide_canvas_object import DeVIDECanvasGlyph",
"import operator",
"import wx # we're going to use this for event handling",
"from module_kits.misc_kit import dprint",
"class DeVIDECanvasEvent:\n def __init__(self):\n ... |
# dummy
| [] | [] |
class canvasSubject:
def __init__(self):
self._observers = {}
def addObserver(self, eventName, observer):
"""Add an observer for a particular event.
eventName can be one of 'enter', 'exit', 'drag', 'buttonDown'
or 'buttonUp'. observer is a callable object that will be
invoked at event time with parameters canvas object,
eventName, and event.
"""
self._observers[eventName].append(observer)
def notifyObservers(self, eventName, event):
for observer in self._observers[eventName]:
observer(self, eventName, event)
| [
[
3,
0,
0.5,
0.9474,
0,
0.66,
0,
205,
0,
3,
0,
0,
0,
0,
2
],
[
2,
1,
0.1316,
0.1053,
1,
0.53,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.1579,
0.0526,
2,
0.71,
0... | [
"class canvasSubject:\n def __init__(self):\n self._observers = {}\n \n def addObserver(self, eventName, observer):\n \"\"\"Add an observer for a particular event.\n\n eventName can be one of 'enter', 'exit', 'drag', 'buttonDown'",
" def __init__(self):\n self._observer... |
from canvasObject import *
from canvas import *
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
120,
0,
1,
0,
0,
120,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
1,
593,
0,
1,
0,
0,
593,
0,
0
]
] | [
"from canvasObject import *",
"from canvas import *"
] |
from wxPython import wx
from canvasSubject import canvasSubject
#############################################################################
class canvasObject(canvasSubject):
def __init__(self, position):
# call parent ctor
canvasSubject.__init__(self)
self._position = position
self._canvas = None
self._observers = {'enter' : [],
'exit' : [],
'drag' : [],
'buttonDown' : [],
'buttonUp' : [],
'buttonDClick' : [],
'motion' : []}
def close(self):
"""Take care of any cleanup here.
"""
pass
def draw(self, dc):
pass
def getBounds(self):
raise NotImplementedError
def getPosition(self):
return self._position
def setPosition(self, destination):
self._position = destination
def getCanvas(self):
return self._canvas
def hitTest(self, x, y):
return False
def isInsideRect(self, x, y, width, height):
return False
def setCanvas(self, canvas):
self._canvas = canvas
#############################################################################
class coRectangle(canvasObject):
def __init__(self, position, size):
canvasObject.__init__(self, position)
self._size = size
def draw(self, dc):
# drawing rectangle!
dc.SetBrush(wx.wxBrush(wx.wxColour(192,192,192), wx.wxSOLID))
dc.DrawRectangle(self._position[0], self._position[1],
self._size[0], self._size[1])
def getBounds(self):
return (self._size)
def getTopLeftBottomRight(self):
return ((self._position[0], self._position[1]),
(self._position[0] + self._size[0] - 1,
self._position[1] + self._size[1] - 1))
def hitTest(self, x, y):
# think carefully about the size of the rectangle...
# e.g. from 0 to 2 is size 2 (spaces between vertices)
return x >= self._position[0] and \
x <= self._position[0] + self._size[0] and \
y >= self._position[1] and \
y <= self._position[1] + self._size[1]
def isInsideRect(self, x, y, width, height):
x0 = (self._position[0] - x)
y0 = (self._position[1] - y)
return x0 >= 0 and x0 <= width and \
y0 >= 0 and y0 <= height and \
x0 + self._size[0] <= width and \
y0 + self._size[1] <= height
#############################################################################
class coLine(canvasObject):
# this is used by the routing algorithm to route lines around glyphs
# with a certain border; this is also used by updateEndPoints to bring
# the connection out of the connection port initially
routingOvershoot = 10
def __init__(self, fromGlyph, fromOutputIdx, toGlyph, toInputIdx):
"""A line object for the canvas.
linePoints is just a list of python tuples, each representing a
coordinate of a node in the line. The position is assumed to be
the first point.
"""
self.fromGlyph = fromGlyph
self.fromOutputIdx = fromOutputIdx
self.toGlyph = toGlyph
self.toInputIdx = toInputIdx
# 'BLACK' removed
colourNames = ['BLUE', 'BROWN', 'MEDIUM FOREST GREEN',
'DARKORANGE1']
self.lineColourName = colourNames[self.toInputIdx % (len(colourNames))]
# any line begins with 4 (four) points
self.updateEndPoints()
canvasObject.__init__(self, self._linePoints[0])
def close(self):
# delete things that shouldn't be left hanging around
del self.fromGlyph
del self.toGlyph
def draw(self, dc):
# lines are 2 pixels thick
dc.SetPen(wx.wxPen(self.lineColourName, 2, wx.wxSOLID))
# simple mode: just the lines thanks.
#dc.DrawLines(self._linePoints)
# spline mode for N points:
# 1. Only 4 points: drawlines. DONE
# 2. Draw line from 0 to 1
# 3. Draw line from N-2 to N-1 (second last to last)
# 4. Draw spline from 1 to N-2 (second to second last)
# if len(self._linePoints) > 4:
# dc.DrawLines(self._linePoints[0:2]) # 0 - 1
# dc.DrawLines(self._linePoints[-2:]) # second last to last
# dc.DrawSpline(self._linePoints[1:-1])
# else:
# dc.DrawLines(self._linePoints)
dc.SetPen(wx.wxPen('BLACK', 4, wx.wxSOLID))
dc.DrawSpline(self._linePoints)
dc.SetPen(wx.wxPen(self.lineColourName, 2, wx.wxSOLID))
dc.DrawSpline(self._linePoints)
def getBounds(self):
# totally hokey: for now we just return the bounding box surrounding
# the first two points - ideally we should iterate through the lines,
# find extents and pick a position and bounds accordingly
return (self._linePoints[-1][0] - self._linePoints[0][0],
self._linePoints[-1][1] - self._linePoints[0][1])
def getUpperLeftWidthHeight(self):
"""This returns the upperLeft coordinate and the width and height of
the bounding box enclosing the third-last and second-last points.
This is used for fast intersection checking with rectangles.
"""
p3 = self._linePoints[-3]
p2 = self._linePoints[-2]
upperLeftX = [p3[0], p2[0]][bool(p2[0] < p3[0])]
upperLeftY = [p3[1], p2[1]][bool(p2[1] < p3[1])]
width = abs(p2[0] - p3[0])
height = abs(p2[1] - p3[1])
return ((upperLeftX, upperLeftY), (width, height))
def getThirdLastSecondLast(self):
return (self._linePoints[-3], self._linePoints[-2])
def hitTest(self, x, y):
# maybe one day we will make the hitTest work, not tonight
# I don't need it
return False
def insertRoutingPoint(self, x, y):
"""Insert new point x,y before second-last point, i.e. the new point
becomes the third-last point.
"""
if (x,y) not in self._linePoints:
self._linePoints.insert(len(self._linePoints) - 2, (x, y))
return True
else:
return False
def updateEndPoints(self):
# first get us just out of the port, then create margin between
# us and glyph
boostFromPort = coGlyph._pHeight / 2 + coLine.routingOvershoot
self._linePoints = [(), (), (), ()]
self._linePoints[0] = self.fromGlyph.getCenterOfPort(
1, self.fromOutputIdx)
self._linePoints[1] = (self._linePoints[0][0],
self._linePoints[0][1] + boostFromPort)
self._linePoints[-1] = self.toGlyph.getCenterOfPort(
0, self.toInputIdx)
self._linePoints[-2] = (self._linePoints[-1][0],
self._linePoints[-1][1] - boostFromPort)
#############################################################################
class coGlyph(coRectangle):
# at start and end of glyph
_horizBorder = 5
# between ports
_horizSpacing = 5
# at top and bottom of glyph
_vertBorder = 15
_pWidth = 10
_pHeight = 10
def __init__(self, position, numInputs, numOutputs,
labelList, module_instance):
# parent constructor
coRectangle.__init__(self, position, (0,0))
# we'll fill this out later
self._size = (0,0)
self._numInputs = numInputs
self.inputLines = [None] * self._numInputs
self._numOutputs = numOutputs
# be careful with list concatenation!
self.outputLines = [[] for i in range(self._numOutputs)]
self._labelList = labelList
self.module_instance = module_instance
self.draggedPort = None
self.enteredPort = None
self.selected = False
self.blocked = False
def close(self):
del self.module_instance
del self.inputLines
del self.outputLines
def draw(self, dc):
normal_colour = (192, 192, 192)
selected_colour = (255, 0, 246)
blocked_colour = (16, 16, 16)
colour = normal_colour
if self.selected:
colour = [selected_colour[i] * 0.5 + colour[i] * 0.5
for i in range(3)]
if self.blocked:
colour = [blocked_colour[i] * 0.5 + colour[i] * 0.5
for i in range(3)]
colour = tuple([int(i) for i in colour])
blockFillColour = wx.wxColour(*colour)
# # we're going to alpha blend a purplish sheen if this glyph is active
# if self.selected:
# # sheen: 255, 0, 246
# # alpha-blend with 192, 192, 192 with alpha 0.5 yields
# # 224, 96, 219
# blockFillColour = wx.wxColour(224, 96, 219)
# else:
# blockFillColour = wx.wxColour(192, 192, 192)
# default pen and font
dc.SetBrush(wx.wxBrush(blockFillColour, wx.wxSOLID))
dc.SetPen(wx.wxPen('BLACK', 1, wx.wxSOLID))
dc.SetFont(wx.wxNORMAL_FONT)
# calculate our size
# the width is the maximum(textWidth + twice the horizontal border,
# all ports, horizontal borders and inter-port borders added up)
maxPorts = max(self._numInputs, self._numOutputs)
portsWidth = 2 * coGlyph._horizBorder + \
maxPorts * coGlyph._pWidth + \
(maxPorts - 1 ) * coGlyph._horizSpacing
# determine maximum textwidth and height
tex = 0
tey = 0
for l in self._labelList:
temptx, tempty = dc.GetTextExtent(l)
if temptx > tex:
tex = temptx
if tempty > tey:
tey = tempty
# this will be calculated with the max width, so fine
textWidth = tex + 2 * coGlyph._horizBorder
self._size = (max(textWidth, portsWidth),
tey * len(self._labelList) + 2 * coGlyph._vertBorder)
# draw the main rectangle
dc.DrawRectangle(self._position[0], self._position[1],
self._size[0], self._size[1])
#dc.DrawRoundedRectangle(self._position[0], self._position[1],
# self._size[0], self._size[1], radius=5)
initY = self._position[1] + coGlyph._vertBorder
for l in self._labelList:
dc.DrawText(l,
self._position[0] + coGlyph._horizSpacing,
initY)
initY += tey
# then the inputs
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
connBrush = wx.wxBrush("GREEN")
disconnBrush = wx.wxBrush("RED")
for i in range(self._numInputs):
brush = [disconnBrush, connBrush][bool(self.inputLines[i])]
self.drawPort(dc, brush,
(horizOffset + i * horizStep,
self._position[1]))
lx = self._position[1] + self._size[1] - coGlyph._pHeight
for i in range(self._numOutputs):
brush = [disconnBrush, connBrush][bool(self.outputLines[i])]
self.drawPort(dc, brush,
(horizOffset + i * horizStep,
lx))
def drawPort(self, dc, brush, pos):
dc.SetBrush(brush)
dc.DrawRectangle(pos[0], pos[1], coGlyph._pWidth, coGlyph._pHeight)
#dc.DrawEllipse(pos[0], pos[1], coGlyph._pWidth, coGlyph._pHeight)
def findPortContainingMouse(self, x, y):
"""Find port that contains the mouse pointer. Returns tuple
containing inOut and port index.
"""
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
bx = horizOffset
by = self._position[1]
for i in range(self._numInputs):
if x >= bx and x <= bx + self._pWidth and \
y >= by and y < by + self._pHeight:
return (0, i)
bx += horizStep
bx = horizOffset
by = self._position[1] + self._size[1] - coGlyph._pHeight
for i in range(self._numOutputs):
if x >= bx and x <= bx + self._pWidth and \
y >= by and y < by + self._pHeight:
return (1, i)
bx += horizStep
return None
def getCenterOfPort(self, inOrOut, idx):
horizOffset = self._position[0] + coGlyph._horizBorder
horizStep = coGlyph._pWidth + coGlyph._horizSpacing
cy = self._position[1] + coGlyph._pHeight / 2
if inOrOut:
cy += self._size[1] - coGlyph._pHeight
cx = horizOffset + idx * horizStep + coGlyph._pWidth / 2
return (cx, cy)
def getLabel(self):
return ' '.join(self._labelList)
def setLabelList(self,labelList):
self._labelList = labelList
| [
[
1,
0,
0.0025,
0.0025,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0051,
0.0025,
0,
0.66,
0.2,
205,
0,
1,
0,
0,
205,
0,
0
],
[
3,
0,
0.0644,
0.1061,
0,
0.6... | [
"from wxPython import wx",
"from canvasSubject import canvasSubject",
"class canvasObject(canvasSubject):\n \n def __init__(self, position):\n # call parent ctor\n canvasSubject.__init__(self)\n \n self._position = position\n self._canvas = None",
" def __init__(sel... |
import wx
from canvasSubject import canvasSubject
from canvasObject import *
class canvas(wx.wxScrolledWindow, canvasSubject):
def __init__(self, parent, id = -1, size = wx.wxDefaultSize):
# parent 1 ctor
wx.wxScrolledWindow.__init__(self, parent, id, wx.wxPoint(0, 0), size,
wx.wxSUNKEN_BORDER)
# parent 2 ctor
canvasSubject.__init__(self)
self._cobjects = []
self._previousRealCoords = None
self._mouseDelta = (0,0)
self._potentiallyDraggedObject = None
self._draggedObject = None
self._observers = {'drag' : [],
'buttonDown' : [],
'buttonUp' : []}
self.SetBackgroundColour("WHITE")
wx.EVT_MOUSE_EVENTS(self, self.OnMouseEvent)
wx.EVT_PAINT(self, self.OnPaint)
self.virtualWidth = 2048
self.virtualHeight = 2048
self._buffer = None
self._buffer = wx.wxEmptyBitmap(self.virtualWidth, self.virtualHeight)
# we're only going to draw into the buffer, so no real client DC
dc = wx.wxBufferedDC(None, self._buffer)
dc.SetBackground(wx.wxBrush(self.GetBackgroundColour()))
dc.Clear()
self.doDrawing(dc)
self.SetVirtualSize((self.virtualWidth, self.virtualHeight))
self.SetScrollRate(20,20)
def eventToRealCoords(self, ex, ey):
"""Convert window event coordinates to canvas relative coordinates.
"""
# get canvas parameters
vsx, vsy = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
# calculate REAL coords
rx = ex + vsx * dx
ry = ey + vsy * dy
return (rx, ry)
def getDC(self):
"""Returns DC which can be used by the outside to draw to our buffer.
As soon as dc dies (and it will at the end of the calling function)
the contents of self._buffer will be blitted to the screen.
"""
cdc = wx.wxClientDC(self)
# set device origin according to scroll position
self.PrepareDC(cdc)
dc = wx.wxBufferedDC(cdc, self._buffer)
return dc
def get_glyph_on_coords(self, rx, ry):
"""If rx,ry falls on a glyph, return that glyph, else return
None.
"""
for cobject in self._cobjects:
if cobject.hitTest(rx, ry) and isinstance(cobject,
coGlyph):
return cobject
return None
def OnMouseEvent(self, event):
# this seems to work fine under windows. If we don't do this, and the
# mouse leaves the canvas, the rubber band remains and no selection
# is made.
if event.ButtonDown():
if not self.HasCapture():
self.CaptureMouse()
elif event.ButtonUp():
if self.HasCapture():
self.ReleaseMouse()
# these coordinates are relative to the visible part of the canvas
ex, ey = event.GetX(), event.GetY()
rx, ry = self.eventToRealCoords(ex, ey)
# add the "real" coords to the event structure
event.realX = rx
event.realY = ry
if self._previousRealCoords:
self._mouseDelta = (rx - self._previousRealCoords[0],
ry - self._previousRealCoords[1])
else:
self._mouseDelta = (0,0)
# FIXME: store binding to object which "has" the mouse
# on subsequent tries, we DON'T have to check all objects, only the
# one which had the mouse on the previous try... only if it "loses"
# the mouse, do we enter the mean loop again.
mouseOnObject = False
# the following three clauses, i.e. the hitTest, mouseOnObject and
# draggedObject should be kept in this order, unless you know
# EXACTLY what you're doing. If you're going to change anything, test
# that connects, disconnects (of all kinds) and rubber-banding still
# work.
# we need to do this expensive hit test every time, because the user
# wants to know when he mouses over the input port of a destination
# module
for cobject in self._cobjects:
if cobject.hitTest(rx, ry):
mouseOnObject = True
cobject.notifyObservers('motion', event)
if not cobject.__hasMouse:
cobject.__hasMouse = True
cobject.notifyObservers('enter', event)
if event.Dragging():
if not self._draggedObject:
if self._potentiallyDraggedObject == cobject:
# the user is dragging inside an object inside
# of which he has previously clicked... this
# definitely means he's dragging the object
mouseOnObject = True
self._draggedObject = cobject
else:
# this means the user has dragged the mouse
# over an object... which means mouseOnObject
# is technically true, but because we want the
# canvas to get this kind of dragEvent, we
# set it to false
mouseOnObject = False
elif event.ButtonUp():
cobject.notifyObservers('buttonUp', event)
elif event.ButtonDown():
if event.LeftDown():
# this means EVERY buttonDown in an object classifies
# as a potential drag. if the user now drags, we
# have a winner
self._potentiallyDraggedObject = cobject
cobject.notifyObservers('buttonDown', event)
elif event.ButtonDClick():
cobject.notifyObservers('buttonDClick', event)
# ends if cobject.hitTest(ex, ey)
else:
if cobject.__hasMouse:
cobject.__hasMouse = False
cobject.notifyObservers('exit', event)
if not mouseOnObject:
# we only get here if the mouse is not inside any canvasObject
# (but it could be dragging a canvasObject!)
if event.Dragging():
self.notifyObservers('drag', event)
elif event.ButtonUp():
self.notifyObservers('buttonUp', event)
elif event.ButtonDown():
self.notifyObservers('buttonDown', event)
if self._draggedObject:
# dragging locks onto an object, even if the mouse pointer
# is not inside that object - it will keep receiving drag
# events!
draggedObject = self._draggedObject
if event.ButtonUp():
# a button up anywhere cancels any drag
self._draggedObject = None
# so, the object can query canvas.getDraggedObject: if it's
# none, it means the drag has ended; if not, the drag is
# ongoing
draggedObject.notifyObservers('drag', event)
if event.ButtonUp():
# each and every ButtonUp cancels the current potential drag object
self._potentiallyDraggedObject = None
# store the previous real coordinates for mouse deltas
self._previousRealCoords = (rx, ry)
def OnPaint(self, event):
# as soon as dc is unbound and destroyed, buffer is blit
# BUFFER_VIRTUAL_AREA indicates that the buffer bitmap is for the
# whole virtual area, not just the client area of the window
dc = wx.wxBufferedPaintDC(self, self._buffer,
style=wx.wxBUFFER_VIRTUAL_AREA)
def doDrawing(self, dc):
"""This function actually draws the complete shebang to the passed
dc.
"""
dc.BeginDrawing()
# clear the whole shebang to background
dc.SetBackground(wx.wxBrush(self.GetBackgroundColour(), wx.wxSOLID))
dc.Clear()
# draw glyphs last (always)
glyphs = []
theRest = []
for i in self._cobjects:
if isinstance(i, coGlyph):
glyphs.append(i)
else:
theRest.append(i)
for cobj in theRest:
cobj.draw(dc)
for cobj in glyphs:
cobj.draw(dc)
# draw all objects
#for cobj in self._cobjects:
# cobj.draw(dc)
dc.EndDrawing()
def addObject(self, cobj):
if cobj and cobj not in self._cobjects:
cobj.setCanvas(self)
self._cobjects.append(cobj)
cobj.__hasMouse = False
def drawObject(self, cobj):
"""Use this if you want to redraw a single canvas object.
"""
dc = self.getDC()
cobj.draw(dc)
def redraw(self):
"""Redraw the whole scene.
"""
dc = self.getDC()
self.doDrawing(dc)
def removeObject(self, cobj):
if cobj and cobj in self._cobjects:
cobj.setCanvas(None)
if self._draggedObject == cobj:
self._draggedObject = None
del self._cobjects[self._cobjects.index(cobj)]
def getMouseDelta(self):
return self._mouseDelta
def getDraggedObject(self):
return self._draggedObject
def getObjectsOfClass(self, classt):
return [i for i in self._cobjects if isinstance(i, classt)]
def getObjectWithMouse(self):
"""Return object currently containing mouse, None if no object has
the mouse.
"""
for cobject in self._cobjects:
if cobject.__hasMouse:
return cobject
return None
def dragObject(self, cobj, delta):
if abs(delta[0]) > 0 or abs(delta[1]) > 0:
# calculate new position
cpos = cobj.getPosition()
npos = (cpos[0] + delta[0], cpos[1] + delta[1])
cobj.setPosition(npos)
# setup DC
dc = self.getDC()
dc.BeginDrawing()
# we're only going to draw a dotted outline
dc.SetBrush(wx.wxBrush('WHITE', wx.wxTRANSPARENT))
dc.SetPen(wx.wxPen('BLACK', 1, wx.wxDOT))
dc.SetLogicalFunction(wx.wxINVERT)
bounds = cobj.getBounds()
# first delete the old rectangle
dc.DrawRectangle(cpos[0], cpos[1], bounds[0], bounds[1])
# then draw the new one
dc.DrawRectangle(npos[0], npos[1], bounds[0], bounds[1])
# thar she goes
dc.EndDrawing()
#############################################################################
| [
[
1,
0,
0.0031,
0.0031,
0,
0.66,
0,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0063,
0.0031,
0,
0.66,
0.3333,
205,
0,
1,
0,
0,
205,
0,
0
],
[
1,
0,
0.0094,
0.0031,
0,
... | [
"import wx",
"from canvasSubject import canvasSubject",
"from canvasObject import *",
"class canvas(wx.wxScrolledWindow, canvasSubject):\n def __init__(self, parent, id = -1, size = wx.wxDefaultSize):\n # parent 1 ctor\n wx.wxScrolledWindow.__init__(self, parent, id, wx.wxPoint(0, 0), size,\n... |
# dummy
| [] | [] |
# dummy
| [] | [] |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""Module containing base class for devide modules.
author: Charl P. Botha <cpbotha@ieee.org>
"""
#########################################################################
class GenericObject(object):
"""Generic object into which we can stuff whichever attributes we want.
"""
pass
#########################################################################
class DefaultConfigClass(object):
pass
#########################################################################
class ModuleBase(object):
"""Base class for all modules.
Any module wishing to take part in the devide party will have to offer all
of these methods.
"""
def __init__(self, module_manager):
"""Perform your module initialisation here.
Please also call this init method
(i.e. ModuleBase.__init__(self)). In your own __init__, you
should create your view and show it to the user.
"""
self._module_manager = module_manager
self._config = DefaultConfigClass()
# modules should toggle this variable to True once they have
# initialised and shown their view once.
self.view_initialised = False
def close(self):
"""Idempotent method for de-initialising module as far as possible.
We can't guarantee the calling of __del__, as Python does garbage
collection and the object might destruct a while after we've removed
all references to it.
In addition, with python garbage collection, __del__ can cause
uncollectable objects, so try to avoid it as far as possible.
"""
# we neatly get rid of some references
del self._module_manager
def get_input_descriptions(self):
"""Returns tuple of input descriptions, mostly used by the graph editor
to make a nice glyph for this module."""
raise NotImplementedError
def set_input(self, idx, input_stream):
"""Attaches input_stream (which is e.g. the output of a previous
module) to this module's input at position idx.
If the previous value was None and the current value is not None, it
signifies a connect and the module should initialise as if it's
getting a new input. This usually happens during the first network
execution AFTER a connection.
If the previous value was not-None and the new value is None, it
signifies a disconnect and the module should take the necessary
actions. This usually happens immediatly when the user disconnects an
input
If the previous value was not-None and the current value is not-None,
the module should take actions as for a changed input. This event
signifies a re-transfer on an already existing connection. This can
be considered an event for which this module is an observer.
"""
raise NotImplementedError
def get_output_descriptions(self):
"""Returns a tuple of output descriptions.
Mostly used by the graph editor to make a nice glyph for this module.
These are also clues to the user as to which glyphs can be connected.
"""
raise NotImplementedError
def get_output(self, idx):
"""Get the n-th output.
This will be used for connecting this output to the input of another
module. Whatever is returned by this object MUST have an Update()
method. However you choose to implement it, the Update() should make
sure that the whole chain of logic resulting in the data object has
executed so that the data object is up to date.
"""
raise NotImplementedError
def logic_to_config(self):
"""Synchronise internal configuration information (usually
self._config)with underlying system.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def config_to_logic(self):
"""Apply internal configuration information (usually self._config) to
the underlying logic.
If this has resulted in changes to the logic, return True, otherwise
return False
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def view_to_config(self):
"""Synchronise internal configuration information with the view (GUI)
of this module.
If this has resulted in changes to the config, return True,
otherwise return False.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def config_to_view(self):
"""Make the view reflect the internal configuration information.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def execute_module(self):
"""This should make the model do whatever processing it was designed
to do.
It's important that when this method is called, the module should be
able to cause ALL of the modules preceding it in a glyph chain to
execute (if necessary). If the whole chain consists of VTK objects,
this is easy.
If not, extra measures need to be taken. According to API,
each output/input data object MUST have an Update() method
that can ensure that the logic responsible for that object has
executed thus making the data object current.
In short, execute_module() should call Update() on all of this modules
input objects, directly or indirectly.
"""
raise NotImplementedError
def view(self):
"""Pop up a dialog with all config possibilities, including optional
use of the pipeline browser.
If the dialog is already visible, do something to draw the user's
attention to it. For a wxFrame-based view, you can do something like:
if not frame.Show(True):
frame.Raise()
If the frame is already visible, this will bring it to the front.
"""
raise NotImplementedError
def get_config(self):
"""Returns current configuration of module.
This should return a pickle()able object that encapsulates all
configuration information of this module. The default just returns
self._config, which is None by default. You can override get_config()
and set_config(), or just make sure that your config info always goes
via self._config
In general, you should never need to override this.
"""
# make sure that the config reflects the state of the underlying logic
self.logic_to_config()
# and then return the config struct.
return self._config
def set_config(self, aConfig):
"""Change configuration of module to that stored in aConfig.
If set_config is called with the object previously returned by
get_config(), the module should be in exactly the same state as it was
when get_config() was called. The default sets the default
self._config and applies it to the underlying logic.
In general, you should never need to override this.
"""
# we update the dict of the existing config with the passed
# parameter. This means that the new config is merged with
# the old, but all new members overwrite old one. This is
# more robust.
self._config.__dict__.update(aConfig.__dict__)
# apply the config to the underlying logic
self.config_to_logic()
# bring it back all the way up to the view
self.logic_to_config()
# but only if we are in view mode
if self.view_initialised:
self.config_to_view()
# the config has been set, so we assumem that the module has
# now been modified.
self._module_manager.modify_module(self)
# convenience functions
def sync_module_logic_with_config(self):
self._module_manager.sync_module_logic_with_config(self)
def sync_module_view_with_config(self):
self._module_manager.sync_module_view_with_config(self)
def sync_module_view_with_logic(self):
self._module_manager.sync_module_view_with_logic(self)
| [
[
8,
0,
0.0275,
0.0169,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
3,
0,
0.053,
0.0169,
0,
0.66,
0.3333,
837,
0,
0,
0,
0,
186,
0,
0
],
[
8,
1,
0.053,
0.0085,
1,
0.75,
... | [
"\"\"\"Module containing base class for devide modules.\n\nauthor: Charl P. Botha <cpbotha@ieee.org>\n\"\"\"",
"class GenericObject(object):\n \"\"\"Generic object into which we can stuff whichever attributes we want.\n \"\"\"\n pass",
" \"\"\"Generic object into which we can stuff whichever attribu... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
import os, sys, time
# usage: parse_log.py log-file [socket-index to focus on]
socket_filter = None
if len(sys.argv) >= 3:
socket_filter = sys.argv[2].strip()
if socket_filter == None:
print "scanning for socket with the most packets"
file = open(sys.argv[1], 'rb')
sockets = {}
for l in file:
if not 'our_delay' in l: continue
try:
a = l.strip().split(" ")
socket_index = a[1][:-1]
except:
continue
# msvc's runtime library doesn't prefix pointers
# with '0x'
# if socket_index[:2] != '0x':
# continue
if socket_index in sockets:
sockets[socket_index] += 1
else:
sockets[socket_index] = 1
items = sockets.items()
items.sort(lambda x, y: y[1] - x[1])
count = 0
for i in items:
print '%s: %d' % (i[0], i[1])
count += 1
if count > 5: break
file.close()
socket_filter = items[0][0]
print '\nfocusing on socket %s' % socket_filter
file = open(sys.argv[1], 'rb')
out_file = 'utp.out%s' % socket_filter;
out = open(out_file, 'wb')
delay_samples = 'dots lc rgb "blue"'
delay_base = 'steps lw 2 lc rgb "purple"'
target_delay = 'steps lw 2 lc rgb "red"'
off_target = 'dots lc rgb "blue"'
cwnd = 'steps lc rgb "green"'
window_size = 'steps lc rgb "sea-green"'
rtt = 'lines lc rgb "light-blue"'
metrics = {
'our_delay':['our delay (ms)', 'x1y2', delay_samples],
'upload_rate':['send rate (B/s)', 'x1y1', 'lines'],
'max_window':['cwnd (B)', 'x1y1', cwnd],
'target_delay':['target delay (ms)', 'x1y2', target_delay],
'cur_window':['bytes in-flight (B)', 'x1y1', window_size],
'cur_window_packets':['number of packets in-flight', 'x1y2', 'steps'],
'packet_size':['current packet size (B)', 'x1y2', 'steps'],
'rtt':['rtt (ms)', 'x1y2', rtt],
'off_target':['off-target (ms)', 'x1y2', off_target],
'delay_sum':['delay sum (ms)', 'x1y2', 'steps'],
'their_delay':['their delay (ms)', 'x1y2', delay_samples],
'get_microseconds':['clock (us)', 'x1y1', 'steps'],
'wnduser':['advertised window size (B)', 'x1y1', 'steps'],
'delay_base':['delay base (us)', 'x1y1', delay_base],
'their_delay_base':['their delay base (us)', 'x1y1', delay_base],
'their_actual_delay':['their actual delay (us)', 'x1y1', delay_samples],
'actual_delay':['actual_delay (us)', 'x1y1', delay_samples]
}
histogram_quantization = 1
socket_index = None
columns = []
begin = None
title = "-"
packet_loss = 0
packet_timeout = 0
delay_histogram = {}
window_size = {'0': 0, '1': 0}
# [35301484] 0x00ec1190: actual_delay:1021583 our_delay:102 their_delay:-1021345 off_target:297 max_window:2687 upload_rate:18942 delay_base:1021481154 delay_sum:-1021242 target_delay:400 acked_bytes:1441 cur_window:2882 scaled_gain:2.432
counter = 0
print "reading log file"
for l in file:
if "UTP_Connect" in l:
title = l[:-2]
if socket_filter != None:
title += ' socket: %s' % socket_filter
else:
title += ' sum of all sockets'
continue
try:
a = l.strip().split(" ")
t = a[0][1:-1]
socket_index = a[1][:-1]
except:
continue
# if socket_index[:2] != '0x':
# continue
if socket_filter != None and socket_index != socket_filter:
continue
counter += 1
if (counter % 300 == 0):
print "\r%d " % counter,
if "lost." in l:
packet_loss = packet_loss + 1
continue
if "Packet timeout" in l:
packet_timeout = packet_timeout + 1
continue
if "our_delay:" not in l:
continue
# used for Logf timestamps
# t, m = t.split(".")
# t = time.strptime(t, "%H:%M:%S")
# t = list(t)
# t[0] += 107
# t = tuple(t)
# m = float(m)
# m /= 1000.0
# t = time.mktime(t) + m
# used for tick count timestamps
t = int(t)
if begin is None:
begin = t
t = t - begin
# print time. Convert from milliseconds to seconds
print >>out, '%f\t' % (float(t)/1000.),
#if t > 200000:
# break
fill_columns = not columns
for i in a[2:]:
try:
n, v = i.split(':')
except:
continue
v = float(v)
if n == "our_delay":
bucket = v / histogram_quantization
delay_histogram[bucket] = 1 + delay_histogram.get(bucket, 0)
if not n in metrics: continue
if fill_columns:
columns.append(n)
if n == "max_window":
window_size[socket_index] = v
print >>out, '%f\t' % int(reduce(lambda a,b: a+b, window_size.values())),
else:
print >>out, '%f\t' % v,
print >>out, float(packet_loss * 8000), float(packet_timeout * 8000)
packet_loss = 0
packet_timeout = 0
out.close()
out = open('%s.histogram' % out_file, 'wb')
for d,f in delay_histogram.iteritems():
print >>out, float(d*histogram_quantization) + histogram_quantization / 2, f
out.close()
plot = [
{
'data': ['upload_rate', 'max_window', 'cur_window', 'wnduser', 'cur_window_packets', 'packet_size', 'rtt'],
'title': 'send-packet-size',
'y1': 'Bytes',
'y2': 'Time (ms)'
},
{
'data': ['our_delay', 'max_window', 'target_delay', 'cur_window', 'wnduser', 'cur_window_packets'],
'title': 'uploading',
'y1': 'Bytes',
'y2': 'Time (ms)'
},
{
'data': ['our_delay', 'max_window', 'target_delay', 'cur_window', 'cur_window_packets'],
'title': 'uploading_packets',
'y1': 'Bytes',
'y2': 'Time (ms)'
},
{
'data': ['get_microseconds'],
'title': 'timer',
'y1': 'Time microseconds',
'y2': 'Time (ms)'
},
{
'data': ['their_delay', 'target_delay', 'rtt'],
'title': 'their_delay',
'y1': '',
'y2': 'Time (ms)'
},
{
'data': ['their_actual_delay','their_delay_base'],
'title': 'their_delay_base',
'y1': 'Time (us)',
'y2': ''
},
{
'data': ['our_delay', 'target_delay', 'rtt'],
'title': 'our-delay',
'y1': '',
'y2': 'Time (ms)'
},
{
'data': ['actual_delay', 'delay_base'],
'title': 'our_delay_base',
'y1': 'Time (us)',
'y2': ''
}
]
out = open('utp.gnuplot', 'w+')
files = ''
#print >>out, 'set xtics 0, 20'
print >>out, "set term png size 1280,800"
print >>out, 'set output "%s.delays.png"' % out_file
print >>out, 'set xrange [0:250]'
print >>out, 'set xlabel "delay (ms)"'
print >>out, 'set boxwidth 1'
print >>out, 'set style fill solid'
print >>out, 'set ylabel "number of packets"'
print >>out, 'plot "%s.histogram" using 1:2 with boxes' % out_file
print >>out, "set style data steps"
#print >>out, "set yrange [0:*]"
print >>out, "set y2range [*:*]"
files += out_file + '.delays.png '
#set hidden3d
#set title "Peer bandwidth distribution"
#set xlabel "Ratio"
for p in plot:
print >>out, 'set title "%s %s"' % (p['title'], title)
print >>out, 'set xlabel "time (s)"'
print >>out, 'set ylabel "%s"' % p['y1']
print >>out, "set tics nomirror"
print >>out, 'set y2tics'
print >>out, 'set y2label "%s"' % p['y2']
print >>out, 'set xrange [0:*]'
print >>out, "set key box"
print >>out, "set term png size 1280,800"
print >>out, 'set output "%s-%s.png"' % (out_file, p['title'])
files += '%s-%s.png ' % (out_file, p['title'])
comma = ''
print >>out, "plot",
for c in p['data']:
if not c in metrics: continue
i = columns.index(c)
print >>out, '%s"%s" using 1:%d title "%s-%s" axes %s with %s' % (comma, out_file, i + 2, metrics[c][0], metrics[c][1], metrics[c][1], metrics[c][2]),
comma = ', '
print >>out, ''
out.close()
os.system("gnuplot utp.gnuplot")
os.system("open %s" % files)
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
688,
0,
3,
0,
0,
688,
0,
0
]
] | [
"import os, sys, time"
] |
# -*- coding: utf-8 -*-
import os
from setuptools import setup, Library
from utp import VERSION
sources = [os.path.join("..", "utp.cpp"),
os.path.join("..", "utp_utils.cpp")]
include_dirs = ["..", os.path.join("..", "utp_config_lib")]
define_macros = []
libraries = []
extra_link_args = []
if os.name == "nt":
define_macros.append(("WIN32", 1))
libraries.append("ws2_32")
sources.append(os.path.join("..", "win32_inet_ntop.cpp"))
extra_link_args.append('/DEF:"../utp.def"')
else:
define_macros.append(("POSIX", 1))
r = os.system('echo "int main() {}"|gcc -x c - -lrt 2>/dev/null')
if r == 0:
libraries.append("rt")
# http://bugs.python.org/issue9023
sources = [os.path.abspath(x) for x in sources]
ext = Library(name="utp",
sources=sources,
include_dirs=include_dirs,
libraries=libraries,
define_macros=define_macros,
extra_link_args=extra_link_args
)
setup(name="utp",
version=VERSION,
description="The uTorrent Transport Protocol library",
author="Greg Hazel",
author_email="greg@bittorrent.com",
maintainer="Greg Hazel",
maintainer_email="greg@bittorrent.com",
url="http://github.com/bittorrent/libutp",
packages=['utp',
'utp.tests'],
ext_modules=[ext],
zip_safe=False,
license='MIT'
)
| [
[
1,
0,
0.0417,
0.0208,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0625,
0.0208,
0,
0.66,
0.0909,
182,
0,
2,
0,
0,
182,
0,
0
],
[
1,
0,
0.1042,
0.0208,
0,
... | [
"import os",
"from setuptools import setup, Library",
"from utp import VERSION",
"sources = [os.path.join(\"..\", \"utp.cpp\"),\n os.path.join(\"..\", \"utp_utils.cpp\")]",
"include_dirs = [\"..\", os.path.join(\"..\", \"utp_config_lib\")]",
"define_macros = []",
"libraries = []",
"extra_lin... |
import os
import ctypes
import socket
import platform
from utp.utp_h import *
from utp.sockaddr_types import *
basepath = os.path.join(os.path.dirname(__file__), "..")
if platform.system() == "Windows":
utp = ctypes.cdll.LoadLibrary(os.path.join(basepath, "utp.dll"))
elif platform.system() == "Darwin":
utp = ctypes.cdll.LoadLibrary(os.path.join(basepath, "libutp.dylib"))
else:
utp = ctypes.cdll.LoadLibrary(os.path.join(basepath, "libutp.so"))
from utp.inet_ntop import inet_ntop, inet_pton
CONNECT = UTP_STATE_CONNECT
WRITABLE = UTP_STATE_WRITABLE
EOF = UTP_STATE_EOF
DESTROYING = UTP_STATE_DESTROYING
CheckTimeouts = utp.UTP_CheckTimeouts
def to_sockaddr(ip, port):
if ":" not in ip:
sin = sockaddr_in()
ctypes.memset(ctypes.byref(sin), 0, ctypes.sizeof(sin))
sin.sin_family = socket.AF_INET
sin.sin_addr.s_addr = inet_addr(ip)
sin.sin_port = socket.htons(port)
return sin
else:
sin6 = sockaddr_in6()
ctypes.memset(ctypes.byref(sin6), 0, ctypes.sizeof(sin6))
sin6.sin6_family = socket.AF_INET6
d = inet_pton(socket.AF_INET6, ip)
# it seems like there should be a better way to do this...
ctypes.memmove(sin6.sin6_addr.Byte, d, ctypes.sizeof(sin6.sin6_addr.Byte))
sin6.sin6_port = socket.htons(port)
return sin6
def from_lpsockaddr(sa, salen):
if sa.contents.ss_family == socket.AF_INET:
assert salen >= ctypes.sizeof(sockaddr_in)
sin = ctypes.cast(sa, psockaddr_in).contents
ip = str(sin.sin_addr.s_addr)
port = socket.ntohs(sin.sin_port)
elif sa.contents.ss_family == socket.AF_INET6:
assert salen >= ctypes.sizeof(sockaddr_in6)
sin6 = ctypes.cast(sa, psockaddr_in6).contents
ip = inet_ntop(socket.AF_INET6, sin6.sin6_addr.Byte)
port = socket.ntohs(sin6.sin6_port)
else:
raise ValueError("unknown address family " + str(sa.contents.family))
return (ip, port)
def wrap_send_to(f):
def unwrap_send_to(userdata, ptr, count, to, tolen):
sa = ctypes.cast(to, LPSOCKADDR_STORAGE)
f(ctypes.string_at(ptr, count), from_lpsockaddr(sa, tolen))
return unwrap_send_to
def wrap_callback(f):
def unwrap_callback(userdata, *a, **kw):
return f(*a, **kw)
return unwrap_callback
class Socket(object):
def set_socket(self, utp_socket, send_to_proc):
self.utp_socket = utp_socket
self.send_to_proc = send_to_proc
def init_outgoing(self, send_to, addr):
send_to_proc = SendToProc(wrap_send_to(send_to))
sin = to_sockaddr(*addr)
utp_socket = utp.UTP_Create(send_to_proc, ctypes.py_object(self),
ctypes.byref(sin), ctypes.sizeof(sin))
self.set_socket(utp_socket, send_to_proc)
def set_callbacks(self, callbacks):
self.callbacks = callbacks
f = UTPFunctionTable(UTPOnReadProc(wrap_callback(self.on_read)),
UTPOnWriteProc(wrap_callback(self.on_write)),
UTPGetRBSize(wrap_callback(callbacks.get_rb_size)),
UTPOnStateChangeProc(wrap_callback(callbacks.on_state)),
UTPOnErrorProc(wrap_callback(callbacks.on_error)),
UTPOnOverheadProc(wrap_callback(callbacks.on_overhead)))
self.functable = f
utp.UTP_SetCallbacks(self.utp_socket,
ctypes.byref(f), ctypes.py_object(self))
def on_read(self, bytes, count):
self.callbacks.on_read(ctypes.string_at(bytes, count))
def on_write(self, bytes, count):
d = self.callbacks.on_write(count)
dst = ctypes.cast(bytes, ctypes.c_void_p).value
ctypes.memmove(dst, d, count)
def connect(self):
if not hasattr(self, "callbacks"):
raise ValueError("Callbacks must be set before connecting")
utp.UTP_Connect(self.utp_socket)
def getpeername(self):
sa = SOCKADDR_STORAGE()
salen = socklen_t(ctypes.sizeof(sa))
utp.UTP_GetPeerName(self.utp_socket, ctypes.byref(sa), ctypes.byref(salen))
return from_lpsockaddr(ctypes.pointer(sa), salen.value)
def rbdrained(self):
utp.UTP_RBDrained(self.utp_socket)
def write(self, to_write):
return utp.UTP_Write(self.utp_socket, to_write)
def close(self):
utp.UTP_Close(self.utp_socket)
# This is just an interface example. You do not have to subclass from it,
# but you do need to pass an object which has this interface.
class Callbacks(object):
def on_read(self, data):
pass
def on_write(self, count):
pass
def get_rb_size(self):
return 0
def on_state(self, state):
pass
def on_error(self, errcode):
pass
def on_overhead(self, send, count, type):
pass
def wrap_incoming(f, send_to_proc):
def unwrap_incoming(userdata, utp_socket):
us = Socket()
us.set_socket(utp_socket, send_to_proc)
f(us)
return unwrap_incoming
def IsIncomingUTP(incoming_connection, send_to, d, addr):
send_to_proc = SendToProc(wrap_send_to(send_to))
if incoming_connection:
incoming_proc = UTPGotIncomingConnection(wrap_incoming(incoming_connection, send_to_proc))
else:
incoming_proc = None
sa = to_sockaddr(*addr)
return utp.UTP_IsIncomingUTP(incoming_proc, send_to_proc, 1, d, len(d),
ctypes.byref(sa), ctypes.sizeof(sa))
| [
[
1,
0,
0.0061,
0.0061,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0122,
0.0061,
0,
0.66,
0.0476,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.0183,
0.0061,
0,
... | [
"import os",
"import ctypes",
"import socket",
"import platform",
"from utp.utp_h import *",
"from utp.sockaddr_types import *",
"basepath = os.path.join(os.path.dirname(__file__), \"..\")",
"if platform.system() == \"Windows\":\n utp = ctypes.cdll.LoadLibrary(os.path.join(basepath, \"utp.dll\"))\n... |
# This module can go away when Python supports IPv6 (meaning inet_ntop and inet_pton on all platforms)
# http://bugs.python.org/issue7171
import socket
import ctypes
from utp.utp_socket import utp
# XXX: the exception types vary from socket.inet_ntop
def inet_ntop(address_family, packed_ip):
if address_family == socket.AF_INET:
# The totals are derived from the following data:
# 15: IPv4 address
# 1: Terminating null byte
length = 16
packed_length = 4
elif address_family == socket.AF_INET6:
# The totals are derived from the following data:
# 45: IPv6 address including embedded IPv4 address
# 11: Scope Id
# 1: Terminating null byte
length = 57
packed_length = 16
else:
raise ValueError("unknown address family " + str(address_family))
if len(packed_ip) != packed_length:
raise ValueError("invalid length of packed IP address string")
dest = ctypes.create_string_buffer(length)
r = utp.inet_ntop(address_family, packed_ip, dest, length)
if r is None:
raise ValueError
return dest.value
# XXX: the exception types vary from socket.inet_pton
def inet_pton(address_family, ip_string):
if address_family == socket.AF_INET:
length = 4
elif address_family == socket.AF_INET6:
length = 16
else:
raise ValueError("unknown address family " + str(address_family))
dest = ctypes.create_string_buffer(length)
r = utp.inet_pton(address_family, ip_string.encode(), dest)
if r != 1:
raise ValueError("illegal IP address string passed to inet_pton")
return dest.raw
inet_ntop = getattr(socket, "inet_ntop", inet_ntop)
inet_pton = getattr(socket, "inet_pton", inet_pton)
| [
[
1,
0,
0.0833,
0.0208,
0,
0.66,
0,
687,
0,
1,
0,
0,
687,
0,
0
],
[
1,
0,
0.1042,
0.0208,
0,
0.66,
0.1667,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.125,
0.0208,
0,
0... | [
"import socket",
"import ctypes",
"from utp.utp_socket import utp",
"def inet_ntop(address_family, packed_ip):\n if address_family == socket.AF_INET:\n # The totals are derived from the following data:\n # 15: IPv4 address \n # 1: Terminating null byte\n length = 16\n ... |
import ctypes
from utp.sockaddr_types import *
# hork
if not hasattr(ctypes, "c_bool"):
ctypes.c_bool = ctypes.c_byte
# Lots of stuff which has to be kept in sync with utp.h...
# I wish ctypes had a C header parser.
UTP_STATE_CONNECT = 1
UTP_STATE_WRITABLE = 2
UTP_STATE_EOF = 3
UTP_STATE_DESTROYING = 4
# typedef void UTPOnReadProc(void *userdata, const byte *bytes, size_t count);
UTPOnReadProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_byte), ctypes.c_size_t)
# typedef void UTPOnWriteProc(void *userdata, byte *bytes, size_t count);
UTPOnWriteProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_byte), ctypes.c_size_t)
# typedef size_t UTPGetRBSize(void *userdata);
UTPGetRBSize = ctypes.CFUNCTYPE(ctypes.c_size_t, ctypes.c_void_p)
# typedef void UTPOnStateChangeProc(void *userdata, int state);
UTPOnStateChangeProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int)
# typedef void UTPOnErrorProc(void *userdata, int errcode);
UTPOnErrorProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int)
# typedef void UTPOnOverheadProc(void *userdata, bool send, size_t count, int type);
UTPOnOverheadProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_bool, ctypes.c_size_t, ctypes.c_int)
class UTPFunctionTable(ctypes.Structure):
_fields_ = (
("on_read", UTPOnReadProc),
("on_write", UTPOnWriteProc),
("get_rb_size", UTPGetRBSize),
("on_state", UTPOnStateChangeProc),
("on_error", UTPOnErrorProc),
("on_overhead", UTPOnOverheadProc),
)
# typedef void UTPGotIncomingConnection(UTPSocket* s);
UTPGotIncomingConnection = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
# typedef void SendToProc(void *userdata, const byte *p, size_t len, const struct sockaddr *to, socklen_t tolen);
SendToProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_byte), ctypes.c_size_t, LPSOCKADDR, socklen_t)
| [
[
1,
0,
0.0196,
0.0196,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.0392,
0.0196,
0,
0.66,
0.0667,
374,
0,
1,
0,
0,
374,
0,
0
],
[
4,
0,
0.1078,
0.0392,
0,
... | [
"import ctypes",
"from utp.sockaddr_types import *",
"if not hasattr(ctypes, \"c_bool\"):\n ctypes.c_bool = ctypes.c_byte",
" ctypes.c_bool = ctypes.c_byte",
"UTP_STATE_CONNECT = 1",
"UTP_STATE_WRITABLE = 2",
"UTP_STATE_EOF = 3",
"UTP_STATE_DESTROYING = 4",
"UTPOnReadProc = ctypes.CFUNCTYPE(No... |
VERSION = '0.1'
| [
[
14,
0,
1,
1,
0,
0.66,
0,
557,
1,
0,
0,
0,
0,
3,
0
]
] | [
"VERSION = '0.1'"
] |
import sys
import utp.utp_socket as utp
import types
import socket
from cStringIO import StringIO
from zope.interface import implements
from twisted.python import failure, log
from twisted.python.util import unsignedID
from twisted.internet import abstract, main, interfaces, error, base, task
from twisted.internet import address, defer
from twisted.internet.tcp import ECONNRESET
from twisted.internet.defer import Deferred, maybeDeferred
from twisted.internet.protocol import DatagramProtocol
def makeAddr(addr):
return address.IPv4Address('UDP', *(addr + ('INET',)))
def _disconnectSelectable(selectable, why, isRead, faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost())
}):
"""
Utility function for disconnecting a selectable.
Supports half-close notification, isRead should be boolean indicating
whether error resulted from doRead().
"""
f = faildict.get(why.__class__)
if f:
if (isRead and why.__class__ == error.ConnectionDone
and interfaces.IHalfCloseableDescriptor.providedBy(selectable)):
selectable.readConnectionLost(f)
else:
selectable.connectionLost(f)
else:
selectable.connectionLost(failure.Failure(why))
class Connection(abstract.FileDescriptor, utp.Callbacks):
def __init__(self, adapter, utp_socket, reactor):
abstract.FileDescriptor.__init__(self, reactor=reactor)
self.reactor.addUTPConnection(self)
self.adapter = adapter
self.protocol = None
self.utp_socket = utp_socket
self.utp_socket.set_callbacks(self)
self.writeTriggered = False
self.writing = False
self.reading = False
logstr = "Uninitialized"
def logPrefix(self):
"""Return the prefix to log with when I own the logging thread.
"""
return self.logstr
def on_read(self, data):
if self.reading:
assert not hasattr(self, "_readBuffer")
self._readBuffer = data
log.callWithLogger(self, self._doReadOrWrite, "doRead")
def doRead(self):
data = self._readBuffer
del self._readBuffer
self.protocol.dataReceived(data)
def get_rb_size(self):
# TODO: extend producer/consumer interfaces in Twisted to support
# fetching the number of bytes before a pauseProducing would happen.
# Then this number, x, would be used like this: rcvbuf - min(x, rcvbuf)
# (so that: rcvbuf-(rcvbuf-x) == x)
return 0
def on_write(self, count):
d = buffer(self._writeBuffer, 0, count)
self._writeBuffer = buffer(self._writeBuffer, count)
return str(d)
def writeSomeData(self, data):
"""
Write as much as possible of the given data to this UTP connection.
The number of bytes successfully written is returned.
"""
if not hasattr(self, "utp_socket"):
return main.CONNECTION_LOST
assert not hasattr(self, "_writeBuffer")
self._writeBuffer = data
self.utp_socket.write(len(data))
sent = len(data) - len(self._writeBuffer)
del self._writeBuffer
return sent
def on_state(self, state):
if state == utp.CONNECT:
self._connectDone()
elif state == utp.WRITABLE:
if self.writing:
self.triggerWrite()
elif state == utp.EOF:
self.loseConnection()
elif state == utp.DESTROYING:
self.reactor.removeUTPConnection(self)
df = maybeDeferred(self.adapter.removeSocket, self.dying_utp_socket)
df.addCallback(self._finishConnectionLost)
del self.dying_utp_socket
def on_error(self, errcode):
if errcode == ECONNRESET:
err = main.CONNECTION_LOST
else:
err = error.errnoMapping.get(errcode, errcode)
self.connectionLost(failure.Failure(err))
def stopReading(self):
self.reading = False
def stopWriting(self):
self.writing = False
def startReading(self):
self.reading = True
def _doReadOrWrite(self, method):
try:
why = getattr(self, method)()
except:
why = sys.exc_info()[1]
log.err()
if why:
_disconnectSelectable(self, why, method=="doRead")
def triggerWrite(self):
self.writeTriggered = False
log.callWithLogger(self, self._doReadOrWrite, "doWrite")
def startWriting(self):
self.writing = True
# UTP socket write state is edge triggered, so we may or may not be
# writable right now. So, just try it. We use reactor.callLater so
# functions like abstract.FileDescriptor.loseConnection don't start
# doWrite before setting self.disconnecting to True.
if not self.writeTriggered:
self.writeTriggered = True
self.reactor.callLater(0, self.triggerWrite)
# These are here because abstract.FileDescriptor claims to implement
# IHalfCloseableDescriptor, but we can not support IHalfCloseableProtocol
def writeConnectionLost(self, reason):
self.connectionLost(reason)
# These are here because abstract.FileDescriptor claims to implement
# IHalfCloseableDescriptor, but we can not support IHalfCloseableProtocol
def readConnectionLost(self, reason):
self.connectionLost(reason)
def connectionLost(self, reason):
abstract.FileDescriptor.connectionLost(self, reason)
if hasattr(self, "utp_socket"):
self.reason = reason
self.utp_socket.close()
self.dying_utp_socket = self.utp_socket
del self.utp_socket
self.closing_df = Deferred()
if hasattr(self, "closing_df"):
return self.closing_df
def _finishConnectionLost(self, r):
protocol = self.protocol
reason = self.reason
df = self.closing_df
del self.protocol
del self.reason
del self.closing_df
if protocol:
protocol.connectionLost(reason)
return df.callback(r)
def getPeer(self):
return makeAddr(self.utp_socket.getpeername())
def getHost(self):
return self.adapter.getHost()
class Client(Connection):
def __init__(self, host, port, connector, adapter, reactor=None, soError=None):
# Connection.__init__ is invoked later in doConnect
self.connector = connector
self.addr = (host, port)
self.adapter = adapter
self.reactor = reactor
self.soError = soError
# ack, twisted. what the heck.
self.reactor.callLater(0, self.resolveAddress)
def __repr__(self):
s = '<%s to %s at %x>' % (self.__class__, self.addr, unsignedID(self))
return s
def stopConnecting(self):
"""Stop attempt to connect."""
return self.failIfNotConnected(error.UserError())
def failIfNotConnected(self, err):
"""
Generic method called when the attemps to connect failed. It basically
cleans everything it can: call connectionFailed, stop read and write,
delete socket related members.
"""
if (self.connected or self.disconnected or
not hasattr(self, "connector")):
return
# HM: maybe call loseConnection, maybe make a new function
self.disconnecting = 1
reason = failure.Failure(err)
# we might not have an adapter if there was a bind error
# but we need to notify the adapter if we failed before connecting
stop = (self.adapter and not hasattr(self, "utp_socket"))
df = maybeDeferred(Connection.connectionLost, self, reason)
if stop:
df.addCallback(lambda r: self.adapter.maybeStopUDPPort())
def more(r):
self.connector.connectionFailed(reason)
del self.connector
self.disconnecting = 0
df.addCallback(more)
return df
def resolveAddress(self):
if abstract.isIPAddress(self.addr[0]):
self._setRealAddress(self.addr[0])
else:
d = self.reactor.resolve(self.addr[0])
d.addCallbacks(self._setRealAddress, self.failIfNotConnected)
def _setRealAddress(self, address):
self.realAddress = (address, self.addr[1])
self.doConnect()
def doConnect(self):
"""I connect the socket.
Then, call the protocol's makeConnection, and start waiting for data.
"""
if self.disconnecting or not hasattr(self, "connector"):
# this happens when the connection was stopped but doConnect
# was scheduled via the resolveAddress callLater
return
if self.soError:
self.failIfNotConnected(self.soError)
return
utp_socket = utp.Socket()
utp_socket.init_outgoing(self.adapter.udpPort.write, self.realAddress)
self.adapter.addSocket(utp_socket)
Connection.__init__(self, self.adapter, utp_socket, self.reactor)
utp_socket.connect()
def _connectDone(self):
self.protocol = self.connector.buildProtocol(self.getPeer())
self.connected = 1
self.logstr = self.protocol.__class__.__name__ + ",client"
self.startReading()
self.protocol.makeConnection(self)
def connectionLost(self, reason):
if not self.connected:
self.failIfNotConnected(error.ConnectError(string=reason))
else:
df = maybeDeferred(Connection.connectionLost, self, reason)
def more(r):
self.connector.connectionLost(reason)
df.addCallback(more)
class Server(Connection):
def __init__(self, utp_socket, protocol, adapter, sessionno, reactor):
Connection.__init__(self, adapter, utp_socket, reactor)
self.protocol = protocol
self.sessionno = sessionno
self.hostname = self.getPeer().host
self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__,
sessionno,
self.hostname)
self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__,
self.sessionno,
self.adapter.udpPort._realPortNumber)
self.startReading()
self.connected = 1
def __repr__(self):
"""A string representation of this connection.
"""
return self.repstr
class Connector(base.BaseConnector):
def __init__(self, host, port, factory, adapter, timeout, reactor=None):
self.host = host
if isinstance(port, types.StringTypes):
try:
port = socket.getservbyname(port, 'tcp')
except socket.error:
e = sys.exc_info()[1]
raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
self.port = port
self.adapter = adapter
self.soError = None
base.BaseConnector.__init__(self, factory, timeout, reactor)
def _makeTransport(self):
return Client(self.host, self.port, self, self.adapter, self.reactor, self.soError)
def getDestination(self):
return address.IPv4Address('UDP', self.host, self.port, 'INET')
class Protocol(DatagramProtocol):
BUFFERSIZE = 2 * 1024 * 1024
def startProtocol(self):
if interfaces.ISystemHandle.providedBy(self.transport):
sock = self.transport.getHandle()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.BUFFERSIZE)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.BUFFERSIZE)
def datagramReceived(self, data, addr):
if self.adapter.acceptIncoming and self.adapter.listening:
cb = self.adapter.connectionReceived
else:
cb = None
utp.IsIncomingUTP(cb, self.transport.write, data, addr)
class Adapter:
def __init__(self, udpPort, acceptIncoming):
self.udpPort = udpPort
self.acceptIncoming = acceptIncoming
# HORK
udpPort.protocol.adapter = self
self.sockets = set()
def addSocket(self, utp_socket):
if not self.udpPort.connected:
assert not self.acceptIncoming
self.udpPort.startListening()
self.sockets.add(utp_socket)
def removeSocket(self, utp_socket):
self.sockets.remove(utp_socket)
return self.maybeStopUDPPort()
def maybeStopUDPPort(self):
if len(self.sockets) == 0:
assert self.udpPort.connected
return self.udpPort.stopListening()
def getHost(self):
return self.udpPort.getHost()
class Port(Adapter, base.BasePort):
implements(interfaces.IListeningPort)
sessionno = 0
def __init__(self, udpPort, factory, reactor):
self.factory = factory
self.reactor = reactor
Adapter.__init__(self, udpPort, acceptIncoming=True)
self.listening = False
def __repr__(self):
if self.udpPort._realPortNumber is not None:
return "<%s of %s on %s>" % (self.__class__, self.factory.__class__,
self.udpPort._realPortNumber)
else:
return "<%s of %s (not listening)>" % (self.__class__, self.factory.__class__)
def maybeStopUDPPort(self):
if not self.listening:
return Adapter.maybeStopUDPPort(self)
def startListening(self):
if self.listening:
return
self.listening = True
if not self.udpPort.connected:
self.udpPort.startListening()
self.factory.doStart()
def stopListening(self):
if not self.listening:
return
self.listening = False
df = maybeDeferred(self.maybeStopUDPPort)
df.addCallback(lambda r: self._connectionLost())
return df
# this one is for stopListening
# the listening port has closed
def _connectionLost(self, reason=None):
assert not self.listening
base.BasePort.connectionLost(self, reason)
self.factory.doStop()
# this one is for calling directly
# the listening port has closed
def connectionLost(self, reason=None):
self.listening = False
self.udpPort.connectionLost(reason)
self._connectionLost(reason)
# a new incoming connection has arrived
def connectionReceived(self, utp_socket):
self.addSocket(utp_socket)
protocol = self.factory.buildProtocol(makeAddr(utp_socket.getpeername()))
if protocol is None:
# XXX: untested path
Connection(self, utp_socket, self.reactor).loseConnection()
return
s = self.sessionno
self.sessionno = s+1
transport = Server(utp_socket, protocol, self, s, self.reactor)
protocol.makeConnection(transport)
def listenUTP(self, port, factory, interface=''):
udpPort = self.listenUDP(port, Protocol(), interface=interface)
utpPort = Port(udpPort, factory, self)
utpPort.startListening()
return utpPort
def createUTPAdapter(self, port, protocol, interface=''):
udpPort = self.listenUDP(port, protocol, interface=interface)
return Adapter(udpPort, acceptIncoming=False)
def connectUTP(self, host, port, factory, timeout=30, bindAddress=None):
if bindAddress is None:
bindAddress = ['', 0]
adapter = None
try:
adapter = self.createUTPAdapter(bindAddress[1], Protocol(), interface=bindAddress[0])
except error.CannotListenError:
e = sys.exc_info()[1]
c = Connector(host, port, factory, None, timeout, self)
se = e.socketError
# We have to call connect to trigger the factory start and connection
# start events, but we already know the connection failed because the
# UDP socket couldn't bind. So we set soError, which causes the connect
# call to fail.
c.soError = error.ConnectBindError(se[0], se[1])
c.connect()
return c
try:
return self.connectUTPUsingAdapter(host, port, factory, adapter, timeout=timeout)
except:
adapter.maybeStopUDPPort()
raise
def connectUTPUsingAdapter(self, host, port, factory, adapter, timeout=30):
c = Connector(host, port, factory, adapter, timeout, self)
c.connect()
return c
# like addReader/addWriter, sort of
def addUTPConnection(self, connection):
if not hasattr(self, "_utp_task"):
self._utp_connections = set()
self._utp_task = task.LoopingCall(utp.CheckTimeouts)
self._utp_task.start(0.050)
self._utp_connections.add(connection)
# like removeReader/removeWriter, sort of
def removeUTPConnection(self, connection):
self._utp_connections.remove(connection)
if len(self._utp_connections) == 0:
self._utp_task.stop()
del self._utp_task
del self._utp_connections
# Ouch.
from twisted.internet.protocol import ClientCreator, _InstanceFactory
def clientCreatorConnectUTP(self, host, port, timeout=30, bindAddress=None):
"""Connect to remote host, return Deferred of resulting protocol instance."""
d = defer.Deferred()
f = _InstanceFactory(self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
self.reactor.connectUTP(host, port, f, timeout=timeout, bindAddress=bindAddress)
return d
ClientCreator.connectUTP = clientCreatorConnectUTP
# Owwww.
from twisted.internet import reactor
reactor.__class__.listenUTP = listenUTP
reactor.__class__.connectUTP = connectUTP
reactor.__class__.createUTPAdapter = createUTPAdapter
reactor.__class__.connectUTPUsingAdapter = connectUTPUsingAdapter
reactor.__class__.addUTPConnection = addUTPConnection
reactor.__class__.removeUTPConnection = removeUTPConnection
del reactor
| [
[
1,
0,
0.0019,
0.0019,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0039,
0.0019,
0,
0.66,
0.027,
579,
0,
1,
0,
0,
579,
0,
0
],
[
1,
0,
0.0058,
0.0019,
0,
0... | [
"import sys",
"import utp.utp_socket as utp",
"import types",
"import socket",
"from cStringIO import StringIO",
"from zope.interface import implements",
"from twisted.python import failure, log",
"from twisted.python.util import unsignedID",
"from twisted.internet import abstract, main, interfaces,... |
import ctypes
import socket
import struct
class SOCKADDR(ctypes.Structure):
_fields_ = (
('family', ctypes.c_ushort),
('data', ctypes.c_byte*14),
)
LPSOCKADDR = ctypes.POINTER(SOCKADDR)
class SOCKET_ADDRESS(ctypes.Structure):
_fields_ = (
('address', LPSOCKADDR),
('length', ctypes.c_int),
)
ADDRESS_FAMILY = ctypes.c_ushort
_SS_MAXSIZE = 128
_SS_ALIGNSIZE = ctypes.sizeof(ctypes.c_int64)
_SS_PAD1SIZE = (_SS_ALIGNSIZE - ctypes.sizeof(ctypes.c_ushort))
_SS_PAD2SIZE = (_SS_MAXSIZE - (ctypes.sizeof(ctypes.c_ushort) + _SS_PAD1SIZE + _SS_ALIGNSIZE))
class SOCKADDR_STORAGE(ctypes.Structure):
_fields_ = (
('ss_family', ADDRESS_FAMILY),
('__ss_pad1', ctypes.c_char * _SS_PAD1SIZE),
('__ss_align', ctypes.c_int64),
('__ss_pad2', ctypes.c_char * _SS_PAD2SIZE),
)
LPSOCKADDR_STORAGE = ctypes.POINTER(SOCKADDR_STORAGE)
class IPAddr(ctypes.Structure):
_fields_ = (
("S_addr", ctypes.c_ulong),
)
def __str__(self):
return socket.inet_ntoa(struct.pack("L", self.S_addr))
class in_addr(ctypes.Structure):
_fields_ = (
("s_addr", IPAddr),
)
class in6_addr(ctypes.Structure):
_fields_ = (
("Byte", ctypes.c_ubyte * 16),
)
class sockaddr_in(ctypes.Structure):
_fields_ = (
("sin_family", ADDRESS_FAMILY),
("sin_port", ctypes.c_ushort),
("sin_addr", in_addr),
("szDescription", ctypes.c_char * 8),
)
psockaddr_in = ctypes.POINTER(sockaddr_in)
class sockaddr_in6(ctypes.Structure):
_fields_ = (
("sin6_family", ADDRESS_FAMILY),
("sin6_port", ctypes.c_ushort),
("sin6_flowinfo", ctypes.c_ulong),
("sin6_addr", in6_addr),
("sin6_scope_id", ctypes.c_ulong),
)
psockaddr_in6 = ctypes.POINTER(sockaddr_in6)
socklen_t = ctypes.c_int
def inet_addr(ip):
return IPAddr(struct.unpack("L", socket.inet_aton(ip))[0])
| [
[
1,
0,
0.0125,
0.0125,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.025,
0.0125,
0,
0.66,
0.0476,
687,
0,
1,
0,
0,
687,
0,
0
],
[
1,
0,
0.0375,
0.0125,
0,
0... | [
"import ctypes",
"import socket",
"import struct",
"class SOCKADDR(ctypes.Structure):\n _fields_ = (\n ('family', ctypes.c_ushort),\n ('data', ctypes.c_byte*14),\n )",
" _fields_ = (\n ('family', ctypes.c_ushort),\n ('data', ctypes.c_byte*14),\n )",
"LPSOCKA... |
'''
Module which brings history information about files from Mercurial.
@author: Rodrigo Damazio
'''
import re
import subprocess
REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')
def _GetOutputLines(args):
'''
Runs an external process and returns its output as a list of lines.
@param args: the arguments to run
'''
process = subprocess.Popen(args,
stdout=subprocess.PIPE,
universal_newlines = True,
shell = False)
output = process.communicate()[0]
return output.splitlines()
def FillMercurialRevisions(filename, parsed_file):
'''
Fills the revs attribute of all strings in the given parsed file with
a list of revisions that touched the lines corresponding to that string.
@param filename: the name of the file to get history for
@param parsed_file: the parsed file to modify
'''
# Take output of hg annotate to get revision of each line
output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename])
# Create a map of line -> revision (key is list index, line 0 doesn't exist)
line_revs = ['dummy']
for line in output_lines:
rev_match = REVISION_REGEX.match(line)
if not rev_match:
raise 'Unexpected line of output from hg: %s' % line
rev_hash = rev_match.group('hash')
line_revs.append(rev_hash)
for str in parsed_file.itervalues():
# Get the lines that correspond to each string
start_line = str['startLine']
end_line = str['endLine']
# Get the revisions that touched those lines
revs = []
for line_number in range(start_line, end_line + 1):
revs.append(line_revs[line_number])
# Merge with any revisions that were already there
# (for explict revision specification)
if 'revs' in str:
revs += str['revs']
# Assign the revisions to the string
str['revs'] = frozenset(revs)
def DoesRevisionSuperceed(filename, rev1, rev2):
'''
Tells whether a revision superceeds another.
This essentially means that the older revision is an ancestor of the newer
one.
This also returns True if the two revisions are the same.
@param rev1: the revision that may be superceeding the other
@param rev2: the revision that may be superceeded
@return: True if rev1 superceeds rev2 or they're the same
'''
if rev1 == rev2:
return True
# TODO: Add filename
args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename]
output_lines = _GetOutputLines(args)
return rev2 in output_lines
def NewestRevision(filename, rev1, rev2):
'''
Returns which of two revisions is closest to the head of the repository.
If none of them is the ancestor of the other, then we return either one.
@param rev1: the first revision
@param rev2: the second revision
'''
if DoesRevisionSuperceed(filename, rev1, rev2):
return rev1
return rev2 | [
[
8,
0,
0.0319,
0.0532,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0745,
0.0106,
0,
0.66,
0.1429,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0851,
0.0106,
0,
0.66... | [
"'''\nModule which brings history information about files from Mercurial.\n\n@author: Rodrigo Damazio\n'''",
"import re",
"import subprocess",
"REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')",
"def _GetOutputLines(args):\n '''\n Runs an external process and returns its output as a list of lines... |
#!/usr/bin/python
'''
Entry point for My Tracks i18n tool.
@author: Rodrigo Damazio
'''
import mytracks.files
import mytracks.translate
import mytracks.validate
import sys
def Usage():
print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0]
print 'Commands are:'
print ' cleanup'
print ' translate'
print ' validate'
sys.exit(1)
def Translate(languages):
'''
Asks the user to interactively translate any missing or oudated strings from
the files for the given languages.
@param languages: the languages to translate
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
missing = validator.missing_in_lang()
outdated = validator.outdated_in_lang()
for lang in languages:
untranslated = missing[lang] + outdated[lang]
if len(untranslated) == 0:
continue
translator = mytracks.translate.Translator(lang)
translator.Translate(untranslated)
def Validate(languages):
'''
Computes and displays errors in the string files for the given languages.
@param languages: the languages to compute for
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
error_count = 0
if (validator.valid()):
print 'All files OK'
else:
for lang, missing in validator.missing_in_master().iteritems():
print 'Missing in master, present in %s: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, missing in validator.missing_in_lang().iteritems():
print 'Missing in %s, present in master: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, outdated in validator.outdated_in_lang().iteritems():
print 'Outdated in %s: %s:' % (lang, str(outdated))
error_count = error_count + len(outdated)
return error_count
if __name__ == '__main__':
argv = sys.argv
argc = len(argv)
if argc < 2:
Usage()
languages = mytracks.files.GetAllLanguageFiles()
if argc == 3:
langs = set(argv[2:])
if not langs.issubset(languages):
raise 'Language(s) not found'
# Filter just to the languages specified
languages = dict((lang, lang_file)
for lang, lang_file in languages.iteritems()
if lang in langs or lang == 'en' )
cmd = argv[1]
if cmd == 'translate':
Translate(languages)
elif cmd == 'validate':
error_count = Validate(languages)
else:
Usage()
error_count = 0
print '%d errors found.' % error_count
| [
[
8,
0,
0.0417,
0.0521,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0833,
0.0104,
0,
0.66,
0.125,
640,
0,
1,
0,
0,
640,
0,
0
],
[
1,
0,
0.0938,
0.0104,
0,
0.66,... | [
"'''\nEntry point for My Tracks i18n tool.\n\n@author: Rodrigo Damazio\n'''",
"import mytracks.files",
"import mytracks.translate",
"import mytracks.validate",
"import sys",
"def Usage():\n print('Usage: %s <command> [<language> ...]\\n' % sys.argv[0])\n print('Commands are:')\n print(' cleanup')\n p... |
'''
Module which compares languague files to the master file and detects
issues.
@author: Rodrigo Damazio
'''
import os
from mytracks.parser import StringsParser
import mytracks.history
class Validator(object):
def __init__(self, languages):
'''
Builds a strings file validator.
Params:
@param languages: a dictionary mapping each language to its corresponding directory
'''
self._langs = {}
self._master = None
self._language_paths = languages
parser = StringsParser()
for lang, lang_dir in languages.iteritems():
filename = os.path.join(lang_dir, 'strings.xml')
parsed_file = parser.Parse(filename)
mytracks.history.FillMercurialRevisions(filename, parsed_file)
if lang == 'en':
self._master = parsed_file
else:
self._langs[lang] = parsed_file
self._Reset()
def Validate(self):
'''
Computes whether all the data in the files for the given languages is valid.
'''
self._Reset()
self._ValidateMissingKeys()
self._ValidateOutdatedKeys()
def valid(self):
return (len(self._missing_in_master) == 0 and
len(self._missing_in_lang) == 0 and
len(self._outdated_in_lang) == 0)
def missing_in_master(self):
return self._missing_in_master
def missing_in_lang(self):
return self._missing_in_lang
def outdated_in_lang(self):
return self._outdated_in_lang
def _Reset(self):
# These are maps from language to string name list
self._missing_in_master = {}
self._missing_in_lang = {}
self._outdated_in_lang = {}
def _ValidateMissingKeys(self):
'''
Computes whether there are missing keys on either side.
'''
master_keys = frozenset(self._master.iterkeys())
for lang, file in self._langs.iteritems():
keys = frozenset(file.iterkeys())
missing_in_master = keys - master_keys
missing_in_lang = master_keys - keys
if len(missing_in_master) > 0:
self._missing_in_master[lang] = missing_in_master
if len(missing_in_lang) > 0:
self._missing_in_lang[lang] = missing_in_lang
def _ValidateOutdatedKeys(self):
'''
Computers whether any of the language keys are outdated with relation to the
master keys.
'''
for lang, file in self._langs.iteritems():
outdated = []
for key, str in file.iteritems():
# Get all revisions that touched master and language files for this
# string.
master_str = self._master[key]
master_revs = master_str['revs']
lang_revs = str['revs']
if not master_revs or not lang_revs:
print 'WARNING: No revision for %s in %s' % (key, lang)
continue
master_file = os.path.join(self._language_paths['en'], 'strings.xml')
lang_file = os.path.join(self._language_paths[lang], 'strings.xml')
# Assume that the repository has a single head (TODO: check that),
# and as such there is always one revision which superceeds all others.
master_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2),
master_revs)
lang_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2),
lang_revs)
# If the master version is newer than the lang version
if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev):
outdated.append(key)
if len(outdated) > 0:
self._outdated_in_lang[lang] = outdated
| [
[
8,
0,
0.0304,
0.0522,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0696,
0.0087,
0,
0.66,
0.25,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0783,
0.0087,
0,
0.66,
... | [
"'''\nModule which compares languague files to the master file and detects\nissues.\n\n@author: Rodrigo Damazio\n'''",
"import os",
"from mytracks.parser import StringsParser",
"import mytracks.history",
"class Validator(object):\n\n def __init__(self, languages):\n '''\n Builds a strings file valida... |
'''
Module for dealing with resource files (but not their contents).
@author: Rodrigo Damazio
'''
import os.path
from glob import glob
import re
MYTRACKS_RES_DIR = 'MyTracks/res'
ANDROID_MASTER_VALUES = 'values'
ANDROID_VALUES_MASK = 'values-*'
def GetMyTracksDir():
'''
Returns the directory in which the MyTracks directory is located.
'''
path = os.getcwd()
while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)):
if path == '/':
raise 'Not in My Tracks project'
# Go up one level
path = os.path.split(path)[0]
return path
def GetAllLanguageFiles():
'''
Returns a mapping from all found languages to their respective directories.
'''
mytracks_path = GetMyTracksDir()
res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK)
language_dirs = glob(res_dir)
master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES)
if len(language_dirs) == 0:
raise 'No languages found!'
if not os.path.isdir(master_dir):
raise 'Couldn\'t find master file'
language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs]
language_tuples.append(('en', master_dir))
return dict(language_tuples)
| [
[
8,
0,
0.0667,
0.1111,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1333,
0.0222,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.1556,
0.0222,
0,
0.66,
... | [
"'''\nModule for dealing with resource files (but not their contents).\n\n@author: Rodrigo Damazio\n'''",
"import os.path",
"from glob import glob",
"import re",
"MYTRACKS_RES_DIR = 'MyTracks/res'",
"ANDROID_MASTER_VALUES = 'values'",
"ANDROID_VALUES_MASK = 'values-*'",
"def GetMyTracksDir():\n '''\n... |
'''
Module which prompts the user for translations and saves them.
TODO: implement
@author: Rodrigo Damazio
'''
class Translator(object):
'''
classdocs
'''
def __init__(self, language):
'''
Constructor
'''
self._language = language
def Translate(self, string_names):
print string_names | [
[
8,
0,
0.1905,
0.3333,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
3,
0,
0.7143,
0.619,
0,
0.66,
1,
229,
0,
2,
0,
0,
186,
0,
1
],
[
8,
1,
0.5238,
0.1429,
1,
0.79,
... | [
"'''\nModule which prompts the user for translations and saves them.\n\nTODO: implement\n\n@author: Rodrigo Damazio\n'''",
"class Translator(object):\n '''\n classdocs\n '''\n\n def __init__(self, language):\n '''\n Constructor",
" '''\n classdocs\n '''",
" def __init__(self, language):\n '''... |
'''
Module which parses a string XML file.
@author: Rodrigo Damazio
'''
from xml.parsers.expat import ParserCreate
import re
#import xml.etree.ElementTree as ET
class StringsParser(object):
'''
Parser for string XML files.
This object is not thread-safe and should be used for parsing a single file at
a time, only.
'''
def Parse(self, file):
'''
Parses the given file and returns a dictionary mapping keys to an object
with attributes for that key, such as the value, start/end line and explicit
revisions.
In addition to the standard XML format of the strings file, this parser
supports an annotation inside comments, in one of these formats:
<!-- KEEP_PARENT name="bla" -->
<!-- KEEP_PARENT name="bla" rev="123456789012" -->
Such an annotation indicates that we're explicitly inheriting form the
master file (and the optional revision says that this decision is compatible
with the master file up to that revision).
@param file: the name of the file to parse
'''
self._Reset()
# Unfortunately expat is the only parser that will give us line numbers
self._xml_parser = ParserCreate()
self._xml_parser.StartElementHandler = self._StartElementHandler
self._xml_parser.EndElementHandler = self._EndElementHandler
self._xml_parser.CharacterDataHandler = self._CharacterDataHandler
self._xml_parser.CommentHandler = self._CommentHandler
file_obj = open(file)
self._xml_parser.ParseFile(file_obj)
file_obj.close()
return self._all_strings
def _Reset(self):
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
self._all_strings = {}
def _StartElementHandler(self, name, attrs):
if name != 'string':
return
if 'name' not in attrs:
return
assert not self._currentString
assert not self._currentStringName
self._currentString = {
'startLine' : self._xml_parser.CurrentLineNumber,
}
if 'rev' in attrs:
self._currentString['revs'] = [attrs['rev']]
self._currentStringName = attrs['name']
self._currentStringValue = ''
def _EndElementHandler(self, name):
if name != 'string':
return
assert self._currentString
assert self._currentStringName
self._currentString['value'] = self._currentStringValue
self._currentString['endLine'] = self._xml_parser.CurrentLineNumber
self._all_strings[self._currentStringName] = self._currentString
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
def _CharacterDataHandler(self, data):
if not self._currentString:
return
self._currentStringValue += data
_KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+'
r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?'
r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*',
re.MULTILINE | re.DOTALL)
def _CommentHandler(self, data):
keep_parent_match = self._KEEP_PARENT_REGEX.match(data)
if not keep_parent_match:
return
name = keep_parent_match.group('name')
self._all_strings[name] = {
'keepParent' : True,
'startLine' : self._xml_parser.CurrentLineNumber,
'endLine' : self._xml_parser.CurrentLineNumber
}
rev = keep_parent_match.group('rev')
if rev:
self._all_strings[name]['revs'] = [rev] | [
[
8,
0,
0.0261,
0.0435,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0609,
0.0087,
0,
0.66,
0.3333,
573,
0,
1,
0,
0,
573,
0,
0
],
[
1,
0,
0.0696,
0.0087,
0,
0.66... | [
"'''\nModule which parses a string XML file.\n\n@author: Rodrigo Damazio\n'''",
"from xml.parsers.expat import ParserCreate",
"import re",
"class StringsParser(object):\n '''\n Parser for string XML files.\n\n This object is not thread-safe and should be used for parsing a single file at\n a time, only.\n... |
#!/usr/bin/python
#Developed by Florin Nicusor Coada for 216 CR
#Based on the udp_chat_server2.py tutorial from professor Christopher Peters
import socket
HOST = '192.168.1.2' #Defaults to "this machine"
IPORT = 50007 #In
OPORT = 50008 #Out
in_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
in_socket.bind((HOST, IPORT))
out_socket= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Who's who
#address to name dict
users={}
##send message to all users
def sendAll(data):
print "sending", data,"to",
for i in users:
out_socket.sendto(data,(i,OPORT))
print i
##kick user
def kick(user,address):
global users
temp={}
##reacreate a list of users without the user that is going to be kicked
for i in users:
if users[i]!=user:
temp[i]=users[i]
else:
##if the user is online, send a message telling him that
##he has been kicked
out_socket.sendto("You have been kicked",(i,OPORT))
if temp==users:
##if user not found return the message to admin
out_socket.sendto("User {0} not found".format(user),(address,OPORT))
else :
##recreate the list without the user that was kicked
users=temp
##ban user (works identical with kick, just different messages returned)
def ban(user,address):
global users
temp={}
for i in users:
if users[i]!=user:
temp[i]=users[i]
else:
out_socket.sendto("You have been banned",(i,OPORT))
if temp==users:
out_socket.sendto("User {0} not found".format(user),(address,OPORT))
else :
users=temp
##remove function used to remove users from the list when they quit
def remove(address):
global users
temp={}
##create a list of users without the quitting user
##and then reinitialise the users list
for i in users:
if i!=address:
temp[i]=users[i]
users=temp
##return a list of users using a special format
##used to identify the users online
def getUsers():
userList="ulist:"
for i in users:
userList+=" "+users[i]
userList+=" "
out_socket.sendto(userList,(i,OPORT))
##send message to a certain user
##used by the private message
def sendTo(user,message,address):
data="From "+user+": "+message
k=0
##look for the recieving user
for i in users:
if users[i]==user:
##if found send message
out_socket.sendto(data,(i,OPORT))
k=1
##if user not found return message to sender
if(k==0):
out_socket.sendto("User {0} not found".format(user),(address,OPORT))
while 1:
#step 1 - Get any data
data,address = in_socket.recvfrom(1024)
address=address[0] #Strip to just IP address
##step 2 - check for special messages
if data=="quit":
remove(address) #Make sure clients quit
#break #For debugging only
##kick case
elif data.startswith("/kick"):
user=data[data.find("-")+1:]
kick(user,address)
##ban case
elif data.startswith("/ban"):
user=data[data.find("-")+1:]
ban(user,address)
##update case
elif data.startswith("/update"):
getUsers()
##private message case
elif data.startswith("/pm"):
user=data[data.find("-")+1:data.find(":")]
message=data[data.find(":")+1:]
print user," ",message
sendTo(user,message,address)
##user case
elif data.startswith("user"):
#New user /change of name
# e.g user:james
username=data[data.find(":")+1:]
##change of name
if users.has_key(address):
sendAll("%s is now called %s"%(users[address],username))
##new users joining
else:
sendAll("%s(%s) has joined"%(username,address))
users[address]=username
## general message
else:
sendAll("%s: %s"%(users[address],data))
out_socket.close()
in_socket.close()
| [
[
1,
0,
0.0284,
0.0071,
0,
0.66,
0,
687,
0,
1,
0,
0,
687,
0,
0
],
[
14,
0,
0.0496,
0.0071,
0,
0.66,
0.0625,
180,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0567,
0.0071,
0,
... | [
"import socket",
"HOST = '192.168.1.2' #Defaults to \"this machine\"",
"IPORT = 50007 #In",
"OPORT = 50008 #Out",
"in_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)",
"in_socket.bind((HOST, IPORT))",
"out_socket= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)",
"users={}",
"def sendA... |
##Developed by Florin Nicusor Coada for 216CR
##Based on the tutorial offered by Christopher Peters
import sqlite3 as sqlite
import SimpleXMLRPCServer
##connect to the database and create a simple users table
con = sqlite.connect(":memory:")
con.execute("create table users(name varchar primary key, pass varchar, ban integer, admin integer)")
cur=con.cursor()
cur.execute("insert into users values ('Florin','cocouta',0,1)")
cur.execute("insert into users values('Dudu','cainerosu',0,0)")
cur.execute("insert into users values('Coco','spammer',0,0)")
cur.execute("insert into users values('Fraguta','cocotat',0,0)")
cur.execute("insert into users values('q','q',1,0)")
class User:
def __init__(self):
self.users={}
##check to see if login details are correct
def checkUser(self,name,passw):
cur.execute("select * from users where name like '{0}'".format(name))
for item in cur:
if(item[0]==name and item[1]==passw):
if(item[2]==1):
return 2
return 1
return 0
##add another user to the database
def addUser(self,name,passw):
cur.execute("select name from users where name like '{0}'".format(name))
for item in cur:
if(str(item[0]).upper()==name.upper()):
return 0
cur.execute("insert into users values ('{0}','{1}',0,0)".format(name,passw))
return 1
##check to see if user has admin privileges
def userType(self,name):
cur.execute("select admin,name from users where name like '{0}'".format(name))
for item in cur:
if(item[0]==1):
return 1
else :
return 0
##change the name of an existing user
def newName(self,name,newname):
cur.execute("select name from users where name like '{0}'".format(newname))
for item in cur:
if(str(item[0]).upper()==newname.upper()):
return 0
cur.execute("update users set name='{0}' where name like '{1}'".format(newname,name))
return 1
##change the password of an existing user
def newPassword(self,oldpass,newpass,name):
cur.execute("select pass from users where name like '{0}'".format(name))
for item in cur:
if(item[0]==oldpass):
cur.execute("update users set pass='{0}' where name like '{1}'".format(newpass,name))
return 1
return 0
##ban a user
def banUser(self,name):
cur.execute("update users set ban=1 where name like '{0}'".format(name))
return 1
user_obj=User()
server=SimpleXMLRPCServer.SimpleXMLRPCServer(("192.168.1.2", 8888))
server.register_instance(user_obj)
#Go into the main listener loop
server.serve_forever()
| [
[
1,
0,
0.0405,
0.0135,
0,
0.66,
0,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0541,
0.0135,
0,
0.66,
0.0714,
73,
0,
1,
0,
0,
73,
0,
0
],
[
14,
0,
0.0946,
0.0135,
0,
0... | [
"import sqlite3 as sqlite",
"import SimpleXMLRPCServer",
"con = sqlite.connect(\":memory:\")",
"con.execute(\"create table users(name varchar primary key, pass varchar, ban integer, admin integer)\")",
"cur=con.cursor()",
"cur.execute(\"insert into users values ('Florin','cocouta',0,1)\")",
"cur.execute... |
#!/usr/bin/python
#Developed by Florin Nicusor Coada for 216 CR
#Based on the udp_chat_client2.py tutorial from professor Christopher Peters
from Tkinter import *
import socket,select
from login import *
import sys
HOST = '192.168.1.2' #Server
OPORT = 50007 # The same port as used by the server
IPORT=50008 #Listening port
out_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
in_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
in_socket.bind(('', IPORT))
user=log()
out_socket.sendto("user:%s"%user,(HOST,OPORT))
##GUI interface
class MyMenu:
def __init__(self,parent):
self.mainframe=Frame(parent)
frame=Frame(self.mainframe)
frame.grid(row=0,column=0)
self.user=user
##Area above chat
self.titleLabel=Label(frame,text="Battle Botz",bg="LightGoldenrod2",font=("Helvetica",24))
self.titleLabel.grid(row=1,column=0,columnspan=5,sticky=NSEW)
self.meLabel=Label(frame,text="by Florin N. Coada",bg="LightGoldenrod2")
self.meLabel.grid(row=1,column=5,columnspan=2,sticky=NSEW)
self.createButton=Button(frame,text="Create")
self.createButton.grid(column=2,row=2,sticky=NSEW)
self.joinButton=Button(frame,text="Join",width=5)
self.joinButton.grid(column=3,columnspan=2,row=2,sticky=NSEW)
self.arangeLabel=Label(frame,width=50)
self.arangeLabel.grid(row=2,column=0,columnspan=2)
##Chat related area
self.textArea=Listbox(frame)
self.typeArea=Entry(frame)
self.sendButton=Button(frame,text="Send",command=self.addToChat,background = 'LightGoldenrod2')
self.users=Label(frame,text="Users:",background = 'LightGoldenrod')
self.userList=Listbox(frame,width=20)
self.scrollbar=Scrollbar(frame)
self.option=Button(frame,text="Options",command=self.newDetails)
self.exit=Button(frame,text="Exit",command=self.exitChat)
self.textArea.grid(column=0,columnspan=4,row=3,rowspan=2,sticky=NSEW)
self.typeArea.grid(column=0,columnspan=3,row=5,rowspan=2,sticky=NSEW)
self.sendButton.grid(column=3,columnspan=2,row=5,sticky=NSEW)
self.userList.grid(column=5,row=4,columnspan=2,sticky=NSEW)
self.users.grid(column=5,row=2,rowspan=2,columnspan=2,sticky=NSEW)
self.scrollbar.grid(column=4,row=3,rowspan=2,sticky=NSEW)
self.option.grid(column=5,row=5,sticky=NSEW)
self.exit.grid(column=6,row=5,sticky=NSEW)
self.scrollbar.configure(command=self.textArea.yview)
self.kickState=0;
## set up the main window
self.mainframe.grid()
## set the title
self.mainframe.master.title("Chat box")
def addToChat(self,*ignore):
message=self.typeArea.get()
if(self.kickState==0 and self.checkMsg(message)==1):
out_socket.sendto(message,(HOST,OPORT))
elif (self.kickState==1):
self.textArea.insert(END,"You have been kicked")
self.textArea.yview(END)
elif (self.kickState==2):
self.textArea.insert(END,"You have been banned")
self.textArea.yview(END)
if self.typeArea.get()=="quit":
self.exitChat()
self.typeArea.delete(0,END)
def updateChat(self):
rlist,wlist,elist=select.select([in_socket],[],[],1)
if len(rlist)!=0:
data=in_socket.recv(1024)
if len(data)!=0 and data.startswith("ulist:")==False:
self.textArea.insert(END,data)
if data.startswith("From"):
self.textArea.itemconfig(END,fg="DarkSeaGreen")
if (data=="You have been kicked"):
self.kickState=1;
elif (data=="You have been banned"):
self.kickState=2;
self.textArea.yview(END)
if(self.kickState==0):
self.userUpdate()
main_win.after(1000,self.updateChat)
def userUpdate(self):
out_socket.sendto("/update",(HOST,OPORT))
k=in_socket.recv(1024)
self.userList.delete(0,END)
tag="Admin"
if (k.startswith("ulist:")):
k=k[k.find(":")+1:]
while k!="":
k=k[k.find(" ")+1:]
user=k[:k.find(" ")]
if k!="":
if(userType(user)==1):
tag="Admin"
else:
tag="User"
self.userList.insert(END,user+" - "+tag)
if (tag=="Admin"):
self.userList.itemconfig(END,fg="RED")
def newDetails(self):
data=details(self.user)
if data[1]!="":
out_socket.sendto("user:"+data[1],(HOST,OPORT))
self.user=data[1]
def exitChat(self):
out_socket.sendto("{0} has left".format(self.user),(HOST,OPORT))
out_socket.sendto("/kick -{0}".format(self.user),(HOST,OPORT))
sys.exit()
def checkMsg(self,message):
if message=="":
return 0
elif message.startswith("/kick"):
if(userType(self.user)==1):
return 1
else:
self.textArea.insert(END,"You are not an admin!")
return 0
elif message.startswith("/ban"):
if(userType(self.user)==1):
name=message[message.find("-")+1:]
banUser(name)
return 1
else:
self.textArea.insert(END,"You are not an admin!")
return 0
elif message.startswith("user:"):
name=message[message.find(":")+1:]
if(newName(self.user,name)==1):
out_socket.sendto(message,(HOST,OPORT))
self.user=name
return 1
else :
self.textArea.insert(END,"Name already taken")
return 0
return 1
##new tkinter root
main_win=Tk()
app = MyMenu(main_win)
main_win.bind('<Return>',app.addToChat)
main_win.after(1000,app.updateChat)
main_win.mainloop()
#Close the socket
out_socket.close()
in_socket.close()
| [
[
1,
0,
0.0244,
0.0061,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0305,
0.0061,
0,
0.66,
0.0526,
687,
0,
2,
0,
0,
687,
0,
0
],
[
1,
0,
0.0366,
0.0061,
0,
... | [
"from Tkinter import *",
"import socket,select",
"from login import *",
"import sys",
"HOST = '192.168.1.2' #Server",
"OPORT = 50007 # The same port as used by the server",
"IPORT=50008 #Listening port",
"out_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)",
"in_socket = socket.socket(s... |
from Tkinter import *
import xmlrpclib
from time import clock, time
server = xmlrpclib.ServerProxy("http://192.168.1.2:8888")
def userType(user):
return server.userType(user)
def newName(oldUname,newUname):
return server.newName(oldUname,newUname)
def banUser(name):
server.banUser(name)
class MyDetails:
def __init__(self,parent,uname):
self.mainframe=Frame(parent)
frame=Frame(self.mainframe)
frame.grid(row=0,column=0)
self.data={} ##data[1] - new name, [2] - new password
self.data[1]=""
self.data[2]=""
self.done=0
self.uname=uname ##used to search the database fo the old pass
##Title labels
self.changeName=Label(frame,text="Change your name",background = 'LightGoldenrod1')
self.changePassword=Label(frame,text="Change your password",background = 'LightGoldenrod1')
self.changeName.grid(row=0,column=0,columnspan=4,sticky=NSEW)
self.changePassword.grid(row=2,column=0,columnspan=4,sticky=NSEW)
##entries and labels
self.newName=Label(frame,text="New name:")
self.oldPass=Label(frame,text="Old Password:")
self.newPass=Label(frame,text="New Password:")
self.newNameEntry=Entry(frame,width=35)
self.oldPassEntry=Entry(frame,width=35,show="*")
self.newPassEntry=Entry(frame,width=35,show="*")
self.newName.grid(row=1,column=0)
self.newNameEntry.grid(row=1,column=1,columnspan=3)
self.oldPass.grid(row=3,column=0)
self.oldPassEntry.grid(row=3,column=1,columnspan=3)
self.newPass.grid(row=4,column=0)
self.newPassEntry.grid(row=4,column=1,columnspan=3)
self.mainframe.grid()
self.mainframe.master.title("Change details")
##button
self.changeName=Button(frame,text="Change Name",command=self.chName)
self.changePass=Button(frame,text="Change Password",command=self.chPass)
self.changeAll=Button(frame,text="Change all",command=self.chAll)
self.exitBtn=Button(frame,text="Exit",command=self.exitDet)
self.changeName.grid(row=5,column=0,sticky=NSEW)
self.changePass.grid(row=5,column=1,sticky=NSEW)
self.changeAll.grid(row=5,column=2,sticky=NSEW)
self.exitBtn.grid(row=5,column=3,sticky=NSEW)
##warnings label
self.warningLabel=Label(frame,text="")
self.warningLabel.grid(row=6,column=0,columnspan=4,sticky=NSEW)
def exitDet(self):
self.done=1
def chName(self):
if self.newNameEntry.get()!="":
if newName(self.uname,self.newNameEntry.get())==1:
self.data[1]=self.newNameEntry.get()
self.done=1
else:
self.warningLabel.configure(text="Name already in use",background = 'DarkRed')
self.warningLabel.update_idletasks()
self.done=0
def chPass(self):
if self.newPassEntry.get()!="":
if server.newPassword(self.oldPassEntry.get(),self.data[2],self.uname)==1:
self.data[2]=self.newPassEntry.get()
self.done= 1
else:
self.warningLabel.configure(text="Password incorect",background = 'DarkRed')
self.warningLabel.update_idletasks()
self.done=0
def chAll(self,*ignore):
if self.newNameEntry.get()!="" and self.newPassEntry.get()!="":
self.data[2]=self.newPassEntry.get()
server.newPassword(self.oldPassEntry.get(),self.data[2],self.uname)
self.data[1]=self.newNameEntry.get()
server.newName(self.uname,self.data[1])
self.done=1
else:
self.warningLabel.configure(text="Name or password incorect/not inserted",background = 'DarkRed')
self.warningLabel.update_idletasks()
self.done=0
##GUI login interface
class MyLogin:
def __init__(self,parent):
self.mainframe=Frame(parent)
frame=Frame(self.mainframe)
frame.grid(row=0,column=0)
self.UserLabel=Label(frame,text="User:")
self.PassLabel=Label(frame,text="Password:")
self.TextLabel=Label(frame,text="")
self.UserEntry=Entry(frame,width=30)
self.PassEntry=Entry(frame,show="*",width=30)
self.LogIn=Button(frame,text="LogIn",command=self.DoLogIn)
self.Reg=Button(frame,text="Register",command=self.Register)
##Grid set up
self.UserLabel.grid(row=0,column=0,columnspan=2,sticky=NSEW)
self.PassLabel.grid(row=1,column=0,columnspan=2,sticky=NSEW)
self.TextLabel.grid(row=3,column=0,columnspan=3,sticky=NSEW)
self.UserEntry.grid(row=0,column=2,sticky=NSEW)
self.PassEntry.grid(row=1,column=2,sticky=NSEW)
self.LogIn.grid(row=2,column=1,sticky=NSEW)
self.Reg.grid(row=2,column=2,sticky=W)
self.mainframe.grid()
self.mainframe.master.title("LonIn or create account")
##Set confirm state
self.confirm=False
##activate on selecting the log in option
def DoLogIn(self,*ignore):
##check if the details are correct or is banned
##status - {0 - wrong details, 1 - correct details, 2- banned user}
status=server.checkUser(self.UserEntry.get(),self.PassEntry.get())
##if stauts - 1 start the count down
if status==1:
self.logInTimer()
self.confirm=True
return 0
##if status 2 print that the user is banned
if status==2:
self.TextLabel.configure(text="Login failed: You are banned",background = 'DarkRed')
self.TextLabel.update_idletasks()
self.UserEntry.delete(0,END)
self.PassEntry.delete(0,END)
return 0
##if status 0 print that the details are wrong
self.TextLabel.configure(text="Login failed: Wrong user/password",background = 'DarkRed')
self.TextLabel.update_idletasks()
self.UserEntry.delete(0,END)
self.PassEntry.delete(0,END)
self.confirm=False
##register an user
def Register(self):
##check to see if the user exists
##the check is case sensitive so the user CoCo will not be allowed if Coco exists
if (server.addUser(self.UserEntry.get(),self.PassEntry.get())==0):
self.TextLabel.configure(text="Please select a different name",background = 'DarkRed')
self.TextLabel.update_idletasks()
self.confirm=False
return False
##if the username is free print the the account has been created
self.TextLabel.configure(text="Account created, you can now log in",background="LightSeaGreen")
self.TextLabel.update_idletasks()
self.UserEntry.delete(0,END)
self.PassEntry.delete(0,END)
return True
##timer activated if the login details are correct
def logInTimer(self):
now=time()
while int(time()-now)!=3:
self.TextLabel.configure(text="Loging in {0}".format(3-int(time()-now)),background="LightSeaGreen")
self.TextLabel.update_idletasks()
def log():
log_win=Tk()
login=MyLogin(log_win)
log_win.bind("<Return>",login.DoLogIn)
while login.confirm==False:
log_win.update()
user=login.UserEntry.get()
log_win.destroy()
server.newName(user,user)
return (user)
def details(uname):
det_win=Tk()
details=MyDetails(det_win,uname)
det_win.bind("<Return>",details.chAll)
while details.done==0:
det_win.update()
data=details.data
det_win.destroy()
return data
| [
[
1,
0,
0.0052,
0.0052,
0,
0.66,
0,
368,
0,
1,
0,
0,
368,
0,
0
],
[
1,
0,
0.0104,
0.0052,
0,
0.66,
0.1,
251,
0,
1,
0,
0,
251,
0,
0
],
[
1,
0,
0.0156,
0.0052,
0,
0.6... | [
"from Tkinter import *",
"import xmlrpclib",
"from time import clock, time",
"server = xmlrpclib.ServerProxy(\"http://192.168.1.2:8888\")",
"def userType(user):\n return server.userType(user)",
" return server.userType(user)",
"def newName(oldUname,newUname):\n return server.newName(oldUname,ne... |
# This is Python example on how to use Mongoose embeddable web server,
# http://code.google.com/p/mongoose
#
# Before using the mongoose module, make sure that Mongoose shared library is
# built and present in the current (or system library) directory
import mongoose
import sys
# Handle /show and /form URIs.
def EventHandler(event, conn, info):
if event == mongoose.HTTP_ERROR:
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
conn.printf('HTTP error: %d\n', info.status_code)
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/show':
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
conn.printf('%s %s\n', info.request_method, info.uri)
if info.request_method == 'POST':
content_len = conn.get_header('Content-Length')
post_data = conn.read(int(content_len))
my_var = conn.get_var(post_data, 'my_var')
else:
my_var = conn.get_var(info.query_string, 'my_var')
conn.printf('my_var: %s\n', my_var or '<not set>')
conn.printf('HEADERS: \n')
for header in info.http_headers[:info.num_headers]:
conn.printf(' %s: %s\n', header.name, header.value)
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/form':
conn.write('HTTP/1.0 200 OK\r\n'
'Content-Type: text/html\r\n\r\n'
'Use GET: <a href="/show?my_var=hello">link</a>'
'<form action="/show" method="POST">'
'Use POST: type text and submit: '
'<input type="text" name="my_var"/>'
'<input type="submit"/>'
'</form>')
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/secret':
conn.send_file('/etc/passwd')
return True
else:
return False
# Create mongoose object, and register '/foo' URI handler
# List of options may be specified in the contructor
server = mongoose.Mongoose(EventHandler,
document_root='/tmp',
listening_ports='8080')
print ('Mongoose started on port %s, press enter to quit'
% server.get_option('listening_ports'))
sys.stdin.read(1)
# Deleting server object stops all serving threads
print 'Stopping server.'
del server
| [
[
1,
0,
0.1129,
0.0161,
0,
0.66,
0,
755,
0,
1,
0,
0,
755,
0,
0
],
[
1,
0,
0.129,
0.0161,
0,
0.66,
0.1667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.4597,
0.5806,
0,
0... | [
"import mongoose",
"import sys",
"def EventHandler(event, conn, info):\n if event == mongoose.HTTP_ERROR:\n conn.printf('%s', 'HTTP/1.0 200 OK\\r\\n')\n conn.printf('%s', 'Content-Type: text/plain\\r\\n\\r\\n')\n conn.printf('HTTP error: %d\\n', info.status_code)\n return True\n ... |
# Copyright (c) 2004-2009 Sergey Lyubka
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $
"""
This module provides python binding for the Mongoose web server.
There are two classes defined:
Connection: - wraps all functions that accept struct mg_connection pointer
as first argument.
Mongoose: wraps all functions that accept struct mg_context pointer as
first argument.
Creating Mongoose object automatically starts server, deleting object
automatically stops it. There is no need to call mg_start() or mg_stop().
"""
import ctypes
import os
NEW_REQUEST = 0
HTTP_ERROR = 1
EVENT_LOG = 2
INIT_SSL = 3
class mg_header(ctypes.Structure):
"""A wrapper for struct mg_header."""
_fields_ = [
('name', ctypes.c_char_p),
('value', ctypes.c_char_p),
]
class mg_request_info(ctypes.Structure):
"""A wrapper for struct mg_request_info."""
_fields_ = [
('user_data', ctypes.c_char_p),
('request_method', ctypes.c_char_p),
('uri', ctypes.c_char_p),
('http_version', ctypes.c_char_p),
('query_string', ctypes.c_char_p),
('remote_user', ctypes.c_char_p),
('log_message', ctypes.c_char_p),
('remote_ip', ctypes.c_long),
('remote_port', ctypes.c_int),
('status_code', ctypes.c_int),
('is_ssl', ctypes.c_int),
('num_headers', ctypes.c_int),
('http_headers', mg_header * 64),
]
mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p,
ctypes.c_int,
ctypes.c_void_p,
ctypes.POINTER(mg_request_info))
class Connection(object):
"""A wrapper class for all functions that take
struct mg_connection * as the first argument."""
def __init__(self, mongoose, connection):
self.m = mongoose
self.conn = ctypes.c_void_p(connection)
def get_header(self, name):
val = self.m.dll.mg_get_header(self.conn, name)
return ctypes.c_char_p(val).value
def get_var(self, data, name):
size = data and len(data) or 0
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_get_var(data, size, name, buf, size)
return n >= 0 and buf or None
def printf(self, fmt, *args):
val = self.m.dll.mg_printf(self.conn, fmt, *args)
return ctypes.c_int(val).value
def write(self, data):
val = self.m.dll.mg_write(self.conn, data, len(data))
return ctypes.c_int(val).value
def read(self, size):
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_read(self.conn, buf, size)
return n <= 0 and None or buf[:n]
def send_file(self, path):
self.m.dll.mg_send_file(self.conn, path)
class Mongoose(object):
"""A wrapper class for Mongoose shared library."""
def __init__(self, callback, **kwargs):
dll_extension = os.name == 'nt' and 'dll' or 'so'
self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
self.dll.mg_start.restype = ctypes.c_void_p
self.dll.mg_modify_passwords_file.restype = ctypes.c_int
self.dll.mg_read.restype = ctypes.c_int
self.dll.mg_write.restype = ctypes.c_int
self.dll.mg_printf.restype = ctypes.c_int
self.dll.mg_get_header.restype = ctypes.c_char_p
self.dll.mg_get_var.restype = ctypes.c_int
self.dll.mg_get_cookie.restype = ctypes.c_int
self.dll.mg_get_option.restype = ctypes.c_char_p
if callback:
# Create a closure that will be called by the shared library.
def func(event, connection, request_info):
# Wrap connection pointer into the connection
# object and call Python callback
conn = Connection(self, connection)
return callback(event, conn, request_info.contents) and 1 or 0
# Convert the closure into C callable object
self.callback = mg_callback_t(func)
self.callback.restype = ctypes.c_char_p
else:
self.callback = ctypes.c_void_p(0)
args = [y for x in kwargs.items() for y in x] + [None]
options = (ctypes.c_char_p * len(args))(*args)
ret = self.dll.mg_start(self.callback, 0, options)
self.ctx = ctypes.c_void_p(ret)
def __del__(self):
"""Destructor, stop Mongoose instance."""
self.dll.mg_stop(self.ctx)
def get_option(self, name):
return self.dll.mg_get_option(self.ctx, name)
| [
[
8,
0,
0.1855,
0.0881,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2453,
0.0063,
0,
0.66,
0.0909,
182,
0,
1,
0,
0,
182,
0,
0
],
[
1,
0,
0.2516,
0.0063,
0,
0.66... | [
"\"\"\"\nThis module provides python binding for the Mongoose web server.\n\nThere are two classes defined:\n\n Connection: - wraps all functions that accept struct mg_connection pointer\n as first argument.",
"import ctypes",
"import os",
"NEW_REQUEST = 0",
"HTTP_ERROR = 1",
"EVENT_LOG = 2",
"INIT_... |
'''
Created on 30/03/2011
@author: Eran_Z
Utilities
'''
def sum(x,y):
return x+y
| [
[
8,
0,
0.3636,
0.6364,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.8636,
0.1818,
0,
0.66,
1,
824,
0,
2,
1,
0,
0,
0,
0
],
[
13,
1,
0.9091,
0.0909,
1,
0.59,
... | [
"'''\nCreated on 30/03/2011\n\n@author: Eran_Z\n\nUtilities\n'''",
"def sum(x,y):\n return x+y",
" return x+y"
] |
'''
Created on 08/04/2011
@author: Eran_Z
Google search (num results), based on Dima's implementation
currently uses deprecated API
'''
import json
import urllib
#N = 25270000000L #25.27 billion, roughly google's index size. Should be reduced for other engines.
N = 1870000000L #roughly the index of the deprecated API
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
data = results['responseData']
ret = data['cursor']['estimatedResultCount']
return long(ret)
| [
[
8,
0,
0.1731,
0.3077,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3846,
0.0385,
0,
0.66,
0.3333,
463,
0,
1,
0,
0,
463,
0,
0
],
[
1,
0,
0.4231,
0.0385,
0,
0.66... | [
"'''\nCreated on 08/04/2011\n\n@author: Eran_Z\n\nGoogle search (num results), based on Dima's implementation\ncurrently uses deprecated API\n'''",
"import json",
"import urllib",
"def showsome(searchfor):\n query = urllib.urlencode({'q': searchfor})\n \n url = 'http://ajax.googleapis.com/ajax/servic... |
'''
Created on 29/03/2011
@author: Eran_Z
Weighting
'''
import search_m
from util_m import sum
from math import log
#Helper functions
def __singleNGDWeight(term1, term2):
return 0 if term1 == term2 else max(0, 1 - search_m.NGD(term1, term2))
def __singleMutualInformationWeight(term1, term2):
return 0 if term1 == term2 else search_m.searchTogether(term1, term2)*1.0/(search_m.searchSingle(term1)*search_m.searchSingle(term2))
def __pij(ci, wj, hi):
return search_m.searchTogether(ci, wj)*1.0/hi
def __plogp(ci, wj, hi):
p = __pij(ci, wj, hi)
return p * log(p, 2)
#Main functions
def uniformWeighter(context, world):
return [1]*len(context)
def NGDWeighter(context, world):
#TODO: test
return map(lambda ci: reduce(sum, map(lambda cj: __singleNGDWeight(ci, cj), context)), context)
def mutualInformationWeighter(context, world):
#TODO: test
return map(lambda ci: reduce(sum, map(lambda cj: __singleMutualInformationWeight(ci, cj), context)), context)
def entropyWeighter(context, world):
#h[i] = sigma(j=1..n) #(ci, wj)
h = map(lambda c: reduce(sum, map(lambda w: search_m.searchTogether(c, w), world)), context)
H = map(lambda i: -reduce(sum, map(lambda w: __plogp(context[i], w, h[i]), world)), range(len(context)))
sigma_H = reduce(sum, H)
return map(lambda i: 1-(H[i]*1.0/sigma_H), range(len(context)))
def regularSupervisedWeighter(context, world):
#TODO: stub
pass
def normalizedSupervisedWeighter(context, world):
#TODO: stub
pass
weightingAlgorithms = {"Uniform": uniformWeighter, "NGD": NGDWeighter, "Mutual Information": mutualInformationWeighter,
"Entropy": entropyWeighter, "Regular Supervised": regularSupervisedWeighter,
"Normalized Supervised": normalizedSupervisedWeighter }
| [
[
8,
0,
0.069,
0.1207,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1552,
0.0172,
0,
0.66,
0.0714,
784,
0,
1,
0,
0,
784,
0,
0
],
[
1,
0,
0.1724,
0.0172,
0,
0.66,... | [
"'''\nCreated on 29/03/2011\n\n@author: Eran_Z\n\nWeighting\n'''",
"import search_m",
"from util_m import sum",
"from math import log",
"def __singleNGDWeight(term1, term2):\n return 0 if term1 == term2 else max(0, 1 - search_m.NGD(term1, term2))",
" return 0 if term1 == term2 else max(0, 1 - search... |
import json
import urllib
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
data = results['responseData']
ret = data['cursor']['estimatedResultCount']
return ret
val = showsome('google')
print val
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
463,
0,
1,
0,
0,
463,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.25,
614,
0,
1,
0,
0,
614,
0,
0
],
[
2,
0,
0.5294,
0.6471,
0,
0.... | [
"import json",
"import urllib",
"def showsome(searchfor):\n query = urllib.urlencode({'q': searchfor})\n \n url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%query\n search_response = urllib.urlopen(url)\n search_results = search_response.read()\n results = json.loads(search... |
from apiclient.discovery import build
def search(searchfor):
service = build("customsearch", "v1",
developerKey="AIzaSyB1KoWaQxP9_o--plv19-JYDevfdhKFzjs")
res = service.cse().list(
q=searchfor,
cx='017576662512468239146:omuauf_lfve',
).execute()
ret = res['queries']['request'][0]['totalResults']
return ret
# instead google you can write string to search for
val = search('google')
# val is returned value from search
print val
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
78,
0,
1,
0,
0,
78,
0,
0
],
[
2,
0,
0.4706,
0.5294,
0,
0.66,
0.3333,
163,
0,
1,
1,
0,
0,
0,
4
],
[
14,
1,
0.3235,
0.1176,
1,
0.0... | [
"from apiclient.discovery import build",
"def search(searchfor):\n service = build(\"customsearch\", \"v1\",\n developerKey=\"AIzaSyB1KoWaQxP9_o--plv19-JYDevfdhKFzjs\")\n res = service.cse().list(\n q=searchfor,\n cx='017576662512468239146:omuauf_lfve',\n ).execute()\n ret = res[... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Setup script for Google API Python client.
Also installs included versions of third party libraries, if those libraries
are not already installed.
"""
import setup_utils
has_setuptools = False
try:
from setuptools import setup
has_setuptools = True
except ImportError:
from distutils.core import setup
packages = [
'apiclient',
'oauth2client',
'apiclient.ext',
'apiclient.contrib',
'apiclient.contrib.buzz',
'apiclient.contrib.latitude',
'apiclient.contrib.moderator',
'uritemplate',
]
install_requires = []
py_modules = []
# (module to test for, install_requires to add if missing, packages to add if missing, py_modules to add if missing)
REQUIREMENTS = [
('httplib2', 'httplib2', 'httplib2', None),
('oauth2', 'oauth2', 'oauth2', None),
('gflags', 'python-gflags', None, ['gflags', 'gflags_validators']),
(['json', 'simplejson', 'django.utils'], 'simplejson', 'simplejson', None)
]
for import_name, requires, package, modules in REQUIREMENTS:
if setup_utils.is_missing(import_name):
if has_setuptools:
install_requires.append(requires)
else:
if package is not None:
packages.append(package)
else:
py_modules.extend(modules)
long_desc = """The Google API Client for Python is a client library for
accessing the Buzz, Moderator, and Latitude APIs."""
setup(name="google-api-python-client",
version="1.0alpha11",
description="Google API Client Library for Python",
long_description=long_desc,
author="Joe Gregorio",
author_email="jcgregorio@google.com",
url="http://code.google.com/p/google-api-python-client/",
install_requires=install_requires,
packages=packages,
py_modules=py_modules,
package_data={
'apiclient': ['contrib/*/*.json']
},
license="Apache 2.0",
keywords="google api client",
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Topic :: Internet :: WWW/HTTP'])
| [
[
8,
0,
0.2,
0.0588,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2353,
0.0118,
0,
0.66,
0.1,
439,
0,
1,
0,
0,
439,
0,
0
],
[
14,
0,
0.2588,
0.0118,
0,
0.66,
... | [
"\"\"\"Setup script for Google API Python client.\n\nAlso installs included versions of third party libraries, if those libraries\nare not already installed.\n\"\"\"",
"import setup_utils",
"has_setuptools = False",
"try:\n from setuptools import setup\n has_setuptools = True\nexcept ImportError:\n from di... |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs, parse_qsl
except ImportError:
from cgi import parse_qs, parse_qsl
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s, safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None):
self.method = method
self.url = url
if parameters is not None:
self.update(parameters)
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(self, True)
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
query = parse_qs(base_url.query)
for k, v in self.items():
query.setdefault(k, []).append(v)
url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params,
urllib.urlencode(query, True), base_url.fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if hasattr(value, '__iter__'):
items.extend((key, item) for item in value)
else:
items.append((key, value))
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
items.extend(self._split_url_string(query).items())
encoded_str = urllib.urlencode(sorted(items))
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout,
proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
is_multipart = method == 'POST' and headers.get('Content-Type',
DEFAULT_CONTENT_TYPE) != DEFAULT_CONTENT_TYPE
if body and method == "POST" and not is_multipart:
parameters = dict(parse_qsl(body))
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters)
req.sign_request(self.method, self.consumer, self.token)
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_CONTENT_TYPE)
if is_multipart:
headers.update(req.to_header())
else:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header())
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
version = self._get_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _get_version(self, request):
"""Verify the correct version request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
built = signature_method.sign(request, consumer, token)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
# HMAC object.
try:
from hashlib import sha1 as sha
except ImportError:
import sha # Deprecated
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| [
[
8,
0,
0.0163,
0.0313,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.034,
0.0014,
0,
0.66,
0.0357,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0354,
0.0014,
0,
0.66,... | [
"\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou... |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import imaplib
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
lambda x: oauth2.build_xoauth_string(url, consumer, token))
| [
[
8,
0,
0.3,
0.575,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.625,
0.025,
0,
0.66,
0.3333,
311,
0,
1,
0,
0,
311,
0,
0
],
[
1,
0,
0.65,
0.025,
0,
0.66,
0.6... | [
"\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou... |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import smtplib
import base64
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
self.docmd('AUTH', 'XOAUTH %s' % \
base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
| [
[
8,
0,
0.2927,
0.561,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.6098,
0.0244,
0,
0.66,
0.25,
311,
0,
1,
0,
0,
311,
0,
0
],
[
1,
0,
0.6341,
0.0244,
0,
0.66,
... | [
"\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou... |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
setup(name='oauth2client',
version='1.0beta1',
description='Google OAuth 2.0 Client Libary for Python',
license='Apache 2.0',
author='Google Inc.',
packages = ['oauth2client'],
package_dir = {'': '..'},
author_email='jcgregorio@google.com',
url='http://code.google.com/p/google-api-python-client',
)
| [
[
1,
0,
0.5769,
0.0385,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
8,
0,
0.8269,
0.3846,
0,
0.66,
1,
234,
3,
9,
0,
0,
0,
0,
1
]
] | [
"from setuptools import setup",
"setup(name='oauth2client',\n version='1.0beta1',\n description='Google OAuth 2.0 Client Libary for Python',\n license='Apache 2.0',\n author='Google Inc.',\n packages = ['oauth2client'],\n package_dir = {'': '..'},\n author_email='jcgregorio@goog... |
# Copyright 2010 Google Inc. All Rights Reserved.
"""An OAuth 2.0 client
Tools for interacting with OAuth 2.0 protected
resources.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
import datetime
import httplib2
import logging
import urllib
import urlparse
try: # pragma: no cover
import simplejson
except ImportError: # pragma: no cover
try:
# Try to import from django, should work on App Engine
from django.utils import simplejson
except ImportError:
# Should work for Python2.6 and higher.
import json as simplejson
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
class Error(Exception):
"""Base error for this module."""
pass
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
pass
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
pass
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
pass
def _abstract():
raise NotImplementedError('You need to override this function')
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method
that applies the credentials to an HTTP transport.
"""
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential.
"""
def get(self):
"""Retrieve credential.
Returns:
oauth2client.client.Credentials
"""
_abstract()
def put(self, credentials):
"""Write a credential.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then signs each request from that object with the OAuth 2.0
access token.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent):
"""Create an instance of OAuth2Credentials
This constructor is not usually called by the user, instead
OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
Args:
token_uri: string, URI of token endpoint.
client_id: string, client identifier.
client_secret: string, client secret.
access_token: string, access token.
token_expiry: datetime, when the access_token expires.
refresh_token: string, refresh token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.store = None
self.token_expiry = token_expiry
self.token_uri = token_uri
self.user_agent = user_agent
# True if the credentials have been revoked or expired and can't be
# refreshed.
self._invalid = False
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked."""
return getattr(self, '_invalid', False)
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled.
"""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled.
"""
self.__dict__.update(state)
self.store = None
def _refresh(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http: An instance of httplib2.Http.request
or something that acts like it.
"""
body = urllib.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token' : self.refresh_token
})
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
logging.info("Refresing access_token")
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds = int(d['expires_in'])) + datetime.datetime.now()
else:
self.token_expiry = None
if self.store is not None:
self.store(self)
else:
# An {'error':...} response body means the token is expired or revoked, so
# we flag the credentials as such.
logging.error('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self._invalid = True
if self.store is not None:
self.store(self)
else:
logging.warning("Unable to store refreshed credentials, no Storage provided.")
except:
pass
raise AccessTokenRefreshError(error_msg)
def authorize(self, http):
"""Authorize an httplib2.Http instance with these credentials.
Args:
http: An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
if headers == None:
headers = {}
headers['authorization'] = 'OAuth ' + self.access_token
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
if resp.status == 401:
logging.info("Refreshing because we got a 401")
self._refresh(request_orig)
headers['authorization'] = 'OAuth ' + self.access_token
return request_orig(uri, method, body, headers,
redirections, connection_type)
else:
return (resp, content)
http.request = new_request
return http
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then signs each request from that object with the OAuth 2.0
access token. This set of credentials is for the use case where you have
acquired an OAuth 2.0 access_token from another place such as a JavaScript
client or another web application, and wish to use it from Python. Because
only the access_token is present it can not be refreshed and will in time
expire.
AccessTokenCredentials objects may be safely pickled and unpickled.
Usage:
credentials = AccessTokenCredentials('<an access token>',
'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Exceptions:
AccessTokenCredentialsExpired: raised when the access_token expires or is
revoked.
"""
def __init__(self, access_token, user_agent):
"""Create an instance of OAuth2Credentials
This is one of the few types if Credentials that you should contrust,
Credentials objects are usually instantiated by a Flow.
Args:
access_token: string, access token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
"""
super(AccessTokenCredentials, self).__init__(
access_token,
None,
None,
None,
None,
None,
user_agent)
def _refresh(self, http_request):
raise AccessTokenCredentialsError(
"The access_token is expired or invalid and can't be refreshed.")
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, client_id, client_secret, scope, user_agent,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for OAuth2WebServerFlow
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string, scope of the credentials being requested.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
self.scope = scope
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.params = kwargs
self.redirect_uri = None
def step1_get_authorize_url(self, redirect_uri='oob'):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'oob' for a non-web-based
application, or a URI that handles the callback from
the authorization server.
If redirect_uri is 'oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
self.redirect_uri = redirect_uri
query = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'scope': self.scope,
}
query.update(self.params)
parts = list(urlparse.urlparse(self.auth_uri))
query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part
parts[4] = urllib.urlencode(query)
return urlparse.urlunparse(parts)
def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope
})
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if simplejson.loads fails?
d = simplejson.loads(content)
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.now() + datetime.timedelta(seconds = int(d['expires_in']))
logging.info('Successfully retrieved access token: %s' % content)
return OAuth2Credentials(access_token, self.client_id, self.client_secret,
refresh_token, token_expiry, self.token_uri,
self.user_agent)
else:
logging.error('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
except:
pass
raise FlowExchangeError(error_msg)
| [
[
8,
0,
0.0113,
0.0113,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0203,
0.0023,
0,
0.66,
0.05,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0248,
0.0023,
0,
0.66,
... | [
"\"\"\"An OAuth 2.0 client\n\nTools for interacting with OAuth 2.0 protected\nresources.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import copy",
"import datetime",
"import httplib2",
"import logging",
"import urllib",
"import urlparse",
"try: # pragma: no cover\n import simp... |
# Copyright 2010 Google Inc. All Rights Reserved.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
import threading
from client import Storage as BaseStorage
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
self._lock.acquire()
try:
f = open(self._filename, 'r')
credentials = pickle.loads(f.read())
f.close()
credentials.set_store(self.put)
except:
credentials = None
self._lock.release()
return credentials
def put(self, credentials):
"""Write a pickled Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._lock.acquire()
f = open(self._filename, 'w')
f.write(pickle.dumps(credentials))
f.close()
self._lock.release()
| [
[
8,
0,
0.0962,
0.0962,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1731,
0.0192,
0,
0.66,
0.2,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2115,
0.0192,
0,
0.66,
... | [
"\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 2.0\ncredentials.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import pickle",
"import threading",
"from client import Storage as BaseStorage",
"class Storage(BaseStorage):\n \"\"\"Store and retrieve a s... |
# Copyright 2010 Google Inc. All Rights Reserved.
"""OAuth 2.0 utilities for Django.
Utilities for using OAuth 2.0 in conjunction with
the Django datastore.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import oauth2client
import base64
import pickle
from django.db import models
from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
if not value:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
class FlowField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Flow):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsField
on a db model class.
"""
def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name
def get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self.put)
return credential
def put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
args = {self.key_name: self.key_value}
entity = self.model_class(**args)
setattr(entity, self.property_name, credentials)
entity.save()
| [
[
8,
0,
0.049,
0.049,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0882,
0.0098,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1078,
0.0098,
0,
0.66,
... | [
"\"\"\"OAuth 2.0 utilities for Django.\n\nUtilities for using OAuth 2.0 in conjunction with\nthe Django datastore.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import oauth2client",
"import base64",
"import pickle",
"from django.db import models",
"from oauth2client.client import St... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use OAuth 2.0 on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
from google.appengine.ext import db
from client import Credentials
from client import Flow
from client import Storage
class FlowProperty(db.Property):
"""App Engine datastore Property for Flow.
Utility property that allows easy storage and retreival of an
oauth2client.Flow"""
# Tell what the user type is.
data_type = Flow
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
return not value
class CredentialsProperty(db.Property):
"""App Engine datastore Property for Credentials.
Utility property that allows easy storage and retrieval of
oath2client.Credentials
"""
# Tell what the user type is.
data_type = Credentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
cred = super(CredentialsProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(cred))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, Credentials):
raise BadValueError('Property %s must be convertible '
'to an Credentials instance (%s)' %
(self.name, value))
return super(CredentialsProperty, self).validate(value)
def empty(self, value):
return not value
class StorageByKeyName(Storage):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self._model = model
self._key_name = key_name
self._property_name = property_name
def get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
entity = self._model.get_or_insert(self._key_name)
credential = getattr(entity, self._property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self.put)
return credential
def put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self._model.get_or_insert(self._key_name)
setattr(entity, self._property_name, credentials)
entity.put()
| [
[
8,
0,
0.1204,
0.0292,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.146,
0.0073,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1606,
0.0073,
0,
0.66,
... | [
"\"\"\"Utilities for Google App Engine\n\nUtilities for making it easier to use OAuth 2.0 on Google App Engine.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import pickle",
"from google.appengine.ext import db",
"from client import Credentials",
"from client import Flow",
"from clie... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility functions for setup.py file(s)."""
__author__ = 'tom.h.miller@gmail.com (Tom Miller)'
import sys
def is_missing(packages):
"""Return True if a package can't be imported."""
retval = True
sys_path_original = sys.path[:]
# Remove the current directory from the list of paths to check when
# importing modules.
try:
# Sometimes it's represented by an empty string?
sys.path.remove('')
except ValueError:
import os.path
try:
sys.path.remove(os.path.abspath(os.path.curdir))
except ValueError:
pass
if not isinstance(packages, type([])):
packages = [packages]
for name in packages:
try:
__import__(name)
retval = False
except ImportError:
retval = True
if retval == False:
break
sys.path = sys_path_original
return retval
| [
[
8,
0,
0.2885,
0.0192,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3462,
0.0192,
0,
0.66,
0.3333,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3846,
0.0192,
0,
0.66,... | [
"\"\"\"Utility functions for setup.py file(s).\"\"\"",
"__author__ = 'tom.h.miller@gmail.com (Tom Miller)'",
"import sys",
"def is_missing(packages):\n \"\"\"Return True if a package can't be imported.\"\"\"\n\n retval = True\n sys_path_original = sys.path[:]\n # Remove the current directory from the list... |
#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Discovery document tests
Unit tests for objects created from discovery documents.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import unittest
import urlparse
try:
from urlparse import parse_qs
except ImportError:
from cgi import parse_qs
from apiclient.http import HttpMockSequence
from oauth2client.client import AccessTokenCredentials
from oauth2client.client import AccessTokenCredentialsError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import FlowExchangeError
from oauth2client.client import OAuth2Credentials
from oauth2client.client import OAuth2WebServerFlow
class OAuth2CredentialsTests(unittest.TestCase):
def setUp(self):
access_token = "foo"
client_id = "some_client_id"
client_secret = "cOuDdkfjxxnv+"
refresh_token = "1/0/a.df219fjls0"
token_expiry = "ignored"
token_uri = "https://www.google.com/accounts/o8/oauth2/token"
user_agent = "refresh_checker/1.0"
self.credentials = OAuth2Credentials(
access_token, client_id, client_secret,
refresh_token, token_expiry, token_uri,
user_agent)
def test_token_refresh_success(self):
http = HttpMockSequence([
({'status': '401'}, ''),
({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
({'status': '200'}, 'echo_request_headers'),
])
http = self.credentials.authorize(http)
resp, content = http.request("http://example.com")
self.assertEqual(content['authorization'], 'OAuth 1/3w')
def test_token_refresh_failure(self):
http = HttpMockSequence([
({'status': '401'}, ''),
({'status': '400'}, '{"error":"access_denied"}'),
])
http = self.credentials.authorize(http)
try:
http.request("http://example.com")
self.fail("should raise AccessTokenRefreshError exception")
except AccessTokenRefreshError:
pass
def test_non_401_error_response(self):
http = HttpMockSequence([
({'status': '400'}, ''),
])
http = self.credentials.authorize(http)
resp, content = http.request("http://example.com")
self.assertEqual(400, resp.status)
class AccessTokenCredentialsTests(unittest.TestCase):
def setUp(self):
access_token = "foo"
user_agent = "refresh_checker/1.0"
self.credentials = AccessTokenCredentials(access_token, user_agent)
def test_token_refresh_success(self):
http = HttpMockSequence([
({'status': '401'}, ''),
])
http = self.credentials.authorize(http)
try:
resp, content = http.request("http://example.com")
self.fail("should throw exception if token expires")
except AccessTokenCredentialsError:
pass
except Exception:
self.fail("should only throw AccessTokenCredentialsError")
def test_non_401_error_response(self):
http = HttpMockSequence([
({'status': '400'}, ''),
])
http = self.credentials.authorize(http)
resp, content = http.request("http://example.com")
self.assertEqual(400, resp.status)
class OAuth2WebServerFlowTest(unittest.TestCase):
def setUp(self):
self.flow = OAuth2WebServerFlow(
client_id='client_id+1',
client_secret='secret+1',
scope='foo',
user_agent='unittest-sample/1.0',
)
def test_construct_authorize_url(self):
authorize_url = self.flow.step1_get_authorize_url('oob')
parsed = urlparse.urlparse(authorize_url)
q = parse_qs(parsed[4])
self.assertEqual(q['client_id'][0], 'client_id+1')
self.assertEqual(q['response_type'][0], 'code')
self.assertEqual(q['scope'][0], 'foo')
self.assertEqual(q['redirect_uri'][0], 'oob')
def test_exchange_failure(self):
http = HttpMockSequence([
({'status': '400'}, '{"error":"invalid_request"}')
])
try:
credentials = self.flow.step2_exchange('some random code', http)
self.fail("should raise exception if exchange doesn't get 200")
except FlowExchangeError:
pass
def test_exchange_success(self):
http = HttpMockSequence([
({'status': '200'},
"""{ "access_token":"SlAV32hkKG",
"expires_in":3600,
"refresh_token":"8xLOxBtZp8" }"""),
])
credentials = self.flow.step2_exchange('some random code', http)
self.assertEqual(credentials.access_token, 'SlAV32hkKG')
self.assertNotEqual(credentials.token_expiry, None)
self.assertEqual(credentials.refresh_token, '8xLOxBtZp8')
def test_exchange_no_expires_in(self):
http = HttpMockSequence([
({'status': '200'}, """{ "access_token":"SlAV32hkKG",
"refresh_token":"8xLOxBtZp8" }"""),
])
credentials = self.flow.step2_exchange('some random code', http)
self.assertEqual(credentials.token_expiry, None)
if __name__ == '__main__':
unittest.main()
| [
[
8,
0,
0.1121,
0.023,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1322,
0.0057,
0,
0.66,
0.0625,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1437,
0.0057,
0,
0.66,
... | [
"\"\"\"Discovery document tests\n\nUnit tests for objects created from discovery documents.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import httplib2",
"import unittest",
"import urlparse",
"try:\n from urlparse import parse_qs\nexcept ImportError:\n from cgi import parse_qs"... |
#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for errors handling
"""
__author__ = 'afshar@google.com (Ali Afshar)'
import unittest
import httplib2
from apiclient.errors import HttpError
JSON_ERROR_CONTENT = """
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "country is required",
"locationType": "parameter",
"location": "country"
}
],
"code": 400,
"message": "country is required"
}
}
"""
def fake_response(data, headers):
return httplib2.Response(headers), data
class Error(unittest.TestCase):
"""Test handling of error bodies."""
def test_json_body(self):
"""Test a nicely formed, expected error response."""
resp, content = fake_response(JSON_ERROR_CONTENT,
{'status':'400', 'content-type': 'application/json'})
error = HttpError(resp, content)
self.assertEqual(str(error), '<HttpError 400 "country is required">')
def test_bad_json_body(self):
"""Test handling of bodies with invalid json."""
resp, content = fake_response('{',
{'status':'400', 'content-type': 'application/json'})
error = HttpError(resp, content)
self.assertEqual(str(error), '<HttpError 400 "{">')
def test_with_uri(self):
"""Test handling of passing in the request uri."""
resp, content = fake_response('{',
{'status':'400', 'content-type': 'application/json'})
error = HttpError(resp, content, 'http://example.org')
self.assertEqual(str(error), '<HttpError 400 when requesting http://example.org returned "{">')
def test_missing_message_json_body(self):
"""Test handling of bodies with missing expected 'message' element."""
resp, content = fake_response('{}',
{'status':'400', 'content-type': 'application/json'})
error = HttpError(resp, content)
self.assertEqual(str(error), '<HttpError 400 "{}">')
def test_non_json(self):
"""Test handling of non-JSON bodies"""
resp, content = fake_response('NOT OK', {'status':'400'})
error = HttpError(resp, content)
self.assertEqual(str(error), '<HttpError 400 "Ok">')
| [
[
8,
0,
0.2011,
0.023,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2299,
0.0115,
0,
0.66,
0.1429,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2644,
0.0115,
0,
0.66,
... | [
"\"\"\"Tests for errors handling\n\"\"\"",
"__author__ = 'afshar@google.com (Ali Afshar)'",
"import unittest",
"import httplib2",
"from apiclient.errors import HttpError",
"JSON_ERROR_CONTENT = \"\"\"\n{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"global\",\n \"reason\": \"required\",\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.