Get departure information.
172338
def departure(stop, destination):
    """"""
    from pyruter.api import Departures

    async def get_departures():
        """"""
        async with aiohttp.ClientSession() as session:
            data = Departures(LOOP, stop, destination, session)
            await data.get_departures()
            print(json.dumps(data.departures, indent=4, sort_keys=True))
    LOOP.run_until_complete(get_departures())
1008837
def get_info(self, key=None, Id=None) -> dict:
        """"""
        if key is not None:
            Id = self[key].Id
        return self.infos.get(Id,{})
1044488
def number(self) -> Optional[Union[str, Set[str]]]:
        """"""
        if "number" not in self.data.columns:
            return None
        if all(self.data.number.isna()):
            return None
        tmp = set(self.data.number)
        if len(tmp) == 1:
            return tmp.pop()
        logging.warn("Several numbers for one flight, consider splitting")
        return tmp
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]]
1088223
def get_data(self):
        """"""
        data = {}
        data['guarded'] = self.guarded[:]
        data['voiced'] = copy.deepcopy(self.voiced)
        data['opers'] = copy.deepcopy(self.opers)
        data['features'] = self.features.copy()
        data['uptime'] = self.uptime.copy()
        data['abuselist'] = self.abuselist.copy()
        data['who_map'] = self.who_map.copy()
        return data
536262
def get_route_to(self, destination='', protocol=''):
        """"""

        # Note, it should be possible to query the FIB:
        # "<show><routing><fib></fib></routing></show>"
        # To add informations to this getter
        routes = {}

        if destination:
            destination = "<destination>{0}</destination>".format(destination)
        if protocol:
            protocol = "<type>{0}</type>".format(protocol)

        cmd = "<show><routing><route>{0}{1}</route></routing></show>".format(protocol, destination)
        try:
            self.device.op(cmd=cmd)
            routes_table_xml = xmltodict.parse(self.device.xml_root())
            routes_table_json = json.dumps(routes_table_xml['response']['result']['entry'])
            routes_table = json.loads(routes_table_json)
        except (AttributeError, KeyError):
            routes_table = []

        if isinstance(routes_table, dict):
            routes_table = [routes_table]

        for route in routes_table:
            d = {
                'current_active': False,
                'last_active': False,
                'age': -1,
                'next_hop': u'',
                'protocol': u'',
                'outgoing_interface': u'',
                'preference': -1,
                'inactive_reason': u'',
                'routing_table': u'default',
                'selected_next_hop': False,
                'protocol_attributes': {}
            }
            destination = route['destination']
            flags = route['flags']

            if 'A' in flags:
                d['current_active'] = True
            else:
                d['current_active'] = False
            if 'C' in flags:
                d['protocol'] = "connect"
            if 'S' in flags:
                d['protocol'] = "static"
            if 'R' in flags:
                d['protocol'] = "rip"
            if 'R' in flags:
                d['protocol'] = "rip"
            if 'O' in flags:
                d['protocol'] = "ospf"
            if 'B' in flags:
                d['protocol'] = "bgp"
            if 'H' in flags:
                d['protocol'] = "host"
            if route['age'] is not None:
                d['age'] = int(route['age'])
            if route['nexthop'] is not None:
                d['next_hop'] = route['nexthop']
            if route['interface'] is not None:
                d['outgoing_interface'] = route['interface']
            if route['metric'] is not None:
                d['preference'] = int(route['metric'])
            if route['virtual-router'] is not None:
                d['routing_table'] = route['virtual-router']

            if destination not in routes.keys():
                routes[destination] = []
            routes[destination].append(d)

        return routes
186488
def get_departures(self, stop_id, route, destination, api_key):
        """"""
        self.stop_id = stop_id
        self.route = route
        self.destination = destination
        self.api_key = api_key

        # Build the URL including the STOP_ID and the API key
        url = \
            'https://api.transport.nsw.gov.au/v1/tp/departure_mon?' \
            'outputFormat=rapidJSON&coordOutputFormat=EPSG%3A4326&' \
            'mode=direct&type_dm=stop&name_dm=' \
            + self.stop_id \
            + '&departureMonitorMacro=true&TfNSWDM=true&version=10.2.1.42'
        auth = 'apikey ' + self.api_key
        header = {'Accept': 'application/json', 'Authorization': auth}

        # Send query or return error
        try:
            response = requests.get(url, headers=header, timeout=10)
        except:
            logger.warning("Network or Timeout error")
            return self.info

        # If there is no valid request
        if response.status_code != 200:
            logger.warning("Error with the request sent; check api key")
            return self.info

        # Parse the result as a JSON object
        result = response.json()

        # If there is no stop events for the query
        try:
            result['stopEvents']
        except KeyError:
            logger.warning("No stop events for this query")
            return self.info

        # Set variables
        maxresults = 1
        monitor = []
        if self.destination != '':
            for i in range(len(result['stopEvents'])):
                destination = result['stopEvents'][i]['transportation']['destination']['name']
                if destination == self.destination:
                    event = self.parseEvent(result, i)
                    if event != None:
                        monitor.append(event)
                    if len(monitor) >= maxresults:
                        # We found enough results, lets stop
                        break
        elif self.route != '':
            # Find the next stop events for a specific route
            for i in range(len(result['stopEvents'])):
                number = result['stopEvents'][i]['transportation']['number']
                if number == self.route:
                    event = self.parseEvent(result, i)
                    if event != None:
                        monitor.append(event)
                    if len(monitor) >= maxresults:
                        # We found enough results, lets stop
                        break
        else:
            # No route defined, find any route leaving next
            for i in range(0, maxresults):
                event = self.parseEvent(result, i)
                if event != None:
                    monitor.append(event)
        if monitor:
            self.info = {
                ATTR_STOP_ID: self.stop_id,
                ATTR_ROUTE: monitor[0][0],
                ATTR_DUE_IN: monitor[0][1],
                ATTR_DELAY: monitor[0][2],
                ATTR_REALTIME: monitor[0][5],
                ATTR_DESTINATION: monitor[0][6],
                ATTR_MODE: monitor[0][7]
                }
        return self.info
