Look for the train actually leaving at time
426681
def get_actual(cls, trip_list, time):
        
        for trip in trip_list:
            if simple_time(trip.departure_time_planned) == time:
                return trip
        return None
547470
def handle_json_GET_stoptrips(self, params):
    """"""
    schedule = self.server.schedule
    stop = schedule.GetStop(params.get('stop', None))
    time = int(params.get('time', 0))
    date = params.get('date', "")

    time_trips = stop.GetStopTimeTrips(schedule)
    time_trips.sort()  # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
    # Keep the first 5 after param 'time'.
    # Need make a tuple to find correct bisect point
    time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
    time_trips = time_trips[:5]
    # TODO: combine times for a route to show next 2 departure times
    result = []
    for time, (trip, index), tp in time_trips:
      service_id = trip.service_id
      service_period = schedule.GetServicePeriod(service_id)
      if date and not service_period.IsActiveOn(date):
        continue
      headsign = None
      # Find the most recent headsign from the StopTime objects
      for stoptime in trip.GetStopTimes()[index::-1]:
        if stoptime.stop_headsign:
          headsign = stoptime.stop_headsign
          break
      # If stop_headsign isn't found, look for a trip_headsign
      if not headsign:
        headsign = trip.trip_headsign
      route = schedule.GetRoute(trip.route_id)
      trip_name = ''
      if route.route_short_name:
        trip_name += route.route_short_name
      if route.route_long_name:
        if len(trip_name):
          trip_name += " - "
        trip_name += route.route_long_name
      if headsign:
        trip_name += " (Direction: %s)" % headsign

      result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
    return result
450631
private List<StationStats> getStationStats(List<Short> stations, VoltTable[] lastDepartResult) {
        final List<StationStats> stationStats = new ArrayList<>(stations.size());
        for (int i = 0; i < stations.size(); i++) {
            final short station = stations.get(i);
            TimestampType lastDepartTime;
            if (lastDepartResult[i].advanceRow()) {
                lastDepartTime = lastDepartResult[i].getTimestampAsTimestamp("last_depart");
            } else {
                lastDepartTime = new TimestampType(0);
            }
            voltQueueSQL(getTrainDeparts, station, lastDepartTime);
            final VoltTable departResult = voltExecuteSQL()[0];

            while (departResult.advanceRow()) {
                final TimestampType departTime = departResult.getTimestampAsTimestamp("time");
                voltQueueSQL(getWaitTimeForTrain, departTime, station, lastDepartTime, departTime);
                lastDepartTime = departTime;
            }

            long totalWaitTime = 0;
            long totalEntries = 0;
            if (departResult.getRowCount() > 0) {
                final VoltTable[] waitTimeResult = voltExecuteSQL();
                for (VoltTable res : waitTimeResult) {
                    if (res.advanceRow()) {
                        final long entries = res.getLong("entries");
                        final long waitTime = res.getLong("wait_sum");
                        // Don't record empty train
                        if (entries > 0) {
                            totalEntries += entries;
                            totalWaitTime += waitTime;
                        }
                    }
                }
            }

            stationStats.add(new StationStats(station, lastDepartTime, totalWaitTime, totalEntries));
        }
        return stationStats;
    }
155394
def stop_tracking(self, end_time = None):
        """"""
        end_time = timegm((end_time or dt.datetime.now()).timetuple())
        return self.conn.StopTracking(end_time)
