departures for a station
183745
def departures(station: str) -> snug.Query[t.List[Departure]]:
    """"""
    return snug.GET('avt', params={'station': station})
1303805
def handle_json_GET_triprows(self, params):
    """"""
    schedule = self.server.schedule
    try:
      trip = schedule.GetTrip(params.get('trip', None))
    except KeyError:
      # if a non-existent trip is searched for, the return nothing
      return
    route = schedule.GetRoute(trip.route_id)
    trip_row = dict(trip.iteritems())
    route_row = dict(route.iteritems())
    return [['trips.txt', trip_row], ['routes.txt', route_row]]
960945
def extract_current_routine(page, stations):
    '''
    '''
    current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text())
    if not current_routines:
        return

    terminal_station = stations['stations'][-1]
    for routine in current_routines:
        if _(routine[0]) == terminal_station:
            distance = int(routine[1])
    stations_to_this_dir = stations['terminal'][terminal_station]

    waiting_station = _(page('.now .stateName').val())
    idx = stations_to_this_dir.index(waiting_station)
    bus_station = stations_to_this_dir[idx - distance + 1]

    return {
        'destinate_station': terminal_station,
        'bus_station': bus_station,
        'waiting_station': waiting_station,
        'distance': distance
    }
419850
public synchronized void onTransportIdle() {
    if (keepAliveDuringTransportIdle) {
      return;
    }
    if (state == State.PING_SCHEDULED || state == State.PING_DELAYED) {
      state = State.IDLE;
    }
    if (state == State.PING_SENT) {
      state = State.IDLE_AND_PING_SENT;
    }
  }
246387
private StationStats getStationStats(short station, VoltTable[] lastDepartResult) {
        TimestampType lastDepartTime;
        if (lastDepartResult[0].advanceRow()) {
            lastDepartTime = lastDepartResult[0].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;
                    }
                }
            }
        }

        return new StationStats(station, lastDepartTime, totalWaitTime, totalEntries);
    }
77602
def check_stop_times(
    feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
    
    table = "stop_times"
    problems = []

    # Preliminary checks
    if feed.stop_times is None:
        problems.append(["error", "Missing table", table, []])
    else:
        f = feed.stop_times.copy().sort_values(["trip_id", "stop_sequence"])
        problems = check_for_required_columns(problems, table, f)
    if problems:
        return format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    # Check trip_id
    problems = check_column_linked_id(
        problems, table, f, "trip_id", feed.trips
    )

    # Check arrival_time and departure_time
    v = lambda x: pd.isnull(x) or valid_time(x)
    for col in ["arrival_time", "departure_time"]:
        problems = check_column(problems, table, f, col, v)

    # Check that arrival and departure times exist for the first and last
    # stop of each trip and for each timepoint.
    # For feeds with many trips, iterating through the stop time rows is
    # faster than uisg groupby.
    if "timepoint" not in f.columns:
        f["timepoint"] = np.nan  # This will not mess up later timepoint check

    indices = []
    prev_tid = None
    prev_atime = 1
    prev_dtime = 1
    for i, tid, atime, dtime, tp in f[
        ["trip_id", "arrival_time", "departure_time", "timepoint"]
    ].itertuples():
        if tid != prev_tid:
            # Check last stop of previous trip
            if pd.isnull(prev_atime) or pd.isnull(prev_dtime):
                indices.append(i - 1)
            # Check first stop of current trip
            if pd.isnull(atime) or pd.isnull(dtime):
                indices.append(i)
        elif tp == 1 and (pd.isnull(atime) or pd.isnull(dtime)):
            # Failure at timepoint
            indices.append(i)

        prev_tid = tid
        prev_atime = atime
        prev_dtime = dtime

    if indices:
        problems.append(
            [
                "error",
                "First/last/time point arrival/departure time missing",
                table,
                indices,
            ]
        )

    # Check stop_id
    problems = check_column_linked_id(
        problems, table, f, "stop_id", feed.stops
    )

    # Check for duplicated (trip_id, stop_sequence) pairs
    cond = f[["trip_id", "stop_sequence"]].dropna().duplicated()
    problems = check_table(
        problems, table, f, cond, "Repeated pair (trip_id, stop_sequence)"
    )

    # Check stop_headsign
    problems = check_column(
        problems, table, f, "stop_headsign", valid_str, column_required=False
    )

    # Check pickup_type and drop_off_type
    for col in ["pickup_type", "drop_off_type"]:
        v = lambda x: x in range(4)
        problems = check_column(
            problems, table, f, col, v, column_required=False
        )

    # Check if shape_dist_traveled decreases on a trip
    if "shape_dist_traveled" in f.columns:
        g = f.dropna(subset=["shape_dist_traveled"])
        indices = []
        prev_tid = None
        prev_dist = -1
        for i, tid, dist in g[["trip_id", "shape_dist_traveled"]].itertuples():
            if tid == prev_tid and dist < prev_dist:
                indices.append(i)

            prev_tid = tid
            prev_dist = dist

        if indices:
            problems.append(
                [
                    "error",
                    "shape_dist_traveled decreases on a trip",
                    table,
                    indices,
                ]
            )

    # Check timepoint
    v = lambda x: x in range(2)
    problems = check_column(
        problems, table, f, "timepoint", v, column_required=False
    )

    if include_warnings:
        # Check for duplicated (trip_id, departure_time) pairs
        cond = f[["trip_id", "departure_time"]].duplicated()
        problems = check_table(
            problems,
            table,
            f,
            cond,
            "Repeated pair (trip_id, departure_time)",
            "warning",
        )

    return format_problems(problems, as_df=as_df)
969378
public synchronized void onTransportTermination() {
    if (state != State.DISCONNECTED) {
      state = State.DISCONNECTED;
      if (shutdownFuture != null) {
        shutdownFuture.cancel(false);
      }
      if (pingFuture != null) {
        pingFuture.cancel(false);
        pingFuture = null;
      }
    }
  }
755959
def parse_departures(self, xml):
        
        obj = xmltodict.parse(xml)
        departures = []

        for departure in obj['ActueleVertrekTijden']['VertrekkendeTrein']:
            newdep = Departure(departure)
            departures.append(newdep)
            #print('-- dep --')
            #print(newdep.__dict__)
            #print(newdep.to_json())
            print(newdep.delay)

        return departures
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;
    }