1313766
def get_visit_fn(cls, kind, is_leaving=False) -> Callable:
        """"""
        method = "leave" if is_leaving else "enter"
        visit_fn = getattr(cls, f"{method}_{kind}", None)
        if not visit_fn:
            visit_fn = getattr(cls, method, None)
        return visit_fn
220514
def check(self):
        '''
        '''

        for info in self.get_info():
            if info.free < info.limit:
                return info
26920
async def get_departures(
        self,
        station_id: str,
        direction_id: Optional[str] = None,
        max_journeys: int = 20,
        products: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        """"""
        self.station_id: str = station_id
        self.direction_id: str = direction_id

        self.max_journeys: int = max_journeys

        self.products_filter: str = _product_filter(products or ALL_PRODUCTS)

        base_url: str = _base_url()
        params: Dict[str, Union[str, int]] = {
            "selectDate": "today",
            "time": "now",
            "input": self.station_id,
            "maxJourneys": self.max_journeys,
            "boardType": "dep",
            "productsFilter": self.products_filter,
            "disableEquivs": "discard_nearby",
            "output": "xml",
            "start": "yes",
        }
        if self.direction_id:
            params["dirInput"] = self.direction_id

        url = base_url + urllib.parse.urlencode(params)

        try:
            with async_timeout.timeout(self._timeout):
                async with self._session.get(url) as response:
                    _LOGGER.debug(f"Response from RMV API: {response.status}")
                    xml = await response.read()
                    _LOGGER.debug(xml)
        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Can not load data from RMV API")
            raise RMVtransportApiConnectionError()

        # pylint: disable=I1101
        try:
            self.obj = objectify.fromstring(xml)
        except (TypeError, etree.XMLSyntaxError):
            _LOGGER.debug(f"Get from string: {xml[:100]}")
            print(f"Get from string: {xml}")
            raise RMVtransportError()

        try:
            self.now = self.current_time()
            self.station = self._station()
        except (TypeError, AttributeError):
            _LOGGER.debug(
                f"Time/Station TypeError or AttributeError {objectify.dump(self.obj)}"
            )
            raise RMVtransportError()

        self.journeys.clear()
        try:
            for journey in self.obj.SBRes.JourneyList.Journey:
                self.journeys.append(RMVJourney(journey, self.now))
        except AttributeError:
            _LOGGER.debug(f"Extract journeys: {objectify.dump(self.obj.SBRes)}")
            raise RMVtransportError()

        return self.data()
548359
def output(self) -> None:
        """"""
        print("%s - %s" % (self.station, self.now))
        print(self.products_filter)

        for j in sorted(self.journeys, key=lambda k: k.real_departure)[
            : self.max_journeys
        ]:
            print("-------------")
            print(f"{j.product}: {j.number} ({j.train_id})")
            print(f"Richtung: {j.direction}")
            print(f"Abfahrt in {j.real_departure} min.")
            print(f"Abfahrt {j.departure.time()} (+{j.delay})")
            print(f"Nächste Haltestellen: {([s['station'] for s in j.stops])}")
            if j.info:
                print(f"Hinweis: {j.info}")
                print(f"Hinweis (lang): {j.info_long}")
            print(f"Icon: {j.icon}")
673526
def GetCountStopTimes(self):
    """"""
    cursor = self._schedule._connection.cursor()
    cursor.execute(
        'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
    return cursor.fetchone()[0]
530839
def get_all_outgoings(chebi_ids):
    ''''''
    all_outgoings = [get_outgoings(chebi_id) for chebi_id in chebi_ids]
    return [x for sublist in all_outgoings for x in sublist]
849825
def get_departures(self, station):
        
        url = 'http://webservices.ns.nl/ns-api-avt?station=' + station

        raw_departures = self._request('GET', url)
        return self.parse_departures(raw_departures)
670012
def trips(self):
    """"""
    trips = set()
    for route in self.routes():
      trips |= route.trips()
    return trips
880033
def journey_options(origin:      str,
                    destination: str,
                    via:         t.Optional[str]=None,
                    before:      t.Optional[int]=None,
                    after:       t.Optional[int]=None,
                    time:        t.Optional[datetime]=None,
                    hsl:         t.Optional[bool]=None,
                    year_card:   t.Optional[bool]=None) -> (
                        snug.Query[t.List[Journey]]):
    """"""
    return snug.GET('treinplanner', params={
        'fromStation':     origin,
        'toStation':       destination,
        'viaStation':      via,
        'previousAdvices': before,
        'nextAdvices':     after,
        'dateTime':        time,
        'hslAllowed':      hsl,
        'yearCard':        year_card,
    })
486611
def get_data(self):
        """"""
        url = self.build_url()
        self.incidents_data = requests.get(url)
        if not self.incidents_data.status_code == 200:
            raise self.incidents_data.raise_for_status()