rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
parser.add_option('-j', '--jobs', default=1, type='int',
|
if sys.stdout.isatty(): jobs = 8 else: jobs = 1 parser.add_option('-j', '--jobs', default=jobs, type='int',
|
def Main(argv): """Doesn't parse the arguments here, just find the right subcommand to execute.""" try: # Do it late so all commands are listed. CMDhelp.usage = ('\n\nCommands are:\n' + '\n'.join([ ' %-10s %s' % (fn[3:], Command(fn[3:]).__doc__.split('\n')[0].strip()) for fn in dir(sys.modules[__name__]) if fn.startswith('CMD')])) parser = optparse.OptionParser(version='%prog ' + __version__) parser.add_option('-j', '--jobs', default=1, type='int', help='Specify how many SCM commands can run in parallel; ' 'default=%default') parser.add_option('-v', '--verbose', action='count', default=0, help='Produces additional output for diagnostics. Can be ' 'used up to three times for more logging info.') parser.add_option('--gclientfile', dest='config_filename', default=os.environ.get('GCLIENT_FILE', '.gclient'), help='Specify an alternate %default file') # Integrate standard options processing. old_parser = parser.parse_args def Parse(args): (options, args) = old_parser(args) level = None if options.verbose == 2: level = logging.INFO elif options.verbose > 2: level = logging.DEBUG logging.basicConfig(level=level, format='%(module)s(%(lineno)d) %(funcName)s:%(message)s') options.entries_filename = options.config_filename + '_entries' if options.jobs < 1: parser.error('--jobs must be 1 or higher') # Always autoflush so buildbot doesn't kill us during lengthy operations. options.stdout = gclient_utils.StdoutAutoFlush(sys.stdout) # These hacks need to die. if not hasattr(options, 'revisions'): # GClient.RunOnDeps expects it even if not applicable. options.revisions = [] if not hasattr(options, 'head'): options.head = None if not hasattr(options, 'nohooks'): options.nohooks = True if not hasattr(options, 'deps_os'): options.deps_os = None if not hasattr(options, 'manually_grab_svn_rev'): options.manually_grab_svn_rev = None if not hasattr(options, 'force'): options.force = None return (options, args) parser.parse_args = Parse # We don't want wordwrapping in epilog (usually examples) parser.format_epilog = lambda _: parser.epilog or '' if argv: command = Command(argv[0]) if command: # 'fix' the usage and the description now that we know the subcommand. GenUsage(parser, argv[0]) return command(parser, argv[1:]) # Not a known command. Default to help. GenUsage(parser, 'help') return CMDhelp(parser, argv) except gclient_utils.Error, e: print >> sys.stderr, 'Error: %s' % str(e) return 1
|
if command == "description":
|
elif command == "description":
|
def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 1: Help() return 0; try: # Create the directories where we store information about changelists if it # doesn't exist. if not os.path.exists(GetInfoDir()): os.mkdir(GetInfoDir()) if not os.path.exists(GetChangesDir()): os.mkdir(GetChangesDir()) if not os.path.exists(GetCacheDir()): os.mkdir(GetCacheDir()) except gclient_utils.Error: # Will throw an exception if not run in a svn checkout. pass # Commands that don't require an argument. command = argv[1] if command == "opened" or command == "status": Opened(command == "status") return 0 if command == "nothave": __pychecker__ = 'no-returnvalues' for filename in UnknownFiles(argv[2:]): print "? " + "".join(filename) return 0 if command == "changes": Changes() return 0 if command == "help": Help(argv[2:]) return 0 if command == "diff" and len(argv) == 2: files = GetFilesNotInCL() print GenerateDiff([x[1] for x in files]) return 0 if command == "settings": # Force load settings GetCodeReviewSetting("UNKNOWN"); del CODEREVIEW_SETTINGS['__just_initialized'] print '\n'.join(("%s: %s" % (str(k), str(v)) for (k,v) in CODEREVIEW_SETTINGS.iteritems())) return 0 if command == "deleteempties": DeleteEmptyChangeLists() return 0 if command == "rename": if len(argv) != 4: ErrorExit("Usage: gcl rename <old-name> <new-name>.") src, dst = argv[2:4] src_file = GetChangelistInfoFile(src) if not os.path.isfile(src_file): ErrorExit("Change '%s' does not exist." % src) dst_file = GetChangelistInfoFile(dst) if os.path.isfile(dst_file): ErrorExit("Change '%s' already exists; pick a new name." % dst) os.rename(src_file, dst_file) print "Change '%s' renamed '%s'." % (src, dst) return 0 if command == "change": if len(argv) == 2: # Generate a random changelist name. changename = GenerateChangeName() elif argv[2] == '--force': changename = GenerateChangeName() # argv[3:] is passed to Change() as |args| later. Change() should receive # |args| which includes '--force'. argv.insert(2, changename) else: changename = argv[2] elif len(argv) == 2: ErrorExit("Need a changelist name.") else: changename = argv[2] # When the command is 'try' and --patchset is used, the patch to try # is on the Rietveld server. 'change' creates a change so it's fine if the # change didn't exist. All other commands require an existing change. fail_on_not_found = command != "try" and command != "change" if command == "try" and changename.find(',') != -1: change_info = LoadChangelistInfoForMultiple(changename, GetRepositoryRoot(), True, True) else: change_info = ChangeInfo.Load(changename, GetRepositoryRoot(), fail_on_not_found, True) if command == "change": Change(change_info, argv[3:]) if command == "description": print change_info.description elif command == "lint": Lint(change_info, argv[3:]) elif command == "upload": UploadCL(change_info, argv[3:]) elif command == "presubmit": PresubmitCL(change_info) elif command in ("commit", "submit"): Commit(change_info, argv[3:]) elif command == "delete": change_info.Delete() elif command == "try": # When the change contains no file, send the "changename" positional # argument to trychange.py. if change_info.GetFiles(): args = argv[3:] else: change_info = None args = argv[2:] TryChange(change_info, args, swallow_exception=False) else: # Everything else that is passed into gcl we redirect to svn, after adding # the files. This allows commands such as 'gcl diff xxx' to work. if command == "diff" and not change_info.GetFileNames(): return 0 args =["svn", command] root = GetRepositoryRoot() args.extend([os.path.join(root, x) for x in change_info.GetFileNames()]) RunShell(args, True) return 0
|
socket.getfqdn().endswith('.google.com') and not 'NO_BREAKPAD' in os.environ):
|
not 'NO_BREAKPAD' in os.environ and (socket.getfqdn().endswith('.google.com') or socket.getfqdn().endswith('.chromium.org'))):
|
def Register(): """Registers the callback at exit. Calling it multiple times is no-op.""" global _REGISTERED if _REGISTERED: return _REGISTERED = True atexit.register(CheckForException)
|
with self.lock:
|
self.lock.acquire() try:
|
def write(self, out): """Thread-safe.""" self.stdout.write(out) should_flush = False with self.lock: if (time.time() - self.last_flushed_at) > self.delay: should_flush = True self.last_flushed_at = time.time() if should_flush: self.stdout.flush()
|
d = abs(abs(prediction) - abs(diff))
|
d = distance(prediction, diff)
|
def __init__(self): self.win = 0 self.loss = 0 self.rate = 1500
|
print "home: %d road: %d" % (tally[match.home].rate, tally[match.road].rate) print "> predicted %d, spread %d, actual %d, delta %d" % (prediction, match.line, diff, d)
|
print " > home: %d road: %d" % (tally[match.home].rate, tally[match.road].rate) print " > predicted %d, spread %d, actual %d, delta %d" % (prediction, match.line, diff, d)
|
def __init__(self): self.win = 0 self.loss = 0 self.rate = 1500
|
tally[match.home].rate += (diff * 100/7)/2 tally[match.road].rate -= (diff * 100/7)/2
|
tally[match.home].rate -= (diff * 100/7)/2 tally[match.road].rate += (diff * 100/7)/2 print " > home: %d road: %d" % (tally[match.home].rate, tally[match.road].rate) print "------"
|
def __init__(self): self.win = 0 self.loss = 0 self.rate = 1500
|
if (x < 0): x = -x if (y < 0): y = y*-1 return x + y
|
if (x < 0) and (y > 0): return y + abs(x) if (y < 0) and (x > 0): return x + abs(y) return abs(x - y)
|
def distance(x, y): if (x < 0): x = -x if (y < 0): y = y*-1 return x + y
|
version = "0.4.1",
|
version = "0.4.2",
|
def finalize_options(self): if self.fix_python: import sys if sys.executable.endswith('/python2'): # this should be more sophisticated, but this # works for our needs here self.requires = self.requires.replace('python ', 'python2 ') self.build_requires = self.build_requires.replace('python ', 'python2 ') self.release = (self.release or "1") + 'python2' bdist_rpm.finalize_options(self)
|
'-level=%s' % transf.level,
|
'-level=%s' % task.level,
|
def execute_task(self, cr, uid, ids, context=None): """ Execute the task """ if context is None: context = {}
|
min_time = time(int(min_hour), int(min_minute)) max_time = time(int(max_hour), int(max_minute))
|
min_time = dttime(int(min_hour), int(min_minute)) max_time = dttime(int(max_hour), int(max_minute))
|
def post(self, lot_id, type) : min_date = self.request.get('mindate') max_date = self.request.get('maxdate') min_hour = self.request.get('minhour') min_minute = self.request.get('minminute') max_hour = self.request.get('maxhour') max_minute = self.request.get('maxminute')
|
max_time = time.max
|
max_time = dttime.max
|
def post(self, lot_id, type) : min_date = self.request.get('mindate') max_date = self.request.get('maxdate') min_hour = self.request.get('minhour') min_minute = self.request.get('minminute') max_hour = self.request.get('maxhour') max_minute = self.request.get('maxminute')
|
rospy.Subscriber('l_'+controller_name+'/state', JointTrajectoryControllerState ,self.stateCb) rospy.Subscriber('r_'+controller_name+'/state', JointTrajectoryControllerState ,self.stateCb)
|
rospy.Subscriber('l_arm_controller/state', JointTrajectoryControllerState ,self.stateCb) rospy.Subscriber('r_arm_controller/state', JointTrajectoryControllerState ,self.stateCb)
|
def __init__(self, node_name): self.node_name = node_name
|
opts, args = getopt.getopt(myargs, 'ql:r:', ['quit','left','right'])
|
opts, args = getopt.getopt(myargs, 'hql:r:', ['quit','left','right'])
|
def stateCb(self, msg): l_sum_tucked = 0 l_sum_untucked = 0 r_sum_tucked = 0 r_sum_untucked = 0 for name_state, name_desi, value_state, value_l_tucked, value_l_untucked, value_r_tucked, value_r_untucked in zip(msg.joint_names, joint_names, msg.actual.positions , l_arm_tucked, l_arm_untucked, r_arm_tucked, r_arm_untucked): if 'l_'+name_desi+'_joint' == name_state: self.l_received = True l_sum_tucked = l_sum_tucked + math.fabs(value_state - value_l_tucked) l_sum_untucked = l_sum_untucked + math.fabs(value_state - value_l_untucked) if 'r_'+name_desi+'_joint' == name_state: self.r_received = True r_sum_tucked = r_sum_tucked + math.fabs(value_state - value_r_tucked) r_sum_untucked = r_sum_untucked + math.fabs(value_state - value_r_untucked)
|
exit()
|
rospy.signal_shutdown("ERROR")
|
def stateCb(self, msg): l_sum_tucked = 0 l_sum_untucked = 0 r_sum_tucked = 0 r_sum_untucked = 0 for name_state, name_desi, value_state, value_l_tucked, value_l_untucked, value_r_tucked, value_r_untucked in zip(msg.joint_names, joint_names, msg.actual.positions , l_arm_tucked, l_arm_untucked, r_arm_tucked, r_arm_untucked): if 'l_'+name_desi+'_joint' == name_state: self.l_received = True l_sum_tucked = l_sum_tucked + math.fabs(value_state - value_l_tucked) l_sum_untucked = l_sum_untucked + math.fabs(value_state - value_l_untucked) if 'r_'+name_desi+'_joint' == name_state: self.r_received = True r_sum_tucked = r_sum_tucked + math.fabs(value_state - value_r_tucked) r_sum_untucked = r_sum_untucked + math.fabs(value_state - value_r_untucked)
|
exit() rospy.spin() else: rospy.spin()
|
rospy.signal_shutdown("Quitting") rospy.spin()
|
def stateCb(self, msg): l_sum_tucked = 0 l_sum_untucked = 0 r_sum_tucked = 0 r_sum_untucked = 0 for name_state, name_desi, value_state, value_l_tucked, value_l_untucked, value_r_tucked, value_r_untucked in zip(msg.joint_names, joint_names, msg.actual.positions , l_arm_tucked, l_arm_untucked, r_arm_tucked, r_arm_untucked): if 'l_'+name_desi+'_joint' == name_state: self.l_received = True l_sum_tucked = l_sum_tucked + math.fabs(value_state - value_l_tucked) l_sum_untucked = l_sum_untucked + math.fabs(value_state - value_l_untucked) if 'r_'+name_desi+'_joint' == name_state: self.r_received = True r_sum_tucked = r_sum_tucked + math.fabs(value_state - value_r_tucked) r_sum_untucked = r_sum_untucked + math.fabs(value_state - value_r_untucked)
|
l_arm_tucked = [0.023, 1.290, 1.891, -1.686, -1.351, -0.184, 0.307] r_arm_tucked = [0.039, 1.262, -1.366, -2.067, -1.231, -1.998, 0.369]
|
l_arm_tucked = [0.06024, 1.248526, 1.789070, -1.683386, -1.7343417, -0.0962141, -0.0864407] r_arm_tucked = [-0.023593, 1.1072800, -1.5566882, -2.124408, -1.4175, -1.8417, 0.21436]
|
def usage(): print __doc__ % vars() rospy.signal_shutdown("Help requested")
|
r_arm_approach = [0.039, 1.262, 0.0, -2.067, -1.231, -1.998, 0.369]
|
r_arm_approach = [0.039, 1.1072, 0.0, -2.067, -1.231, -1.998, 0.369]
|
def usage(): print __doc__ % vars() rospy.signal_shutdown("Help requested")
|
else: rospy.spin()
|
def stateCb(self, msg): l_sum_tucked = 0 l_sum_untucked = 0 r_sum_tucked = 0 r_sum_untucked = 0 for name_state, name_desi, value_state, value_l_tucked, value_l_untucked, value_r_tucked, value_r_untucked in zip(msg.joint_names, joint_names, msg.actual.positions , l_arm_tucked, l_arm_untucked, r_arm_tucked, r_arm_untucked): if 'l_'+name_desi+'_joint' == name_state: self.l_received = True l_sum_tucked = l_sum_tucked + math.fabs(value_state - value_l_tucked) l_sum_untucked = l_sum_untucked + math.fabs(value_state - value_l_untucked) if 'r_'+name_desi+'_joint' == name_state: self.r_received = True r_sum_tucked = r_sum_tucked + math.fabs(value_state - value_r_tucked) r_sum_untucked = r_sum_untucked + math.fabs(value_state - value_r_untucked)
|
|
if IPortal.providedBy(site.__parent__):
|
if site.__parent__ is not None:
|
def principalRemovingHandler(ev): sites = [getSite()] if sites[0] is not None: if IPortal.providedBy(site.__parent__): site = site.__parent__ sites = [site] + [site for site in site.values() if ISite.providedBy(site)] for site in sites: for name, manager in getUtilitiesFor(IPersonalSpaceManager, context=site): manager.unassignPersonalSpace(ev.principal)
|
site = getSite() if site is not None: if site.__parent__ is not None:
|
sites = [getSite()] if sites[0] is not None: if IPortal.providedBy(site.__parent__):
|
def principalRemovingHandler(ev): site = getSite() if site is not None: if site.__parent__ is not None: site = site.__parent__ sites = [site] + [site for site in site.values() if ISite.providedBy(site)] else: sites = [site] for site in sites: for name, manager in getUtilitiesFor(IPersonalSpaceManager, context=site): manager.unassignPersonalSpace(ev.principal)
|
sites = [site] + [site for site in site.values() if ISite.providedBy(site)] else: sites = [site]
|
sites = [site] + [site for site in site.values() if ISite.providedBy(site)]
|
def principalRemovingHandler(ev): site = getSite() if site is not None: if site.__parent__ is not None: site = site.__parent__ sites = [site] + [site for site in site.values() if ISite.providedBy(site)] else: sites = [site] for site in sites: for name, manager in getUtilitiesFor(IPersonalSpaceManager, context=site): manager.unassignPersonalSpace(ev.principal)
|
sites = [getSite()] if sites[0] is not None:
|
site = getSite() sites = [site] if site is not None:
|
def principalRemovingHandler(ev): sites = [getSite()] if sites[0] is not None: if site.__parent__ is not None: site = site.__parent__ sites = [site] + [site for site in site.values() if ISite.providedBy(site)] for site in sites: for name, manager in getUtilitiesFor(IPersonalSpaceManager, context=site): manager.unassignPersonalSpace(ev.principal)
|
if site is not None and site.__parent__ is not None: sites = [site.__parent__] + [site for site in site.__parent__.values() if ISite.providedBy(site)]
|
if site is not None: if site.__parent__ is not None: site = site.__parent__ sites = [site] + [site for site in site.values() if ISite.providedBy(site)]
|
def principalRemovingHandler(ev): site = getSite() if site is not None and site.__parent__ is not None: sites = [site.__parent__] + [site for site in site.__parent__.values() if ISite.providedBy(site)] else: sites = [site] for site in sites: for name, manager in getUtilitiesFor(IPersonalSpaceManager, context=site): manager.unassignPersonalSpace(ev.principal)
|
print "OUTS",[outs.at(i) for i in range(outs.length())] result = intarray_as_string(outs,skip0=0) print "RSLT",result
|
result = intarray_as_string(outs,skip0=1)
|
def recognize_and_align(image,linerec,lmodel,beam=1000,nocseg=0): """Perform line recognition with the given line recognizer and language model. Outputs an object containing the result (as a Python string), the costs, the rseg, the cseg, the lattice and the total cost. The recognition lattice needs to have rseg's segment numbers as inputs (pairs of 16 bit numbers); SimpleGrouper produces such lattices. cseg==None means that the connected component renumbering failed for some reason.""" # run the recognizer lattice = ocropus.make_OcroFST() rseg = iulib.intarray() linerec.recognizeLineSeg(lattice,rseg,image) # perform the beam search through the lattice and the model v1 = iulib.intarray() v2 = iulib.intarray() ins = iulib.intarray() outs = iulib.intarray() costs = iulib.floatarray() ocropus.beam_search(v1,v2,ins,outs,costs,lattice,lmodel,beam) # do the conversions print "OUTS",[outs.at(i) for i in range(outs.length())] result = intarray_as_string(outs,skip0=0) print "RSLT",result # compute the cseg if not nocseg: rmap = rseg_map(ins) cseg = None if len(rmap)>1: cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise Exception("renumbering failed") else: cseg = None # return everything we computed return Record(image=image, output=result, raw=outs, costs=costs, rseg=rseg, cseg=cseg, lattice=lattice, cost=iulib.sum(costs))
|
raise Exception("bad character %d in '%s'"%(c,s))
|
raise Exception("bad character %d in '%s' (%s)"%(c,s,type(s)))
|
def add_line(fst,s): s = re.sub('\s+',' ',s) state = fst.Start() if state<0: state = fst.AddState() fst.SetStart(state) for i in range(len(s)): c = ord(s[i]) if c>=32 and c<128: pass else: # print "skipping %d"%c raise Exception("bad character %d in '%s'"%(c,s)) continue nstate = fst.AddState() if s[i]==" ": fst.AddArc(state,c,c,0.0,nstate) fst.AddArc(state,openfst.epsilon,openfst.epsilon,1.0,nstate) fst.AddArc(nstate,c,c,0.0,nstate) else: fst.AddArc(state,c,c,0.0,nstate) state = nstate fst.SetFinal(state,0.0001)
|
for line in lines: add_line(fst,line)
|
count = 0 for line in lines: count += 1 try: add_line(fst,line) except: print "on line",count raise
|
def make_line_fst(lines): fst = Fst() for line in lines: add_line(fst,line) det = Fst() openfst.Determinize(fst,det) openfst.Minimize(det) temp = "/tmp/%d.fst"%os.getpid() det.Write(temp) result = ocropus.make_OcroFST() result.load(temp) os.unlink(temp) return result
|
yield line
|
yield unicode(line,"utf-8")
|
def lines_of_file(file): for line in open(file).readlines(): if line[-1]=="\n": line = line[:-1] if line=="": continue yield line
|
def __init__(self,cmodel=None,segmenter="DpSegmenter",best=10,maxcost=10.0, minheight=0.5,minaspect=0.5,maxaspect=20.0):
|
def __init__(self,cmodel=None,segmenter="DpSegmenter",best=10,maxcost=10.0,minheight=0.5):
|
def __init__(self,cmodel=None,segmenter="DpSegmenter",best=10,maxcost=10.0, minheight=0.5,minaspect=0.5,maxaspect=20.0): self.debug = 0 self.segmenter = components.make_ISegmentLine(segmenter) self.grouper = components.make_IGrouper("SimpleGrouper") # self.grouper.pset("maxdist",5) # self.grouper.pset("maxrange",5) self.cmodel = cmodel self.best = best self.maxcost = maxcost self.min_height = minheight self.min_aspect = minaspect self.max_aspect = maxaspect
|
self.min_aspect = minaspect self.max_aspect = maxaspect
|
def __init__(self,cmodel=None,segmenter="DpSegmenter",best=10,maxcost=10.0, minheight=0.5,minaspect=0.5,maxaspect=20.0): self.debug = 0 self.segmenter = components.make_ISegmentLine(segmenter) self.grouper = components.make_IGrouper("SimpleGrouper") # self.grouper.pset("maxdist",5) # self.grouper.pset("maxrange",5) self.cmodel = cmodel self.best = best self.maxcost = maxcost self.min_height = minheight self.min_aspect = minaspect self.max_aspect = maxaspect
|
|
if bbox.height()<self.min_height*mheight: continue
|
def recognizeLineSeg(self,lattice,rseg,image,keep=0): """Recognize a line. lattice: result of recognition rseg: intarray where the raw segmentation will be put image: line image to be recognized"""
|
|
if aspect<self.min_aspect: continue if aspect>self.max_aspect: continue
|
def recognizeLineSeg(self,lattice,rseg,image,keep=0): """Recognize a line. lattice: result of recognition rseg: intarray where the raw segmentation will be put image: line image to be recognized"""
|
|
produces such lattices."""
|
produces such lattices. cseg==None means that the connected component renumbering failed for some reason."""
|
def recognize_and_align(image,linerec,lmodel,beam=10000): """Perform line recognition with the given line recognizer and language model. Outputs an object containing the result (as a Python string), the costs, the rseg, the cseg, the lattice and the total cost. The recognition lattice needs to have rseg's segment numbers as inputs (pairs of 16 bit numbers); SimpleGrouper produces such lattices.""" ## run the recognizer lattice = ocropus.make_OcroFST() rseg = iulib.intarray() linerec.recognizeLine(rseg,lattice,image) ## perform the beam search through the lattice and the model v1 = iulib.intarray() v2 = iulib.intarray() ins = iulib.intarray() outs = iulib.intarray() costs = iulib.floatarray() ocropus.beam_search(v1,v2,ins,outs,costs,lattice,lmodel,beam) ## do the conversions result = intarray_as_string(outs) ## compute the cseg rmap = rseg_map(ins) cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise "renumbering failed" ## return everything we computed return Record(image=image, output=result, raw=outs, costs=costs, rseg=rseg, cseg=cseg, lattice=lattice, cost=iulib.sum(costs))
|
cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise "renumbering failed"
|
cseg = None if len(rmap)>1: cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise Exception("renumbering failed")
|
def recognize_and_align(image,linerec,lmodel,beam=10000): """Perform line recognition with the given line recognizer and language model. Outputs an object containing the result (as a Python string), the costs, the rseg, the cseg, the lattice and the total cost. The recognition lattice needs to have rseg's segment numbers as inputs (pairs of 16 bit numbers); SimpleGrouper produces such lattices.""" ## run the recognizer lattice = ocropus.make_OcroFST() rseg = iulib.intarray() linerec.recognizeLine(rseg,lattice,image) ## perform the beam search through the lattice and the model v1 = iulib.intarray() v2 = iulib.intarray() ins = iulib.intarray() outs = iulib.intarray() costs = iulib.floatarray() ocropus.beam_search(v1,v2,ins,outs,costs,lattice,lmodel,beam) ## do the conversions result = intarray_as_string(outs) ## compute the cseg rmap = rseg_map(ins) cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise "renumbering failed" ## return everything we computed return Record(image=image, output=result, raw=outs, costs=costs, rseg=rseg, cseg=cseg, lattice=lattice, cost=iulib.sum(costs))
|
cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise "renumbering failed"
|
cseg = None if len(rmap)>1: cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise Exception("renumbering failed")
|
def compute_alignment(lattice,rseg,lmodel,beam=10000): """Given a lattice produced by a recognizer, a raw segmentation, and a language model, computes the best solution, the cseg, and the corresponding costs. These are returned as Python data structures. The recognition lattice needs to have rseg's segment numbers as inputs (pairs of 16 bit numbers); SimpleGrouper produces such lattices.""" ## perform the beam search through the lattice and the model v1 = iulib.intarray() v2 = iulib.intarray() ins = iulib.intarray() outs = iulib.intarray() costs = iulib.floatarray() ocropus.beam_search(v1,v2,ins,outs,costs,lattice,lmodel,beam) ## do the conversions result = intarray_as_string(outs) ## compute the cseg rmap = rseg_map(ins) cseg = iulib.intarray() cseg.copy(rseg) try: for i in range(cseg.length()): cseg.put1d(i,int(rmap[rseg.at1d(i)])) except IndexError: raise "renumbering failed" ## return everything we computed return Record(output=result, raw=outs, costs=costs, rseg=rseg, cseg=cseg, lattice=lattice, cost=iulib.sum(costs))
|
self.space_cost = 4.0
|
self.space_cost = 9999.0
|
def __init__(self): self.nonspace_cost = 4.0 self.space_cost = 4.0 self.aspect_threshold = 2.0 self.maxrange = 30
|
self.maxcost = 10.0
|
self.maxcost = 30.0
|
def set_defaults(self): self.debug = 0 self.segmenter = components.make_ISegmentLine("DpSegmenter") self.grouper = components.make_IGrouper("SimpleGrouper") self.cmodel = None self.best = 10 self.maxcost = 10.0 self.reject_cost = 10.0 self.min_height = 0.5 self.rho_scale = 1.0 self.maxoverlap = 0.8 self.spacemodel = SimpleSpaceModel() self.linemodel = SimpleLineModel()
|
ucls = cls if type(cls)==str: ucls = unicode(cls,"utf-8") category = unicodedata.category(ucls[0]) if bbox.height()<self.min_height*mheight and category[0]=="L": continue
|
def recognizeLineSeg(self,lattice,rseg,image): """Recognize a line. lattice: result of recognition rseg: intarray where the raw segmentation will be put image: line image to be recognized"""
|
|
self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey'])
|
self.assertEquals({'value': '123', 'quoted': True, 'path': '/'}, response.cookies['plone.app.drafts.targetKey'])
|
def test_save(self): request = self.app.REQUEST response = request.response current = ICurrentDraftManagement(request) self.assertEquals(False, current.save()) self.failIf('plone.app.drafts.targetKey' in response.cookies) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/'}, response.cookies['plone.app.drafts.draftName']) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" current.path = '/test' self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/test'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/test'}, response.cookies['plone.app.drafts.draftName']) self.assertEquals({'value': '/test', 'path': '/test'}, response.cookies['plone.app.drafts.path'])
|
self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/'}, response.cookies['plone.app.drafts.draftName'])
|
self.assertEquals({'value': '123', 'quoted': True, 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'quoted': True, 'path': '/'}, response.cookies['plone.app.drafts.draftName'])
|
def test_save(self): request = self.app.REQUEST response = request.response current = ICurrentDraftManagement(request) self.assertEquals(False, current.save()) self.failIf('plone.app.drafts.targetKey' in response.cookies) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/'}, response.cookies['plone.app.drafts.draftName']) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" current.path = '/test' self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/test'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/test'}, response.cookies['plone.app.drafts.draftName']) self.assertEquals({'value': '/test', 'path': '/test'}, response.cookies['plone.app.drafts.path'])
|
self.assertEquals({'value': '123', 'path': '/test'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/test'}, response.cookies['plone.app.drafts.draftName']) self.assertEquals({'value': '/test', 'path': '/test'}, response.cookies['plone.app.drafts.path'])
|
self.assertEquals({'value': '123', 'quoted': True, 'path': '/test'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'quoted': True, 'path': '/test'}, response.cookies['plone.app.drafts.draftName']) self.assertEquals({'value': '/test', 'quoted': True, 'path': '/test'}, response.cookies['plone.app.drafts.path'])
|
def test_save(self): request = self.app.REQUEST response = request.response current = ICurrentDraftManagement(request) self.assertEquals(False, current.save()) self.failIf('plone.app.drafts.targetKey' in response.cookies) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.failIf('plone.app.drafts.draftName' in response.cookies) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/'}, response.cookies['plone.app.drafts.draftName']) self.failIf('plone.app.drafts.path' in response.cookies) current.targetKey = u"123" current.draftName = u"draft-1" current.path = '/test' self.assertEquals(True, current.save()) self.assertEquals({'value': '123', 'path': '/test'}, response.cookies['plone.app.drafts.targetKey']) self.assertEquals({'value': 'draft-1', 'path': '/test'}, response.cookies['plone.app.drafts.draftName']) self.assertEquals({'value': '/test', 'path': '/test'}, response.cookies['plone.app.drafts.path'])
|
'path': '/', 'value': 'deleted'}
|
'path': '/', 'quoted': True, 'value': 'deleted'}
|
def test_discard(self): request = self.app.REQUEST response = request.response current = ICurrentDraftManagement(request) current.discard() deletedToken = {'expires': 'Wed, 31-Dec-97 23:59:59 GMT', 'max_age': 0, 'path': '/', 'value': 'deleted'} self.assertEquals(deletedToken, response.cookies['plone.app.drafts.targetKey']) self.assertEquals(deletedToken, response.cookies['plone.app.drafts.draftName']) self.assertEquals(deletedToken, response.cookies['plone.app.drafts.path']) current.path = "/test" current.discard() deletedToken['path'] = '/test' self.assertEquals(deletedToken, response.cookies['plone.app.drafts.targetKey']) self.assertEquals(deletedToken, response.cookies['plone.app.drafts.draftName']) self.assertEquals(deletedToken, response.cookies['plone.app.drafts.path'])
|
dataset, mapping = npy_cached_load(self.cellpath) queryset = FEATURE_VIEW(load_file(self.qpath))
|
records, mapping = npy_cached_load(self.cellpath) query = load_file(self.qpath) queryset = FEATURE_VIEW(query)
|
def run(self): dataset, mapping = npy_cached_load(self.cellpath) queryset = FEATURE_VIEW(load_file(self.qpath)) flann = pyflann.FLANN() params = flann.build_index(dataset, kwargs=self.params) INFO(params) results, dists = flann.nn_index(queryset, self.params['nn'], checks=self.params['checks']) INFO(results) INFO(dists)
|
params = flann.build_index(dataset, kwargs=self.params)
|
params = flann.build_index(FEATURE_VIEW(records), kwargs=self.params)
|
def run(self): dataset, mapping = npy_cached_load(self.cellpath) queryset = FEATURE_VIEW(load_file(self.qpath)) flann = pyflann.FLANN() params = flann.build_index(dataset, kwargs=self.params) INFO(params) results, dists = flann.nn_index(queryset, self.params['nn'], checks=self.params['checks']) INFO(results) INFO(dists)
|
def run_parallel(dbdir, cells, querydir, querysift, outputFilePaths, params, num_threads=4):
|
def run_parallel(dbdir, cells, querydir, querysift, outputFilePaths, params, num_threads=8):
|
def run_parallel(dbdir, cells, querydir, querysift, outputFilePaths, params, num_threads=4): semaphore = threading.Semaphore(num_threads) threads = [] for cell, outputFilePath in zip(cells, outputFilePaths): if not os.path.exists(outputFilePath): thread = Query(dbdir, cell, querydir, querysift, outputFilePath, params, semaphore) threads.append(thread) thread.start() for thread in threads: thread.join()
|
data, mapping= npy_cached_load(argv[1])
|
data, mapping, keyset = npy_cached_load(argv[1])
|
def npy_cached_load(directory, map_only=False): """Efficiently loads a matrix of sift features and reverse lookup table for a directory of sift files.""" cellid = getcellid(directory) data_out = getfile(directory, cellid + '-features.npy') key_out = getfile(directory, cellid + '-keys.npy') map_out = getfile(directory, cellid + '-map.p') if not os.path.exists(data_out) or not os.path.exists(map_out) or not os.path.exists(key_out): INFO('finding sift files') npy_save_sift_directory(directory, cellid) mapping = pickle.load(open(map_out)) if map_only: return mapping, np.load(key_out) return np.load(data_out), mapping, np.load(key_out)
|
def query(querydir, querysift, dbdir, mainOutputDir, nClosestCells, copytopmatch, copy_top_n_percell=0): lat, lon = info.getQuerySIFTCoord(querysift) closest_cells = util.getclosestcells(lat, lon, dbdir) outputFilePaths = [] cells_in_range = [(cell, dist) for cell, dist in closest_cells[0:nClosestCells] if dist < cellradius + ambiguity+matchdistance] if verbosity > 0: print "checking query: {0} \t against {1} \t cells".format(querysift, len(cells_in_range)) for cell, dist in cells_in_range: if verbosity > 1: print "querying cell: {0}, distance: {1} with:{2}".format(cell, dist, querysift) outputFilePath = os.path.join(mainOutputDir, querysift + ',' + cell + ',' + str(dist) + ".res") outputFilePaths.append(outputFilePath) if not os.path.exists(outputFilePath): subprocess.call(["/home/ericl/kdtree1-128", dbdir, cell, querydir, querysift, outputFilePath]) if copy_top_n_percell > 0: outputDir = os.path.join(mainOutputDir, querysift + ',' + cell + ',' + str(dist)) copy_topn_results(os.path.join(dbdir, cell), outputDir, outputFilePath, 4) combined = combine_topn_votes(outputFilePaths, float('inf')) [g, y, r, b, o] = check_topn_img(querysift, combined, topnresults) if copytopmatch: match = g or y or r or b or o copy_top_match(querydir, querysift.split('sift.txt')[0], combined, match) return [g, y, r, b, o]
|
def write_scores(querysift, ranked_matches, outdir): if not os.path.exists(outdir): os.makedirs(outdir) outfile = open(os.path.join(outdir, querysift + ".top"), 'w') for matchedimg, score in ranked_matches: outfile.write(str(score)) outfile.write('\t') outfile.write(matchedimg) outfile.write('\n')
|
|
if not os.path.exists(outputFilePath): subprocess.call(["/home/ericl/kdtree1-128", dbdir, cell, querydir, querysift, outputFilePath])
|
query = Query(dbdir, cell, querydir, querysift, outputFilePath) query.run()
|
def query2(querydir, querysift, dbdir, mainOutputDir, nClosestCells, copytopmatch, copy_top_n_percell=0): lat, lon = info.getQuerySIFTCoord(querysift) closest_cells = util.getclosestcells(lat, lon, dbdir) outputFilePaths = [] cells_in_range = [(cell, dist) for cell, dist in closest_cells[0:nClosestCells] if dist < cellradius + ambiguity+matchdistance] latquery, lonquery = info.getQuerySIFTCoord(querysift) if verbosity > 0: print "checking query: {0} \t against {1} \t cells".format(querysift, len(cells_in_range)) for cell, dist in cells_in_range: latcell, loncell = cell.split(',') latcell = float(latcell) loncell = float(loncell) actualdist = info.distance(latquery, lonquery, latcell, loncell) if verbosity > 1: print "querying cell: {0}, distance: {1} with:{2}".format(cell, actualdist, querysift) outputFilePath = os.path.join(mainOutputDir, querysift + ',' + cell + ',' + str(actualdist) + ".res") outputFilePaths.append(outputFilePath) if not os.path.exists(outputFilePath): subprocess.call(["/home/ericl/kdtree1-128", dbdir, cell, querydir, querysift, outputFilePath]) if copy_top_n_percell > 0: outputDir = os.path.join(mainOutputDir, querysift + ',' + cell + ',' + str(actualdist)) copy_topn_results(os.path.join(dbdir, cell), outputDir, outputFilePath, 4)
|
shutil.copyfile(default, local)
|
shutil.copyfile(default, local + '.tmp') os.rename(local + '.tmp', local)
|
def getfile(directory, name): default = os.path.join(os.path.dirname(directory), name) if IS_REMOTE(directory): local = os.path.join(CACHE_PATH, name) if os.path.exists(local): return local elif os.path.exists(default): INFO('copying %s to local cache' % name) shutil.copyfile(default, local) return local return default
|
elif player != self.currentAct.player.nickname:
|
elif (isinstance(self.currentAct, script.Action) and player != self.currentAct.player.nickname):
|
def update(self, player, response): if not self.running: return if player is None: self.adapter.reply('You didn\'t specify a player.') return elif player != self.currentAct.player.nickname: # People are allowed to sit out, out of turn if (response[0] != script.Action.SitOut and response[0] != script.Action.AutopostBlinds): self.adapter.reply('Don\'t act out of turn!') return if response[0] not in self.currentAct.actionNames(): self.displayAct() return try: self.currentAct = self.actIter.send(response) # handle cards dealt .etc here while not isinstance(self.currentAct, script.Action): self.displayAct() self.currentAct = self.actIter.next() self.displayAct() except StopIteration: #self.adapter.reply('END!!') # if adapter stops then this becomes none. if self.script is not None: # restart next hand. self.start(self.script)
|
bettingFinished = False
|
self.bettingFinished = False
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
reOpenBetting = False
|
self.reOpenBetting = False
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
bettingClosed = False
|
self.bettingClosed = False
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
while not bettingFinished:
|
while not self.bettingFinished:
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
if bettingClosed and reOpenBetting: bettingFinished = True
|
if self.bettingClosed and self.reOpenBetting: self.bettingFinished = True
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
elif self.lastBettor == player: bettingFinished = True
|
elif self.finishBetting(player):
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
elif self.lastBettor == player: bettingClosed = True if self.capBettor and not reOpenBetting: reOpenBetting = True else: bettingFinished = True break
|
elif self.finishBetting(player): break
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
if bettingClosed and reOpenBetting:
|
if self.bettingClosed and self.reOpenBetting:
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
activePlayers = [p for p in players if p.stillActive] activeNonAllInPlayers = \ [p for p in activePlayers if not p.isAllIn]
|
lamActPlayers = lambda p: \ p.stillActive and not p.isAllIn activeNonAllInPlayers = filter(lamActPlayers, players)
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
if player.betPlaced > self.lastBet:
|
if player.betPlaced == self.currentBet: pass elif player.betPlaced > self.lastBet:
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
elif player.betPlaced == self.currentBet: pass
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
|
if len(activePlayers) < 2: bettingFinished = True break
|
def run(self): bettingFinished = False # Whether to re-open betting when a shorty goes all-in # and caps the betting reOpenBetting = False # Betting Round is closed. bettingClosed = False
|
|
seats = [P('a'), P('b')]
|
seats = [P('a'), P('b'), P('c')]
|
def __init__(self, s): self.nickname = s
|
r.setSeatBetPlaced(-2, 10) r.setSeatBetPlaced(-1, 20) r.setBetSize(20)
|
bb = 2 r.setSeatBetPlaced(-2, 1) r.setSeatBetPlaced(-1, bb) r.setBetSize(bb)
|
def __init__(self, s): self.nickname = s
|
s = int(raw_input()) if s == 1910:
|
cc = raw_input() if cc[0] == 'a': s = int(cc[1:])
|
def __init__(self, s): self.nickname = s
|
if blindState == Action.PostSB: player.paidState = table.Player.PaidState.PaidBB
|
def run(self): seats = self.table.seats dealer = self.table.dealer # Rotate the seats around the dealer. # If we have 6 seats and dealer = seat 3 then we get a list like: # [p3, p4, p5, p0, p1, p2] seats = seats[dealer:] + seats[:dealer]
|
|
elif blindState == Action.PostSBBB:
|
elif blindState == Action.PostBB:
|
def run(self): seats = self.table.seats dealer = self.table.dealer # Rotate the seats around the dealer. # If we have 6 seats and dealer = seat 3 then we get a list like: # [p3, p4, p5, p0, p1, p2] seats = seats[dealer:] + seats[:dealer]
|
preflopRotator.setBetSize(bb)
|
preflopRotator.setBetSize(table.convFact)
|
def run(self): seats = self.table.seats dealer = self.table.dealer # Rotate the seats around the dealer. # If we have 6 seats and dealer = seat 3 then we get a list like: # [p3, p4, p5, p0, p1, p2] seats = seats[dealer:] + seats[:dealer]
|
sidebar.addItem(QtGui.QTextEdit(), notesIcon, 'Notes')
|
notesWidget = QtGui.QTextEdit() notesFont = QtGui.QFont('monospace') notesFont.setPointSize(10) notesWidget.setCurrentFont(notesFont) sidebar.addItem(notesWidget, notesIcon, 'Notes')
|
def createSidebarItems(self): icon = lambda s: QtGui.QIcon('./data/gfx/icons/' + s)
|
self.adapter.privmsg('genjix', {'cards': c})
|
if not debug_oneman: self.adapter.privmsg(player.nickname, {'cards': c}) else: self.adapter.privmsg(debug_nick, {'cards': c})
|
def pmHands(self, cardsDealt): players = cardsDealt.players for player in players: c = cardsDealt.get_player_hand(player) self.adapter.privmsg('genjix', {'cards': c})
|
self.cash.addPlayer('a', 0) self.cash.addPlayer('b', 1) self.cash.addPlayer('c', 2) self.cash.addPlayer('d', 3) self.cash.addMoney('a', 5000) self.cash.addMoney('b', 5000) self.cash.addMoney('c', 6000) self.cash.addMoney('d', 8000) self.cash.sitIn('a') self.cash.sitIn('b') self.cash.sitIn('c') self.cash.sitIn('d') self.cash.setAutopost('a', True) self.cash.setAutopost('b', True) self.cash.setAutopost('c', True) self.cash.setAutopost('d', True) def msg(self, user, message): print('%s: %s'%(user, message))
|
if debug_oneman: self.cash.addPlayer('a', 0) self.cash.addPlayer('b', 1) self.cash.addPlayer('c', 2) self.cash.addPlayer('d', 3) self.cash.addMoney('a', 5000) self.cash.addMoney('b', 5000) self.cash.addMoney('c', 6000) self.cash.addMoney('d', 8000) self.cash.sitIn('a') self.cash.sitIn('b') self.cash.sitIn('c') self.cash.sitIn('d') self.cash.setAutopost('a', True) self.cash.setAutopost('b', True) self.cash.setAutopost('c', True) self.cash.setAutopost('d', True) def debug_strip(self, message):
|
def __init__(self, prot, chan): reload(script) reload(table) self.prot = prot self.chan = chan self.cash = table.Table(9, 0.25, 0.5, 0, 5000, 25000) self.cash.registerScheduler(Schedule(self.reply)) self.handler = Handler(self) self.cash.registerHandler(self.handler) self.cash.setStartupDelayTime(0)
|
"""player = user
|
return player, command, param def strip_message(self, user, message): player = user
|
def msg(self, user, message): print('%s: %s'%(user, message))
|
param = None"""
|
param = None return player, command, param def msg(self, user, message): print('%s: %s'%(user, message)) if debug_oneman: player, command, param = self.debug_strip(message) else: player, command, param = self.strip_message(user, message)
|
def msg(self, user, message): print('%s: %s'%(user, message))
|
scr = script.Script(self) if self.handler: self.handler.start(scr)
|
def start(self): """Start the game.""" if self.gameState != GameState.Starting: if self.gameState == GameState.Running: print('Game already running.') else: print('Start game cancelled.') return self.gameState = GameState.Running print('Game started.') # select a random dealer occupiedSeats = \ [i for i, p in enumerate(self.seats) if p and not p.sitOut] self.dealer = random.choice(occupiedSeats)
|
|
if self.seats[i] and not self.seats[i].sitOut]
|
if self.seats[i] is not None and not self.seats[i].sitOut]
|
def nextDealer(self): # Get list of indices of the seats rotatedSeats = [i for i, p in enumerate(self.seats)] # Rotate it around the current dealer position + 1 rotatedSeats = \ rotatedSeats[self.dealer+1:] + rotatedSeats[:self.dealer+1] # Filter empty seats and sitting out players filterSeats = [i for i in rotatedSeats \ if self.seats[i] and not self.seats[i].sitOut] # Return next suitable candidate self.dealer = filterSeats[0]
|
self.wgt.setStyleSheet(common.loadStyleSheet('style.css'))
|
self.wgt.setStyleSheet(str(common.loadStyleSheet('style.css')))
|
def addchip(chip, scene, pos): other = scene.addPixmap(chip) other.setTransformationMode(QtCore.Qt.SmoothTransformation) other.setFlags(other.ItemIsMovable) other.setPos(*pos)
|
self.pay(price)
|
else: self.pay(price)
|
def raiseto(self, bet): price = bet - self.bet if price >= self.parent.stack: self.pay(self.parent.stack) raise AllIn(self) self.pay(price)
|
for player in self.players: bettor = player.betpart bettor.begin_stack = player.stack
|
def run(self): for player in self.players: bettor = player.betpart bettor.begin_stack = player.stack
|
|
if self.num_bettors() < 2:
|
if self.num_active_bettors() < 2:
|
def fold(self, bettor): bettor.fold() if self.num_bettors() < 2: self.state = Rotator.BettingFinished
|
self.last_bettor = bettor self.last_raise = raise_size self.current_bet = bettor.bet else: if self.state == Rotator.BettingCapped: self.state = Rotator.BettingOpen self.last_bettor = bettor self.last_raise = bettor.bet - self.current_bet self.current_bet = bettor.bet
|
self.normal_raise(bettor) else: self.normal_raise(bettor) def normal_raise(self, bettor): if self.state == Rotator.BettingCapped: self.state = Rotator.BettingOpen self.last_bettor = bettor self.last_raise = bettor.bet - self.current_bet self.current_bet = bettor.bet
|
def raiseto(self, bettor, amount): if (not bettor.min_raise <= amount <= bettor.max_raise or not bettor.can_raise): raise IllegalRaise(bettor) try: bettor.raiseto(amount) except AllIn as allin: raise_size = bettor.bet - self.current_bet if raise_size < self.last_raise: self.state = Rotator.BettingCapped self.cap_bettor = bettor else: self.last_bettor = bettor self.last_raise = raise_size self.current_bet = bettor.bet else: # Re-open betting if self.state == Rotator.BettingCapped: self.state = Rotator.BettingOpen self.last_bettor = bettor self.last_raise = bettor.bet - self.current_bet self.current_bet = bettor.bet
|
players = [P('UTG', 100), P('SS', 6), P('CO', 100), P('BTN', 100)]
|
players = [P('UTG', 80), P('SS', 100), P('CO', 100), P('BTN', 100)]
|
def __repr__(self): return self.nickname
|
for w in [w for w in widgets if w not in self.exceptions]:
|
for w in widgetsNotInExceptions:
|
def _multiSetVisible(self, widgets, state): if self.currentState == state: return newExceptions = [] if state: self.setVisible(False) else: if self.currentState != None: newExceptions = [w for w in widgets if not w.isVisible()] # get the tab bar to reset the active tab position tabList = self.parent().findChildren(QTabBar, None) if len(tabList) > 0: tabBar = tabList[0] self.activeTab = tabBar.currentIndex() self.currentState = state
|
pots.remove(unpot)
|
pots.pots.remove(unpot)
|
def run(self): # Active people in the current hand # Added to the list preflop as the hand progresses. activePlayers = []
|
bettor.darkbet -= unpot.size bettor.stack += unpot.size
|
def run(self): # Active people in the current hand # Added to the list preflop as the hand progresses. activePlayers = []
|
|
self.edit.setMaximumSize(50,28)
|
self.edit.setMaximumSize(60,28)
|
def __init__(self): super(MdiTable, self).__init__() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle(self.tr('Table titilonius')) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) self.setMinimumHeight(200)
|
self.wgt.setStyleSheet(common.loadStyleSheet('./data/gfx/table/default/style.css'))
|
if QtCore.QDir.setCurrent('./data/gfx/table/default/'): self.wgt.setStyleSheet(common.loadStyleSheet('style.css'))
|
def __init__(self): super(MdiTable, self).__init__() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle(self.tr('Table titilonius')) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) self.setMinimumHeight(200)
|
self.slider.setValue(int(value) - 1)
|
self.slider.setValue(round(float(value)) - 1)
|
def textChanged(self, value): self.slider.setValue(int(value) - 1)
|
return 'Uncalled bet. %s won %d\n'%(self.pname, self.bet)
|
return 'Uncalled bet of %d returned to %s\n'%(self.bet, pname)
|
def __repr__(self): pname = self.player.nickname return 'Uncalled bet. %s won %d\n'%(self.pname, self.bet)
|
response = yield UncalledBet(player, potSize)
|
betSize = returnedBet.betSize response = yield UncalledBet(player, betSize)
|
def run(self): seats = self.table.seats dealer = self.table.dealer # Rotate the seats around the dealer. # If we have 6 seats and dealer = seat 3 then we get a list like: # [p3, p4, p5, p0, p1, p2] seats = seats[dealer:] + seats[:dealer]
|
if rotator.last_raise > 0:
|
if rotator.current_bet > 0:
|
def run(self): # Active people in the current hand # Added to the list preflop as the hand progresses. activePlayers = []
|
self.running = False
|
def __init__(self, adapter): self.running = False self.adapter = adapter self.script = None self.actIter = None self.currentAct = None
|
|
self.script = None self.actIter = None self.currentAct = None
|
self.stop()
|
def __init__(self, adapter): self.running = False self.adapter = adapter self.script = None self.actIter = None self.currentAct = None
|
self.cash.setAutopost('a', True)
|
"""self.cash.setAutopost('a', True)
|
def __init__(self, prot, chan): reload(script) reload(table) self.prot = prot self.chan = chan self.cash = table.Table(9, 0.25, 0.5, 0, 5000, 25000) self.cash.registerScheduler(Schedule(self.reply)) self.handler = Handler(self) self.cash.registerHandler(self.handler) self.cash.setStartupDelayTime(0)
|
self.cash.setAutopost('d', True)
|
self.cash.setAutopost('d', True)"""
|
def __init__(self, prot, chan): reload(script) reload(table) self.prot = prot self.chan = chan self.cash = table.Table(9, 0.25, 0.5, 0, 5000, 25000) self.cash.registerScheduler(Schedule(self.reply)) self.handler = Handler(self) self.cash.registerHandler(self.handler) self.cash.setStartupDelayTime(0)
|
if not bettor.active: return False elif bettor == self.last_bettor:
|
if bettor == self.last_bettor:
|
def prompt_open(self, bettor): if not bettor.active: # Player folded. Continue on. return False elif bettor == self.last_bettor: # Table went a full cycle without re-raising. Finish up. self.state = Rotator.BettingFinished return False elif bettor.stack == 0: # Player is all-in. Continue on. return False
|
players = [P('a', 900), P('b', 200), P('c', 800), P('SB', 150), P('BB', 800)]
|
players = [P('U', 900), P('SB', 900), P('BB', 900)]
|
def show_all(players): for b in [p.bettor for p in players]: print b
|
rotator = Rotator(players, 1, 1)
|
players[1].bettor.pay(50) players[2].bettor.pay(100) rotator = Rotator(players, 100, 100)
|
def show_all(players): for b in [p.bettor for p in players]: print b
|
rotator = Rotator(players, 0, 1) do_rotation(rotator) show_all(players)
|
rotator = Rotator(players, 0, 100)
|
def show_all(players): for b in [p.bettor for p in players]: print b
|
def __init__(self): super(MdiTable, self).__init__()
|
def __init__(self, parent): super(MdiTable, self).__init__(parent)
|
def __init__(self): super(MdiTable, self).__init__() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle(self.tr('Table titilonius')) #self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) self.setMinimumHeight(200)
|
if abs(curr_aspect - aspect) > 0.00000001:
|
if abs(curr_aspect - aspect) > 0.00000001 and not self.isMaximized():
|
def resizeEvent(self, event): super(MdiTable, self).resizeEvent(event) #return size = self.contentsRect().size()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.