Return data from nearest city (IP or coordinates).
190226
async def nearest_city(
            self,
            latitude: Union[float, str] = None,
            longitude: Union[float, str] = None) -> dict:
        """"""
        return await self._nearest('city', latitude, longitude)
640031
function getNearestDataPoint2(mouseY) {
            let adjustedMouseY = mouseY - margin.bottom,
                epsilon = yScale.bandwidth(),
                nearest = [];

            layers.map(function (data) {
                let found = data.values.find((d2) => Math.abs(adjustedMouseY >= yScale(d2[nameLabel])) && Math.abs(adjustedMouseY - yScale(d2[nameLabel]) <= epsilon * 2));

                if (found) {
                    found.values = data.values;
                    found.key = found.name;
                    nearest.push(found)
                }
            });

            return nearest.length ? nearest[0] : undefined;
        }
129037
def _getdata(self, data_source, start=None, end=None):
        """"""
        assert start is not None or end is not None, 'should at least specify start or end'
        start = start if start is not None else 0
        if end is None:
            end = data_source[0][1].shape[0] if data_source else 0
        s = slice(start, end)
        return [
            x[1][s]
            if isinstance(x[1], (np.ndarray, NDArray)) else
            # h5py (only supports indices in increasing order)
            array(x[1][sorted(self.idx[s])][[
                list(self.idx[s]).index(i)
                for i in sorted(self.idx[s])
            ]]) for x in data_source
        ]
408761
def ip_to_geojson(ipaddress, name="Point"):
    """"""

    geo = ip_to_geo(ipaddress)

    point = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "name": name
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        geo["longitude"],
                        geo["latitude"]
                    ]
                }
            }
        ]
    }

    return point
3392
def Peripheral(self, data=None, subset=None):
        """"""
        return self.factory.get_object(jssobjects.Peripheral, data, subset)
181845
async def nearest_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """"""
        # Since user data is more granular than state or CDC data, find the
        # user report whose coordinates are closest to the provided
        # coordinates:
        nearest_user_report = get_nearest_by_coordinates(
            await self.user_reports(), 'latitude', 'longitude', latitude,
            longitude)

        try:
            # If the user report corresponds to a known state in
            # flunearyou.org's database, we can safely assume that's the
            # correct state:
            nearest_state = next((
                state for state in await self.state_data()
                if state['place_id'] == nearest_user_report['contained_by']))
        except StopIteration:
            # If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a
            # place ID), calculate the nearest state by measuring the distance
            # from the provided latitude/longitude to flunearyou.org's
            # latitude/longitude that defines each state:
            nearest_state = get_nearest_by_coordinates(
                await self.state_data(), 'lat', 'lon', latitude, longitude)

        return {'local': nearest_user_report, 'state': nearest_state}
1318297
def to_ip(self, values, from_unit):
        """"""
        if from_unit in self._ip_units:
            return values, from_unit
        elif from_unit == 'degC-hours':
            return self.to_unit(values, 'degF-hours', from_unit), 'degF-hours'
        else:
            return self.to_unit(values, 'degF-days', from_unit), 'degF-days'
1341039
def distance_to(self, other):
        """"""
        return np.linalg.norm(self.position-other.position)
589435
def to_ip(self, values, from_unit):
        """"""
        if from_unit in self.ip_units:
            return values, from_unit
        elif from_unit == 'tonne':
            return self.to_unit(values, 'ton', from_unit), 'ton'
        else:
            return self.to_unit(values, 'lb', from_unit), 'lb'
34553
def local_ip():
    """"""
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith('127.'):
        # Check eth0, eth1, eth2, en0, ...
        interfaces = [
            i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
        ]  # :(
        for interface in interfaces:
            try:
                ip = interface_ip(interface)
                break
            except IOError:
                pass
    return ip
197555
def getlocals(back=2):
    """"""
    import inspect
    fr = inspect.currentframe()
    try:
        while fr and back != 0:
            fr1 = fr
            fr = fr.f_back
            back -= 1
    except:
        pass
    return fr1.f_locals
472063
async def city(self, city: str, state: str, country: str) -> dict:
        """"""
        data = await self._request(
            'get',
            'city',
            params={
                'city': city,
                'state': state,
                'country': country
            })
        return data['data']
1212169
def get_dataset(self, key, info, out=None):
        """"""

        logger.debug("Reading %s.", key.name)
        values = self.file_content[key.name]
        selected = np.array(self.selected)
        if key.name in ("Latitude", "Longitude"):
            values = values / 10000.
        if key.name in ('Tsurf', 'CloudTopPres', 'CloudTopTemp'):
            goods = values > -9998.
            selected = np.array(selected & goods)
            if key.name in ('Tsurf', "Alt_surface", "CloudTopTemp"):
                values = values / 100.
            if key.name in ("CloudTopPres"):
                values = values / 10.
        else:
            selected = self.selected
        info.update(self.finfo)

        fill_value = np.nan

        if key.name == 'ct':
            fill_value = 0
            info['_FillValue'] = 0
        ds = DataArray(values, dims=['y', 'x'], attrs=info).where(selected, fill_value)

        # update dataset info with file_info
        return ds
423360
def _get_local_ip(self):
        """"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # Use Google Public DNS server to determine own IP
            sock.connect(('8.8.8.8', 80))

            return sock.getsockname()[0]
        except socket.error:
            try:
                return socket.gethostbyname(socket.gethostname())
            except socket.gaierror:
                return '127.0.0.1'
        finally:
            sock.close()
502829
def get_data(self):
        """"""
        url = self.build_url()
        self.locationApiData = requests.get(url)
        if not self.locationApiData.status_code == 200:
            raise self.locationApiData.raise_for_status()
1110225
def datapoint(self, ind):
        
        if self.height is None:
            return self.data[ind]
        return self.data[ind, ...].copy()
1314249
def find_nearest_index(arr, value):
    """"""
    arr = np.array(arr)
    index = (abs(arr-value)).argmin()
    return index