rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
def stop_event(self): """ Event to send on stop. """ if hasattr(self.handler, 'item'): return Event(PLAY_END, self.handler.item) return None | def stop_event(self): """ Event to send on stop. """ if hasattr(self.handler, 'item'): return Event(PLAY_END, self.handler.item) return None | |
if r == None or r == '': | if value == None or value == '': | def __getitem__(self, attr): """ Return the specific attribute """ if attr[:7] == 'parent(' and attr[-1] == ')' and self.parent: return self.parent[attr[7:-1]] |
return len(r) | return len(value) | def __getitem__(self, attr): """ Return the specific attribute """ if attr[:7] == 'parent(' and attr[-1] == ')' and self.parent: return self.parent[attr[7:-1]] |
def _cover_filter(x): | def _cover_filter(self, x): | def _cover_filter(x): """ filter function to get valid cover names """ return re.search(config.AUDIO_COVER_REGEXP, x, re.IGNORECASE) |
osd._deletefromcache(self.filename) | osd.bitmapcache.__delitem__(self.filename) | def eventhandler(self, event): |
if self.visual and self.player and self.player.playerGUI.visible: | if self.visual: | def eventhandler( self, event=None, arg=None ): """ eventhandler to simulate hide/show of mpav """ if self.visual and self.player and self.player.playerGUI.visible: if event == TOGGLE_OSD and self.view in [0, 1]: if self.view == 1: self.dock() |
w = c.width - 2*c.spacing h = c.height - 2*c.spacing x = c.x - c.spacing y = c.y - c.spacing | w = c.width - 2*c.spacing h = c.height - 2*c.spacing x = c.x + c.spacing y = c.y + c.spacing try: r = c.types['default'].rectangle x -= r.x y -= r.y w += 2*r.x h += 2*r.y except: pass | def dock(self): if self.player: rc.app(self.player) |
print 'plugin %s deactivated, reason: %s' % (name, reason) | print 'plugin %s deactivated\nreason: %s' % (name, reason) | def __load_plugin__(name, type, level, args, number): """ load the plugin and add it to the lists """ global __plugin_type_list__ global __named_plugins__ global __plugin_basedir__ # fallback module = name object = '%s.PluginInterface' % module special = None # locate the plugin: files = [] if not isinstance(nam... |
command = '%s -vo null -ao %s %s %s "%s"' % (mpl, config.MPLAYER_AO_DEV, demux, extra_opts, filename) | def play(self, item, playerGUI): """ play a audioitem with mplayer """ if item.url: filename = item.url else: filename = item.filename | |
command = '%s -cache 100' % command | extra_opts += ' -cache 100' command = '%s -vo null -ao %s %s %s' % (mpl, config.MPLAYER_AO_DEV, demux, extra_opts) command = command.replace('\n', '').split(' ') command.append(filename) | def play(self, item, playerGUI): """ play a audioitem with mplayer """ if item.url: filename = item.url else: filename = item.filename |
self.errorFunction = None | self.errorFunction = self.mbus_error | def __init__(self, name='default'): """ Create the mbus address and connect to the mbus """ # build mbus name including app=freevo addr = get_address(name) addr['app'] = 'freevo' |
site = server.Site(root) | rewriter = rewrite.RewriterResource(root, helpimagesrewrite) site = server.Site(rewriter) | def main(): # the start and stop stuff will be handled from the freevo script logfile = '%s/webserver-%s.log' % (config.LOGDIR, os.getuid()) log.startLogging(open(logfile, 'a')) if os.path.isdir(os.path.join(os.environ['FREEVO_PYTHON'], 'www/htdocs')): docRoot = os.path.join(os.environ['FREEVO_PYTHON'], 'www/htdocs')... |
return 'mediadbItem() object' return 'mediadbItem() object for %s' % basename | return 'mediadbItem() object for %s' % self.url return 'mediadbItem() object for %s' % self.basename | def __str__(self): """ String function for debugging. """ if not self.basename: return 'mediadbItem() object' return 'mediadbItem() object for %s' % basename |
if dir == 1: nd = dir << _IOC_DIRSHIFT if dir == 2: nd = -2147483648 if dir == 3: nd = -1073741824 return (nd | (ord(type) << _IOC_TYPESHIFT) | | return (lshift(dir, _IOC_DIRSHIFT) | (ord(type) << _IOC_TYPESHIFT) | | def _IOC(dir,type,nr,size): # FIXME: this is a very bad hack to avoid the future warning for # the next python version. The real code is nd = dir << _IOC_DIRSHIFT # but for dir > 1 this shifts the first 1 bit to position 32 which will # result in an overflow with sign changing. And I have no idea if this is # working i... |
if self.name.find(u"The ") == 0: return self.name[4:] return self.name | return self.sort_name | def sort(self, mode=None): """ Returns the string how to sort this item """ if mode == 'date' and self.mode == 'file' and \ os.path.isfile(self.filename): return u'%s%s' % (os.stat(self.filename).st_ctime, Unicode(self.filename)) if self.name.find(u"The ") == 0: return self.name[4:] return self.name |
self += newvel | self.pos += newvel | def update( self, newpos, newvel, newval, isbetterfunc=operator.lt ): if newpos is None: self += newvel else: # We use slice notation to make sure to only change the list # elements self[:] = newpos self.vel = Vector(newvel) self.val = newval if isbetterfunc(self.val, self.bestval): self.stagnantcount = 0 self.improved... |
self[:] = newpos | self.pos = Vector(newpos) | def update( self, newpos, newvel, newval, isbetterfunc=operator.lt ): if newpos is None: self += newvel else: # We use slice notation to make sure to only change the list # elements self[:] = newpos self.vel = Vector(newvel) self.val = newval if isbetterfunc(self.val, self.bestval): self.stagnantcount = 0 self.improved... |
self[:] = pos | self.pos = Vector(pos) | def reset( self, pos, vel, val ): self[:] = pos self.vel = Vector(vel) self.val = val self.bestpos = Vector(pos) self.bestval = val self.resetcounts() |
realvec.extend([0.0] * 5-len(realvec)) | realvec.extend([0.0] * (5-len(realvec))) | def __call__( self, vec ): realvec = vec[:5] if len(realvec) < 5: realvec.extend([0.0] * 5-len(realvec)) realvec.extend([0.0] * 5) realvec.append(1.0) |
if not exists(dest_stat): | if not stat_exists(dest_stat): | def compare_files(src_path, dest_path): '''see what the differences are between src and dest, and fix it if not a dry run src_path is the file in the synctool/overlay tree dest_path is the file in the system UPDATE_CACHE is a name cache of files that have been updated it helps avoiding duplicate checks for files that... |
single_files(cfg, single_file) | (changed, full_path) = single_files(cfg, single_file) if changed: on_update(cfg, full_path) | def main(): global CONF_FILE, DRY_RUN, VERBOSE, QUIET, UNIX_CMD, LOGFILE, SYMLINK_MODE progname = os.path.basename(sys.argv[0]) diff_file = None single_file = None if len(sys.argv) > 1: try: opts, args = getopt.getopt(sys.argv[1:], "hc:l:d:1:fvqx", ['help', 'conf=', 'log=', 'diff=', 'single=', 'fix', 'verbose', 'qui... |
override = os.path.join(masterdir, 'overlay', "%s.%s" % (dest[1:], group)) if path_exists(override): if full_path != override: verbose('override by $masterdir%s' % override[master_len:]) full_path = override | possible_override = os.path.join(masterdir, 'overlay', "%s.%s" % (dest[1:], group)) if path_exists(possible_override): override = possible_override | def treewalk_overlay(args, dir, files): '''scan the overlay directory and check against the live system''' (cfg, base_path, groups, all_groups) = args base_len = len(base_path) masterdir = cfg['masterdir'] master_len = len(masterdir) dest_dir = dir[base_len:] if not dest_dir: dest_dir = '/' for file in files: full_... |
if override and full_path != override: verbose('overridden by $masterdir%s' % override[master_len:]) continue | def treewalk_overlay(args, dir, files): '''scan the overlay directory and check against the live system''' (cfg, base_path, groups, all_groups) = args base_len = len(base_path) masterdir = cfg['masterdir'] master_len = len(masterdir) dest_dir = dir[base_len:] if not dest_dir: dest_dir = '/' for file in files: full_... | |
override = os.path.join(masterdir, 'tasks', "%s.%s" % (dest[1:], group)) if path_exists(override): if full_path != override: verbose('override by $masterdir%s' % override[master_len:]) full_path = override | possible_override = os.path.join(masterdir, 'tasks', "%s.%s" % (dest[1:], group)) if path_exists(possible_override): override = possible_override | def treewalk_tasks(args, dir, files): '''scan the tasks directory and run the necessary tasks''' (cfg, base_path, groups, all_groups) = args base_len = len(base_path) masterdir = cfg['masterdir'] master_len = len(masterdir) dest_dir = dir[base_len:] if not dest_dir: dest_dir = '/' for file in files: full_path = os.... |
_rcsid="$Id: fitting_toolkit.py,v 1.8 2003-07-03 14:17:50 mendenhall Exp $" | _rcsid="$Id: fitting_toolkit.py,v 1.9 2003-10-03 17:45:40 mendenhall Exp $" | def derivs(self): #analytic derivatives for a 2-d gaussian #z0+a*exp( -(x-xmu)**2/(2*xsig**2) -(y-ymu)**2/(2.0*ysig**2)) z0, a, xmu, xsigma, ymu, ysigma = self.funcparams n=self.pointcount x=self.xarray[0,:n] y=self.xarray[1,:n] xsigi=-1.0/(2.0*xsigma**2) ysigi=-1.0/(2.0*ysigma**2) dx=x-xmu dx2=dx*dx dy=y-ymu dy2=dy*dy... |
self.funcparams=Numeric.zeros(self.param_count, self.atype) | def __init__(self, funclist, pointhint=1000): fit.__init__(self, pointhint) self.basis=funclist self.param_count=len(funclist) self.funcparams=Numeric.zeros(self.param_count, self.atype) | |
self.funcparams=Numeric.zeros(self.param_count, self.atype) | def __init__(self, degree, pointhint=1000, xcenter=0.0): fit.__init__(self, pointhint) self.xcenter=xcenter self.param_count=degree+1 self.funcparams=Numeric.zeros(self.param_count, self.atype) | |
if sys.exc_value[0]==35: | if sys.exc_info()[1].args==(35,): | def read(self, maxlen=None, mode=None): "read data from USB. If mode is None or 0, strip trailing nulls for ASCII, otherwise leave alone" self.check_usb_status() try: if maxlen is None: res=self.usb_recv.read() else: res=self.usb_recv.read(maxlen) if not mode: zp=res.find('\0') if zp>=0: res=res[:zp] #trim any nulls r... |
raise LabProError("USB server disconnected unexpectedly") | raise LabProError("USB server disconnected unexpectedly", sys.exc_info()[1].args) | def read(self, maxlen=None, mode=None): "read data from USB. If mode is None or 0, strip trailing nulls for ASCII, otherwise leave alone" self.check_usb_status() try: if maxlen is None: res=self.usb_recv.read() else: res=self.usb_recv.read(maxlen) if not mode: zp=res.find('\0') if zp>=0: res=res[:zp] #trim any nulls r... |
try: err, =self.command(23, "id", "error", (self.lid,)) except: self.log_traceback() self.connected=0 del connection_dict[self.lid] self.lid=None self.core.close() self.abort_channel.close() del self.core, self.abort_channel self.core=None self.abortChannel=None | if self.connected: try: err, =self.command(23, "id", "error", (self.lid,)) except: self.log_traceback() self.connected=0 del connection_dict[self.lid] self.lid=None self.core.close() self.abort_channel.close() del self.core, self.abort_channel self.core=None self.abortChannel=None | def disconnect(self): try: err, =self.command(23, "id", "error", (self.lid,)) #execute destroy_link except: self.log_traceback() #if we can't close nicely, we'll close anyway self.connected=0 del connection_dict[self.lid] self.lid=None self.core.close() self.abort_channel.close() del self.core, self.abort_channel sel... |
connection.unlock_completely() | connection.unlock() | def onepass(self): connection=self.connection() |
khi=clip(searchsorted(xa,x),1,npoints) | khi=clip(searchsorted(xa,x),1,len(xa)) | def splint(xa, ya, y2a, x): """splint(x_vals, y_vals, y2_vals, x) returns the interpolated from from the spline x can either be a scalar or a listable item, in which case a Numeric Float array will be returned and the multiple interpolations will be done somewhat more efficiently if the array is in reasonable order""" ... |
e1411a.__init__(self, slot, "multimeter/thermometer") | scanning_voltmeter.__init__(self, slot, "multimeter/thermometer") | def __init__(self, slot=7): e1411a.__init__(self, slot, "multimeter/thermometer") |
args.get('absolute_error_tolerance', 1e-12), | """def adaptive_partial_integrals(self, xgrid, relative_error_tolerance=1e-12, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. | |
depth, funcgrid, old_integrals, relative_error_tolerance, absolute_error_tolerance, debug, extrapolate=recur_data | depth, funcgrid, old_integrals, absolute_error_tolerance, relative_error_tolerance, debug, extrapolate=recur_data | """def adaptive_partial_integrals(self, xgrid, relative_error_tolerance=1e-12, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. |
if hasattr(self, "saved_xarray"): raise exceptions.AssertionError, "Don't even think of initializing the resampling more than once!" | assert not hasattr(self, "saved_xarray"), "Don't even think of initializing the resampling more than once!" | def setup_resampling(self): "setup_resampling() caches the 'real' arrays of x and y, so they can be resampled for bootstrapping, and seeds a random generator" if hasattr(self, "saved_xarray"): raise exceptions.AssertionError, "Don't even think of initializing the resampling more than once!" self.saved_xarray=self.xarra... |
if not hasattr(self, "saved_xarray"): raise exceptions.AssertionError, "resampling not set up yet. Call setup_resampling() first." | assert hasattr(self, "saved_xarray"), "resampling not set up yet. Call setup_resampling() first." | def resample(self): "resample() randomly draws a set of points equal in size to the original set from the cached data for bootstrapping" if not hasattr(self, "saved_xarray"): raise exceptions.AssertionError, "resampling not set up yet. Call setup_resampling() first." ranlist=Numeric.floor(self.get_random_list(self.poi... |
class LabPro_Mac_USB(USB_data_mixin, USB_Mac_mixin, LabPro): | class LabPro_Mac_USB(USB_data_mixin, USB_Mac_mixin, RawLabPro): | def close(self): self.__keep_running=0 try: self.usb_send.write("****QUIT****\n") except: pass |
LabPro.__init__(self,'') | RawLabPro.__init__(self,'') | def __init__(self): LabPro.__init__(self,'') |
y2=_linalg.solve_banded((1,1), trimat, u, debug=1) | y2=_linalg.solve_banded((1,1), trimat, u, debug=0) | def _spline(x, y, yp1=None, ypn=None): """y2 = spline(x_vals,y_vals, yp1=None, ypn=None) returns the y2 table for the spline as needed by splint()""" n=len(x) u=_numpy.zeros(n,_numpy.Float) x=_numpy.asarray(x, _numpy.Float) y=_numpy.asarray(y, _numpy.Float) dx=x[1:]-x[:-1] dx2=(x[2:]-x[:-2]) dy=(y[1:]-y[:-1]) dydx=d... |
Y[1]=(1.0+V[0]*dx*dx*0.5)/ypsifact[1] | Y[1]=(1.0+math.sqrt(V[0])*dx)/ypsifact[1] | def generate_table(order, final_x=None, npoints=None): "generate a spline table of H[n](x) exp(-x^2/2) ... a Hermite-Gauss basis function, using the Numerov method" if final_x is None: final_x=hermite_x_bound if npoints is None: npoints=hermite_n_points Y=Numeric.zeros(npoints+1, Numeric.Float) dx=float(final_x)/npoi... |
if debug==1: print "accepted results at depth ", depth, "x, dx = %7.3f, %10.6f" % (x1, dx), "scaled error = ", eps/absolute_error_tolerance, eps /(dx**order) | if debug==1: print "accepted results at depth ", depth, "x, dx = %7.3f, %10.6f" % (x1, dx), "scaled error = ", eps/ (abs(total)*relative_error_tolerance) | """def partial_integrals(self, xgrid, relative_error_tolerance=1e-12, derivs=2, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1, allow_recursion=True) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. The choices for derivs are 0, 1 or 2, anything e... |
if debug==1: print "rejected results at depth ", depth, "x, dx = %7.3f, %10.6f" % (x1, dx), "scaled error = ", eps/absolute_error_tolerance, eps/(dx**order) | if debug==1: print "rejected results at depth ", depth, "x, dx = %7.3f, %10.6f" % (x1, dx), "scaled error = ", eps/ (abs(total)*relative_error_tolerance) | """def partial_integrals(self, xgrid, relative_error_tolerance=1e-12, derivs=2, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1, allow_recursion=True) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. The choices for derivs are 0, 1 or 2, anything e... |
temp=LogLogInterpolatingFunction(be, bh) | temp=self.IntermediateInterpolator(be, bh) | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=LogLogInterpolatingFunction(be, bh) #// create a temporary InterpolatingFunction to integrat... |
absolute_error_tolerance=0.0, relative_error_tolerance=1e-6, derivs=1) scale=1.0/sum(integral) if reversed: lowerSlope=-1.0/binheights[0] upperSlope=-1.0/binheights[-1] else: lowerSlope=1.0/binheights[0] upperSlope=1.0/binheights[-1] | absolute_error_tolerance=0, relative_error_tolerance=1e-6) scale=1.0/sum(integral) | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=LogLogInterpolatingFunction(be, bh) #// create a temporary InterpolatingFunction to integrat... |
integral[-1]=1.0 | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=LogLogInterpolatingFunction(be, bh) #// create a temporary InterpolatingFunction to integrat... | |
lowerSlope=lowerSlope, upperSlope=upperSlope | lowerSlope=1.0/(scale*binheights[0]), upperSlope=1.0/(scale*binheights[-1]) | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=LogLogInterpolatingFunction(be, bh) #// create a temporary InterpolatingFunction to integrat... |
spect=[1.0/(e*e) for e in energies] | spect=[10000.0/(e*e) for e in energies] | def bessj_adaptive(n, z, derivs=1): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=8 g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.partial_integrals(g, absolute_error_tolerance=1e-14, relative_error_tolerance=1e-14, debug=0, derivs=derivs))/math.pi, f.total_func_evals |
"a*x**b" | "a*x**b where a and b are constant" | def value_with_derivatives(self, x): dx=x-self.x0 return self.a*dx*dx+self.b*dx+self.c, 2*self.a*dx+self.b, 2*self.a |
C2Function.__init__(self, left, right) | def __init__(self, left, right): C2Function.__init__(self, left, right) self.left=self.convert_arg(left) self.right=self.convert_arg(right) if isinstance(left, C2BinaryFunction): p1, p2 = '(', ')' else: p1, p2='', '' self.name=p1+left.name+p2+self.name+right.name #put on parentheses to kepp hierachy obvious | |
self.name=p1+left.name+p2+self.name+right.name | self.name=p1+self.left.name+p2+self.name+self.right.name | def __init__(self, left, right): C2Function.__init__(self, left, right) self.left=self.convert_arg(left) self.right=self.convert_arg(right) if isinstance(left, C2BinaryFunction): p1, p2 = '(', ')' else: p1, p2='', '' self.name=p1+left.name+p2+self.name+right.name #put on parentheses to kepp hierachy obvious |
def read(self, maxlen=8, feature=0): | def read(self, maxlen=8, feature=0, send_command=1): | def read(self, maxlen=8, feature=0): "read data from USB" self.check_usb_status() if feature: maxlen=104 self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); else: self.usb_send.write("READ %d\n" % maxlen); res='' tries=0 while not res and tries < 5: try: res=self.usb_recv.read(maxlen+16) #packet + header except IOError:... |
self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); else: | if send_command: self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); elif send_command: | def read(self, maxlen=8, feature=0): "read data from USB" self.check_usb_status() if feature: maxlen=104 self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); else: self.usb_send.write("READ %d\n" % maxlen); res='' tries=0 while not res and tries < 5: try: res=self.usb_recv.read(maxlen+16) #packet + header except IOError:... |
while not res and tries < 5: | while len(res)<maxlen+16 and tries < 5: | def read(self, maxlen=8, feature=0): "read data from USB" self.check_usb_status() if feature: maxlen=104 self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); else: self.usb_send.write("READ %d\n" % maxlen); res='' tries=0 while not res and tries < 5: try: res=self.usb_recv.read(maxlen+16) #packet + header except IOError:... |
res=self.usb_recv.read(maxlen+16) | res+=self.usb_recv.read(maxlen+16-len(res)) | def read(self, maxlen=8, feature=0): "read data from USB" self.check_usb_status() if feature: maxlen=104 self.usb_send.write("FEAT %d %d\n" %(maxlen,0)); else: self.usb_send.write("READ %d\n" % maxlen); res='' tries=0 while not res and tries < 5: try: res=self.usb_recv.read(maxlen+16) #packet + header except IOError:... |
res=self.read(feature=1) if not res: return None, None | res=self.read(feature=1, send_command=self.got_last_packet) if not res: self.got_last_packet=0 return None, None self.got_last_packet=1 | def get_continuous_scan_packet(self, resync=0): res=self.read(feature=1) if not res: return None, None trailer=res[-8:] err, readaddr, writeaddr, index, junk=struct.unpack('<BHHHB', trailer) |
print mcc.analog_input(0, gain=mcc.GAIN5_DIFF) | print mcc.analog_input(0, gain=mcc.GAIN2_DIFF) | def stop_analog_scan(self): self.write((16,)) self.scanning=0 |
mcc.setup_analog_scan(sweeps=-1, channels=(0,), gains=mcc.GAIN1_DIFF, rate=500) actcount=0 try: while actcount<100: index, res=mcc.get_continuous_scan_packet() | mcc.setup_analog_scan(sweeps=-1, channels=(0,), gains=mcc.GAIN2_DIFF, rate=3000) try: actcount=0 print time.asctime() while actcount<10000: actcount, res=mcc.get_continuous_scan_packet() | def stop_analog_scan(self): self.write((16,)) self.scanning=0 |
print Numeric.array_str(res[:,0], precision=3, suppress_small=1, max_line_width=10000) actcount+=1 | if not actcount%100: print actcount print time.asctime() | def stop_analog_scan(self): self.write((16,)) self.scanning=0 |
y, yp, ypp = fn.value_with_derivatives(x) | y, yp, ypp = self.fn.value_with_derivatives(x) | def value_with_derivatives(self, x): y, yp, ypp = fn.value_with_derivatives(x) ys=self.yscale return native(y*ys, yp*ys, ypp*ys) |
return y, yhi-ylo+((3*b*b-1)*y2hi-(3*a*a-1)*y2lo)*(h*h)/6.0, b*y2hi+a*y2lo | return y, (yhi-ylo)/h+((3*b*b-1)*y2hi-(3*a*a-1)*y2lo)*h/6.0, b*y2hi+a*y2lo | def splint(xa, ya, y2a, x, derivs=False): """returns the interpolated from from the spline x can either be a scalar or a listable item, in which case a Numeric Float array will be returned and the multiple interpolations will be done somewhat more efficiently. If derivs is not False, return y, y', y'' instead of just y... |
self.mask32=~Numeric.array(0xffff, Numeric.UnsignedInt32) | def __init__(self, p=250, q=103, seed=None): self.floatscale=1.0/float(1L<<64) self.single_floatscale=1.0/float(1L<<32) self.p=p self.q=q self.seed(seed) | |
q1[count:] &= ~0xfff | q1[count:] &= self.mask32 | def double_float_random_series(self, count): "return a series of 52-bit significance double-precision randoms on [0,1)." q1 = self.fast_random_series(2*count) #take bits from the random pool q1[count:] &= ~0xfff#mask off low bits to prevent rounding when combined to 52-bit mantissas q1=q1*self.single_floatscale #conver... |
self.mask32=~Numeric.array(0xffff, Numeric.UnsignedInt32) | def __init__(self, seed=None): self.floatscale=1.0/float(1L<<64) self.single_floatscale=1.0/float(1L<<32) self.r250=r250(seed) self.r521=r521(seed) | |
print 10*"%08lx "%tuple(r.fast_random_series(10)) | print 10*"%08lx "%tuple(r.fast_random_series(10).tolist()) | def fast_random_series(self, count): return self.r250.fast_random_series(count) ^ self.r521.fast_random_series(count) |
left= ( ( (169*ypp0 + 1024*ypp1 - 41*ypp2)*dx2+ (2727*yp0 - 5040*yp1 + 423*yp2) )*dx2 + (17007*y0 + 24576*y1 - 1263*y2) )* (dx2/40320.0) right= ( ( (-41*ypp0 + 1024*ypp1 + 169*ypp2)*dx2+ (-423*yp0 + 5040*yp1 - 2727*yp2) )*dx2 + (-1263*y0 + 24576*y1 + 17007*y2) )* (dx2/40320.0) | left= ( ( (169*ypp0 + 1024*ypp1 - 41*ypp2)*dx2 + (2727*yp0 - 5040*yp1 + 423*yp2) )*dx2 + (17007*y0 + 24576*y1 - 1263*y2) )* (dx2/40320.0) right= ( ( (169*ypp2 + 1024*ypp1 - 41*ypp0)*dx2 - (2727*yp2 - 5040*yp1 + 423*yp0) )*dx2 + (17007*y2 + 24576*y1 - 1263*y0) )* (dx2/40320.0) | """def partial_integrals(self, xgrid, relative_error_tolerance=1e-12, derivs=2, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1, allow_recursion=True) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. The choices for derivs are 0, 1 or 2, anything e... |
right= ( (22*y0 + 256*y1 + 202*y2) + dx *(3*yp0 + 40*yp1 - 13*yp2) ) * dx /960. | right= ( (202*y2 + 256*y1 + 22*y0) - dx*(13*yp2 - 40*yp1 - 3*yp0) ) * dx /960. | """def partial_integrals(self, xgrid, relative_error_tolerance=1e-12, derivs=2, absolute_error_tolerance=1e-12, depth=0, debug=0, extrapolate=1, allow_recursion=True) Return the integrals of a function between the sampling points xgrid. The sum is the definite integral. The choices for derivs are 0, 1 or 2, anything e... |
np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] if reversed: be=be[::-1] bh=bh[::-1] temp=self.IntermediateInterpolator(be, bh) | if not isinstance(binheights, C2Function): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] if reversed: be=be[::-1] bh=bh[::-1] temp=self.IntermediateInterpolator(be, bh) else: temp=binheights | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=self.IntermediateInterpolator(be, bh) #// create a temporary InterpolatingFunction to integr... |
lowerSlope=1.0/(scale*binheights[0]), upperSlope=1.0/(scale*binheights[-1]) | lowerSlope=1.0/(scale*temp(bincenters[0])), upperSlope=1.0/(scale*temp(bincenters[-1])) | def __init__(self, bincenters, binheights): np=len(binheights) be=_numeric.array(bincenters) bh=_numeric.array(binheights) reversed = be[1] < be[0] #// check for backwards channels if reversed: be=be[::-1] bh=bh[::-1] temp=self.IntermediateInterpolator(be, bh) #// create a temporary InterpolatingFunction to integr... |
if 0: | if 1: | def bessj_adaptive(n, z, derivs=1): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=8 g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.partial_integrals(g, absolute_error_tolerance=1e-14, relative_error_tolerance=1e-14, debug=0, derivs=derivs))/math.pi, f.total_func_evals |
if 1: print "\nTesting LinLogInverseIntegratedDensity" | if 0: print "\nTesting LinLogInverseIntegratedDensity for 1/e^2" | def bessj_adaptive(n, z, derivs=1): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=8 g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.partial_integrals(g, absolute_error_tolerance=1e-14, relative_error_tolerance=1e-14, debug=0, derivs=derivs))/math.pi, f.total_func_evals |
print "\nTesting LinLogInverseIntegratedDensity for 1/e using a C2Function instead of a table" energies=[float(2.0**n) for n in range(21)] e0=energies[-1] e1=energies[0] pf=LinLogInverseIntegratedDensity(energies[::-1], C2PowerLaw(a=1000.0, b=-1)) print energies[0], energies[-1] for i in range(41): r=(0.025*i)**2 m... | def bessj_adaptive(n, z, derivs=1): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=8 g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.partial_integrals(g, absolute_error_tolerance=1e-14, relative_error_tolerance=1e-14, debug=0, derivs=derivs))/math.pi, f.total_func_evals | |
if type(data) is Numeric.ArrayType: | if type(data) is numArrayType: | def pack_array(data): "convert array to NI format" if type(data) is Numeric.ArrayType: typecode=data.typecode() if bigendian: #must swap bytes d=array.array(data.typecode()) d.fromstring(data.tostring()) d.byteswap() datastr=d.tostring() else: datastr=data.tostring() elif bigendian: typecode=data.typecode data.byteswap... |
if 1: | if 0: | def as(x): return _numeric.array_str(x, precision=3) |
return sum(f.partial_integrals(g))/math.pi print bessj(0, 0.1), bessj(0,5), bessj(2,3), bessj(2,30) | return sum(f.partial_integrals(g))/math.pi, f.total_func_evals def bessj_adaptive(n, z): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=8 g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.adaptive_partial_integrals(g, absolute_error_tolerance=1e-12, debug=0))/math.pi, f.total_func_evals ... | def bessj(n, z, point_density=2): f=C2cos(C2Linear(slope=n) - C2Constant(z) * C2sin) pc=int((abs(z)+abs(n)+2)*point_density) g=_numeric.array(range(pc), _numeric.Float)*(math.pi/(pc-1)) return sum(f.partial_integrals(g))/math.pi |
misses=0 if state['error']: raise LabProError(state['error']) syst=state['system state'] & 7 if syst==1: raise LabProError('Waiting for data when none being collected') if syst==4: break | def wait_for_data_done(self, flasher=0): misses=0 while(misses<5): if flasher: self.flash_led('yellow', 0.25) try: state=self.get_system_config() misses=0 if state['error']: raise LabProError(state['error']) syst=state['system state'] & 7 if syst==1: raise LabProError('Waiting for data when none being collected') if sy... | |
_rcsid="$Id: fitting_toolkit.py,v 1.7 2003-05-30 13:31:55 mendenhall Exp $" | _rcsid="$Id: fitting_toolkit.py,v 1.8 2003-07-03 14:17:50 mendenhall Exp $" | def derivs(self): #analytic derivatives for a 2-d gaussian #z0+a*exp( -(x-xmu)**2/(2*xsig**2) -(y-ymu)**2/(2.0*ysig**2)) z0, a, xmu, xsigma, ymu, ysigma = self.funcparams n=self.pointcount x=self.xarray[0,:n] y=self.xarray[1,:n] xsigi=-1.0/(2.0*xsigma**2) ysigi=-1.0/(2.0*ysigma**2) dx=x-xmu dx2=dx*dx dy=y-ymu dy2=dy*dy... |
fxarray[:,i]=self.numeric_deriv(i, self.deriv_step[i]) | if not self.frozen[i]: fxarray[:,i]=self.numeric_deriv(i, self.deriv_step[i]) | def derivs(self): "default deriv is automatic numeric derivatives, override this for analytic derivatives" n=self.pointcount fxarray=Numeric.zeros((n, self.param_count), self.atype) for i in range(self.param_count): fxarray[:,i]=self.numeric_deriv(i, self.deriv_step[i]) return fxarray |
sumarray=Numeric.zeros(self.pointcount, self.atype) | sumarray=Numeric.zeros(len(x), self.atype) | def function(self, p, x): if self.firstpass: #first call from hessian_fit is meaningless, all coefficients zero, save time return 0.0 |
self.usb_send, self.usb_recv, self.usb_err=os.popen3(os.path.join(os.path.dirname(__file__),"LabProUSB"),'b',0) | self.usb_send, self.usb_recv, self.usb_err=os.popen3(os.path.join(os.path.dirname(__file__),"LabProUSBMacServer"),'b',0) | def setup_serial(self,port_name=None): self.usb_send, self.usb_recv, self.usb_err=os.popen3(os.path.join(os.path.dirname(__file__),"LabProUSB"),'b',0) fcntl.fcntl(self.usb_recv, fcntl.F_SETFL, os.O_NONBLOCK) #pipes must be nonblocking fcntl.fcntl(self.usb_err, fcntl.F_SETFL, os.O_NONBLOCK) #pipes must be nonblocking s... |
sx=xp1-xp | sx=-(xp1-xp) | def local_transform(self): "by default, do abcd_transform on self.beam, assuming small angles" ar=Numeric.array dot=Numeric.dot tr=Numeric.transpose xp, yp, zp=tuple(self.beam.local_direction) #it better be a small angle, so sin(theta)=theta for this to work dx, dy, dz=tuple(self.beam.local_x0) #dz should always be ze... |
sy=yp1-yp | sy=-(yp1-yp) | def local_transform(self): "by default, do abcd_transform on self.beam, assuming small angles" ar=Numeric.array dot=Numeric.dot tr=Numeric.transpose xp, yp, zp=tuple(self.beam.local_direction) #it better be a small angle, so sin(theta)=theta for this to work dx, dy, dz=tuple(self.beam.local_x0) #dz should always be ze... |
self.__dict__[i]=extras[i] | setattr(self, i, extras[i]) | def __init__(self, marks, color=None, **extras): self.color=color self.marks=marks #copy any extra information directly into the class dictionary for i in extras.keys(): self.__dict__[i]=extras[i] |
yextrap=((y[1]-y[0])/h0 - h0*(y2[0]+2.0*y2[1])/6.0)*h1+y2[0]*h1*h1/2.0 | yextrap=y[0]+((y[1]-y[0])/h0 - h0*(y2[0]+2.0*y2[1])/6.0)*h1+y2[0]*h1*h1/2.0 | def spline_extension(x, y, y2, xmin=None, xmax=None): """x, y, y2 = spline_extension(x_vals,y_vals, y2vals, xmin=None, xmax=None) returns the x, y, y2 table for the spline as needed by splint() with adjustments to allow quadratic extrapolation outside the range x[0]-x[-1], from xmin (or x[0] if xmin is None) to xmax (o... |
yextrap=((y[-1]-y[-2])/h0 + h0*(2.0*y2[-2]+y2[-1])/6.0)*h1+y2[-1]*h1*h1/2.0 | yextrap=y[-1]+((y[-1]-y[-2])/h0 + h0*(2.0*y2[-2]+y2[-1])/6.0)*h1+y2[-1]*h1*h1/2.0 | def spline_extension(x, y, y2, xmin=None, xmax=None): """x, y, y2 = spline_extension(x_vals,y_vals, y2vals, xmin=None, xmax=None) returns the x, y, y2 table for the spline as needed by splint() with adjustments to allow quadratic extrapolation outside the range x[0]-x[-1], from xmin (or x[0] if xmin is None) to xmax (o... |
return self.ranbuf, self.counter | return Numeric.array(self.ranbuf), self.counter | def getstate(self): return self.ranbuf, self.counter |
class r250_521(ran_shift): | class r250_521(r250): | def __init__(self, seed=None): ran_shift.__init__(self, 521, 168, seed) |
self.floatscale=1.0/float(1L<<64) self.single_floatscale=1.0/float(1L<<32) self.r250=r250(seed) self.r521=r521(seed) self.mask32=~Numeric.array(0xffff, Numeric.UnsignedInt32) | r250.__init__(self, seed) self.r521=r521(seed) | def __init__(self, seed=None): self.floatscale=1.0/float(1L<<64) self.single_floatscale=1.0/float(1L<<32) self.r250=r250(seed) self.r521=r521(seed) self.mask32=~Numeric.array(0xffff, Numeric.UnsignedInt32) |
return self.r250.getstate(), self.r521.getstate() | return r250.getstate(self), self.r521.getstate() | def getstate(self): return self.r250.getstate(), self.r521.getstate() |
self.r250.setstate(state[0]) | r250.setstate(self, state[0]) | def setstate(self, state): self.r250.setstate(state[0]) self.r521.setstate(state[1]) |
return self.r250.next() ^ self.r521.next() | return r250.next(self) ^ self.r521.next() | def next(self): return self.r250.next() ^ self.r521.next() |
return self.r250.fast_random_series(count) ^ self.r521.fast_random_series(count) | return r250.fast_random_series(self, count) ^ self.r521.fast_random_series(count) | def fast_random_series(self, count): return self.r250.fast_random_series(count) ^ self.r521.fast_random_series(count) |
psi[0]=0 | psi[-1]=0 | def generate_table(order, final_x=None, npoints=None): "generate a spline table of H[n](x) exp(-x^2/2) ... a Hermite-Gauss basis function, using the Numerov method" if final_x is None: final_x=hermite_x_bound if npoints is None: npoints=hermite_n_points Y=Numeric.zeros(npoints+1, Numeric.Float) dx=float(final_x)/npoi... |
"send a packet with timeoiut handling" | "send a packet with timeout handling" | def sendfrag_with_timeout(sock, block, timeout_seconds=1.0): "send a packet with timeoiut handling" n=len(block) nsent=0 while(nsent<n): rlist, wlist, xlist=select.select([],[sock],[], timeout_seconds) if not wlist: raise EOFError, "Blocked write in sendfrag()" nsent+=sock.send(block[nsent:]) |
except IOError, VXI_11_Error: | except (IOError, VXI_11_Error): | def setup_device(self): self.lock() try: self.clear() try: self.check_scpi_errors() except SCPI_Error: #clear any initial errors without bailing out pass self.write("*cls;*sre 0;:stat:ques:enable #H0800;*ese 63;:init:cont off;") err, reason, setup_check=self.mav_transaction(":diag:otd? (@100);:stat:ques:cond?") otdstat... |
except IOError, Timeout_Error: | except (IOError, Timeout_Error): | def onepass(self): #used by our device thread to read out data, overridden here due to permanent lock self.consecutive_failures+=1 try: err, reason, data = self.transaction("*wai;:data:fifo?;:init;") result, junk = handle_iee488_binary_block( data) count=len(result)//4 if count==self.scan_channels: self.save_read_data(... |
except IOError, Timeout_Error: | except (IOError, Timeout_Error): | def get_data(self): #used by our device thread to read out data self.consecutive_failures+=1 try: self.write_data(0,0) #only write lazy data err, reason, data = self.transaction(":dig:data:lw96:mon?") words=[long(i) for i in data.split(",")] if len(words)==3: for i in range(3): if words[i] < 0: words[i] += 2L<<31 #now,... |
except IOError, Timeout_Error: | except (IOError, Timeout_Error): | def get_data(self): #used by our device thread to read out data self.consecutive_failures+=1 try: err, reason, data = self.mav_transaction(":init;:form real,32;:fetch?") result, junk = handle_iee488_binary_block( data) count=len(result)//4 if count==self.scan_channels: self.save_read_data(list(struct.unpack(">%df"%coun... |
except IOError, Timeout_Error: | except (IOError, Timeout_Error): | def get_data(self): #used by our device thread to read out data self.consecutive_failures+=1 try: err, reason, data = self.transaction(self.data_read_str) d=int(data) if d<0: d+=256 self.save_read_data(d) self.consecutive_failures=0 except IOError, Timeout_Error: self.log_error("Timeout on loop %d"%self.loop_count) sel... |
u=_numeric.zeros(n,Float) y2=_numeric.zeros(n,Float) x=_numeric.asarray(x, Float) y=_numeric.asarray(y, Float) | u=_numeric.zeros(n,_numeric.Float) y2=_numeric.zeros(n,_numeric.Float) x=_numeric.asarray(x, _numeric.Float) y=_numeric.asarray(y, _numeric.Float) | def _spline(x, y, yp1=None, ypn=None): """y2 = spline(x_vals,y_vals, yp1=None, ypn=None) returns the y2 table for the spline as needed by splint()""" n=len(x) u=_numeric.zeros(n,Float) y2=_numeric.zeros(n,Float) x=_numeric.asarray(x, Float) y=_numeric.asarray(y, Float) dx=x[1:]-x[:-1] dxi=1.0/dx dx2i=1.0/(x[2:]-x[:-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.