1052089
public static final double departure(WayPoint loc1, WayPoint loc2)
    {
        return departure(loc2.getLatitude(), loc1.getLatitude());
    }
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
827113
def GetDirections(self, origin, destination, sensor = False, mode = None, waypoints = None, alternatives  = None, avoid = None, language  = None, units = None,
                        region = None, departure_time  = None, arrival_time = None):
        '''
        '''
        
        params = {
            'origin': origin,
            'destination': destination,
            'sensor': str(sensor).lower()
        }

        
        if mode:
            params['mode'] = mode
            
        if waypoints:
            params['waypoints'] = waypoints
            
        if alternatives:
            params['alternatives'] = alternatives
            
        if avoid:
            params['avoid'] = avoid
            
        if language:
            params['language'] = language
            
        if units:
            params['units'] = units
            
        if region:
            params['region'] = region
            
        if departure_time:
            params['departure_time'] = departure_time
            
        if arrival_time:
            params['arrival_time'] = arrival_time
        
        
        if not self.premier:
            url = self.get_url(params)
        else:
            url = self.get_signed_url(params)

        return self.GetService_url(url)
624375
def new_mapping(self, lineup, station, channel, channelMinor,
                   validFrom, validTo, onAirFrom, onAirTo):
        """"""

        if self.__v_mapping:
            # [Mapping: FL09567:X, 11097, 45, None, 2010-06-29 00:00:00.00, None, None, None]
            print("[Mapping: %s, %s, %s, %s, %s, %s, %s, %s]" % 
                  (lineup, station, channel, channelMinor, validFrom, validTo, 
                   onAirFrom, onAirTo))
121519
def _departure(self) -> datetime:
        """"""
        departure_time = datetime.strptime(
            self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M"
        ).time()
        if departure_time > (self.now - timedelta(hours=1)).time():
            return datetime.combine(self.now.date(), departure_time)
        return datetime.combine(self.now.date() + timedelta(days=1), departure_time)
197070
public VoltTable[] run(short station, long ttl_seconds) throws VoltAbortException {
        voltQueueSQL(getLastDeparts, station);

        // For each station, calculate the wait time between departures
        final StationStats stats = getStationStats(station, voltExecuteSQL());
        voltQueueSQL(updateWaitTime,
                        stats.station,
                        stats.lastDepartTime,
                        stats.totalTime,
                        stats.totalEntries);
        // Prune old data
        voltQueueSQL(deleteOldData, -ttl_seconds);

        return voltExecuteSQL(true);
    }
973617
def get_stations(self):
        
        request = requests.get("{}/stations".format(
            self.base_url))
        if request.status_code != 200:
            return None
        return request.json()
731869
def GetStopTimes(self, problems=None):
    """"""
    # In theory problems=None should be safe because data from database has been
    # validated. See comment in _LoadStopTimes for why this isn't always true.
    cursor = self._schedule._connection.cursor()
    cursor.execute(
        'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,'
        'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint '
        'FROM stop_times '
        'WHERE trip_id=? '
        'ORDER BY stop_sequence', (self.trip_id,))
    stop_times = []
    stoptime_class = self.GetGtfsFactory().StopTime
    if problems is None:
      # TODO: delete this branch when StopTime.__init__ doesn't need a
      # ProblemReporter
      problems = problems_module.default_problem_reporter
    for row in cursor.fetchall():
      stop = self._schedule.GetStop(row[6])
      stop_times.append(stoptime_class(problems=problems,
                                       stop=stop,
                                       arrival_secs=row[0],
                                       departure_secs=row[1],
                                       stop_headsign=row[2],
                                       pickup_type=row[3],
                                       drop_off_type=row[4],
                                       shape_dist_traveled=row[5],
                                       stop_sequence=row[7],
                                       timepoint=row[8]))
    return stop_times