def construct(self): a = "a" b = "b" c = "c" d = "d" preferences = {a: [b, c, d], b: [c, d, a], c: [d, b, a], d: [a, b, c]} T = PreferenceTable(preferences, center=[-3.5, 0, 0]) C = Cycle([a, b, c, a], [b, c, d, b], center=[3, 0, 0]) self.play(*T.create()) self.play(*T.propose(a, b), *T.propose(b, c), *T.propose(c, d)) self.play(*T.accept_proposal(a, b), *T.accept_proposal(b, c), *T.accept_proposal(c, d)) self.wait() self.play(*C.create()) self.play(*C.accept(0, 1)) self.play(*C.reject(0, 1)) self.wait() # for anim in C.create_from_table(T): # self.play(anim) # self.wait(2) # self.play(*C.cut_first_prefs(T)) # self.wait(2) # self.play(*C.accept_second_prefs(T)) # self.wait(2) # self.play(*C.uncreate()) self.wait(2)
def dashboard(name=None): cycle_insts = [Cycle.load(c) for c in cycles] notices = Notice.load_list(notices_fname)[::-1] today = datetime.today().weekday() chef = Cycle.load('cooking_schedule')[today] return render_template('dashboard.html', cycles=cycle_insts, notices=notices, chef=chef)
def play1(self, waves=False): pygame.init() self.DISPLAY = pygame.display.set_mode((self.W, self.H), 0) self.DISPLAY.fill(self.BACKGROUND) quit_draw = False for n, cycle in enumerate(self.complex_intervals): if n == 0: self.complex_cycles.append( Cycle(cycle[0], self.W / 2, self.H / 2, cycle[1], cycle[2])) else: self.complex_cycles.append( Cycle(cycle[0], self.complex_cycles[n - 1].x, self.complex_cycles[n - 1].y, cycle[1], cycle[2])) while not quit_draw: self.DISPLAY.fill(self.BACKGROUND) for n, cycle in enumerate(self.complex_cycles): self.draw_circle(cycle) cycle.angle = self.time cycle.update_point() if n < len(self.complex_cycles) - 1: self.complex_cycles[n + 1].x_center = cycle.x self.complex_cycles[n + 1].y_center = cycle.y self.complex_point = [ self.complex_cycles[-1].x, self.complex_cycles[-1].y ] pygame.draw.circle(self.DISPLAY, (255, 0, 0), self.complex_point, 2) self.complex_drawing.append(self.complex_point) # przesuwanie if waves: for n in range(len(self.complex_drawing)): self.complex_drawing[n] = (self.complex_drawing[n][0] + 1, self.complex_drawing[n][1]) self.complex_drawing = [ point for point in self.complex_drawing if point[0] < 1520 ] else: if self.time > 2 * math.pi: self.complex_drawing = [] self.time = 0 if len(self.complex_drawing) > 1: pygame.draw.lines(self.DISPLAY, (255, 255, 255), False, self.complex_drawing) for event in pygame.event.get(): if event.type == pygame.QUIT: quit_draw = True pygame.quit() quit() pygame.display.flip() self.time += self.dt self.CLOCK.tick(self.FPS)
def main(): driller = Cycle() serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.setblocking(0) serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serv.bind(("localhost", 7777)) serv.listen(1) handler = SocketHandler(driller, serv, is_server=True) driller.register(serv.fileno(), handler, select.EPOLLIN) handler.read_util('\n', HttpServer()) driller.drill()
def getCycle(self): query = "SELECT * from cycle" result = Database.connectDB(self, query) if not result: return Cycle(None, None, None, None, None, None, None, None, None, None, None, None, None, None) else: return Cycle(result[0][0], result[0][1], result[0][2], result[0][3], result[0][4], result[0][5], result[0][6], result[0][7], result[0][8], result[0][9], result[0][10], result[0][11], result[0][12], result[0][13])
def __loadConfig(self, config): if "numRelays" in config: self.numRelays = config["numRelays"] numRelays = self.numRelays if "cycles" in config: for key, cycleList in config["cycles"].items(): subCycles = [] if "numRelays" in cycleList: numRelays = cycleList["numRelays"] for sub in cycleList["subCycles"]: if "seconds" in sub and "mode" in sub: subCycles.append(SubCycle(sub["seconds"], sub["mode"])) elif "cycleName" in sub: subCycles.append(sub) break self.cycles.append(Cycle(subCycles, numRelays, key)) for cycle in self.cycles: subCycles = [] for subCycle in cycle.subCycles: if type(subCycle) is SubCycle: subCycles.append(subCycle) elif type(subCycle) is dict and "cycleName" in subCycle: newSubCycle = self.getCycle(subCycle["cycleName"]) if type(newSubCycle) is Cycle: subCycles.append(newSubCycle) break cycle.subCycles = subCycles
def generateCycles(markets, currencyFilter): cycles = [] counter = 0 for index1 in range(len(markets)): markets[index1].print_market() if (markets[index1].get_sourceCurrency() == currencyFilter): for index2 in range(index1 + 1, len(markets)): for i in range(2): for j in range(2): if markets[index1].currencies[ 1 - i] == markets[index2].currencies[j]: for index3 in range(index2 + 1, len(markets)): for k in range(2): if markets[index2].currencies[ 1 - j] == markets[index3].currencies[ k] and markets[ index1].currencies[ i] == markets[ index3].currencies[ 1 - k]: print('match ' + markets[index1].code + ' ' + markets[index2].code + ' ' + markets[index3].code + ' ' + str(i == 0) + ' ' + str(j == 0) + ' ' + str(k == 0)) currCycle = Cycle([ markets[index1], markets[index2], markets[index3] ], [(i == 0), (j == 0), (k == 0)]).rotate( ['ETH', 'BTC', 'USDT']) # if currCycle.leftCurrency(0) == 'ETH' and (currCycle.leftCurrency(1) == 'USDT' or currCycle.leftCurrency(2) == 'USDT'): if 1 == 1: cycles += [ currCycle, currCycle.reverse() ] counter += 1 print('counter %d' % counter) return cycles
class WorkspaceWindowManager(object): """ window manager mixin for a wm with workspaces """ def __wm_screen_init__( self ): log.debug( "WorkspaceWindowManager.__wm_screen_init__" ) self.workspaces = Cycle() self.workspaceDict = {} def __wm_init__( self ): log.debug( "WorkspaceWindowManager.__wm_init__" ) workspace = self.workspaces.current() if workspace: workspace.activate() def current_frame( self ): ws = self.workspaces.current() if ws: return ws.current_frame def set_current_frame( self, frame ): if frame: self.workspaces.current().current_frame = frame else: log.error( "wtf, set_current_frame got a null frame" ) def set_current_workspace( self, index ): if( index != self.workspaces.index and index >= 0 and index < len( self.workspaces ) ): self.workspaces.current().deactivate() self.workspaces.index = index self.workspaces.current().activate() def get_workspace_by_name( self, name ): (ws,index) = self.workspaceDict[ name ] return ws def new_workspace( self, screen, type=TABBED, name="" ): try: (ws,index) = self.workspaceDict[ name ] except KeyError: ws = Workspace( screen, type, name ) index = len(self.workspaces) self.workspaceDict[ name ] = (ws,index) self.workspaces.append( ws ) self.set_current_workspace( index ) return ws
class WorkspaceWindowManager(object): """ window manager mixin for a wm with workspaces """ def __wm_screen_init__(self): log.debug("WorkspaceWindowManager.__wm_screen_init__") self.workspaces = Cycle() self.workspaceDict = {} def __wm_init__(self): log.debug("WorkspaceWindowManager.__wm_init__") workspace = self.workspaces.current() if workspace: workspace.activate() def current_frame(self): ws = self.workspaces.current() if ws: return ws.current_frame def set_current_frame(self, frame): if frame: self.workspaces.current().current_frame = frame else: log.error("wtf, set_current_frame got a null frame") def set_current_workspace(self, index): if (index != self.workspaces.index and index >= 0 and index < len(self.workspaces)): self.workspaces.current().deactivate() self.workspaces.index = index self.workspaces.current().activate() def get_workspace_by_name(self, name): (ws, index) = self.workspaceDict[name] return ws def new_workspace(self, screen, type=TABBED, name=""): try: (ws, index) = self.workspaceDict[name] except KeyError: ws = Workspace(screen, type, name) index = len(self.workspaces) self.workspaceDict[name] = (ws, index) self.workspaces.append(ws) self.set_current_workspace(index) return ws
def __init__(self ,progs, visualizer,gwidth = 90, glength = 120 , gfriction = 1): self.cycle = Cycle() self.ground = Ground(glength , gwidth ,gfriction ) self.players =[] for i in range(2): for j in range(5): self.players.append(Player(self.ground, progs[i] , i , j , Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) )) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, self.players[j].pos.x, self.players[j].pos.y) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, indexi[j] * gwidth / 2, indexj[j] * glength / 2 * (-1) ** (i)) self.ball = Ball(self.ground) self.state = State(self.players , self.ball) self.referee = Referee(self.state) self.visualizer = visualizer
def __init__(self, host, port, terminalID = "", password = None): self.receivers = {} self.quitMessage = "" self.password = password self.nickNames = Cycle(NICKNAMES) self._terminalID = terminalID # shorthand for server in terminal self._currentReceiverKey = None self._connection = Connection(host, port, self._parseInput) self._logger = Logger("%s/%s" % (host, "SERVER")) self._clientObject = self._newReceiver(self.nickNames.val()) self._welcomeEvent = threading.Event() self._reconnectEvent = threading.Event() self._reconnectEvent.set()
def construct(self): title = Text("Preference Cycles:") self.play(Create(title)) self.wait(1) self.play(ApplyMethod(title.shift, 3 * UP)) self.wait(1) definition = Tex("A sequence of players $a_1, a_2, \ldots, a_r$", color=WHITE).scale(0.8).shift(1.9 * UP) self.play(Create(definition)) self.wait(1) cycle = Cycle(["$a_1$", "$a_2$", "$a_3$", "$a_4$", "$a_5$", "$a_1$"], ["$b_1$", "$b_2$", "$b_3$", "$b_4$", "$b_5$", "$b_1$"], center=[0,-0.5,0]) self.play(*[Create(a) for a in cycle.A_mobs[:-1]]) definition2 = Tex("with first preferences $b_1, b_2, \ldots, b_r$", color=WHITE).scale(0.8).shift(1.4 * UP) self.play(Create(definition2)) self.wait(1) self.play(*[Create(b) for b in cycle.B_mobs[:-1]]) first_pref_arrows = [arrow for i,arrow in enumerate(cycle.arrows[:-2]) if i % 2 == 0] second_pref_arrows = [arrow for i,arrow in enumerate(cycle.arrows[:-2]) if i % 2 == 1] self.play(*[Create(ar.curr_arrow()) for ar in first_pref_arrows]) self.wait(2) definition3 = Tex("where the second favorite of $a_i$ is $b_{i+1},$", color=WHITE).scale(0.8).shift(2.4 * DOWN) self.play(Create(definition3)) self.wait(1) self.play(*[Create(ar.curr_arrow()) for ar in second_pref_arrows]) self.wait(2) definition4 = Tex("wrapping around for $a_r$ and $a_1$.", color=WHITE).scale(0.8).shift(2.9 * DOWN) self.play(Create(definition4)) self.play(Create(cycle.A_mobs[-1]), Create(cycle.B_mobs[-1])) self.play(Create(cycle.arrows[-2].curr_arrow()), Create(cycle.arrows[-1].curr_arrow())) self.wait(5) self.play(*[Uncreate(d) for d in (definition, definition2, definition3, definition4)]) self.wait(1) elimination = Tex("We \\emph{eliminate} the cycle by having $b_1$ reject $a_1$.", color=WHITE).scale(0.8).shift(1.5 * UP) self.play(Create(elimination)) self.wait(1) self.play(*(cycle.reject(0,0) + cycle.reject(5,5))) self.wait(1) elimination2 = Tex("Each $b_i$ has $a_i$ as its least favorite, so it rejects", color=WHITE).scale(0.8).shift(2.4 * DOWN) self.play(Create(elimination2)) elimination3 = Tex("$a_i$ to match with $a_{i-1}$.", color=WHITE).scale(0.8).shift(2.9 * DOWN) self.play(Create(elimination3)) self.wait(1) for i in range(5): self.play(*cycle.reject(i+1,i+1)) self.play(*cycle.accept(i,i+1)) self.wait(5)
def animate_rotation_elimination(self, p, q): C = Cycle(p + [p[0]], q + [q[0]], center=[3.5, 0, 0], width=0.9 * config['frame_x_radius']) for anim in C.create_from_table(self.T): self.scene.play(anim) self.scene.wait(1) self.scene.play(*C.cut_first_prefs(self.T)) self.scene.wait(1) self.scene.play(*C.accept_second_prefs(self.T)) self.scene.wait(1) self.scene.play(*C.uncreate()) self.scene.wait(1)
def generateParamString(procName, inParamList, image, drawable): """ Generate a string of the form '(foo,)' or '()' Returns None for unhandled types (an error) """ result = SpecialParams.get(procName) if result: return result # else generate param string dynamically # TODO why GParam and GimpParam ?? result = "(" # If we are eval'ing in GimpFu context (see elsewhere) # omit the first parameter, the run mode if ProcedureCategory.doesGimpFuHideRunMode(procName): startParam = 1 else: startParam = 0 for aType in inParamList[startParam:]: if aType == "GimpParamString" or aType == "GParamString": # often the name of an item but sometimes a filename or dirname # and sometimes a quoted numeric like "1" which scriptfu strips of quotes? result = appendParameter(result, Cycle.str()) elif aType == "GParamInt": result = appendParameter(result, Cycle.int()) elif aType == "GParamUInt": # TODO this does not suffice. Change gimpfu to cast to GParamUint result = appendParameter(result, Cycle.int()) elif aType == "GParamUChar": # GParamUChar usually used as an int-valued enum, often True/False # TODO this does not suffice. Change gimpfu to cast to GParamUint result = appendParameter(result, Cycle.int()) elif aType == "GParamDouble": result = appendParameter(result, Cycle.float()) elif aType == "GParamBoolean": # bool is int ?? result = appendParameter(result, Cycle.int()) elif aType == "GimpParamItem": # Item is superclass of Drawable, etc. # Use a convenient one result = appendParameter(result, 'drawable') elif aType == "GParamEnum" or aType == "GimpParamEnum": # Sometimes run_mode e.g. for Internal gimp-file-load-layers # enums are ints # TODO an interactive mode of testing # 1 is NONINTERACTIVE result = appendParameter(result, '1') elif aType == "GimpParamImage": # reference a symbol in Python context at time of eval result = appendParameter(result, 'image') elif aType == "GimpParamDrawable": # reference a symbol in Python context at time of eval result = appendParameter(result, 'drawable') elif aType == "GimpParamLayer": # reference a symbol in Python context at time of eval # assert drawable is-a Layer result = appendParameter(result, 'drawable') elif aType == "GimpParamRGB": # a 3-tuple suffices, GimpFu marshals to a Gimp.RGB result = appendParameter(result, '(12, 13, 14)') elif aType == "GimpParamUnit": # call out to Gimp for a defined constant # result = appendParameter(result, 'Gimp.Unit.UNIT_PIXEL') # int works? # TODO should we cycle out of the range of the enum type? result = appendParameter(result, Cycle.int()) elif aType == "GimpParamFloatArray": # a 4-tuple often suffices # TODO prefixed with len ?? result = appendParameter(result, '4, (1.0, 1.0, 5.0, 5.0)') result = appendParameter(result, '(1.0, 1.0, 5.0, 5.0)') elif aType == "GimpParamUInt8Array": # a 4-tuple often suffices e.g. gimp-image-set-colormap result = appendParameter(result, '(1, 2, 3, 4)') elif aType == "GimpParamVectors": # refer to test harness object result = appendParameter(result, 'fooVectors') elif aType == "GParamObject": # Usually a GFile # refer to test harness object result = appendParameter(result, 'fooFile') elif aType == "GimpParamObjectArray": """ Usually an array of Gimp.Drawable. The signature of many procedures changed in 3.0 to take: n_drawables, drawables Refer to "drawable", since GimpFu will convert to GimpParamDrawableArray automatically. However, this depends on the int for n_drawables being 1. """ # assert drawable is a wrapped GimpFu Adapter #print(f"Drawable: {drawable}") # DEBUG unwrapped result = appendParameter(result, 'drawable') # TODO more types # GimpParamParasite # GimpParamUInt8Array 10 # GimpParamChannel 12 # GimpParamUnit 13 # GimpParamVectors 23 # GimpParamDisplay 2 # GimpParamStringArray else: # some type we don't handle, omit test TestStats.sample("omit for param type") TestStats.sample(f"omit for param type: {aType}") TestLog.say(f"unhandled type {aType} for {procName}") return "" result = result + ')' # assert result is '()' or of the form '(foo,)' return result
def loadData(filename, parent=None, gui=True): """ Loads material data from an ERANOS output file. Returns a list 'cycles' with all the Cycle instances. """ # Open file eranosFile = open(filename, "r") cycles = [] # Find the names of all the fuel regions fuelNames = [] m = fileReSeek(eranosFile, "^->LISTE_MILIEUX.*") fuelNames += re.findall("'(FUEL\d+)'", m.group()) while True: line = eranosFile.readline().strip() fuelNames += re.findall("'(FUEL\d+)'", line) if line[-1] == ";": break # Determine if there is a blanket material m = fileReSeek(eranosFile, "^->BLANKET.*") if m: fuelNames += ["BLANK"] else: eranosFile.seek(0) # Determine default cooling period position = eranosFile.tell() m = fileReSeek(eranosFile, "^->COOLINGTIME\s+(\S+).*") if m: try: if m.groups()[0][:6] == "(PASSE": auto_cooling = True else: auto_cooling = False cooling_time = float(m.groups()[0]) except: cooling_time = 30 else: cooling_time = None eranosFile.seek(position) # Determine cycle information while True: m = fileReSeek(eranosFile, ".*->CYCLE\s+(\d+).*") if not m: break n = int(m.groups()[0]) m = fileReSeek(eranosFile, "^->PASSE\s\((\d+)\).*") if not m: break timestep = int(m.groups()[0]) m = fileReSeek(eranosFile, "^->ITER\s(\d+).*") iterations = int(m.groups()[0]) # Determine cooling period if auto_cooling: cooling_time = timestep*iterations*0.15/0.85 cycles.append(Cycle(n, timestep, iterations, cooling_time)) eranosFile.seek(0) # Determine how many materials to read total n_materials = 0 for cycle in cycles: n_materials += len(cycle.times())*len(fuelNames) # Create progress bar if gui: progress = QProgressDialog("Loading ERANOS Data...", "Cancel", 0, n_materials, parent) progress.setWindowModality(Qt.WindowModal) progress.setWindowTitle("Loading...") progress.setMinimumDuration(0) progress.setValue(0) pValue = 0 for cycle in cycles: print("Loading Cycle {0}...".format(cycle.n)) # Determine critical mass fileReSeek(eranosFile, " ECCO6.*") xsDict = {} for i in fuelNames: m = fileReSeek(eranosFile, "\sREGION :(FUEL\d+|BLANK)\s*") name = m.groups()[0] m = fileReSeek(eranosFile, "\s*TOTAL\s+(\S+)\s+(\S+)\s+\S+\s+(\S+).*") nuSigmaF = float(m.groups()[0]) SigmaA = float(m.groups()[1]) Diff = float(m.groups()[2]) xsDict[name] = (nuSigmaF, SigmaA, Diff) # Find beginning of cycle m = fileReSeek(eranosFile, ".*M A T E R I A L B A L A N C E.*") # Find TIME block and set time for node, time in enumerate(cycle.times()): # Progress bar if gui: QCoreApplication.processEvents() if (progress.wasCanceled()): return None # Loop over fuel names for i in fuelNames: m = fileReSeek(eranosFile,"\s+MATERIAL\s(FUEL\d+|BLANK)\s+") name = m.groups()[0] volume = float(eranosFile.readline().split()[-1]) for n in range(5): eranosFile.readline() # Read in material data material = readMaterial(eranosFile) material.volume = volume if time == 0: material.nuFissionRate = xsDict[name][0] material.absorptionRate = xsDict[name][1] material.diffRate = xsDict[name][2] cycle.materials[(node,name)] = material #print (node,name) # Set progress bar value pValue += 1 if gui: progress.setValue(pValue) #print((cycle.n, time, name)) # Only for debugging # Read uranium added/required feed for i in range(3): # Determine if there is additional mass or not enough regexList = [" 'REQUIRED FEED FOR FUEL (\d).*", " 'ADDITIONAL FEED FOR FUEL (\d).*"] m, index = fileReSeekList(eranosFile,regexList) if index == 0: # We don't have enough fissile material cycle.extraMass = False mat = "FUEL{0}".format(m.groups()[0]) m = fileReSeek(eranosFile," ->REPLMASS2\s+(\S+).*") cycle.requiredFeed += float(m.groups()[0]) m = fileReSeek(eranosFile," ->REPLMASS1\s+(\S+).*") cycle.uraniumAdded[mat] = float(m.groups()[0]) m = fileReSeek(eranosFile," ->POWER\d\s+(\S+).*") cycle.materials[(5,mat)].power = float(m.groups()[0]) else: # Additional mass was produced cycle.extraMass = True mat = "FUEL{0}".format(m.groups()[0]) m = fileReSeek(eranosFile," ->EXTRA\s+(\S+).*") cycle.additionalFeed[mat] = float(m.groups()[0]) m = fileReSeek(eranosFile," ->REPLMASS\s+(\S+).*") cycle.uraniumAdded[mat] = float(m.groups()[0]) m = fileReSeek(eranosFile," ->POWER\d\s+(\S+).*") cycle.materials[(5,mat)].power = float(m.groups()[0]) posb = eranosFile.tell() for i in range(4): # Get DPA information regexList = [" 'DPA of FUEL (\d).*", " 'DPA of BLANKET'.*"] m, index = fileReSeekList(eranosFile,regexList) if index == 0: # We don't have enough fissile material mat = "FUEL{0}".format(m.groups()[0]) m = fileReSeek(eranosFile," ->DPA\dC\s+(\S+).*") #print (m.group(), m.groups()) #print (mat) cycle.materials[(5,mat)].dpa = float(m.groups()[0]) else: # Additional mass was produced mat = "BLANK" m = fileReSeek(eranosFile," ->DPABC\s+(\S+).*") #print (m.group(), m.groups()) cycle.materials[(5,mat)].dpa = float(m.groups()[0]) #cycle.materials[(0,mat)].dpa = float(m.groups()[0]) eranosFile.seek(posb) # Read charge and discharge vectors at end of ERANOS output file charge = Material() discharge = Material() onestreamch = Material() onestreamdis = Material() listeiso = ['Th232','Pa231','Pa233','U232','U233','U234','U235','U236','U238','Np237', 'Np239','Np238','Pu238','Pu239','Pu240','Pu241','Pu242','Am241','Am242g', 'Am242m','Am243','Cm242','Cm243','Cm244','Cm245','Cm246','Cm247','Cm248', 'Bk249','Cf249','Cf250','Cf251','Cf252','sfpU234','sfpU235','sfpU236', 'sfpU238','sfpNp237','sfpPu238','sfpPu239','sfpPu240','sfpPu241','sfpPu242', 'sfpAm241','sfpAm242m','sfpAm243','sfpCm243','sfpCm244','sfpCm245'] m = fileReSeek(eranosFile," ->CHARGE\s+(\S+).*") words = m.group().split() words.pop(0) value = [float(val) for val in words] for i in range(10): words = eranosFile.readline().split() value.extend([float(val) for val in words]) for iso in range(33): charge.addMass(listeiso[iso],value[iso]) onestreamch.addMass(listeiso[iso],value[iso]) for iso in range(16): charge.addMass(listeiso[iso+33],value[iso+33],True) onestreamch.addMass(listeiso[iso+33],value[iso+33],True) charge.expandFPs() m = fileReSeek(eranosFile," ->DISCHARGE\s+(\S+).*") words = m.group().split() words.pop(0) value = [float(val) for val in words] for i in range(10): words = eranosFile.readline().split() value.extend([float(val) for val in words]) for iso in range(33): discharge.addMass(listeiso[iso],value[iso]) onestreamdis.addMass(listeiso[iso],value[iso]) for iso in range(16): discharge.addMass(listeiso[iso+33],value[iso+33],True) onestreamdis.addMass(listeiso[iso+33],value[iso+33],True) discharge.expandFPs() chblank = Material() disblank = Material() m = fileReSeek(eranosFile," ->CHBLANK\s+(\S+).*") words = m.group().split() words.pop(0) value = [float(val) for val in words] for i in range(10): words = eranosFile.readline().split() value.extend([float(val) for val in words]) for iso in range(33): chblank.addMass(listeiso[iso],value[iso]) onestreamch.addMass(listeiso[iso],value[iso]) for iso in range(16): chblank.addMass(listeiso[iso+33],value[iso+33],True) onestreamch.addMass(listeiso[iso+33],value[iso+33],True) chblank.expandFPs() onestreamch.expandFPs() m = fileReSeek(eranosFile," ->DISBLANK\s+(\S+).*") words = m.group().split() words.pop(0) value = [float(val) for val in words] for i in range(10): words = eranosFile.readline().split() value.extend([float(val) for val in words]) for iso in range(33): disblank.addMass(listeiso[iso],value[iso]) onestreamdis.addMass(listeiso[iso],value[iso]) for iso in range(16): disblank.addMass(listeiso[iso+33],value[iso+33],True) onestreamdis.addMass(listeiso[iso+33],value[iso+33],True) disblank.expandFPs() onestreamdis.expandFPs() #posb = eranosFile.tell() eranosFile.seek(posb) try: mat = "BLANK" m = fileReSeek(eranosFile," ->POWERB\s+(\S+).*") n = len(cycles) #print (n, float(m.groups()[0])) cycle.materials[(5,mat)].power = float(m.groups()[0]) except: print('WARNING: No Blanket Discharge Power') eranosFile.seek(posb) try: # Determine reaction rates for FUEL3, FUEL6, FUEL9, and # BLANK. First we need to load material balance data. Is this # just reading the same data as the last timestep of the last # cycle??? n = len(cycles) + 1 cycle = Cycle(n, 0, 0, 0) cycles.append(cycle) for i in fuelNames: m = fileReSeek(eranosFile,"\s+MATERIAL\s(FUEL\d+|BLANK)\s+") name = m.groups()[0] volume = float(eranosFile.readline().split()[-1]) for n in range(5): eranosFile.readline() # Read in material data material = readMaterial(eranosFile) material.volume = volume cycle.materials[(0,name)] = material # Now read fission, absorption, and diffusion rates to be able to # determine the critical mass fuelNames = ['FUEL3', 'FUEL6', 'FUEL9', 'BLANK'] fileReSeek(eranosFile, " ECCO6.*") for name in fuelNames: m = fileReSeek(eranosFile, "\sREGION :(FUEL\d+|BLANK)\s*") name = m.groups()[0] m = fileReSeek(eranosFile, "\s*TOTAL\s+(\S+)\s+(\S+)\s+\S+\s+(\S+).*") cycle.materials[(0,name)].nuFissionRate = float(m.groups()[0]) cycle.materials[(0,name)].absorptionRate = float(m.groups()[1]) cycle.materials[(0,name)].diffRate = float(m.groups()[2]) m = fileReSeek(eranosFile, "\s*TOTAL FLUX =\s+(\S+)\s*") cycle.materials[(0,name)].flux = float(m.groups()[0]) #print(m.groups()[0]) except: # No ECCO calculation at end? print('WARNING: No ECCO_BLANK calculation at end of run?') # Create progress bar if gui: progress = QProgressDialog("Expanding fission products...", "Cancel", 0, n_materials, parent) progress.setWindowModality(Qt.WindowModal) progress.setWindowTitle("Loading...") progress.setMinimumDuration(0) progress.setValue(0) pValue = 0 # Expand all fission products for cycle in cycles: # Progress bar if gui: QCoreApplication.processEvents() if (progress.wasCanceled()): return None print("Expanding fission products for Cycle {0}...".format(cycle.n)) for mat in cycle.materials.values(): mat.expandFPs() # Set progress bar value pValue += 1 if gui: progress.setValue(pValue) # Close file and return eranosFile.close() return cycles, charge, discharge, chblank, disblank, onestreamch, onestreamdis
def __init__(self, body, header=None, maxsize=20): self.header = header or [] self.body = body self.maxsize = maxsize self.cycle = Cycle(chop(self.body, maxsize))
class Simulator(object): def __init__(self ,progs, visualizer,gwidth = 90, glength = 120 , gfriction = 1): self.cycle = Cycle() self.ground = Ground(glength , gwidth ,gfriction ) self.players =[] for i in range(2): for j in range(5): self.players.append(Player(self.ground, progs[i] , i , j , Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) )) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, self.players[j].pos.x, self.players[j].pos.y) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, indexi[j] * gwidth / 2, indexj[j] * glength / 2 * (-1) ** (i)) self.ball = Ball(self.ground) self.state = State(self.players , self.ball) self.referee = Referee(self.state) self.visualizer = visualizer def send_data(self): for i in range(10): self.visualizer.stdin.write(`int(self.state.players[i].pos.x)`+'\n') self.visualizer.stdin.write(`int(self.state.players[i].pos.y)`+'\n') #print >>sys.stderr, 'THIS IS RS, PLAYER %d: %d, %d'%(i, int(self.state.players[i].pos.x), int(self.state.players[i].pos.y)) self.visualizer.stdin.write(`int(self.state.ball.pos.x)`+'\n') self.visualizer.stdin.write(`int(self.state.ball.pos.y)`+'\n') self.visualizer.stdin.write(`self.state.game_state `+'\n') #def player_move(self, i , coefficient=1.0/100): # self.players[i].move(coefficient) def ball_move(self , coefficient=1.0/100): self.ball.move(coefficient) width = self.ground.width length = self.ground.length while True: x = self.ball.pos.x y = self.ball.pos.y if x <= width/2 and x >= -width/2 and y <= length/2 and y >= -length/2: break #print >>sys.stderr, 'BALL IS OUTSIDE GROUND, VELOCITY IS: %f, %f'%(self.ball.vel.x, self.ball.vel.y) if x>(width/2) : self.ball.vel.x= -self.ball.vel.x self.ball.pos.x= width-x #print >>sys.stderr, 'THE BALL WENT TOO RIGHT, NEW X: %f'%(self.ball.pos.x) if x<-(width/2) : self.ball.vel.x= -self.ball.vel.x self.ball.pos.x= -width-x #print >>sys.stderr, 'THE BALL WENT TOO LEFT, NEW X: %f'%(self.ball.pos.x) if y>(length/2) : self.state.update( self.referee.is_goal(self.ball , self.ground) ) self.ball.vel.y= -self.ball.vel.y self.ball.pos.y= length-y #print >>sys.stderr, 'THE BALL WENT TOO UP, NEW Y: %f'%(self.ball.pos.y) if y<(-(length/2)) : self.state.update( self.referee.is_goal(self.ball , self.ground) ) self.ball.pos.y= -length-y self.ball.vel.y=-self.ball.vel.y #print >>sys.stderr, 'THE BALL WENT TOO DOWN, NEW Y: %f'%(self.ball.pos.y) # def check_pos(self , coefficient=1.0/100): # a = range(10) # random.shuffle(a) # sizes = [i/20.0 for i in xrange(1, 11)] # random.shuffle(sizes) # for i in a: # temp_pos = self.players[i].pos # for j in range(10): # if( ( self.players[j].is_overlap(sizes[i], sizes[j], temp_pos) ) and (j!=i)): # self.players[i].move(-coefficient) # break def move(self): # for j in xrange(100): # for i in xrange(10): # self.player_move(i) # self.ball_move() # self.check_pos() #for t in xrange(steps_per_cycle): coefficient = 1.0/config.steps_per_cycle q = deque(self.players) if self.state.kicked: if self.ball.vel.len() < 4: self.ball.vel = Vector(2*random.choice([-1, 1]), 2*random.choice([-1, 1])) for t in xrange(config.steps_per_cycle): self.ball_move(coefficient) for p in self.players: p.rsteps = config.steps_per_cycle no_change = 0 #print >>sys.stderr, 'move called' #player_size = random.choice([0.3, 0.4, 0.5]) while len(q): c = q.popleft() #print >>sys.stderr, 'moving %d, %d, %d'%(c.team, c.number, c.rsteps) c.move(coefficient) c.rsteps-=1 change = True for other in self.players: if c==other: continue if c.is_overlap(config.player_size, config.player_size, other.pos): c.move(-coefficient) c.rsteps+=1 change = False break if change: no_change=0 else: no_change+=1 if c.rsteps: q.append(c) if no_change==20: #print >>sys.stderr, 'breaking' #for p in self.players: # print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(p.team, # p.number, # p.pos.x, # p.pos.y) #print >>sys.stderr, 'BALL: %f, %f'%(self.ball.pos.x, # self.ball.pos.y) break # while True: # change = False # for p in self.players: # if not p.rsteps: # continue # p.move(coefficient) # p.rsteps-=1 # change = True # for other in self.players: # if other==p: # continue # if p.is_overlap(config.player_size, config.player_size, # other.pos): # p.move(-coefficient) # change = False # break # if not change: # break def goto_kickoff(self): self.ball.pos = Vector(0, 0) self.ball.vel = Vector(0, 0) gwidth = config.gwidth glength = config.glength for i in xrange(2): for j in xrange(5): self.players[i*5+j].pos=Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) self.players[i*5+j].vel = Vector(0, 0) def simulate(self) : global cycle_length #print self.state.game_state prev_locs = [Vector(0, 0) for i in xrange(10)] for i in xrange(game_duration): #print >>sys.stderr, 'CYCLE #%d'%(i) self.state.kicked = False self.referee.update_state() self.send_data() #self.state.update() for j in xrange(10): self.players[j].comm.send_state(self.state) #print >>sys.stderr, 'DOOOOOOOOOOOOOOOOOOOOOOONE SENDING DATA AT %f'%(time.time()) time.sleep(cycle_length) self.cycle.update_players(self.state) self.move() soc = 0 for (i, p) in enumerate(self.players): soc += (p.pos-prev_locs[i]).len() if soc < 1 and self.state.game_state!=state.kickoff_team1 and self.state.game_state!=state.kickoff_team2: self.ball.vel += Vector(random.choice([-1, 1])*5, random.choice([-1, 1])*5) print 'accel' prev_locs = [Vector(p.pos.x, p.pos.y) for p in self.players] if self.state.game_state==state.team1_goal: self.state.game_state = state.kickoff_team2 self.goto_kickoff() if self.state.game_state==state.team2_goal: self.state.game_state = state.kickoff_team1 self.goto_kickoff() if(self.state.last_kicked != None): pass for i in xrange(10): self.players[i].comm.terminate()
def get_visit_order(geo_points): """THIS IS THE ONLY FUNCTION THAT YOU NEED TO MODIFY FOR PHASE 5. The only argument, *geoPoints*, is a list of points that user has marked. Each element of geoPoints is an instance of the GeoPoint class. You need to create your graph using these points. You obtain the distance between two points by calling the *getDistance* function; for example: get_distance(geoPoints[0], geoPoints[1]) Run your tsp solver and return the locations visit order. The return value, *order*, must be a list of indices of points, specifying the visit order. In the example implementation below, we visit each point by the order in which they were marked (clicked). """ # longueur = len(geoPoints) print "first leg length: ", get_distance(geo_points[0], geo_points[1]) # order = range(longueur) # default order # order += [order[0]] # longueur_totale = 0 # for x in xrange(longueur-1): # longueur_totale += get_distance(geoPoints[x], geoPoints[x+1]) # longueur_totale += get_distance(geoPoints[-1],geoPoints[0]) # print "Longueur totale du cycle Google maps : " +str(longueur_totale) # print order graph = Graph(name='Graphe test') for k in xrange(len(geo_points)): coords = [geo_points[k].lat, geo_points[k].lng] test_node = Node(name='Ntest {0:d}'.format(k), data=coords) graph.add_node(test_node) for i in range(graph.get_nb_nodes()): for j in range( i ): # pas de redondance , donc nb_edges = nb_nodes * (nb_nodes-1) /2 start = graph.get_node(i) arrival = graph.get_node(j) # print start , arrival , '\n' e_data = [ start, arrival, get_distance(geo_points[i], geo_points[j]) ] e = Edge(name='Edge' + str(i) + '-' + str(j), data=e_data) graph.add_edge(e) graph.add_to_dict(e) cycle1 = Cycle("Kruskal", original_graph=graph, method='kruskal') graph_min = cycle1 repetitions = xrange(len(geo_points)) for num_node in repetitions: cycle2 = Cycle(name="Prim" + str(num_node), original_graph=graph, method='prim', num_node=num_node) if graph_min is None or cycle2.weight < graph_min.weight: graph_min = cycle2 print "Longueur totale du cycle etudiant : " + str(graph_min.weight) graph_min.plot_graph() return graph_min.ordrerd_list
def construct(self): text1 = Text("How do we know a preference cycle exists?") self.play(Write(text1)) self.wait(1) self.play(ApplyMethod(text1.shift, 3 * UP)) self.wait(2) As = [a1, a2, a3, a4] = ["$a_1$", "$a_2$", "$a_3$", "$a_4$"] Bs = [b1, b2, b3, b4] = ["$b_1$", "$b_2$", "$b_3$", "$b_5$"] C = Cycle(As, Bs, center=[-0.5, 0, 0]) A_mobs = C.A_mobs B_mobs = C.B_mobs self.play(Create(A_mobs[0])) self.play(Create(B_mobs[0]), Create(B_mobs[1]), Create(C.arrows[0].curr_arrow()), Create(C.arrows[1].curr_arrow())) self.wait(2) text2 = Tex( "$b_2$ must hold a proposal from someone other than $a_1$").shift( 2 * DOWN) text3 = Tex( "That player will prefer $b_2$ the most by construction").next_to( text2, DOWN) self.play(Write(text2)) self.wait(2) self.play(Write(text3)) self.wait(2) self.play(Create(C.arrows[2].curr_arrow())) self.play(Create(A_mobs[1])) self.play(Uncreate(text2), Uncreate(text3)) self.wait(2) text3 = Tex("$a_2$ must also hold a proposal from someone").shift(2 * DOWN) text4 = Tex("If $a_2$ holds a proposal from $b_2$ then").next_to( text3, DOWN) text5 = Tex("$b_2$ and $a_2$ would already be matched").next_to( text4, DOWN) text6 = Tex("$a_1$ would not be on $b_2$'s preference list").next_to( text4, DOWN) text7 = Tex("$b_2$ would not be on $a_1$'s preference list").next_to( text4, DOWN) self.play(Write(text3)) self.wait(2) self.play(Write(text4)) self.wait(2) self.play(Write(text5), Indicate(A_mobs[1]), Indicate(B_mobs[1])) self.wait(2) self.play(ReplacementTransform(text5, text6), Indicate(A_mobs[0])) self.wait(2) self.play(ReplacementTransform(text6, text7)) self.wait(2) self.play(Create(C.arrows[3].curr_arrow())) self.play(Create(B_mobs[2])) self.wait(2) self.play(Uncreate(text3), Uncreate(text4), Uncreate(text7)) text8 = Tex( "Repeating this will eventually lead us to cycling \\\\ since there are only a finite number of players" ).shift(2 * DOWN) dots = Tex("$\cdots$").next_to(C.arrows[6].curr_arrow(), RIGHT) self.play(Write(text8), Create(A_mobs[2]), Create(B_mobs[3]), Create(A_mobs[3]), Create(C.arrows[4].curr_arrow()), Create(C.arrows[5].curr_arrow()), Create(C.arrows[6].curr_arrow()), Write(dots)) self.wait(2)
def __wm_screen_init__( self ): log.debug( "WorkspaceWindowManager.__wm_screen_init__" ) self.workspaces = Cycle() self.workspaceDict = {}
def construct(self): why_text = Tex("Why we can remove cycles") self.play(Write(why_text)) self.play(ApplyMethod(why_text.shift, UP * 3.5)) lemma1 = r""" \begin{align*} \text{Lemma 1: }&\text{in any stable $M$ in the reduced table,}\\ &a_i\text{ and }b_i \text{ are matched either}\\ &\text{for all }i \text{ or for no }i\end{align*}""" lemma1 = Tex(lemma1).next_to(why_text, DOWN * 2) self.play(Write(lemma1)) def math_list(base, start, end): return [ "$" + base + "_" + str(i) + "$" for i in range(start, end) ] As = math_list("a", 1, 5) + ["$a_1$"] Bs = math_list("b", 1, 5) + ["$b_1$"] c = Cycle(As, Bs, center = DOWN * 1.5) self.play(*c.create()) self.wait(1) say_text = Tex("Let $b_3$ reject $a_3$") \ .next_to(lemma1, DOWN * 2) \ .shift(LEFT * 3) self.play(Write(say_text)) next_text = Tex("$a_3$ proposes to $b_4$") \ .next_to(lemma1, DOWN * 2) \ .shift(RIGHT * 3) self.wait(1) self.play(*c.reject(2, 2)) self.wait(1) self.play(Write(next_text)) self.play(*c.accept(2, 3)) self.play(*c.reject(3, 3)) self.play(*c.accept(3, 4)) self.play(*(c.reject(4, 4) + c.reject(0, 0))) self.play(*c.accept(0, 1)) self.play(*c.reject(1, 1)) self.play(*c.accept(1, 2)) self.play(*(c.uncreate())) self.wait(1) thus_text = Tex(r"""Thus if any $a_i$ is not matched with its $b_i$\\ then no $a_i$ can match with its $b_i$""") \ .next_to(lemma1, DOWN * 6) self.play(Write(thus_text)) self.wait(1) self.play(*[ Uncreate(m) for m in [thus_text, next_text, say_text] ]) shift_amt = 15 let_m = Tex(r""" Let $M$ be a stable matching where each $a_i$ is matched\\ with its $b_i$. Let $M'$ be the same matching, but each\\ $a_i$ is matched with its second choice $b_{i+1}$ """).next_to(why_text, DOWN * 2).shift(RIGHT * shift_amt) self.add(let_m) self.play(*[ ApplyMethod(t.shift, LEFT * shift_amt) for t in [lemma1, let_m] ]) lemma2 = Tex("Lemma 2: $M'$ is stable if $M$ is stable") \ .next_to(let_m, DOWN * 2) self.play(Write(lemma2)) self.wait() As = ["$a_k$", ""] Bs = ["$b_k$", "$b_{k+1}$"] c = Cycle(As, Bs, center = DOWN * 1.5) c.reject(0, 0) c.accept(0, 1) mobjs = c.get_all_mobjs() mobjs.pop(2) self.play(*[ Create(m) for m in mobjs ]) b_better_text = Tex(r"Each $b_i$ is better\\ off in $M'$ than $M$") \ .shift(LEFT * 4 + DOWN) self.play(Write(b_better_text)) a_happy_text = Tex(r"$a_k$ can only prefer \\"+\ r"$b_k$ to its current match\\" +\ r"but $b_k$ is happier with\\" +\ r"$a_{k-1}$, so $M'$ is\\" +\ r"stable here") \ .shift(RIGHT * 4 + DOWN * 2) self.play(Write(a_happy_text)) self.play(*[ Uncreate(m) for m in mobjs + [b_better_text, a_happy_text] ]) continue_m = Tex(r"Thus $M$ stable $\Rightarrow$ $M'$ stable,\\" +\ r"so if there exists a stable matching, we\\" +\ r"can find it by proceeding with $M'$ and\\" +\ r"eliminating our cycle") \ .shift(DOWN * 1.5) self.play(Write(continue_m)) self.wait(2) self.play(*[ ApplyMethod(t.shift, RIGHT * shift_amt) for t in [lemma1, let_m] ] + [ Uncreate(m) for m in [continue_m] ] + [ ApplyMethod(t.shift, DOWN * 0.8) for t in [lemma2] ]) plus = TextMobject("+").shift(UP * 0.5) impl = TextMobject("$\\Leftarrow$") \ .rotate_in_place(PI/2).shift(DOWN) self.play(Create(impl), Create(plus)) self.wait(1) final = Tex(r"We can always eliminate cycles without\\"\ r"changing the result").next_to(impl, DOWN) self.play(Write(final)) self.wait(2)
def play(self): pygame.init() self.DISPLAY = pygame.display.set_mode((self.W, self.H), 0) self.DISPLAY.fill(self.BACKGROUND) quit_draw = False for n, cycle in enumerate(self.intervals_x): if n == 0: self.cycles_x.append( Cycle(cycle[0], 800, 100, cycle[1], cycle[2])) else: self.cycles_x.append( Cycle(cycle[0], self.cycles_x[n - 1].x, self.cycles_x[n - 1].y, cycle[1], cycle[2])) for n, cycle in enumerate(self.intervals_y): if n == 0: self.cycles_y.append( Cycle(cycle[0], 200, 600, cycle[1], cycle[2])) else: self.cycles_y.append( Cycle(cycle[0], self.cycles_y[n - 1].x, self.cycles_y[n - 1].y, cycle[1], cycle[2])) while not quit_draw: self.DISPLAY.fill(self.BACKGROUND) for n, cycle in enumerate(self.cycles_x): self.draw_circle(cycle) cycle.angle += self.time / 60 cycle.update_point() if n < len(self.cycles_x) - 1: self.cycles_x[n + 1].x_center = cycle.x self.cycles_x[n + 1].y_center = cycle.y for n, cycle in enumerate(self.cycles_y): self.draw_circle(cycle) cycle.angle += self.time / 60 cycle.update_point() if n < len(self.cycles_y) - 1: self.cycles_y[n + 1].x_center = cycle.x self.cycles_y[n + 1].y_center = cycle.y self.point_x = [self.cycles_x[-1].x, self.cycles_x[-1].y] self.point_y = [self.cycles_y[-1].x, self.cycles_y[-1].y] pygame.draw.circle(self.DISPLAY, (255, 0, 0), self.point_x, 2) pygame.draw.circle(self.DISPLAY, (255, 0, 0), self.point_y, 2) self.drawing.append([self.point_x[0], self.point_y[1]]) pygame.draw.line(self.DISPLAY, (255, 255, 255), self.point_x, self.drawing[-1]) pygame.draw.line(self.DISPLAY, (255, 255, 255), self.point_y, self.drawing[-1]) if self.time > 2 * math.pi: self.drawing = [] if len(self.drawing) > 1: pygame.draw.lines(self.DISPLAY, (255, 255, 255), False, self.drawing) for event in pygame.event.get(): if event.type == pygame.QUIT: quit_draw = True pygame.quit() quit() pygame.display.flip() self.CLOCK.tick(self.FPS)
class IRCServer(): """ class for connecting to an IRC server 1 server per connection """ _reconnectTimeout = 300 def __init__(self, host, port, terminalID = "", password = None): self.receivers = {} self.quitMessage = "" self.password = password self.nickNames = Cycle(NICKNAMES) self._terminalID = terminalID # shorthand for server in terminal self._currentReceiverKey = None self._connection = Connection(host, port, self._parseInput) self._logger = Logger("%s/%s" % (host, "SERVER")) self._clientObject = self._newReceiver(self.nickNames.val()) self._welcomeEvent = threading.Event() self._reconnectEvent = threading.Event() self._reconnectEvent.set() #------------------------------------------------------------------------- def connect(self): """ connect to the host/port raises error on fail """ try: connection = self._connection.connect() except Exception as e: raise IRCServerError("Connection failed: [%s] %s"%(e.__name__, e)) if(self.password): self.sendRaw("PASS %s" % (self.password)) self.sendRaw("NICK %s" % self.nickNames.val()) self.sendRaw("USER %s %s * :%s"%(LOGIN_NAME, socket.gethostname(), REAL_NAME)) self._welcomeEvent.clear() self._welcomeEvent.wait() def disconnect(self, message = None): if(self.isConnected()): if not message: message = self.quitMessage self.sendCmd("QUIT", None, message) self._connection.disconnect() def reconnect(self): """ reconnecting function prevents multiple threads from trying to reconnect at once pauses all reconnect tries until reconnect succeeds or fails """ if not self._reconnectEvent.is_set(): self._reconnectEvent.wait() else: self._reconnectEvent.clear() self.disconnect() error = None for timer in range(5, self._reconnectTimeout, 15): self.log("Reconnecting...") try: self.connect() except Exception as e: error = e time.sleep(timer) else: break else: self.logE("Reconnect failed after %ds: %s"%(timer/60, error)) self._reconnectEvent.set() #------------------------------------------------------------------------- def sendRaw(self, data): """sends raw data strings to the server connection""" try: self._connection.send(data.rstrip()) except Exception as e: self.reconnect() self.logE("Data send failed: %s" % e) def sendCmd(self, command, meta=None, *message): # TODO limit message length my receiver's full name@host """ sends command with optional meta data and message will split messages to ensure they're under the maximum length """ if meta: if isinstance(meta, list): meta = " ".join(meta) command = "%s %s" % (command, meta) if message: msg = " ".join(list(message)) strLim = MESSAGE_LENGTH_LIMIT - (len(command) + 2) a=0 for a in range(strLim, len(msg), strLim): self.sendRaw("%s :%s" % (command, msg[a-strLim:a])) self.sendRaw("%s :%s" % (command, msg[a:len(msg)])) else: self.sendRaw(command) def _parseInput(self, line): """overloadable function to receive commands from conected server""" self.log(line) #------------------------------------------------------------------------- def _newReceiver(self, name): if any(name.startswith(prefix) for prefix in CHANNEL_PREFIXES): newRec = IRCChannel(name, self._connection.host) else: newRec = IRCClient(name, self._connection.host) self.receivers[name.lower()] = newRec if len(self.receivers) == 1: self.swapCurrentReceiver(name) return newRec def _delReceiver(self, name): """ removes the specified receiver from the list """ self.receivers.pop(name.lower()) def _renameReceiver(self, oldName, newName): """ renames the receiver and alters the key to it """ old = self.receivers.pop(oldName.lower()) old.name = newName self.receivers[newName.lower()] = old def swapCurrentReceiver(self, name): name = name.lower() if name in self.receivers: self._currentReceiverKey = name else: raise IRCServerError("Unknown user/channel: %s" % name) def listReceivers(self): return [b.name for b in self.receivers.values()] #------------------------------------------------------------------------- def getReceiver(self, name=None): """ returns a Receiver class object if no name specified, uses the current receiver """ if not name: if(not self._currentReceiverKey): raise IRCServerError("No known channels/users for this Server!") return self.receivers[self._currentReceiverKey] elif isinstance(name, IRCReceiver): name = str(name) name = name.lower() try: receiver = self.receivers[name] except KeyError as e: raise IRCServerError("No channel/user found matching [%s]" % (name)) else: return receiver def getChannel(self, name=None): receiver = self.getReceiver(name) if(isinstance(receiver, IRCChannel)): return receiver raise IRCServerError("[%s] is not a channel" % name) def getClient(self, name=None): receiver = self.getReceiver(name) if(isinstance(receiver, IRCClient)): return receiver raise IRCServerError("[%s] is not a client" % name) #------------------------------------------------------------------------- def isConnected(self): """""" return self._connection.isConnected() def getHost(self): """returns host string""" return self._connection.host def getNick(self): """returns the current nickname""" return self._clientObject.name #------------------------------------------------------------------------- def log(self, message): self._logger.log(message) print("[%s]%s" % (self._terminalID, message)) def logE(self, message): self.log("[ERROR]: %s" % (message))
def __wm_screen_init__(self): log.debug("WorkspaceWindowManager.__wm_screen_init__") self.workspaces = Cycle() self.workspaceDict = {}
# kruskal_tree = Mst(original_graph=G, method='kruskal') # kruskal_tree.plot_graph() # print 'Poids total du graphe : ' + header.__getitem__('NAME') + ' = ' + # str(kruskal_tree.weight) + '\n' # for i in prim_tree.get_nodes(): # print i.get_id() , prim_tree.get_neighbors(i) , ' ------ ' , # i.ancestor.get_id(), '\n\n' nb_nodes = G.get_nb_nodes() graph_min = None # graph_min = Graph() # graph_min.add_weight(float('infinity')) if method is None or method == 'kruskal': cycle1 = Cycle(name=header['NAME'], original_graph=G, method='kruskal') graph_min = cycle1 # print "nombre de noeuds : ", nb_nodes if method is None or method == 'prim': if nb_nodes > 600 and method is None: repetitions = [ randint(0, G.get_nb_nodes() - 1) for i in xrange(50) ] print repetitions else: repetitions = xrange(nb_nodes) for num_node in repetitions: cycle2 = Cycle(name=header['NAME'], original_graph=G, method='prim',
from cycle import Cycle, Notice upstairs_bathroom = Cycle('Upstairs Bathroom', ['Nick', 'Lawrence', 'Hunter'], 'upstairs_bathroom') downstairs_bathroom = Cycle('Downstairs Bathroom', ['Sam', 'Ashleigh', 'Jess', 'Alex'], 'downstairs_bathroom') kitchen = Cycle( 'Kitchen', ['Alex', 'Jess', 'Hunter', 'Nick', 'Ashleigh', 'Lawrence', 'Sam'], 'kitchen') notices = [] Notice.save_list(notices, "notices") chefs = [ "Jess", "Sam", "Lawrence", "Hunter", "Nick", "No one loves you :(", "Ashleigh" ] Cycle.easy_save(chefs, 'cooking_schedule')
def update_cycle(iden): c = Cycle.load(iden) c.advance() c.save() return redirect('/')
def doIt(): bittrex = BittrexMarketGenerator() bittrex_markets = bittrex.get_markets(bittrex.get_market_json()) #print('### KRAKEN MARKETS ###') #kraken_markets.update_markets() #for market in kraken_markets: #market.print_market() #print('bid %.12f' % market.get_bid()) #print('ask %.12f' % market.get_ask()) #print('### BITTREX MARKETS ###') #bittrex.update_markets(bittrex_markets) #for market in bittrex_markets: #market.print_market() #print('bid %f' % market.get_bid()) #print('ask %f' % market.get_ask()) print('### BITTREX MARKETS ###') bittrex.update_markets(bittrex_markets) if (currency_filter != None): cycles = CycleGenerator.generateCycles(bittrex_markets, currency_filter) else: cycles = CycleGenerator.generateCyclesNoFilter(bittrex_markets) for c in cycles: print(Cycle.printCycle(c)) cycleExecutionCount = 0 for i in range(1, 99999999999): time.sleep(1) sys.stdout.flush() if cycleExecutionCount > 5: return print(i, '==========') for c in cycles: if c.hasProblems: continue try: print(c) [taker, limit, noFeeRate, startingAmt] = c.calcTakerReturn() if taker > return_threshold: #if taker > 1.015 and limit > 0.5 and c.leftCurrency(0) == 'ETH': # if taker > 1.015 and limit > 0.5: print('') print('Found a profitable cycle!') print(Cycle.printCycle(c)) print('taker conversion factor: %f' % float(taker)) print('taker percentage %f%%' % float((taker - 1) * 100)) print('taker profit on 5k: %f' % float(taker * 5000 - 5000)) print('taker limiting factor %f' % float(limit)) print('taker limited return %f' % float( (taker * limit - limit))) print('noFeeRate %f' % float(noFeeRate)) print('startingAmt %f' % float(startingAmt)) if doPerformExecuteTrade == True: try: # below while condition needs to change, and may even need to be moved to the trade executer class #while (taker > 1.015): while (taker > return_threshold): print('still profitable, executing cycle') CycleTrader.executeCycle(c, startingAmt) [taker, limit, noFeeRate, startingAmt] = c.calcTakerReturn() print( 'no longer profitable, moving on to find another opportunity' ) except: traceback.print_exc() print( 'Encountered exception when calling trade executor!' ) cycleExecutionCount += 1 # return else: print('Not executing trades') # else: # print('taker not profitable') # maker = c.calcMakerReturn() # if maker > return_threshold: # print('maker conversion factor %f' % float(maker)) # print('maker percentage %f%%' % float((maker-1)*100)) # print('maker profit on $5k: $%f' % float(maker*5000-5000)) # else: # print('maker not profitable') except KeyboardInterrupt: return except: #traceback.print_exc() print(Cycle.printCycle(c)) c.hasProblems = True print('Something went wrong in calculating/printing returns!')