def __create_station(self, line, string): """ check if station have connect point then return a station object """ station_elements = string.split(':') if len(station_elements) > 2: id, station, _, conn = station_elements return Station(id, line, station, conn.strip()) id, station = station_elements return Station(id, line, station)
def readStationsJson(stationsFileName): if stationsFileName is None: return {} stationsDict = {} try: with open(stationsFileName, 'r') as inFile: allLines = inFile.readlines() for aLine in allLines: aStation = Station(aLine) stationsDict[aStation.mongo_id] = Station(aLine) except Exception as ex: # this exception handling should be improved some time. return {} return stationsDict
def run_pipeline(initial_orders): global engine global SIMULTION_METHOD global service_stations SIMULTION_METHOD = 'PIPELINE' service_stations = {} for type in types: service_stations[type] = Station(type, [ ingredient for ingredient, v in ingredients_dict.iteritems() if ingredients_dict[ingredient]['type'] == type ]) # for arrival in initial_orders: # print str(arrival.data['order']) + ' at ' + str(arrival.data['order'].start_time) engine = eng.Engine(initial_orders) start_time = engine.current_time engine.run() end_time = engine.current_time total_time = end_time - start_time # orders = len(engine.completed_orders) # mean_time = total_time / NUM_ORDERS mean_wait = numpy.mean(map(lambda x: x.wait_time, engine.completed_orders)) # std_dev = numpy.std(map(lambda x: x.wait_time, engine.completed_orders)) # print '----------PIPELINE----------' # print 'Number of orders processed: ' + str(orders) # print 'Mean time per sandwich ' + str(mean_time) # print "Mean waiting time: " + str(mean_wait) # print 'Standard deviation of wait times: ' + str(std_dev) return mean_wait
def create_station(self, url, parent=None): if self.locked: print("Locked") return self.application.mark_busy() self.locked = True win_wait = self.pls_wait() while Gtk.events_pending(): Gtk.main_iteration() try: Station(self, url, parent) except Exception as err: traceback.print_exc() win_wait.destroy() self.popup(err) self.locked = False self.application.unmark_busy() else: self.db.save() win_wait.destroy() self.locked = False self.application.unmark_busy() return
def getValues(self): if self.save: station = Station(self.name, self.technology, self.lat, self.lon, self.capacity, self.turbine, self.rotor, self.no_turbines, self.area, self.scenario, power_file=self.power_file) if self.grid_line is not None: station.grid_line = self.grid_line if 'PV' in self.technology: if self.direction is not None: station.direction = self.direction if self.tilt is not None: station.tilt = self.tilt if self.storage_hours is not None: if self.technology == 'CST': try: if self.storage_hours != self.cst_tshours: station.storage_hours = float(self.storage_hours) except: pass elif self.technology == 'Solar Thermal': try: if self.storage_hours != self.st_tshours: station.storage_hours = float(self.storage_hours) except: pass return station else: return None
def storeStationsDB(self): stations_list = [] stations = pd.read_csv(PATH_STATIONS_FILE, sep=';') for i in range(0, len(stations)): lat = stations.iloc[i]['Latitude'].split(':')[1].strip() lon = stations.iloc[i]['Longitude'].split(':')[1].strip() coord = 'SRID=4674;POINT({lon} {lat})'.format(lat=lat, lon=lon) omm = stations.iloc[i]['Estacao'].split('OMM:')[1].replace( ')', '').strip() name = stations.iloc[i]['Estacao'].split(' : ')[1].split( '-')[0].strip() estate = stations.iloc[i]['Estacao'].split('-')[1].split( '(')[0].strip() altitude = stations.iloc[i]['Altitude'].split(':')[1].strip() station = Station(omm=omm, name=name, geom=coord, estate=estate, altitude=altitude) stations_list.append(station) session.add(station) session.commit()
def add_from_file(self, location): if self.locked: print("Locked") return self.locked = True self.application.mark_busy() win_wait = self.pls_wait() while Gtk.events_pending(): Gtk.main_iteration() try: Station(self, location, None, True) except Exception as err: traceback.print_exc() win_wait.destroy() self.popup(err) self.locked = False self.application.unmark_busy() else: win_wait.destroy() self.db.save() self.locked = False self.application.unmark_busy() return
def create_stations(filename='data/stops.txt'): """ Reads in lines of stops GTFS file and creates stops objects parameters: filename - string, the filename of the GTFS stops file returns: list of stations in the file, as Station objects """ with open(filename, newline='') as stops: station_info = csv.reader(stops) # skip first line, which is just attribute names next(station_info) # empty list to hold stations stations = [] # parse all the lines and create stations for row in station_info: # assign each attribute of Station based on line in file (stop_id, stop_code, stop_name, stop_desc, platform_code, platform_name,\ stop_lat, stop_lon, zone_id, stop_address, stop_url, level_id,\ location_type, parent_station, wheelchair_boarding, municipality, on_street, at_street,vehicle_type) = tuple(row) # create Station instance with those attributes try: stations.append(Station(stop_id, stop_code, stop_name, stop_desc, \ platform_code, platform_name, stop_lat, stop_lon, stop_address, \ zone_id, stop_url, level_id, location_type, parent_station,\ wheelchair_boarding, municipality, on_street, at_street,vehicle_type)) except ValueError: print("Value error at row : "+str(row)+"\n") return stations
def get_station_timetable(lineId, pageId): STA = Station("http://www.ekikara.jp/newdata/ekijikoku/" + lineId + "/" + pageId + ".htm") timetable = STA.get_timetable() # return make_response(jsonify({"timetable": timetable}), 200) response = make_response(json.dumps({"timetable": timetable}, ensure_ascii=False, sort_keys=True, separators=(',', ': ')), 200) response.headers['Content-Type'] = 'application/json' return response
def load_data(self, file): # self.save_to_db() self.clean() if not os.path.isfile(file): print("incorrect path") return f = open(file, "r") try: xml_doc = ET.fromstring(f.read()) dtd = ET.DTD(open(self.dtd_path)) #if not dtd.validate(xmlDoc): # print("Dtd validation not passed") # return except: print("Error while parsing. Invalid document") return for xml_railroad in xml_doc.findall("Railroads/Railroad"): road_id = int(xml_railroad.get('id')) road_name = xml_railroad.get('road_name') railroad = Railroad(road_id, road_name) for xml_station in xml_railroad.findall("Stations/Station"): station_id = int(xml_station.get('id')) station_name = xml_station.get('name') station_address = xml_station.get('address') station_tracks = int(xml_station.get('tracks')) station = Station(station_id, station_name, station_address, station_tracks) railroad.stations.add(station) self.stations[station_id] = station self.railroads[road_id] = railroad self.print_data() return 0
def put_station_in_list(all_stations, *args): dis_unit_trans = lambda dis: dis / 1000 if dis > 10 else dis if len(args) < 4: return name = args[0] line = args[1] conn = args[2] dis = args[3] if get_station_by_name(name, all_stations) == None: station = Station() station.add_line(line) station.set_name(name) dis = dis_unit_trans(float(dis.group())) station.add_conn(conn, dis) all_stations.append(station) else: station = get_station_by_name(name, all_stations) station.add_line(line) dis = dis_unit_trans(float(dis.group())) station.add_conn(conn, dis)
def scrape_bon_appetite_menus(self): for cafe_name, (school, cafe_id) in MenuScraper.bon_appetit_dict.items(): url = f"https://legacy.cafebonappetit.com/api/2/menus?cafe={cafe_id}" self.driver.get(url) menu_data = json.loads(self.driver.find_element_by_tag_name("pre").text) food_id_to_items = menu_data['items'] for day in menu_data['days']: all_meals = day['cafes'][cafe_id]['dayparts'][0] for meal in all_meals: start_time = datetime.strptime(meal['starttime'], "%Y-%m-%dT%H:%M:%S") end_time = datetime.strptime(meal['starttime'], "%Y-%m-%dT%H:%M:%S") menu = Menu(cafe_name, meal['label'], start_time, end_time, None) stations = meal['stations'] for station in stations: menu_station = Station(station['label']) for food_id in station['items']: food_item = FoodItem( name=food_id_to_items[food_id]['label'], dining_hall='bon appetite', nutrition_facts=food_id_to_items[food_id]['nutrition_details'], ingredients=None, ) menu_station.add_food_item(food_item) menu.add_station(menu_station) self.menus.append(menu)
def setup_value(line_name, alist, conn=False): """ Set value in instance type for all stations and all transfer points. """ from station import Station from hub import Hub ls_instance = [] for item in alist: ls_inform = item.split(':') flag_set = False if conn and len(ls_inform) == 4: new_instance = Hub() new_instance.conn = ls_inform[-1] flag_set = True if not conn: new_instance = Station() flag_set = True if flag_set: new_instance.name = ls_inform[1] new_instance.line = line_name new_instance.id = ls_inform[0] if not conn or conn and len(ls_inform) == 4: ls_instance.append(new_instance) return ls_instance
async def play(self, ctx: commands.Context, index: int = 1): if self.client is None: await ctx.send("I haven't been logged into Pandora, yet!") return # Get that f****r's current voice channel. voice_state = ctx.author.voice if voice_state is None or voice_state.channel is None: await ctx.send("You aren't in any voice channel... you tit!") return stations = self.client.get_station_list() index -= 1 if index < 0 or index > (len(stations) - 1): await ctx.send("There are no stations with that index.") return # Create the station handler station: Station = Station(dir = self.directory, loop = self.loop, station = stations[index]) await station._fill_buffer() if ctx.voice_client is None: voice = await voice_state.channel.connect() else: voice = ctx.voice_client await voice.move_to(voice_state.channel) # Kick off the playlist await self.play_station(ctx, station=station, voice=voice)
def __init__(self, st, et, stations): super(StationArray, self).__init__() self.st = st self.et = et self.stations = stations for station in stations: self[station] = Station(st, et, station)
def simulate(): num_stn = input('Enter number of stations (power of 2):') num_stn=int(num_stn) max_num_stn=2**(ceil(log(num_stn,2))) num_data = input('Enter number of data per station:') num_data=int(num_data) createWalsh(max_num_stn) print() print(walsh) stns=[] for i in range(num_stn): frames = input('Enter a string of length '+str(num_data)+' data for station '+str(i)+': ') frames=list(frames) # Now create the station object tempstn=Station(i,num_data,walsh[i],frames) stns.append(tempstn) for i in range(num_stn,max_num_stn): frames=num_data*'i' frames=list(frames) tempstn=Station(i,num_data,walsh[i],frames) stns.append(tempstn) print() # Send data for every data for i in range(num_data): code=[0 for i in range(max_num_stn)] # Send for every station for j in range(max_num_stn): # code=code+stns[j].sendData(i) code = [x+y for x,y in zip(code, stns[j].sendData(i))] print('Code word in channel is '+str(code)) print('Decoding for every station') decode_cdma(code,num_stn,max_num_stn) print(15*'=') print()
def get_stations(self, postcode): stations = [] fuel_data = self.load_ref_data() for item in fuel_data["stations"]["items"]: if item["address"].endswith(f"{postcode}"): station = Station(item["brand"], item["name"], item["code"], item["address"]) stations.append(station) return stations
def __init__(self): self.screen = curses.initscr() # settings self.settings = CursesSettings(self) # station manager self.sm = Station() self.play_station = self.sm.stations[self.current_station] # player self.player = Player()
def collect_stations(): """ Create a simple chain of train stations """ first_station = "武蔵境" second_station = "三鷹" third_station = "吉祥寺" # Creating a set of stations s = Station(first_station, "2 Chome-1-12 Kyonancho, Musashino-shi, 〒180-0023, Japan") s1 = Station(second_station, "3 Chome-46 Shimorenjaku, Mitaka-shi, 〒181-0013, Japan") s2 = Station( third_station, "2 Chome−1 Musashino-shi, Kichijōji Minamichō, 〒180-0003, Japan") print("Hello, there. The train station to start is", s.get_name()) print("Next, we proceed to", s1.get_name()) print("Finally, we rest at", s2.get_name())
def getStationFromTrueStation(self, trueStation): if trueStation < 0: raise StationError("True station may not be less than 0.0.") regNo = 0 for reg in self._regionList: regNo += 1 if reg.absStaIsInMyRange(trueStation): staVal = trueStation - reg.trueBeginStation + reg.beginStation return Station(station=staVal, region=regNo, alignment=self) raise StationError( "True station is greater than alignment's trueEndStation")
def load(self): station = None with open("data.json") as f: d = json.load(f) fuelList = list() for f in d["fuel"]: fuelList.append(Fuel(f["name"], f["tank"])) station = Station(d["name"]) station.__fuelList__ = fuelList return station
def validateDeviceConfigUi(self, valuesDict, typeId, devId): stationID = valuesDict['address'].encode('ascii','ignore').lower() province = valuesDict['province'].encode('ascii','ignore').upper() station = Station(province,stationID) indigo.server.log(station.url()) try: urllib2.urlopen(station.url()) except urllib2.HTTPError, e: errorsDict = indigo.Dict() errorsDict['address'] = "Station not found or isn't responding" self.errorLog("Error getting station %s data: %s" % (stationID, str(e))) return (False, valuesDict, errorsDict)
def on_left_pressed(self): if not self.was_pressed: print("made new station") self.was_pressed = True self.world.stationList.append(Station(pygame.mouse.get_pos())) self.counter += 1 print(self.counter) print(self.world.stationList[-1]) else: print("moving station") self.world.stationList[self.counter - 1].change_pos( pygame.mouse.get_pos())
def load_stations(data_list, stations_data): """Create and return station objects""" # Create a stations object stations = Stations() # Create a station object for every station # and append to the stations object for item in stations_data: station_object = Station(item[0], float(item[2]), float(item[1])) stations.append_station(item[0], station_object) return stations
def main(): print("create a standing train station: enter the appropriate values for your station.") station_1 = Station() # Create a new station that is the same as station_1 before runnning the simulation. print("create a walking and standing train station: enter the appropriate values for your station.") station_2 = Station() train_1 = Train() # Create a standing only escalator. print("Create a standing only escalator: enter the data for the behavior you have observed.") escalator_1 = Escalator() # Create a standing and walking escalator. print("Create a standing and walking escalator: enter the data for the behavio you have observed.") escalator_2 = Escalator() print("failure threshold", FAILURE_TRESHOLD) for i in range(RUNS): print("station population", station_1.pop, "\n") failures = simulation(station_1, train_1, escalator_1)[0] print(failures, "failures") if failures >= FAILURE_TRESHOLD: station_1.train_wait += 60 print("failure threshold reached.") else: pass print("End standing station test.\nStart standing and walking station test.\n") for i in range(RUNS): print("station population", station_1.pop, "\n") failures = simulation(station_2, train_1, escalator_2)[0] print(failures, "failures") if failures >= FAILURE_TRESHOLD: station_2.train_wait += 60 print("failure threshold reached.") else: pass print("the time between trains for the station with standing only escalators is: ", station_1.train_wait / 60) print("The time between trains for the station with standing and walking escalators is: ", station_2.train_wait / 60)
async def cmdStationCreate(self, message=None, cmd=None, failed=False): duplicate = False for s in stations: duplicate = duplicate or (cmd[2] == s.waveLength) if (duplicate): await message.channel.send("Wavelength " + cmd[2] + " already exists!") else: s = Station(waveLength=cmd[2], verbose=self.verbose, owner=message.author.nick) stations.append(s) await message.channel.send("Created station " + s.waveLength)
def getLayout3(): width, height, gridSize = 840, 620, 20 wallLayout = [[0 for row in range(0, height / gridSize + 1)] for col in range(0, width / gridSize + 1)] for x in range(0, width / gridSize): for y in range(0, height / gridSize): if x in {0, 0, width / gridSize, width / gridSize - 1} or y in { 0, 0, height / gridSize - 1, height / gridSize - 1 }: wallLayout[x][y] = 1 for i in range(1, width / (3 * gridSize) - 1): for j in range(1, height / gridSize): if i % 2: wallLayout[3 * i + 1][j] = 1 wallLayout[3 * i + 2][j] = 1 wallLayout[3 * i + 3][j] = 1 for m in range(2, width / gridSize - 2): for n in range(2, height / gridSize - 1, 8): wallLayout[m][n] = 0 wallLayout[m + 1][n] = 0 wallLayout[m][n + 1] = 0 wallLayout[m][n + 2] = 0 wallLayout[m + 1][n + 1] = 0 stations = [] for p in range(1, width / gridSize - 2): if not (p + 1) % 6: stations.append(Station([p, 1])) stations.append(Station([p, height / gridSize - 2])) for s in stations: x, y = s.pos wallLayout[x][y] = 0 return width, height, gridSize, wallLayout, stations
def test_base_station(): ''' This test tests the basic functionality of the station class Does not use any records or lambdas. ''' from station import Station station = Station() station.add_record(5) station.add_record(3) station.add_record(10) assert station.get_record("first") == 5 assert station.get_record("last") == 10 station.add_record(6) assert station.get_record("last") == 6
def create_station(self): message = [ 'Введите название станции(Формат: больше 2х букв или цифр.):' ] name = self.__data_input(message) if name and not self.__is_duplicate_name(self.stations, name): try: station = Station(name) except ValueError as val: self.__print_unsuccessful(val) else: self.stations.append(station) self.__print_object_created_successfully(station)
def getLayout1(): width, height, gridSize = 1000, 1000, 50 wallLayout = [[0 for row in range(0, height / gridSize + 1)] for col in range(0, width / gridSize + 1)] for x in range(0, width / gridSize): for y in range(0, height / gridSize): if x == 0 or y == 0 or x == width / gridSize - 1 or y == height / gridSize - 1: wallLayout[x][y] = 1 stations = [] for i in range(width / (2 * gridSize) - 2, width / (2 * gridSize) + 2): for j in range(1, 3): stations.append(Station([i, j])) return width, height, gridSize, wallLayout, stations