def testScheduleCompletion(self): #Verify scheduling completion of an arrival simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500) #create first station station1 = Station.Station(1, 20.0) #create second station station2 = Station.Station(2, 40.0) #add stations to simulator simulator.addStation(station1) simulator.addStation(station2) #create frame msg1 = Frame(1, 'Hello Station 2', 1, 2) #create event evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1) #add event to q simulator.addEvent(evt1) #process event simulator.processSingleEvent() evtQ = simulator.evtQ self.assertEquals(evtQ._qsize(), 2) #evt2 = evtQ[0] evt2 = evtQ.get() self.assertEquals(evt2.eventType, Event.TRANSMIT_COMPLETE) self.assertAlmostEquals(evt2.time, 126.73) self.assertEquals(evt2.stationId, 1) #evt3 = evtQ[1] evt3 = evtQ.get()
def __init__(self, path: str = None, citySep: str = ".", fileSep: str = "_") -> None: """ :param path: path where network structure is saved. It contains folders with csv files :param citySep: separator of city (instead space), e.g. "Warszawa Centralna" to "Warszawa.Centralna" :param fileSep: separator of file name. It concatenates city name and city bilkomCode, e.g. "Siemiatycze_5103355" """ super().__init__() if path is not None: for cityFromFile in os.listdir(path): if isdir(join(path, cityFromFile)): cityFromFileSep = cityFromFile.split(fileSep) cityFrom = cityFromFileSep[0].replace(citySep, " ") codeFrom = cityFromFileSep[1] cityCodeFrom = Station(cityFrom, codeFrom) self.stationList.append(cityCodeFrom) self[cityFrom] = {} for cityToFile in os.listdir(join(path, cityFromFile)): cityToFilePath = join(path, cityFromFile, cityToFile) if isfile(cityToFilePath): cityToFileSep = cityToFile.split(fileSep) cityTo = cityToFileSep[0].replace(citySep, " ") codeTo = cityToFileSep[1] cityCodeTo = Station(cityTo, codeTo) self.stationList.append(cityCodeTo) self[cityFrom][cityTo] = pd.read_csv( cityToFilePath)
def getFilePathFromUser(): try: print 'Podaj sciezke do pliku txt, np.: ./dane/plik_z_depeszami.txt ' filePath = raw_input() synop = gS.getSynopFile(path=filePath) station = St.Station(synopCode=synop[0], getSynopType='file') dateFirst = station.decodeDate() wrongDateSum = 0 for eggs in synop: station = St.Station(synopCode=eggs, getSynopType='file') date = station.decodeDate() if dateFirst == date: pass else: wrongDateSum += 1 if wrongDateSum > 0: print 'Depesze pochodza z roznych okresow, mozliwy bedzie jedynie wydruk pliku Xlsx!' rep = synop return True, False, rep else: rep = synop return True, True, rep except IOError: rep = 'Niepoprawnie wprowadzono sciezke do pliku!' return False, False, rep except IndexError: rep = 'Podano pusty plik!' return False, False, rep
def main(): """ all the test of the class Line """ #Header print("*******************") print(" Line module test") print("*******************") #creation of 5 stations A = Station("A", [1., 0.]) B = Station("B", [2., 0.]) C = Station("C", [3., 0.]) D = Station("D", [4., 0.]) E = Station("E", [5., 0.]) Line_1 = Line([A, B, C, D, E], "underground", "Line_1") ############################################################################ # Declaration TEST # ############################################################################ assert Line_1.station == [A, B, C, D, E] print("self.station OK") assert Line_1.mode == "underground" print("self.mode OK") assert Line_1.name == "Line_1" print("self.name OK") ############################################################################ # Message end # ############################################################################ print("Line is OK") print("*******************") print(Line_1._repr_())
def init_city(self): """we set some Stations in place.""" if 'init' in DEBUG: print("Setting main station...") self.stations.append(Station.Station(self,(int((MAX_X-RIGHT_OFFSET)/2), int (MAX_Y/2)),\ "square")) # TODO: make sure that every shape exists if 'init' in DEBUG: print("Setting stations...") for i in range(0, MAXSTATIONS): pos = self.random_pos() if pos: s = Station.Station(self, pos) self.stations.append(s)
def run(): print 'mission bot begin.\n' log('\n\nbot started\n') while True: if not station.startConversation(agent): print 'Error: Could not find target agent.' return False mission = pic.extractTextR(panel.MissionName).strip() missionType = '' print mission if mission in battle: missionType = 'b' elif mission in transport: missionType = 't' elif mission in skip: if not station.declineMission(): return False else: continue else: print 'Error: Cant find bot for mission \'' + mission + '\'.' return False record(mission, 'begin') if not station.acceptMission(): print 'Error: Accept mission failed.' return False # mouse.moveToP(panel.center(panel.Mission)) # result = findAtFull('x') # if not result: # return False # mouse.leftClickAtP(result) if not general.setMissionWaypoint(True): print 'Error: Cant set mission waypoint.' return False if missionType == 'b': if not runBattle(mission): return False elif missionType == 't': if not runTransport(mission): return False record(mission, 'complete')
def testBackoff1(self): #Test retransmission after one collision, using specified #rather than random backoff simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500) station1 = Station.Station(1, 20.0) simulator.addStation(station1) msg1 = Frame(1, 'Hello Station 2', 1, 2) evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1) station2 = Station.Station(2, 40.0) simulator.addEvent(evt1) simulator.addStation(station1) simulator.addStation(station2) msg2 = Frame(2, 'Hello Station 1', 2, 1) evt2 = Event(Event.ARRIVAL, 123.50, 2, msg2) simulator.addEvent(evt2) simulator.processSingleEvent() self.assertAlmostEquals(simulator.simTime, 123.45) simulator.processSingleEvent() #should transmit msg2 #and schedule collision detection evtQ = simulator.evtQ self.assertEquals(evtQ._qsize(), 2) evt3 = evtQ.get() self.assertEquals(evt3.eventType, Event.COLLISION_DETECT) self.assertAlmostEquals(evt3.time, 123.45, 0) self.assertEquals(evt3.stationId, 2) evt4 = evtQ.get() self.assertEquals(evt4.eventType, Event.COLLISION_DETECT) self.assertAlmostEquals(evt4.time, 126.45, 0) self.assertEquals(evt4.stationId, 1) simulator.processSingleEvent() evt4 = evtQ.get() self.assertEquals(evt4.eventType, Event.JAMMING_END) simulator.processSingleEvent() evt5 = evtQ.get() self.assertEquals(evt5.eventType, Event.JAMMING_END) simulator.processSingleEvent() simulator.set_back_off_time(1.5) evt6 = evtQ.get() self.assertEquals(evt6.eventType, Event.TRANSMIT_ATTEMPT) self.assertAlmostEquals(evt6.time, 126.45 + 1.5) simulator.processSingleEvent() simulator.set_back_off_time(.9) evt7 = evtQ.get() self.assertEquals(evt7.eventType, Event.TRANSMIT_ATTEMPT) self.assertAlmostEquals(evt7.time, 126.45 + .9)
def testAddEvent(self): #test adding events to the simulator simulator = CSMA_CD_Simulator.CSMA_CD_Simulator( 500) #500 meters diameter station1 = Station.Station(1, 20.0) station2 = Station.Station(2, 80.0) simulator.addStation(station1) simulator.addStation(station2) msg1 = Frame(1, 'Hello Station 2', 1, 2) msg2 = Frame(2, 'Hello Station 1', 2, 1) evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1) evt2 = Event(Event.ARRIVAL, 234.56, 2, msg2) simulator.addEvent(evt2) simulator.addEvent(evt1) # not in time order evtQ = simulator.evtQ self.assertEquals(evtQ._qsize(), 2)
def load(self): file = open(self.DATA_FILE, "rb") count = int.from_bytes(file.read(4), "little") index = int.from_bytes(file.read(4), "little") for i in range(0, count): type = int.from_bytes(file.read(4), "little") if type == CanvasItem.OBSTACLE: item = Obstacle(self) self._obs[item.get_index] = item elif type == CanvasItem.ACCESS: item = Ap(self) self._aps[item.get_index] = item elif type == CanvasItem.STATION: item = Station(self) self._sts[item.get_index] = item item.load(file) self._items[item.get_index()] = item if index == 31337: index = self.NO_SELECTION self._index = index items = self._items.values() for item in items: item.draw() file.close()
def __init__(self): threading.Thread.__init__(self) logging.info("Audio thread created, initializing fictTuner..") self.lastStation = Station.StaticStation() self.lastPosition = 0 self.tuner = None self.booted = False
def make_station_at_planet(self, planet, elements, universe): station = Station.Station(universe, 32) station.mass.enter_orbit(planet, planet.mass.universe_radius*1.5, self.R.random()*math.pi*2.0, 0.000001*self.R.randint(-20,20)) station.name = planet.name+" Station" elements.append(station) self.make_ship_at_station( station, elements, universe)
def createStations(config): """ createStations(config) ==> None For each station defined in the config file createStations() will create a station object and populate it with the correct list of probes. It will then add the new station to the dictionary of stations. """ trace("createStations()") for section in config.sections(): if section.capitalize().startswith("Station"): myPressureProbes = myHumidityProbes = [] myTemperatureProbes = [] name = section.capitalize() for option in config.options(section): value = config.get(section, option) opt = option.capitalize() if opt == "Name": name = value.capitalize() elif opt == "Temperature": myTemperatureProbes = getProbeList(value, temperatureProbes) elif opt == "Pressure": myPressureProbes = getProbeList(value, pressureProbes) elif opt == "Humidity": myHumidityProbes = getProbeList(value, humidityProbes) stations[name] = Station.Station(myTemperatureProbes, myPressureProbes, myHumidityProbes, name)
def secondReactXlsx(synop, synopType, fileNameAndPath): statList = [] for eggs in synop: station = St.Station(getSynopType=synopType, synopCode=eggs) statList.append(station) pXR.printXlsx(station=statList, fileName=fileNameAndPath[0], path=fileNameAndPath[1])
def initialize(self): Station.initialize() self.station = Station.get() print('Station:') print(self.station) firebase.initialize() print('Firebase initialized') if not 'id' in self.station: document = firebase.send('stations', None, self.station) Station.set({'id': document.id}) self.station['id'] = document.id print('New station added to online database') bluetoothThread = threading.Thread(target=self.bluetooth) bluetoothThread.start() readingsThread = threading.Thread(target=self.sendReadings) readingsThread.start()
def addStop(self, stop_properties): """ stop_properties = [stop_id, stop_name, stop_desc, stop_lat, stop_lon] """ if stop_properties[0] not in self.StopList: self.numStop = self.numStop + 1 newStop = Station.Station(*stop_properties) self.StopList[newStop.id] = newStop
def run(): print '--> mission New Frontiers - Raw Materials (6 of 7)' if not station.openInventory(): return False if not station.loadItem('mission_cargo'): return False if not station.closeInventory(): return False if not station.undock(): return False pilot.autopilot() if not general.setMissionWaypoint(): return False if not station.startConversation(agent): return False if not station.completeMission(): return False if not station.undock(): return False pilot.autopilot() print '<-- mission New Frontiers - Raw Materials (6 of 7)\n' return True
def run(): print '--> mission Technological Secrets 2' # this is a transport mission if not (station.openInventory() \ and station.loadItem('dna_sample') \ and station.closeInventory()): return False if not station.undock(): return False pilot.autopilot() if not general.setMissionWaypoint(): return False if not station.startConversation(agent): return False if not station.completeMission(): return False if not station.undock(): return False pilot.autopilot() print '<-- mission Technological Secrets 2\n' return True
def buildStations(self): # Build stations here self.stations = [] for stationData in self.stationFileData: newStation = Station.buildStation(stationData) # Sometimes it's not quite implemented, this prevents runtime errors if newStation is not None: self.stations.append(newStation) logging.info("Stations have been built")
def testMediaBusy(self): #Test whether the media is bus simulator2 = CSMA_CD_Simulator.CSMA_CD_Simulator(500) station1 = Station.Station(1, 20.0) station2 = Station.Station(2, 40.0) simulator2.addStation(station1) simulator2.addStation(station2) msg1 = Frame(1, 'Hello Station 2', 1, 2) evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1) simulator2.addEvent(evt1) simulator2.processSingleEvent() #should transmit msg #and schedule completion self.assertFalse(simulator2.media_busy(40, 123.50)) self.assertTrue(simulator2.media_busy(40, 123.60)) #check media after the transmission is completed at 126.73 self.assertFalse(simulator2.media_busy(40, 126.85)) self.assertTrue(simulator2.media_busy(60, 126.85))
def build_all_stations(df_stops): # takes all items of the stopID dataset to build stations # df_trips à filtrer à 0;+5h ensuite pour ne pas alourdir. l = {} for index, row in df_stops.iterrows(): newstation = st.Station(row['stop_id'], row['stop_name'], row['stop_desc'], row['stop_lat'], row['stop_lon']) l[row.stop_id] = newstation return l
def build_all_stations(df): # takes all items of the stopID dataset to build stations l = [] for index, row in df.iterrows(): l.append( st.Station(row['stop_id'], row['stop_name'], row['stop_desc'], row['stop_lat'], row['stop_lon'])) if index == 60: pdb.set_trace() return l
def find_all(): url_string = 'http://api.gios.gov.pl/pjp-api/rest/station/findAll' with urllib.request.urlopen(url_string) as url: json_string = str(url.read().decode()) result = Station.station_from_dict(json.loads(json_string)) stations_dict = {} for station in result: stations_dict[station.station_name] = station.id return jsonify(stations_dict)
def __init__(self,master = None): super().__init__(master) self.pack() self.station = Station() #binds station name and com ports for it self.stations = [1, 2, 3] self.portsDict = {self.stations[0] : ('COM3','COM2'), self.stations[1] : ('COM5','COM4'), self.stations[2] : ('COM7','COM6')} self.__createWidgets() self.flPortsOpen = False
def main(): #Constants for ease of use/test TIMEPARKED_CONST = 5 SOC_CONST = 44 BATCAPACITY_CONST = 60 MAXCHARGERATE_CONST = 10 print('Ford EV Smart Charge - Charging Station Simulation') chargingStation = Station() while(1): print('What would you like to do?\n' , '1. Add car to parking spot on station\n' , '2. Remove car from parking spot on station\n', '3. Display current parking spot configuration\n' '...\n', '9. Quit simulation', sep="") option = int(input("")) if option == 1: if len(chargingStation.cars) >= 6: print('All parking spots are currently full.\n') else: SOC = float(input('Enter current state of charge of battery (%): ')) batCapacity = float(input('Enter max capacity of battery (kWh): ')) maxChargeRate = float(input('Enter max rate of charge battery can handle (kW): ')) car = Car(SOC, batCapacity, maxChargeRate) chargingStation.add_car(car) print('Car\'s parking spot is', car.parkingSpot) chargingStation.calc_rate_options(car) elif option == 2: chargingStation.remove_car(car) elif option == 3: chargingStation.display_parking_spots() elif option == 9: return
def __init__(self, filename): self.train = {"stationIndex": 0, "occupants": []} self.stations = [] self.passengerCount = 1 infile = open(filename) i = 1 for line in infile: self.train["occupants"].append(Queue()) self.stations.append(Station(line[:-1], False, i, Queue())) i += 1 self.stations[0].trainHere = True infile.close()
def checkDate(stationList): dateList = [] for spam in stationList: station = St.Station(getSynopType='file', depesza=spam) dateList.append(station.decodeDate()) sumListLen = 0 listLen = len(stationList) + 1 for eggs in range(listLen): if eggs == dateList[eggs]: sumListLen += 1 if sumListLen == listLen: return True else: return False
def send(self, route, data): self.station = Station.get() dataToSend = { "stationId": self.station['id'], "address": self.localAddress, "route": route, "data": data } try: dataToSend = json.dumps(dataToSend) self.clientSocket.send(dataToSend) self.clientSocket.send('\n') except Exception as error: print('An error occured while sending via bluetooth: ', str(error))
def add_item(self, type): if type == CanvasItem.ACCESS: item = Ap(self, self.SPAWN_X, self.SPAWN_Y) self._aps[item.get_index()] = item elif type == CanvasItem.STATION: item = Station(self, self.SPAWN_X, self.SPAWN_Y) self._sts[item.get_index()] = item elif type == CanvasItem.OBSTACLE: item = Obstacle(self, self.SPAWN_X, self.SPAWN_Y) self._obs[item.get_index()] = item self._items[item.get_index()] = item self._index = item.get_index() item.draw() self.connect(item)
def testJamming(self): simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500) station1 = Station.Station(1, 20.0) simulator.addStation(station1) msg1 = Frame(1, 'Hello Station 2', 1, 2) evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1) station2 = Station.Station(2, 40.0) simulator.addEvent(evt1) simulator.addStation(station1) simulator.addStation(station2) msg2 = Frame(2, 'Hello Station 1', 2, 1) evt2 = Event(Event.ARRIVAL, 123.50, 2, msg2) simulator.addEvent(evt2) simulator.processSingleEvent() self.assertAlmostEquals(simulator.simTime, 123.45) simulator.processSingleEvent() #should transmit msg2 #and schedule collision detection evtQ = simulator.evtQ self.assertEquals(evtQ._qsize(), 2) evt3 = evtQ.get() self.assertEquals(evt3.eventType, Event.COLLISION_DETECT) self.assertAlmostEquals(evt3.time, 123.45, 0) self.assertEquals(evt3.stationId, 2) evt4 = evtQ.get() self.assertEquals(evt4.eventType, Event.COLLISION_DETECT) self.assertAlmostEquals(evt4.time, 126.45, 0) self.assertEquals(evt4.stationId, 1) #test jamming simulator.processSingleEvent() evt4 = evtQ.get() self.assertEquals(evt4.eventType, Event.JAMMING_END) simulator.processSingleEvent() evt5 = evtQ.get() self.assertEquals(evt5.eventType, Event.JAMMING_END)
def build_station(self, pos): """builds a random station at position pos""" if not self.building_place(pos): if 'station' in DEBUG: print "can't build at ", pos self.status = "No place for station here." return if self.score >= STATIONCOST: station = Station.Station(self, pos) self.stations.append(station) if 'station' in DEBUG: print "build station at ", pos self.status = "build station for $" + str(STATIONCOST) self.score -= STATIONCOST else: self.status = "Not enough money left to build station. You need $" + str( STATIONCOST)
def run(): print '--> mission New Frontiers - Raw Materials (3 of 7)' if not station.activateShip('shuttle'): return False if not station.undock(): return False pilot.autopilot() if not station.openInventory(): return False if not station.loadItem('datacore'): return False if not station.closeInventory(): return False if not general.setMissionWaypoint(): return False if not station.undock(): return False pilot.autopilot() if not station.startConversation(agent): return False if not station.completeMission(): return False if not station.activateShip('dominix'): return False print '<-- mission New Frontiers - Raw Materials (3 of 7)\n' return True
def editStation(self): if len(self.stations) == 0: print "You have not added any stations. Please add stations and try again" return print "Please choose a station to edit" for index, station in enumerate(self.stations): print index + 1, " ", station try: choice = int(raw_input()) except ValueError: print "Please enter a valid integer" return if choice < 1 or choice > len(self.stations): print "Please enter a valid integer" return self.stations[choice - 1] = Station.Station()
def secondReactChart(obsType, synop, synopType, name, path): valuesDict = {} date = 'YYYYMMDDHHMM' for eggs in synop: station = St.Station(getSynopType=synopType, synopCode=eggs) if obsType[0] == 1: valuesDict[station.decodeCityCountry() ['miasto']] = station.decodeTemp() elif obsType[0] == 2: valuesDict[station.decodeCityCountry() ['miasto']] = station.decodeDewPointTemp() elif obsType[0] == 3: valuesDict[station.decodeCityCountry() ['miasto']] = station.decodeStationAtmPressure() elif obsType[0] == 4: valuesDict[station.decodeCityCountry() ['miasto']] = station.decodeSeaLvlPressure() date = station.decodeDate() pC.drawChart(valuesDict=valuesDict, dataType=obsType[1], date=date, fileName=name, outputPath=path) return 'Wydrukowano wykres'
def runBattle(mission): print 'battle mission' bot = battle[mission] # bot = the_damsel_in_distress if bot == pick_your_position: if not station.activateShip('shuttle'): return False if not station.undock(): return False pilot.autopilot() if not general.warpToMissionLocation(): return False if not bot.run(): return False if not general.backToAgentStation(): return False if not station.startConversation(agent): return False if not station.completeMission(): return False if not station.repair(): print 'Error: repair faild' return False if bot == pick_your_position: if not station.activateShip('dominix'): return False return True
class Application(Frame): def __init__(self,master = None): super().__init__(master) self.pack() self.station = Station() #binds station name and com ports for it self.stations = [1, 2, 3] self.portsDict = {self.stations[0] : ('COM3','COM2'), self.stations[1] : ('COM5','COM4'), self.stations[2] : ('COM7','COM6')} self.__createWidgets() self.flPortsOpen = False def __del__(self): self.destroy() self.quit() def __createWidgets(self): self.grid() #statins combobox self.stationsCombo = Combobox(self,values = self.stations) #set monitor at first self.stationsCombo.set(self.stations[0]) self.stationsCombo.grid(column=0,row=0,sticky='nwse') #stations label self.stationsLabel = Label(self,text='station',font='Arial 8') self.stationsLabel.grid(column=2,row=0,sticky='w') #open port button self.openPortsBut = Button(self,text='open ports',command=self.openPortsEvent) self.openPortsBut.grid(column=0,row=1,sticky='nwse') #open port label self.openPortLabel = Label(self,text='closed',font='Arial 8') self.openPortLabel.grid(column=2,row=1,sticky='w') #send button self.sendBut = Button(self,text="send",command=self.sendEvent) self.sendBut.grid(column=0,row=2,sticky='nwse') #address combo self.addressCombo = Combobox(self,values=self.stations) self.addressCombo.set(self.stations[0]) self.addressCombo.grid(column=0,row=3,sticky='nwse') #address label self.addressLabel = Label(self,text='addressed to',font='Arial 8') self.addressLabel.grid(column=2,row=3,sticky='w') #edit text self.textbox = Text(self,height=12,width=64,font='Arial 8',wrap=WORD) self.textbox.focus_set() self.textbox.grid(column=0,row=4,columnspan=5) #error Label self.errorLabel = Label(self,text='no errors',font='Arial 8') self.errorLabel.grid(column=0,row=5,sticky='w') def openPortsEvent(self): stationAddr = self.stationsCombo.get() isMonitor = self.stations[0] == int(stationAddr) try: self.station.run(self.stationsCombo.get(),isMonitor,self.portsDict[int(stationAddr)]) self.openPortLabel['text'] = 'opened: ' + stationAddr self.flPortsOpen = True self.parallelShowPortData() self.errorLabel['text'] = 'no errors' except serial.SerialException as e: self.errorLabel['text'] = e def sendEvent(self): try: if not self.flPortsOpen: raise serial.SerialException('ports are close') msg = self.textbox.get('1.0',END) self.station.send(int(self.addressCombo.get()),msg.encode('utf-8')) #all is clear self.errorLabel['text'] = 'no errors' except (serial.SerialException, AddrError) as e: self.errorLabel['text'] = e def showPortData(self): while True: msg = self.station.transit().decode('utf-8') #show self.textbox.delete('1.0',END) self.textbox.insert('1.0',msg) def parallelShowPortData(self): readThread = threading.Thread(target=self.showPortData) readThread.start()
from BikeAlg import * from Station import * from EndLocation import * from DisPair import * from SugPair import * #pip install geopy #stations are created using custom inputs for all stations, but use coordinates found in actual station data s1 = Station(id = '1', capacity = 16, longitude = -77.0532,latitude = 38.8589, demand = 0, bikeAvail = 2, docAvail = 14) s2 = Station(id = '2', capacity = 16, longitude = -77.0533,latitude = 38.8572, demand = 0, bikeAvail = 4, docAvail = 12) s3 = Station(id = '3', capacity = 16, longitude = -77.0492,latitude = 38.8564, demand = 0, bikeAvail = 8, docAvail = 8) s4 = Station(id = '4', capacity = 16, longitude = -77.0495,latitude = 38.8601, demand = 0, bikeAvail = 2, docAvail = 13) s5 = Station(id = '5', capacity = 16, longitude = -77.0594,latitude = 38.8578, demand = 0, bikeAvail = 5, docAvail = 15) #prop is a field calculated in actual simulation(see station class) and assigned, but we created custom prop for algorithm testing purposes s1.prop = .5 s2.prop = .5 s3.prop = .5 s4.prop = .5 s5.prop = .5 #Creating dictionary of stations and creating list out of dictionary dic = {'1':s1, '2':s2, '3':s3, '4':s4, '5':s5} sl = list(dic.values()) #Instantiaing algorithm taking the parameter (rad) being the radius that the algorithm searches/considers ba = BikeAlg(5) loc = EndLocation(-77.0512, 38.8588) d = 1 ba.preProcess(sl, loc) ba.getSuggest(loc, 0) print("Stations within: " + str(d) + " miles"); print()
class Application(Frame): def __init__(self,master = None): super().__init__(master) self.pack() self.station = Station() self.__createWidgets() def __del__(self): self.destroy() self.quit() def allocButton(self,col,line,callback,lbl,anchor='wesn'): #open port button but = Button(self,text=lbl,command=callback) but.grid(column=col,row=line,sticky=anchor) return but def allocLabel(self,col,line,lbl,anchor='wesn',text_font='Arial 8'): #current station label label = Label(self,text=lbl,font=text_font) label.grid(column=col,row=line,sticky=anchor) return label def allocStationAddress(self,col,line,lbl,text='192.168.1.2 6000'): #curent station address addr = Entry(self) addr.grid(column=col,row=line,sticky='nwes') addr.insert(0,text) label = self.allocLabel(col+1,line,lbl) return (addr,label) def allocCheckButton(self,col,line,txt): var = IntVar() checkBut = Checkbutton(self,text=txt,variable=var,onvalue=1,offvalue=0) checkBut.grid(column=col,row=line) return (checkBut,var) def __createWidgets(self): self.grid() self.curServAddrEntry,self.curLabel = self.allocStationAddress(0,0,'current station') self.nextServAddrEntry,self.nextLabel = self.allocStationAddress(0,1,'next station','192.168.1.2 6001') self.dstServAddrEntry,self.destLabel = self.allocStationAddress(0,2,'dest station','192.168.1.2 6001') #run server button self.runServerBut = self.allocButton(0,3,self.openServPortEvent,'run server') #connect client to next server button self.connectToNextServBut = self.allocButton(1,3,self.connectToNextServEvent,'connect to next server') #start button self.startBut = self.allocButton(2,3,self.startStationProc,'start') #send button self.sendBut = self.allocButton(0,4,self.sendEvent,'send') #monitor checkbox self.monitorCheckBox, self.monitorChboxVar = self.allocCheckButton(4,1,'is monitor?') #edit text self.textbox = Text(self,height=12,width=64,font='Arial 8',wrap=WORD) self.textbox.focus_set() self.textbox.grid(column=0,row=5,columnspan=5) def startStationProc(self): try: self.station.run(self.talkSock,self.clientSock,self.servSock.inetAddr,self.monitorChboxVar.get()) #self.openPortLabel['text'] = 'opened: ' + stationAddr self.flPortsOpen = True self.parallelCatchTransitMesages() self.startBut['state'] = DISABLED self.monitorCheckBox['state'] = DISABLED except (OSError,AttributeError) as e: messagebox.showerror('error',e) def connectToNextServEvent(self): try: IP,port = self.nextServAddrEntry.get().split(' ') #check address if (IP,port) == self.servSock.inetAddr: raise OSError('it is forbidden to connect to the same station') self.clientSock = TCP_ClientSockWrapper(IP,port) self.connectToNextServBut['state'] = DISABLED except OSError as e: messagebox.showerror('error',e) def openServPortEvent(self): #split to [IP, port] try: IP,port = self.curServAddrEntry.get().split(' ') self.servSock = TCP_ServSockWrapper(IP,port) self.parallelClientAccept() self.runServerBut['state'] = DISABLED except OSError as e: messagebox.showerror('error',e) def sendEvent(self): try: msg = self.textbox.get('1.0',END) self.station.send( self.dstServAddrEntry.get().split(' ') ,msg.encode('utf-8')) except (OSError,AddrError) as e: messagebox.showerror('error',e) def catchTransitMesages(self): while True: try: b_msg,sa_addr = self.station.transit() #show self.textbox.delete('1.0',END) self.textbox.insert('1.0',b_msg.decode('utf-8')) except OSError as e: messagebox.showerror('error',e) def acceptClient(self): sock,addr = self.servSock.raw_sock.accept() self.talkSock = SockWrapper(raw_sock = sock, inetAddr = addr) def parallelClientAccept(self): acceptThread = threading.Thread(target=self.acceptClient) acceptThread.start() def parallelCatchTransitMesages(self): readThread = threading.Thread(target=self.catchTransitMesages) readThread.start()
def addStation(self): try: self.stations.append(Station.Station()) except ValueError: print "Capacity should be an integer. Please try again"
def __init__(self,master = None): super().__init__(master) self.pack() self.station = Station() self.__createWidgets()