1258278
def get_next_departures(stop, filter_line=None, num_line_groups=1, verbose=False):
    

    # Get departures table from online service
    # (great: we don't have to iterate over multiple pages).

    url = BVG_URL_PAT % stop
    if verbose:
        print('- Fetching table for URL "%s".' % url)
    try:
        tables = pd.read_html(url.encode('utf-8'))
    except urllib.error.URLError:
        msg = 'Not connected to the internet?'
        termcolor.cprint(msg, 'red', attrs=['bold'])
        sys.exit(1)
    except ValueError:
        return []
    table = tables[0]
    table.columns = ['Departure', 'Line', 'Destination']

    if verbose:
        print('- Got table with %d entries for "%s".' % (len(table), stop))

    # Cleanup

    # Drop entries with '*' in column Departure...
    # (causes trouble when resulting in an empty table!)
    # table = table[table.Departure.apply(lambda row: " *" not in row)]
    # So, instead remove '*' in column Departure...
    table.is_copy = False # prevents SettingWithCopyWarning
    table.Departure = table.apply(
        lambda row: re.sub('\s*\*\s*', '', row.Departure), axis=1)

    # Replace regex ' +' with ' ' in column Line...
    table.Line = table.apply(lambda row: re.sub(' +', ' ', row.Line), axis=1)

    # Filter desired number of unique combinations of Line and Destination column.
    indices = []
    for i in range(num_line_groups):
        try:
            indices += sorted([tab.index.values[i] 
                for line_dest, tab in table.groupby(['Line', 'Destination'])])
        except IndexError:
            break
    table = table[table.index.map(lambda x: x in indices)]

    # Insert a left-most column with minutes and seconds from now 
    # until the departure time.
    table.insert(0, "Wait", table.Departure.apply(lambda dep: wait_time(dep)))

    # Filter on desired lines only
    if filter_line:
        table = table[table.Line.apply(
            lambda cell: filter_line.lower().encode('utf-8') in cell.lower())]

    return table
280230
private function findLastRoute()
    {
        $method = $this->lastRouteMethod;
        $index = count($this->routes[$method])-1;

        return $this->routes[$method][$index];
    }
504691
def trains(self):
        """"""
        for row in self._rows:
            train_no = row.get('station_train_code')
            initial = train_no[0].lower()
            if not self._opts or initial in self._opts:
                train = [
                    # Column: '车次'
                    train_no,
                    # Column: '车站'
                    '\n'.join([
                        colored.green(row.get('from_station_name')),
                        colored.red(row.get('to_station_name')),
                    ]),
                    # Column: '时间'
                    '\n'.join([
                        colored.green(row.get('start_time')),
                        colored.red(row.get('arrive_time')),
                    ]),
                    # Column: '历时'
                    self._get_duration(row),
                    # Column: '商务'
                    row.get('swz_num'),
                    # Column: '一等'
                    row.get('zy_num'),
                    # Column: '二等'
                    row.get('ze_num'),
                    # Column: '软卧'
                    row.get('rw_num'),
                    # Column: '硬卧'
                    row.get('yw_num'),
                    # Column: '软座'
                    row.get('rz_num'),
                    # Column: '硬座'
                    row.get('yz_num'),
                    # Column: '无座'
                    row.get('wz_num')
                ]
                yield train
1243662
def _delay(self) -> int:
        """"""
        try:
            return int(self.journey.MainStop.BasicStop.Dep.Delay.text)
        except AttributeError:
            return 0
176114
def record_leaving(self, time, code, frame_key, parent_stats):
        """"""
        try:
            stats = parent_stats.get_child(code)
            time_entered = self._times_entered.pop((code, frame_key))
        except KeyError:
            return
        time_elapsed = time - time_entered
        stats.deep_time += max(0, time_elapsed)
26766
def GetTimeSecs(self):
    """"""
    if self.arrival_secs != None:
      return self.arrival_secs
    elif self.departure_secs != None:
      return self.departure_secs
    else:
      return None
326918
public function actionTrack(): void
	{
		if ($this->getPost('leave')) {
			$this->tracking->leave();
		}
		if ($this->getPost('url')) {
			$this->tracking->track();
		}
		$this->terminate();
	}
