rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if self.__curindex_type==float64:
if pts.dtype==float64:
def nn(self, pts, qpts, num_neighbors = 1, **kwargs): """ Returns the num_neighbors nearest points in dataset for each point in testset. """ if not pts.dtype.type in allowed_types: raise FLANNException("Cannot handle type: %s"%pts.dtype)
array.shape = (-1,array.size)
array = array.reshape(-1,array.size)
def ensure_2d_array(array, flags, **kwargs): array = require(array, requirements = flags, **kwargs) if len(array.shape) == 1: array.shape = (-1,array.size) return array
except:
except Exception as e: print e
def load_flann_library(): root_dir = os.path.abspath(os.path.dirname(__file__)) libname = 'libflann' if sys.platform == 'win32': libname = 'flann' flann = None loaded = False while (not loaded) and root_dir!="/": try: flann = load_library(libname, os.path.join(root_dir,'lib')) loaded = True except: root_dir = os.path.dirname(root_dir) return flann
def kmeans(self, pts, num_clusters, centers_init = "random", max_iterations = None,
def kmeans(self, pts, num_clusters, max_iterations = None,
def kmeans(self, pts, num_clusters, centers_init = "random", max_iterations = None, dtype = None, **kwargs): """ Runs kmeans on pts with num_clusters centroids. Returns a numpy array of size num_clusters x dim.
"resultsLog", "workspace", "displayInfo"
"resultsLog", "workspace", "displayInfo", "infoLineEdit"
def import_to_global(modname, attrs=None, math=False): """ import_to_global(modname, (a,b,c,...), math): like "from modname import a,b,c,...", but imports to global namespace (__main__). If math==True, also registers functions with QtiPlot's math function list. """ import sys import os sys.path.append(os.path.dirname(__file__)) mod = __import__(modname) for submod in modname.split(".")[1:]: mod = getattr(mod, submod) if attrs==None: attrs=dir(mod) for name in attrs: f = getattr(mod, name) setattr(__main__, name, f) # make functions available in QtiPlot's math function list if math and callable(f): qti.mathFunctions[name] = f
script = self._find_exe(script)
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def _find_exe(self, script_name): if self.script_path is None: script_name = os.path.join(self.cwd, script_name) if not os.path.exists(script_name): raise OSError( "Script %s does not exist" % script_name) return script_name for path in self.script_path: fn = os.path.join(path, script_name) if os.path.exists(fn): return fn raise OSError( "Script %s could not be found in %s" % (script_name, ':'.join(self.script_path)))
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
proc = subprocess.Popen(all, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, shell=(sys.platform=='win32'), env=clean_environ(self.environ)) stdout, stderr = proc.communicate(stdin)
if debug: proc = subprocess.Popen(all, cwd=cwd, shell=(sys.platform=='win32'), env=clean_environ(self.environ)) else: proc = subprocess.Popen(all, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, shell=(sys.platform=='win32'), env=clean_environ(self.environ)) if debug: stdout,stderr = proc.communicate() else: stdout, stderr = proc.communicate(stdin)
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
capture_temp=False, assert_no_temp=False):
capture_temp=False, assert_no_temp=False, split_cmd=True):
def __init__(self, base_path=None, template_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True, capture_temp=False, assert_no_temp=False): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
if ' ' in script:
if self.split_cmd and ' ' in script:
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
assert not args, ( "You cannot give a multi-argument script (%r) " "and arguments (%s)" % (script, args)) script, args = script.split(None, 1) args = shlex.split(args)
if args: pass else: script, args = script.split(None, 1) args = shlex.split(args)
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
all_proc_results = [script] + args
environ=clean_environ(self.environ)
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
proc = subprocess.Popen(all, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, env=clean_environ(self.environ))
proc = Popen(all, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, env=environ)
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
self, all_proc_results, stdin, stdout, stderr,
self, all, stdin, stdout, stderr,
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
"""
def main(): try: fetch_threads = [] parser = OptionParser(usage="Usage: %prog [options] url") parser.add_option("-s", "--max-speed", dest="max_speed", help="Specifies maximum speed (bytes per second)." " Useful if you don't want the program to suck up" " all of your bandwidth", metavar="SPEED") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4, help="You can specify an alternative number of" " connections here.", metavar="NUM") parser.add_option("-o", "--output", dest="output_file", help="By default, data does to a local file of " "the same name. If this option is used, downloaded" " data will go to this file.") (options, args) = parser.parse_args() print "Options: ", options print "args: ", args if len(args) != 1: parser.print_help() sys.exit(1) # General configuration urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPCookieProcessor())) socket.setdefaulttimeout(120) # 2 minutes url = args[0] output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) print "Need to fetch %s\n" % report_bytes(filesize) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() #create output file out_fd = os.open(output_file, os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) # Blank spaces trail below to erase previous output. TODO: Need to # do this better. pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file os.remove(state_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True
self.progress[int(self.name)] += fetch_size
self.progress[int(self.name)][0] += fetch_size self.progress[int(self.name)][1] += elapsed
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
progress = [ 0 for i in len_list ]
progress = [ [0,0.0] for i in len_list ]
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
print "\r",progress,
report_string = get_progress_report(progress) print "\r", report_string,
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
print "\r",progress,
print "\r", get_progress_report(progress)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
parser.add_option("-n", "--num-connections", dest="num_connections", default=4,
parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4,
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time
th.sleep_timer = dwnld_sofar / (options.max_speed * \ 1024 - conn_state.elapsed_time)
def download(url, options): fetch_threads = [] try: output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() print "Need to fetch %s\n" % report_bytes(conn_state.filesize - sum(conn_state.progress)) #create output file with a .part extension to indicate partial download out_fd = os.open(output_file+".part", os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file and move the dwnld to output file from .part file os.remove(state_file) os.rename(output_file+".part", output_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True except Exception, e: # TODO: handle other types of errors too. print e for thread in fetch_threads: thread._need_to_quit = True
help="Specifies maximum speed (bytes per second)."
type="int", help="Specifies maximum speed (Kbytes per second)."
def main(options, args): try: general_configuration() url = args[0] download(url, options) except KeyboardInterrupt, k: sys.exit(1) except Exception, e: # TODO: handle other types of errors too. print e pass
start_offset += i
start_offset += len_list[i]
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
return self.sys_log("HDF5_DIR=%s make -j%s" % (self.blddir, jobs(self.name)))
return self.sys_log("make -j%s" % (jobs(self.name)))
def _build(self): return self.sys_log("HDF5_DIR=%s make -j%s" % (self.blddir, jobs(self.name)))
f.close()
def find_cgal_vers(self, installed=False, in_build=False): v = '' f = self.find_cgal_inc(installed, in_build) if f: while True: line = f.readline() if not line: break v = re.findall(r'#define CGAL_VERSION ([^\r\n]*)', line) if v: v = v[0] break verbose(2, 'CGAL version=%s' % v) f.close() return v
foptions['timeStep'] = 1E-8
foptions['timeStep'] = 1E-4
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
numIterations=1
numIterations=5
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
cwd = os.getcwd()
cwd = os.getcwd() topdir = os.path.abspath(topdir)
def __init__(self, cname, topdir, make_path): # create build directories cwd = os.getcwd() self.topdir = topdir self.blddir = os.path.join(os.getcwd(), "build-%s" % cname) self.logdir = os.path.join(self.blddir, "log") self.bindir = os.path.join(self.blddir, "bin") self.libdir = os.path.join(self.blddir, "lib") for p in [self.blddir, self.logdir, self.libdir, self.bindir ]: if not os.path.isdir(p): try: os.makedirs(p) except: fatal("error creating directory " + p)
env['CXX'] = 'cxx'
env['CXX'] = 'c++'
def generate(env): cppTool.generate(env) if not env.get('CXXVERSION'): try: line = os.popen("/bin/bash -c 'gcc --version 2>&1'").readline() env['CXXVERSION'] = re.compile(r'[^(]*[^)]*\) ([^\n ]*)').findall(line)[0] except: env['CXXVERSION'] = '4.2.1' env['COMPILER'] = 'gcc-' + env['CXXVERSION'] env['CXXFLAGS'] = CLVar('-Wall -fno-strict-aliasing -Woverloaded-virtual -ftemplate-depth-200 -frounding-math') if is64Bit(): env.Append(CPPDEFINES=CLVar('OS_64BIT')) if env['DEBUG']: env.Append(CXXFLAGS=['-g', '-O0']) else: env.Append(CXXFLAGS=['-O3', '-finline-limit=500']) if env['OPENMP']: env.Append(CXXFLAGS=['-fopenmp']) if env['PARALLEL']: env['CXX'] = 'mpicxx' env.Append(CXXFLAGS=['-DFVM_PARALLEL']) #bug fix for mpich env.Append(CXXFLAGS=['-DMPICH_IGNORE_CXX_SEEK']) else: env['CXX'] = 'cxx' env['CCFLAGS'] = env['CXXFLAGS'] env['SHCXXFLAGS'] = CLVar('$CXXFLAGS -fPIC')
return self.sys_log("make -j%s" % jobs(self.name))
return self.sys_log("HDF5_DIR=%s make -j%s" % (self.blddir, jobs(self.name)))
def _build(self): return self.sys_log("make -j%s" % jobs(self.name))
rr, wr, er = select.select(plist, [], plist)
rr, wr, er = select(plist, [], plist)
def sys_log(self, cmd, show=False): "Execute a system call and log the result." # get configuration variable e = config(self.name, self.state) e = e.replace('BUILDDIR', self.blddir) e = e.replace('SRCDIR', self.sdir) e = e.replace('TMPBDIR', self.bdir) e = e.replace('LOGDIR', self.logdir) cmd = cmd + " " + e debug(cmd) f = None if self.logfile != '': f = open(self.logfile, 'a') print >> f, "EXECUTING:", cmd p = Popen(cmd, shell=True, stderr=PIPE, stdout=PIPE) pid = p.pid plist = [p.stdout, p.stderr] done = 0 while not done: rr, wr, er = select.select(plist, [], plist) if er: print 'er=',er for fd in rr: data = os.read(fd.fileno(), 1024) if data == '': plist.remove(fd) if plist == []: done = 1 else: if fd == p.stderr: print >>f, data, if show: cprint('DYELLOW', data, False) else: if show: print data, print >>f, data, if f: f.close() try: return os.waitpid(pid, 0)[1] except: return 0
for cmd in config('ALL', 'before'): f.write('%s\n' % cmd)
for cmd in config('ALL', 'before'): exp = re.findall(r'export (\S+)=(\S+)', cmd) if exp: f.write('setenv %s %s\n' % (exp[0][0], exp[0][1])) else: f.write('%s\n' % cmd)
def write_env(bld, cwd, cname): # write out env.csh for people who haven't yet learned bash env_name = os.path.join(cwd, 'env.csh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "setenv LD_LIBRARY_PATH " + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "setenv PYTHONPATH " + os.environ['PYTHONPATH'] except: pass print >> f, "setenv PATH %s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "setenv MEMOSA_CONFNAME %s" % cname f.close() # write out env.sh env_name = os.path.join(cwd, 'env.sh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "export LD_LIBRARY_PATH=" + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "export PYTHONPATH=" + os.environ['PYTHONPATH'] except: pass print >> f, "export PATH=%s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "export MEMOSA_CONFNAME=%s" % cname f.close() return env_name
self.faceNodesCoord = self.geomField.coordinate[self.mesh.getCells()].newSizedClone( self.nfaces.sum()*4 )
SIZE = int(self.nfaces.sum()*4) self.faceNodesCoord = self.geomField.coordinate[self.mesh.getCells()].newSizedClone( SIZE )
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
self.FaceCentroidVels = self.geomField.coordinate[self.mesh.getCells()].newSizedClone( self.nfaces.sum() )
SIZE = int(self.nfaces.sum()) self.FaceCentroidVels = self.geomField.coordinate[self.mesh.getCells()].newSizedClone( SIZE )
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
env.AppendUnique(CPPDEFINES='RLOG_COMPONENT=%s' % target[1:-3])
env.AppendUnique(CPPDEFINES='RLOG_COMPONENT=%s' % target)
def createSwigModule(self, target, sources=[], deplibs=[], atype=None,**kwargs):
'<div id="${preview_id}" class="richtemplates-rst" ' 'style="display:none;"></div>',
'<div id="${preview_id}" class="richtemplates-rst-preview ' 'richtemplates-rst" style="display:none;"></div>',
def render(self, name, value, attrs=None): html = super(RestructuredTextareaWidget, self).render(name, value, attrs)
u'<tbody class="datatable-tbody">',
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
img_tag = u'<img src="%s" />' % src
img_tag = u'<img src="%s" alt="%s" />' % (src, src)
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
u'</tr></tbody>' % (tr_class, img_tag, label_for,
u'</tr>' % (tr_class, img_tag, label_for,
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>') output.append(u'</table>')
output.append(u'</tbody></table>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
print options['force']
def handle_label(self, app=None, **options): if app is None: raise CommandError("Specify at least one app") if app not in settings.INSTALLED_APPS: raise CommandError("%s not found at INSTALLED_APPS" % app) MEDIA_ROOT = os.path.abspath(options['media_root'])
logging.debug(msg)
logger.debug(msg)
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logging.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logging.warn(msg)
logging.warn(msg)
logger.warn(msg)
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logging.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logging.warn(msg)
R = 0.354 Delta = 0.153
R = 0.354 * nm Delta = 0.153 * nm
def rho(r): R = 0.354 Delta = 0.153 R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
r = arange(0, 1, 0.01)
r = arange(0, 1 * nm, 0.01 *nm)
def rho(r): R = 0.354 Delta = 0.153 R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
if self._input_report_queue:
if self._input_report_queue and self.__input_processing_thread.is_alive():
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
while self.__reading_thread and self.__reading_thread.is_alive():
while self.__reading_thread and self.__reading_thread.is_active():
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
if not raw_report: continue
if not raw_report or self.__abort: break
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report: continue hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) hid_object._input_report_queue.reuse(raw_report)
hid_object._input_report_queue.reuse(raw_report)
if hid_object._input_report_queue: hid_object._input_report_queue.reuse(raw_report)
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report: continue hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) hid_object._input_report_queue.reuse(raw_report)
if not self.__abort: self.__abort = True
if not self.__active: return self.__abort = True
def abort(self): if not self.__abort: self.__abort = True if self.is_alive() and self.__overlapped_read_obj: # force overlapped events completition SetEvent(self.__overlapped_read_obj.h_event)
self.__active = False self.__abort = True
def run(self): if not self.raw_report_size: # don't raise any error as the hid object can still be used # for writing reports raise HIDError("Attempting to read input reports on non "\ "capable HID device") over_read = OVERLAPPED() over_read.h_event = CreateEvent(None, 0, 0, None) if over_read.h_event: self.__overlapped_read_obj = over_read else: raise HIDError("Error when create hid event resource")
byte_index = (index * self.__bit_size) % 8 bit_value = (value & ((1 << self.__bit_size) - 1)) << byte_index self.__value[byte_index] &= bit_value self.__value[byte_index] |= bit_value
bit_index = (index * self.__bit_size) % 8 bit_mask = ((1 << self.__bit_size) - 1) self.__value[byte_index] &= ~(bit_mask << bit_index) self.__value[byte_index] |= (value & bit_mask) << bit_index
def __setitem__(self, index, value): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 byte_index = (index * self.__bit_size) % 8 bit_value = (value & ((1 << self.__bit_size) - 1)) << byte_index self.__value[byte_index] &= bit_value self.__value[byte_index] |= bit_value else: raise IndexError
byte_index = (index * self.__bit_size) % 8 return ((self.__value[byte_index] >> byte_index) & self.__bit_size )
bit_index = (index * self.__bit_size) % 8 return ((self.__value[byte_index] >> bit_index) & ((1 << self.__bit_size) - 1) )
def __getitem__(self, index): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 byte_index = (index * self.__bit_size) % 8 return ((self.__value[byte_index] >> byte_index) & self.__bit_size ) else: raise IndexError
self.posted_event.set()
def post(self, raw_report): if self.__locked_down: self.posted_event.set() return self.fresh_lock.acquire() self.fresh_queue.append( raw_report ) self.fresh_lock.release() self.posted_event.set()
if bytes_read.value: input_report_queue.post( buf_report )
input_report_queue.post( buf_report )
def run(self): time.sleep(0.050) # this fixes an strange python threading bug if not self.raw_report_size: # don't raise any error as the hid object can still be used # for writing reports raise HIDError("Attempting to read input reports on non "\ "capable HID device")
res.append( "value=%s)"%hex(self.__value) )
res.append( "value=%s" % str(self.get_value()))
def __repr__(self): res = [] if self.string_index: res.append( self.get_usage_string() ) res.append( "page_id=%s"%hex(self.page_id) ) res.append( "usage_id=%s"%hex(self.usage_id) ) if self.__value != None: res.append( "value=%s)"%hex(self.__value) ) else: res.append( "value=[None])" ) usage_type = "" if self.is_button(): usage_type = "Button" elif self.is_value(): usage_type = "Value" return usage_type + "Usage item, %s (" % hex(get_full_usage_id ( \ self.page_id, self.usage_id)) + ', '.join(res) + ')'
byref(raw_data), sizeof(raw_data)) )
byref(self.__raw_data), len(self.__raw_data)) )
def set_raw_data(self, raw_data): """Set usage values based on given raw data, item[0] is report_id, lenght should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type """ #pre-parsed data should exist if not self.__hid_object.ptr_preparsed_data: raise HIDError("HID object close or unable to request preparsed "\ "report data") #valid lenght if len(raw_data) != self.__raw_report_size: raise HIDError( "Report size has to be %d elements (bytes)" \ % self.__raw_report_size ) # copy to internal storage self.__alloc_raw_data(raw_data) if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) data_list_type = HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA bufer data_list = self.__usage_data_list data_len = c_ulong(len(data_list))
nength: %(hid_caps.output_report_byte_length)d byte(s)
length: %(hid_caps.output_report_byte_length)d byte(s)
def __getitem__(self, key): if '.' not in key: return self.parent[key] else: all_keys = key.split('.') curr_var = self.parent[all_keys[0]] for item in all_keys[1:]: new_var = getattr(curr_var, item) curr_var = new_var return new_var
t.byteswap(True)
if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True)
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
if dtype==np.uint8 and arr.max()>255:
if arr.dtype==np.uint8 and arr.max()>255:
def SaveFileSequence(arr,basename=None,format='gif',tiffBits=16): if basename==None: basename=wx.SaveFileSelector('Array as Sequence of Gifs -- numbers automatically added to','.'+format) if format in _gif_names: pass elif format in _tif_names: if tiffBits not in [8,16,32]: print 'Unsupported tiff format! Choose 8 or 16 bit.' return else: print 'Unsupported Format! Choose Gif or Tiff format' return if dtype==np.uint8 and arr.max()>255: arr=np.array(arr*255./arr.max(),np.uint8) if len(arr.shape)==2: SaveSingle(arr,os.path.splitext(basename)[0]+'_0_000'+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==3: for i in range(arr.shape[0]): SaveSingle(arr[i],os.path.splitext(basename)[0]+'_0_'+str('%03d' % i)+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==4: for i in range(arr.shape[0]): for j in range(arr.shape[1]): SaveSingle(arr[i,j],os.path.splitext(basename)[0]+'_'+str(i)+'_'+str('%03d' % j)+'.'+format,format=format,tiffBits=tiffBits) else: print 'This function does not support saving arrays with more than 4 dimensions!'
t.byteswap(True)
if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True)
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
t.byteswap(True)
if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True)
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8
datatype = GetDatatype(im)
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8
datatype = GetDatatype(im)
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
from bluetooth import BluetoothError
import bluesock
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
import bluesock
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
except (BluetoothError, IOError):
except (bluesock.bluetooth.BluetoothError, IOError):
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
def _ls_read(self):
def _ls_get_status(self, n_bytes):
def _ls_read(self): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
b = self.brick.ls_get_status(self.port) if b >= n_bytes: return b except I2CPendingError: sleep(0.01) raise I2CError, 'ls_get_status timeout'
def _ls_read(self): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
data = self._ls_read()
self._ls_get_status(n_bytes) data = self.brick.ls_read(self.port)
def _i2c_query(self, address, format): """Reads an i2c value from given address, and returns a value unpacked according to the given format. Format is the same as in the struct module. """ n_bytes = struct.calcsize(format) msg = chr(self.I2C_DEV) + chr(address) if not self.lastpoll: self.lastpoll = time() if self.lastpoll+0.02 > time(): diff = time() - self.lastpoll sleep(0.02 - diff) self.brick.ls_write(self.port, msg, n_bytes) data = self._ls_read() self.lastpoll = time() if len(data) < n_bytes: raise I2CError, 'Read failure' return struct.unpack(format, data[-n_bytes:]) # TODO: why could there be more than n_bytes?
'mode': (0x41, 'b'), 'number': (0x42, 'b'), 'red': (0x43, 'b'), 'green': (0x44, 'b'), 'blue': (0x45, 'b'), 'white': (0x46, 'b') 'index': (0x47, 'b'), 'normred': (0x48, 'b'), 'normgreen': (0x49, 'b'), 'normblue': (0x4A, 'b'), 'all_data': (0x42, '9b'),
'mode': (0x41, 'B'), 'number': (0x42, 'B'), 'red': (0x43, 'B'), 'green': (0x44, 'B'), 'blue': (0x45, 'B'), 'white': (0x46, 'B') 'index': (0x47, 'B'), 'normred': (0x48, 'B'), 'normgreen': (0x49, 'B'), 'normblue': (0x4A, 'B'), 'all_data': (0x42, '9B'),
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
'rawwhite': (0x48, '<H')
'rawwhite': (0x48, '<H'), 'all_raw_data': (0x42, '<4H')
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
red = self.read_value('rawred') green = self.read_value('rawgreen') blue = self.read_value('rawblue') white = self.read_value('rawwhite')
red, green, blue, white = self.read_value('all_raw_data')
def get_passive_color(self): """"Returns color values when in passive or raw mode. """ red = self.read_value('rawred') green = self.read_value('rawgreen') blue = self.read_value('rawblue') white = self.read_value('rawwhite') return PassiveColor(red, green, blue, white)
option.subControls = ( Qt.QStyle.SC_ScrollBarAddLine|Qt.QStyle.SC_ScrollBarSubLine
option.subControls = ( Qt.QStyle.SC_ScrollBarAddLine|Qt.QStyle.SC_ScrollBarSubLine|
def paintEvent(self, event) : if len(self.highlight_positions_list) > 0 : painter = Qt.QPainter(self)
def data(index = -1) :
def data(self, index = -1) :
def data(index = -1) : if index < 0 : index = self.index() return self.actions_list[index].data()
sys.path.append("client-pygame/lib")
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
import osci
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
"version": "%d.%d.%d%s" % osci.version,
"version": options.version,
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
shutil.copy2('client-pygame/lib/osci/version.py', 'server/lib/ige/ospace/ClientVersion.py') shutil.copy2('client-pygame/lib/osci/versiondata.py', 'server/lib/ige/ospace/versiondata.py')
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
_index_products([product])
if product.active: _index_products([product])
def index_product(product): """Indexes passed product. """ if product.is_variant(): try: product = product.parent.get_default_variant() except AttributeError: return _index_products([product])
revision.committer,
revision.get_apparent_author(),
def _changesetFromRevision(self, branch, revision_id): """ Generate changeset for the given Bzr revision """ from datetime import datetime from vcpx.tzinfo import FixedOffset, UTC
super(DarcsChangeset, self).setLog(self.ignore_this.sub('', log))
log = self.ignore_this.sub('', log) if not SynchronizableTargetWorkingDir.PATCH_NAME_FORMAT: if log: log = self.revision + '\n' + log else: log = self.revision super(DarcsChangeset, self).setLog(log)
def setLog(self, log): """Strip away the "Ignore-this:" noise from the changelog."""
phrase_counter = 0 phrases = dict () okeys = set ()
okeys = dict ()
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
okeys.add (okey) phrases[(okey, phrase)] = 0 phrase_counter += 1 if options.verbose and phrase_counter % 1000 == 0: print >> sys.stderr, '%dk phrases imported from %s.' % (phrase_counter / 1000, keyword_file)
okeys[okey] = [phrase] else: okeys[okey].append(phrase)
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
freq_total += freq ikeys = g ([[]], okey.split (), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join (i) if ikey in ip_map: ip_map[ikey].add (k) else: ip_map[ikey] = set ([k])
ikeys = g ([[]], okey.split (), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join (i) if ikey in ip_map: ip_map[ikey].add (k) else: ip_map[ikey] = set ([k]) for okey in okeys: for phrase in okeys[okey]: process_phrase(okey, phrase, 0) if options.verbose and phrase_counter % 1000 == 0: print >> sys.stderr, '%dk phrases imported from %s.' % (phrase_counter / 1000, keyword_file) del okeys
def process_phrase (okey, phrase, freq): global phrase_counter, phrases, freq_total, i_map phrase_counter += 1 k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq freq_total += freq ikeys = g ([[]], okey.split (), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join (i) if ikey in ip_map: ip_map[ikey].add (k) else: ip_map[ikey] = set ([k])
s = self.__dict[dict_prefix][1] s.append(schema_info)
s = self.__dict[dict_prefix] s[1].append(schema_info)
def __register_dict(self, dict_prefix, max_key_length, schema_info): if dict_prefix not in self.__dict: s = self.__dict[dict_prefix] = [max_key_length, [], None, dict(), -1] else: s = self.__dict[dict_prefix][1] s.append(schema_info)
process_phrase(k, p, 0)
process_phrase(k, p[1:] if p.startswith(u'*') else p, 0)
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
if phrase.startswith(u'*'): phrase = phrase[1:]
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
files[index] = index.encode('utf-7')
files[index] = 'idx_' + index.encode('utf-7')
def dump_dict_index(index): file_path = os.path.join(dest_dir, dict_prefix, '%s.json' % files[index]) f = open(file_path, 'wb') json.dump(indexed_phrases, f, indent=(2 if options.pretty else None)) if options.verbose: print >> sys.stderr, '%d phrases of index %s written to %s.' % (indexed_phrase_count, index, file_path)
for ikey in io_map: s = set() for okey in io_map[ikey]: s |= set(keywords[okey]) for x in s: print u'\t'.join([ikey, x]).encode('utf-8')
if options.ikey: for ikey in io_map: s = set() for okey in io_map[ikey]: s |= set(keywords[okey]) for x in s: print u'\t'.join([ikey, x]).encode('utf-8') else: for spelling in spelling_map: ikey = spelling_map[spelling] s = set() for okey in io_map[ikey]: s |= set(keywords[okey]) for x in s: print u'\t'.join([spelling, ikey, x]).encode('utf-8')
def to_js_regex(r): p = r.split(None, 1) if len(p) < 2: return r p[1] = back_ref.sub(ur'$\1', back_ref_g.sub(ur'$\1', p[1])) return u' '.join(p)
spelling_map[t] = s
spelling_map[t] = ikey
def apply_alternative_rule(d, r): for x in d.keys(): if not r[0].search(x): continue y = transform(x, r) if y == x: continue if y not in d: d[y] = d[x] elif self.__report_errors: raise SpellingCollisionError('AlternativeRule', (x, d[x], y, d[y])) return d
x = line.strip ()
x = line.strip ().decode ('utf-8')
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
max_key_length = 3
max_key_length = 2
def debug(*what): print >> sys.stderr, '[DEBUG]: ', ' '.join(map(unicode, what))
max_key_length = int(value)
max_key_length = max(2, int(value))
def to_js_regex(r): p = r.split(None, 1) if len(p) < 2: return r p[1] = back_ref.sub(ur'$\1', back_ref_g.sub(ur'$\1', p[1])) return u' '.join(p)
k, w = x.split(None, 1)
k, w = x.split(u'\t', 1)
def debug(*what): print >> sys.stderr, u'[DEBUG]: ', u' '.join(map(unicode, what))
spelling_map = reduce(apply_alternative_rule, alternative_rules, spelling_map)
def apply_alternative_rule(d, r): for x in d.keys(): if not r[0].search(x): continue y = transform(x, r) if y == x: continue if y not in d: d[y] = d[x] elif self.__report_errors: raise SpellingCollisionError('AlternativeRule', (x, d[x], y, d[y])) return d
the_input_file="/local/scratch/hauth/data/ZPJ2010/mu_data.root"
the_input_file="/local/scratch/hauth/data/ZPJ2010/mu_data_2010a+b.root"
def multiline_text(line1,line2,line3="",line4=""): string = "#scale[.8]{#splitline{#splitline{%s}{%s}}{#splitline{%s}{%s}}}" %(line1,line2,line3,line4) return string
print "<<< " + w
if self.DEBUG: print "<<< " + w
def writeWord(self, w): print "<<< " + w self.writeLen(len(w)) self.writeStr(w)
print ">>> " + ret
if self.DEBUG: print ">>> " + ret
def readWord(self): ret = self.readStr(self.readLen()) print ">>> " + ret return ret
self.assertTrue('Please log in' in self.browser.contents)
self.assertTrue('Login Name' in self.browser.contents)
def test_unauthenticated(self): ''' unauthenticated users do not have the necessary permissions to view the review list ''' self.browser.open('http://nohost/plone/full_review_list') self.assertTrue('Please log in' in self.browser.contents)