def run(self): print_lock.acquire() print("Thread", self.name) print_lock.release() conn = create_connection() while True: name = self.queue.get() t = None while t is None: try: t = Train.add_train(name, conn, self.hafas) except http.client.BadStatusLine: conn = create_connection() except KolstatError as e: print_lock.acquire() print(name , str(e)) print_lock.release() break if t is not None: print_lock.acquire() print(name, t.get_relation_string()) print_lock.release() self.queue.task_done()
def trainsearch(request): if request.method == 'POST': form = TrainSearchForm(request.POST) if form.is_valid(): data = form.cleaned_data query = dict(search_operator = data['operator'] , search_number = data['number']) if data['operator']: ss = data['operator'] + ' ' + str(data['number']) else: ss = str(data['number']) sr = Train.search(ss) if len(sr) == 0: query.update(dict(message = 'Brak pociągów w bazie danych spełniających kryteria wyszukiwania')) return query elif len(sr) > 1: query.update(dict(trains = sr)) return query else: train, = sr raise Redirect(reverse('kolstat-train', args=[train.category.name, train.number])) else: return dict(message = 'Musisz podać numer pociągu') return dict()
def train(request, operator, number, variant = None): res = Train.search(operator + ' ' + number, variant) if len(res) != 1: raise Redirect(reverse('kolstat-trains-search')) ktrain, = res return dict(train = ktrain)
def train_add(request): if request.method == 'POST': form = AddTrainForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] train = Train.add_train(name) raise Redirect(reverse('kolstat-train', args=[train.operator, train.number])) else: form = AddTrainForm() return dict(form = form)
#!/usr/bin/env python2 # coding: utf-8 import os,sys os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings' sys.path.extend(('../..', '../../..')) from kolstatapp.models import Train from .normal_to_hafas import save_cache, acquire x = input('Podaj pociąg (np. KM 6010) ').strip() if ' ' in x: oper, numer = x.split(' ') else: oper = '' numer = x tt = Train.search(x) if len(tt) > 0: t, = tt t.delete_train() else: print("Brak pociągu")
def train_date(request, operator, number, variant = None, date = None): res = Train.search(operator + ' ' + number, variant) if len(res) != 1: raise Redirect(reverse('kolstat-trains-search')) ktrain, = res d = datetime.datetime.strptime(date, '%Y-%m-%d').date() try: tt, = ktrain.traintimetable_set.filter(date = d).select_related() except ValueError: raise KolstatError('Pociąg nie kursuje w tym dniu') table = {} stations = [] trains = [tt] + tt.get_coupled() juz = 0 for t in trains: ans = [] for s in t.stops(): ans.append((s.station, s)) not_added=[] last = -1 for st, s in ans: if st in list(table.keys()): while len(table[st]) <= juz: table[st].append("") table[st].append(s) idx = stations.index(st) stations[idx:idx] = not_added last = idx + len(not_added) not_added = [] else: table[st] = [""] * juz + [s] not_added.append(st) stations[last+1:last+1] = not_added not_added = [] juz += 1 pres = [] for st in stations: while len(table[st]) < juz: table[st].append("") km = [] stops = [] short = False pocz = True kon = True for s in table[st]: if type(s) == type(""): km.append("") stops.append(None) else: km.append(s.distance) stops.append(s) short |= s.is_short() if s.arrival is not None: pocz = False if s.departure is not None: kon = False pres.append((km, st, short, pocz, kon, stops)) return dict(train = ktrain, timetable = tt, table = pres, ile = juz, trains = [x.train for x in trains])
def journeys(request): return dict(journeys = [(j, Train.fromHafas(HafasTrain.fromId(j.trainId))) for j in Journey.objects.filter(user = request.user).order_by('date')])
def import_train(yaml, mode, dijkstra_lock, mysql_lock): train = Train() name = yaml['name'] category, number = name.split(' ') try: with mysql_lock: t, = train.search(name, variant = yaml['variant']) except ValueError: pass else: if mode == 'force' or True: t.delete() else: return with mysql_lock: train.category = TrainCategory.objects.get(name = category) train.number = number train.variant = yaml['variant'] with mysql_lock: train.save() operations = yaml['operations'] for oper in operations: if oper['mode'] == 'interval': start = oper['from'] end = oper['to'] dates = [ end ] while start != end: dates.append(start) start += DZIEN elif oper['mode'] == 'single': dates = [ oper['date'] ] elif oper['mode'] == 'multi': dates = oper['dates'] timetable = oper['timetable'] tts = [] for i in dates: tts.append(TrainTimetable(train = train, date =i)) with mysql_lock: TrainTimetable.objects.bulk_create(tts) tts = train.traintimetable_set.all() ttbd = {} for x in tts: ttbd[x.date] = x stops = [] tt = ttbd[dates[0]] i = 1 prev = None arr_over = False for description in timetable: stop = TrainStop(timetable = tt) try: stop.station = Station.search(description['station'])[0] except IndexError: print(description) raise if 'departure' in description: stop.departure = datetime.combine(tt.date, time_from_yaml(description.get('departure', None))) if 'arrival' in description: stop.arrival = datetime.combine(tt.date, time_from_yaml(description.get('arrival', None))) stop.track = description.get('track', None) stop.platform = description.get('platform', None) stop.order = i if prev is not None: if arr_over or stop.arrival < prev.departure: # stop.arrival_overnight = 1 arr_over = True if arr_over or (stop.arrival is not None and stop.departure is not None and stop.arrival > stop.departure): # stop.departure_overnight = 1 arr_over = True if prev is None: stop.distance = 0.0 else: dijkstra_lock.acquire() stop.distance = prev.distance + Dijkstra.length(prev.station.gskID, stop.station.gskID) dijkstra_lock.release() prev = stop stops.append(stop) i += 1 with mysql_lock: TrainStop.objects.bulk_create(stops) cursor = connection.cursor() for d, tt in ttbd.items(): if d == dates[0]: continue tto = ttbd[dates[0]] ttn = ttbd[d] with mysql_lock: cursor.execute(''' INSERT INTO kolstatapp_trainstop (timetable_id, station_id, arrival, departure, track, platform, distance, "order") SELECT {0}, station_id, arrival + '{2} days', departure + '{2} days', track, platform, distance, "order" FROM kolstatapp_trainstop WHERE timetable_id = {1}'''.format(ttn.pk, tto.pk, (d - dates[0]).days)) with mysql_lock: transaction.commit_unless_managed()
#!/usr/bin/env python2 # coding: utf-8 import os,sys os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings' sys.path.extend(('../..', '../../..')) from kolstatapp.models import Train from .normal_to_hafas import save_cache, acquire x = input('Podaj pociąg (np. KM 6010) ').strip() tt = Train.search(x) if len(tt) > 0: t, = tt print("Było") else: t = Train.add_train(x) print(t.get_relation_string())
# coding: utf-8 import os,sys os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings' sys.path.extend(('../../../', '../../../../')) from kolstatapp.models import Train, Discount, TrainStop, Station from datetime import date discounts = Discount.objects.all() KM6014, = Train.search('KM 6014') TLK31108, = Train.search('TLK 31108') TLK15117, = Train.search('TLK 15117') RW, = Station.search('Ruda Wielka') RA, = Station.search('Radom') WW, = Station.search('Warszawa Wschodnia') GD, = Station.search('Gdynia Główna') dzien = date(2013, 1, 3) Ruda_Wielka = TrainStop.objects.get(timetable__date = dzien, timetable__train = KM6014, station = RW) Radom1 = TrainStop.objects.get(timetable__date = dzien, timetable__train = KM6014, station = RA) Radom2 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK31108, station = RA) WW1 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK31108, station = WW) WW2 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK15117, station = WW) Gdynia = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK15117, station = GD)