123889
def get_routes(departure, dest, vehicle='vlakbus', time='', date=''):
    """"""

    def _get_leaf_element(table, path):
        """Returns leaf element's text in given path"""
        res = table.xpath(path + '/*[not(*)]')
        if res:
            return res[0].text
        return table.xpath(path + '/text()')[0]

    if time == '':
        time = datetime.datetime.now().strftime('%H:%M')

    if date == '':
        date = datetime.datetime.now().strftime('%d.%m.%Y')

    try:
        req = requests.get(CPSK_URL.format(vehicle),
                           params={'date': date, 'time': time, 'f': departure,
                                   't': dest, 'submit': 'true'})
    except:
        return False

    tree = html.fromstring(req.text)
    html_tables = tree.xpath('//div[@id="main-res-inner"]/table/tbody')
    routes = []

    for table in html_tables:
        drive = Drive()
        datalen = len(table.xpath('./tr'))

        prevdate = ''
        for i in range(1, datalen-1):
            line = Line()
            trf = './tr[' + str(i) + ']'
            trt = './tr[' + str(i+1) + ']'
            line.f = _get_leaf_element(table, trf + '/td[3]')
            line.t = _get_leaf_element(table, trt + '/td[3]')
            line.departure = _get_leaf_element(table, trf + '/td[5]')
            line.arrival = _get_leaf_element(table, trt + '/td[4]')
            line.vehicle = table.xpath(trf + '/td[7]/img[1]')[0] \
                                .get('title').replace('Autobus', 'Bus')
            if line.vehicle == 'Presun':
                line.walk_duration = table.xpath(trf + '/td[7]/text()')[0] \
                    .replace('Presun asi ', '')

            delay = table.xpath(trf + '/td[7]/div[1]/' +
                                'span[@class!="nodelay"]/text()')
            if delay and delay[0] is not u'Aktuálne bez meškania':
                mins = delay[0].replace(u'Aktuálne meškanie ', '') \
                               .replace(u' minúty', '') \
                               .replace(u' minútu', '') \
                               .replace(u' minút', '')

                minstr = 'minutes' if mins is not '1' else 'minute'

                line.delay = ' ({0} {1} delay)'.format(mins, minstr)

            platform = table.xpath(trf + '/td[6]/span[1]/text()')
            platform2 = table.xpath(trf + '/td[6]/table/tr[1]/' +
                                    'td[1]/span[1]/text()')
            if platform:
                line.platform = '[{0}]'.format(platform[0])
            elif platform2:
                line.platform = '[{0}]'.format(platform2[0])

            _date = table.xpath(trf + '/td[2]/text()')[0]
            if _date is not ' ':
                prevdate = _date
            line.date = prevdate

            drive.lines.append(line)

        drive.duration = table.xpath('./tr[' + str(datalen) +
                                     ']/td[3]/p/strong[1]/text()')[0]

        try:
            drive.distance = table.xpath('./tr[' + str(datalen) +
                                         ']/td[3]/p/strong[2]/text()')[0]
        except IndexError:
            drive.distance = 'Distance not known'

        routes.append(drive)

    return routes
153579
def go(self):
        
        DEBUG and self._name and Log.note("GO! {{name|quote}}", name=self.name)

        if self._go:
            return

        with self.lock:
            if self._go:
                return
            self._go = True

        DEBUG and self._name and Log.note("internal GO! {{name|quote}}", name=self.name)
        jobs, self.job_queue = self.job_queue, None
        threads, self.waiting_threads = self.waiting_threads, None

        if threads:
            DEBUG and self._name and Log.note("Release {{num}} threads", num=len(threads))
            for t in threads:
                t.release()

        if jobs:
            for j in jobs:
                try:
                    j()
                except Exception as e:
                    Log.warning("Trigger on Signal.go() failed!", cause=e)
1013078
def left(self):
        """"""
        if self._has_real():
            return self._data.real_left
        return self._data.left
847560
function now() {
      var pos = {line: line, column: column}

      pos.offset = self.toOffset(pos)

      return pos
    }
310699
def get_train_stops(self, train_code, date=None):
        
        if date is None:
            date = datetime.date.today().strftime("%d %B %Y")

        url = self.api_base_url + 'getTrainMovementsXML'
        params = {
            'TrainId': train_code,
            'TrainDate': date
        }

        response = requests.get(
            url, params=params, timeout=10)

        if response.status_code != 200:
            return []

        return self._parse_train_movement_data(response.content)
551088
function touchEnd(element, clientX, clientY) {
  element[symbols.dragging] = false;
  if (element[deltaXSymbol] >= 20) {
    // Finished going right at high speed.
    element[symbols.goLeft]();
  } else if (element[deltaXSymbol] <= -20) {
    // Finished going left at high speed.
    element[symbols.goRight]();
  } else {
    // Finished at low speed.
    trackTo(element, clientX);
    const travelFraction = element.travelFraction;
    if (travelFraction >= 0.5) {
      element[symbols.goRight]();
    } else if (travelFraction <= -0.5) {
      element[symbols.goLeft]();
    }
  }
  element.travelFraction = 0;
  element[deltaXSymbol] = null;
  element[deltaYSymbol] = null;
}