def test_station(self): colors = IntEnum("colors", "blue green red", start=0) s = Station(40020, "test_station", colors.red) print(s) t = Train("BLUEL999", Train.status.in_service) s.run(t, "a", 90000, "a") t = Train("BLUEL998", Train.status.in_service) s.run(t, "a", 90001, "a")
def post(self): train_args = add_train_parser.parse_args() ordered = Train.query.order_by(Train.id.desc()).all() if ordered and Train.query.filter_by(name=train_args['name']).first(): abort( 400, 'Train %s already exists. Please choose a new name.' % train_args['name']) if 'id' not in train_args: if ordered: highest = ordered[0].id else: highest = 0 train_id = highest + 1 else: train_id = train_args['id'] train = Train(id=train_id, name=train_args['name']) train.speed = 0.0 train.length = trainLength train.width = trainWidth train.height = trainHeight train.mass = trainMass train.crewCount = 0 train.passengerCount = 0 db.session.add(train) db.session.commit() return train, 201
def train(self): con = self.con() train_id = q.get() while train_id: result = con.query(Train).filter_by(train_id=train_id).all() if result: if result[0].status: train_id = q.get() continue else: train = self.get_train_info(train_id) tra_id = result[0].id else: train = self.get_train_info(train_id) # 写入train tra = Train(train_id=train_id, train_name=train['name'], course_num=train['course_num']) con.add(tra) con.commit() tra_id = tra.id #保留train index page url = 'http://edu.51cto.com/center/wejob/index/view?id=%d&force=3&orig=try' % ( train_id) for course in train['courses']: if con.query(Train_course).filter_by( train_course_id=course['train_course_id']).filter_by( tra_id=tra_id).all(): continue tra_cou = Train_course( tra_id=tra_id, train_course_id=course['train_course_id'], course_name=course['course_name'], course_id=course['course_id'], lesson_num=course['lesson_num'], number=course['number']) con.add(tra_cou) con.commit() cou_id = tra_cou.id lessons = self.get_course_info(train_id, int(course['train_course_id'])) for lesson in lessons: lesson['course_id'] = course['course_id'] lesson['cou_id'] = cou_id self.insert_lesson(con, lesson) con.query(Train_course).filter_by(id=cou_id).update( {'status': 1}) con.query(Train).filter_by(train_id=train_id).update({'status': 1}) print('微职位%s爬取完成' % train_id) if q.qsize(): train_id = q.get() else: print('线程退出')
def save_direct_trains(start_trains, end_trains): """save direct edges """ direct_plans = [] if len(start_trains) <= len(end_trains): for (k,v) in start_trains.items(): if k in end_trains and v < end_trains[k]: # direct k_train = Train.objects(train_no=k).get() direct_plan = Direct_Plan(v, end_trains[k], k_train) direct_plans.append(direct_plan) else: for (k,v) in end_trains.items(): if k in start_trains and v > start_trains[k]: # direct k_train = Train.objects(train_no=k).get() direct_plan = Direct_Plan(start_trains[k], v, k_train) direct_plans.append(direct_plan) # if direct_plans: return direct_plans
def gettrain(train_code): #mc_key = md5("stations") #stations = MC.get(mc_key) train_code = str.upper(train_code) train = Train.objects(__raw__={'board_train_code':{'$all':[train_code,]}}).get() if 'callback' in request.query: callback = request.query.callback response.content_type = 'application/javascript' return callback + '(' + train.to_json() + ');' else: response.content_type = 'application/json' return json.dumps(train.to_dict(), indent=4)
def _build_trains(self): """Constructs and assigns train objects to stations""" trains = [] curr_loc = 0 b_dir = True for train_id in range(self.num_trains): tid = str(train_id).zfill(3) train = Train(f"{self.color.name[0].upper()}L{tid}", Train.status.in_service) trains.append(train) if b_dir: self.stations[curr_loc].arrive_b(train, None, None) else: self.stations[curr_loc].arrive_a(train, None, None) curr_loc, b_dir = self._get_next_idx(curr_loc, b_dir) return trains
def setup(bot): with open("metro-config.json", encoding="utf8") as o: configs = json.loads(o.read()) districts = [ District(bot, d["cat_id"], d["role_id"], d["station_id"]) for d in configs["districts"] ] metro = configs["metro"] trains = [ Train(bot, t["channel_id"], t["role_id"], t["direction"], t["start"]) for t in metro["trains"] ] transit_id = metro["cat_id"] looped = metro["looped"] speed = metro["speed"] wait = metro["wait"] new_metro = Metro(districts, trains, transit_id, looped, speed, wait) return new_metro
def testdb_command(): db.drop_all() db.create_all() block1 = Block(id=1, number=1, line="green", length=100.0, grade=0.5, speedLimit=55, elevation=0.5, cumulative_elevation=0.5, occupancy=False) db.session.add(block1) tcBlock1 = TrackControllerBlock(id=1, occupancy=False, maintenance=False, broken=False) db.session.add(tcBlock1) block2 = Block(id=2, number=2, line="green", length=100.0, grade=1.0, speedLimit=55, elevation=1.0, cumulative_elevation=1.5, occupancy=False) db.session.add(block2) tcBlock2 = TrackControllerBlock(id=2, occupancy=False, maintenance=False, broken=False) db.session.add(tcBlock2) block3 = Block(id=3, number=3, line="green", length=100.0, grade=1.5, speedLimit=55, elevation=1.5, cumulative_elevation=3.0, occupancy=False) db.session.add(block3) tcBlock3 = TrackControllerBlock(id=3, occupancy=False, maintenance=False, broken=False) db.session.add(tcBlock3) switch1 = Switch(id=1, state=False) db.session.add(switch1) block1.switch = switch1 crossing1 = Crossing(id=1, state=False) db.session.add(crossing1) block3.crossing = crossing1 station1 = Station(id=1, name="Station 1") db.session.add(station1) block2.station = station1 light1 = Light(id=1, state=False) db.session.add(light1) light2 = Light(id=2, state=False) db.session.add(light1) switch1.lights.append(light1) switch1.lights.append(light2) # block1.message = "hello" train1 = Train(id=1, name="train1", length=1000.0, width=100.0, height=100.0, mass=1000.0, crewCount=0, passengerCount=0) db.session.add(train1) train1.front_block = block1 # block1.train_id = block1.front_train.id msg1 = Message(id=1, text="50,GO") db.session.add(msg1) msg1.block = block1 msg1.train = train1 msg2 = Message(id=2, text="100,GO") db.session.add(msg2) msg2.block = block2 msg3 = Message(id=3, text="0,STOP") db.session.add(msg3) msg3.block = block3 request = CTCRequest(id=0, type=0, input="") db.session.add(request) db.session.commit() # user1 = User(username='******', password='******') # db.session.add(user1) # # chatroom1 = ChatRoom(name='Super Awesome Chat Room') # db.session.add(chatroom1) # # user1.created_rooms.append(chatroom1) # # message1 = Message(creator=user1.username,text="Hello, there!", chatroom=chatroom1.name) # db.session.add(message1) # db.session.commit() print('Initialized the testing database.')
def post(self): user_name = self.request.get("user_name", default_value=None) biz = self.request.get("biz", default_value=None) time = self.request.get("time", default_value=None) if user_name is None: self.error(404) self.response.out.write("user_name required") return if biz is None: self.error(404) self.response.out.write("biz required") return if time is None: self.error(404) self.response.out.write("time required") return biz_name = None biz_rating = None biz_address = None try: biz_info = get_biz_info(biz) if biz_info: biz_name = biz_info["name"] biz_rating = int(biz_info["rating"]) biz_address = biz_info["location"]["display_address"] else: self.error(404) self.response.out.write("Invalid biz ID or Yelp API error") return except: self.error(404) self.response.out.write("Invalid biz ID or Yelp API error") return try: business = None business_gql = Business.gql("where y_business_id = :1", biz) if business_gql.count() == 0: business = Business(y_business_id=biz, name=biz_name, rating=biz_rating, address=biz_address) business.put() else: for biz in business_gql: business = biz break train = None departure_time = datetime.datetime.fromtimestamp(float(time)) train_gql = Train.gql("where business = :1 and departure_time = :2", business, departure_time) if train_gql.count() == 0: train = Train(destination=business, departure_time=departure_time) train.put() else: for t in train_gql: train = t break user = get_user_by_name(user_name) if user is None: user = User(name=user_name, train=train, subscriptions=[]) user.train = train user.put() result = [] if train: result.append(train.get_train_info()) self.response.out.write(json.dumps(result)) except: self.error(404)
y_tr, y_tst, w = syn_data_lin(x_train, x_test, shape=args.shape, scale=args.scale) elif args.genmodel.lower() == "epistasia": print("Epistasia model") y_tr, y_tst = syn_data_epis(x_train, x_test, shape=args.shape, scale=args.scale) else: raise argparse.ArgumentTypeError( 'Linear or epistasia are only supported.') print("Saving to: " + ytr_name) np.savetxt(snp_name, snp_list, delimiter=",") np.savetxt(ytr_name, y_tr, delimiter=',') np.savetxt(ytst_name, y_tst, delimiter=',') if os.path.exists(C_name) and not args.recreation: C = np.loadtxt(C_name, delimiter=",") else: print("Computing GWAS") C = computeCor(y_tr) print("Saving to :" + C_name) np.savetxt(C_name, C, delimiter=",") xTr, xTst = readGWAS(C, args.k) r = Train(xTr, xTst, y_tr, y_tst, args.method) print([args, "r2 = " + str(r)]) fname = "results/out.txt" with open(fname, 'a') as fh: fh.write([args, "r2 = " + str(r) + '\n'])
def save_tranfer_one_plans(start_trains, end_trains): """save one tranfer plans """ tranfer_one_plans = [] #save tranfer result trains = lambda train:[(t,train[t.train_no]) for t in Train.objects(__raw__={"train_no":{"$in":train.keys()}})] start_train_seqs = trains(start_trains) start_sta_info =lambda d: dict([(s.sta_name, s) for s in d[0].edges if s.seq_no > d[1]]) #s.arrive_time,s.city_same start_trains_stas_v = map(start_sta_info, start_train_seqs) end_train_seqs = trains(end_trains) end_sta_info =lambda d: dict([(s.sta_name, s) for s in d[0].edges if s.seq_no < d[1]])#s.depart_time,s.city_same end_trains_stas_ev = map(end_sta_info, end_train_seqs) for i,sl in enumerate(start_trains_stas_v): set_one = set(sl.keys()) train_one = start_train_seqs[i] for j,el in enumerate(end_trains_stas_ev): train_two = end_train_seqs[j] if len(train_one[0].cross_bureaus) == 1 and len(train_two[0].cross_bureaus) == 1: break #tranfer is not taking place in two bureau trains set_two = set(el.keys()) set_union = set_one & set_two same_city_sta = [(st1,st2) for st1 in set_one - set_union for st2 in set_two - set_union \ if sl[st1].city_same and sl[st1].city_same==el[st2].city_same] union_sets_sta = [] union_sets_sta = list(set_union) union_sets_sta.extend(same_city_sta) if union_sets_sta: try: #union_sets_sta_dict = [] #union_sets_sta_dict = zip(union_sets_sta, union_sets_sta) #union_sets_sta_dict.extend(same_city_sta) union_sets_connct_time = [] union_sets_connct_time = [connect_time(sl[t].arrive_time, el[t].depart_time) for t in set_union] union_sets_connct_time.extend([connect_time(sl[t1].arrive_time, el[t2].depart_time) for (t1,t2) in same_city_sta]) except TypeError, e: print "type error" except Exception, ex: print "other error" #union_sets_all = dict(zip(union_sets_sta,union_sets_connct_time)) #union_sets_filter = sorted(union_sets_all.items(), key=lambda x: x[1]) transit_time = max(union_sets_connct_time) for i,x in enumerate(union_sets_connct_time): if x == transit_time and i<len(set_union): transit_sta = union_sets_sta[i] transit_sta_seqs = (sl[transit_sta].seq_no, el[transit_sta].seq_no) tranfer_one = Tranfer_One_Plan(train_one[0],train_one[1], train_two[0],train_two[1], transit_sta_seqs, transit_sta,transit_time) tranfer_one_plans.append(tranfer_one) break elif x == transit_time and i>=len(set_union): if_city_same = True transit_stas = union_sets_sta[i] transit_sta_seqs = (sl[transit_stas[0]].seq_no, el[transit_stas[1]].seq_no) tranfer_one = Tranfer_One_Plan(train_one[0],train_one[1], train_two[0],train_two[1], transit_sta_seqs, transit_stas,transit_time,if_city_same) tranfer_one_plans.append(tranfer_one) break else: continue
def save_tranfer_two_plans( start_sta, start_trains_kv, end_sta, end_trains_kv ): """ tranfer two plan includes one direct plan and tranfer one plan """ #results,start_trains,end_trains = save_direct_plans(start_sta, end_sta) direct_train = Train.objects( train_no = start_trains_kv)