repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
scivision/pymap3d
pymap3d/ned.py
ned2geodetic
def ned2geodetic(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters) """ x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
python
def ned2geodetic(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters) """ x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
[ "def", "ned2geodetic", "(", "n", ":", "float", ",", "e", ":", "float", ",", "d", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x", ",", "y", ",", "z", "=", "enu2ecef", "(", "e", ",", "n", ",", "-", "d", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "ecef2geodetic", "(", "x", ",", "y", ",", "z", ",", "ell", ",", "deg", "=", "deg", ")" ]
Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- lat : float target geodetic latitude lon : float target geodetic longitude h : float target altitude above geodetic ellipsoid (meters)
[ "Converts", "North", "East", "Down", "to", "target", "latitude", "longitude", "altitude" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L68-L107
train
237,000
scivision/pymap3d
pymap3d/ned.py
ned2ecef
def ned2ecef(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ return enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg)
python
def ned2ecef(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ return enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg)
[ "def", "ned2ecef", "(", "n", ":", "float", ",", "e", ":", "float", ",", "d", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "return", "enu2ecef", "(", "e", ",", "n", ",", "-", "d", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")" ]
North, East, Down to target ECEF coordinates Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters)
[ "North", "East", "Down", "to", "target", "ECEF", "coordinates" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L110-L146
train
237,001
scivision/pymap3d
pymap3d/ned.py
ecef2ned
def ecef2ned(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return n, e, -u
python
def ecef2ned(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return n, e, -u
[ "def", "ecef2ned", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "ecef2enu", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "n", ",", "e", ",", "-", "u" ]
Convert ECEF x,y,z to North, East, Down Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Results ------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters)
[ "Convert", "ECEF", "x", "y", "z", "to", "North", "East", "Down" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L149-L188
train
237,002
scivision/pymap3d
pymap3d/ned.py
ecef2nedv
def ecef2nedv(x: float, y: float, z: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enuv(x, y, z, lat0, lon0, deg=deg) return n, e, -u
python
def ecef2nedv(x: float, y: float, z: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters) """ e, n, u = ecef2enuv(x, y, z, lat0, lon0, deg=deg) return n, e, -u
[ "def", "ecef2nedv", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "ecef2enuv", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")", "return", "n", ",", "e", ",", "-", "u" ]
for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude deg : bool, optional degrees input/output (False: radians in/out) Results ------- (Vector) n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinate (meters)
[ "for", "VECTOR", "between", "two", "points" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/ned.py#L233-L268
train
237,003
scivision/pymap3d
pymap3d/vallado.py
azel2radec
def azel2radec(az_deg: float, el_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259 """ az = atleast_1d(az_deg) el = atleast_1d(el_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if az.shape != el.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') az = radians(az) el = radians(el) lat = radians(lat) lon = radians(lon) # %% Vallado "algorithm 28" p 268 dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) lha = arctan2(-(sin(az) * cos(el)) / cos(dec), (sin(el) - sin(lat) * sin(dec)) / (cos(dec) * cos(lat))) lst = datetime2sidereal(time, lon) # lon, ra in RADIANS """ by definition right ascension [0, 360) degrees """ return degrees(lst - lha) % 360, degrees(dec)
python
def azel2radec(az_deg: float, el_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259 """ az = atleast_1d(az_deg) el = atleast_1d(el_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if az.shape != el.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') az = radians(az) el = radians(el) lat = radians(lat) lon = radians(lon) # %% Vallado "algorithm 28" p 268 dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) lha = arctan2(-(sin(az) * cos(el)) / cos(dec), (sin(el) - sin(lat) * sin(dec)) / (cos(dec) * cos(lat))) lst = datetime2sidereal(time, lon) # lon, ra in RADIANS """ by definition right ascension [0, 360) degrees """ return degrees(lst - lha) % 360, degrees(dec)
[ "def", "azel2radec", "(", "az_deg", ":", "float", ",", "el_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "az", "=", "atleast_1d", "(", "az_deg", ")", "el", "=", "atleast_1d", "(", "el_deg", ")", "lat", "=", "atleast_1d", "(", "lat_deg", ")", "lon", "=", "atleast_1d", "(", "lon_deg", ")", "if", "az", ".", "shape", "!=", "el", ".", "shape", ":", "raise", "ValueError", "(", "'az and el must be same shape ndarray'", ")", "if", "not", "(", "lat", ".", "size", "==", "1", "and", "lon", ".", "size", "==", "1", ")", ":", "raise", "ValueError", "(", "'need one observer and one or more (az,el).'", ")", "if", "(", "(", "lat", "<", "-", "90", ")", "|", "(", "lat", ">", "90", ")", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'-90 <= lat <= 90'", ")", "az", "=", "radians", "(", "az", ")", "el", "=", "radians", "(", "el", ")", "lat", "=", "radians", "(", "lat", ")", "lon", "=", "radians", "(", "lon", ")", "# %% Vallado \"algorithm 28\" p 268", "dec", "=", "arcsin", "(", "sin", "(", "el", ")", "*", "sin", "(", "lat", ")", "+", "cos", "(", "el", ")", "*", "cos", "(", "lat", ")", "*", "cos", "(", "az", ")", ")", "lha", "=", "arctan2", "(", "-", "(", "sin", "(", "az", ")", "*", "cos", "(", "el", ")", ")", "/", "cos", "(", "dec", ")", ",", "(", "sin", "(", "el", ")", "-", "sin", "(", "lat", ")", "*", "sin", "(", "dec", ")", ")", "/", "(", "cos", "(", "dec", ")", "*", "cos", "(", "lat", ")", ")", ")", "lst", "=", "datetime2sidereal", "(", "time", ",", "lon", ")", "# lon, ra in RADIANS", "\"\"\" by definition right ascension [0, 360) degrees \"\"\"", "return", "degrees", "(", "lst", "-", "lha", ")", "%", "360", ",", "degrees", "(", "dec", ")" ]
converts azimuth, elevation to right ascension, declination Parameters ---------- az_deg : float or numpy.ndarray of float azimuth (clockwise) to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination of target [degrees] from D.Vallado Fundamentals of Astrodynamics and Applications p.258-259
[ "converts", "azimuth", "elevation", "to", "right", "ascension", "declination" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vallado.py#L19-L80
train
237,004
scivision/pymap3d
pymap3d/vallado.py
radec2azel
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268 """ ra = atleast_1d(ra_deg) dec = atleast_1d(dec_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if ra.shape != dec.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') ra = radians(ra) dec = radians(dec) lat = radians(lat) lon = radians(lon) lst = datetime2sidereal(time, lon) # RADIANS # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE lha = lst - ra # %% #Eq. 4-12 p. 267 el = arcsin(sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(lha)) # %% combine Eq. 4-13 and 4-14 p. 268 az = arctan2(-sin(lha) * cos(dec) / cos(el), (sin(dec) - sin(el) * sin(lat)) / (cos(el) * cos(lat))) return degrees(az) % 360.0, degrees(el)
python
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268 """ ra = atleast_1d(ra_deg) dec = atleast_1d(dec_deg) lat = atleast_1d(lat_deg) lon = atleast_1d(lon_deg) if ra.shape != dec.shape: raise ValueError('az and el must be same shape ndarray') if not(lat.size == 1 and lon.size == 1): raise ValueError('need one observer and one or more (az,el).') if ((lat < -90) | (lat > 90)).any(): raise ValueError('-90 <= lat <= 90') ra = radians(ra) dec = radians(dec) lat = radians(lat) lon = radians(lon) lst = datetime2sidereal(time, lon) # RADIANS # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE lha = lst - ra # %% #Eq. 4-12 p. 267 el = arcsin(sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(lha)) # %% combine Eq. 4-13 and 4-14 p. 268 az = arctan2(-sin(lha) * cos(dec) / cos(el), (sin(dec) - sin(el) * sin(lat)) / (cos(el) * cos(lat))) return degrees(az) % 360.0, degrees(el)
[ "def", "radec2azel", "(", "ra_deg", ":", "float", ",", "dec_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "ra", "=", "atleast_1d", "(", "ra_deg", ")", "dec", "=", "atleast_1d", "(", "dec_deg", ")", "lat", "=", "atleast_1d", "(", "lat_deg", ")", "lon", "=", "atleast_1d", "(", "lon_deg", ")", "if", "ra", ".", "shape", "!=", "dec", ".", "shape", ":", "raise", "ValueError", "(", "'az and el must be same shape ndarray'", ")", "if", "not", "(", "lat", ".", "size", "==", "1", "and", "lon", ".", "size", "==", "1", ")", ":", "raise", "ValueError", "(", "'need one observer and one or more (az,el).'", ")", "if", "(", "(", "lat", "<", "-", "90", ")", "|", "(", "lat", ">", "90", ")", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "'-90 <= lat <= 90'", ")", "ra", "=", "radians", "(", "ra", ")", "dec", "=", "radians", "(", "dec", ")", "lat", "=", "radians", "(", "lat", ")", "lon", "=", "radians", "(", "lon", ")", "lst", "=", "datetime2sidereal", "(", "time", ",", "lon", ")", "# RADIANS", "# %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE", "lha", "=", "lst", "-", "ra", "# %% #Eq. 4-12 p. 267", "el", "=", "arcsin", "(", "sin", "(", "lat", ")", "*", "sin", "(", "dec", ")", "+", "cos", "(", "lat", ")", "*", "cos", "(", "dec", ")", "*", "cos", "(", "lha", ")", ")", "# %% combine Eq. 4-13 and 4-14 p. 268", "az", "=", "arctan2", "(", "-", "sin", "(", "lha", ")", "*", "cos", "(", "dec", ")", "/", "cos", "(", "el", ")", ",", "(", "sin", "(", "dec", ")", "-", "sin", "(", "el", ")", "*", "sin", "(", "lat", ")", ")", "/", "(", "cos", "(", "el", ")", "*", "cos", "(", "lat", ")", ")", ")", "return", "degrees", "(", "az", ")", "%", "360.0", ",", "degrees", "(", "el", ")" ]
converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension to target [degrees] dec_deg : float or numpy.ndarray of float declination to target [degrees] lat_deg : float observer WGS84 latitude [degrees] lon_deg : float observer WGS84 longitude [degrees] time : datetime.datetime time of observation Results ------- az_deg : float or numpy.ndarray of float azimuth clockwise from north to point [degrees] el_deg : float or numpy.ndarray of float elevation above horizon to point [degrees] from D. Vallado "Fundamentals of Astrodynamics and Applications " 4th Edition Ch. 4.4 pg. 266-268
[ "converts", "right", "ascension", "declination", "to", "azimuth", "elevation" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/vallado.py#L83-L146
train
237,005
scivision/pymap3d
pymap3d/aer.py
ecef2aer
def ecef2aer(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] """ xEast, yNorth, zUp = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return enu2aer(xEast, yNorth, zUp, deg=deg)
python
def ecef2aer(x: float, y: float, z: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] """ xEast, yNorth, zUp = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg) return enu2aer(xEast, yNorth, zUp, deg=deg)
[ "def", "ecef2aer", "(", "x", ":", "float", ",", "y", ":", "float", ",", "z", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "xEast", ",", "yNorth", ",", "zUp", "=", "ecef2enu", "(", "x", ",", "y", ",", "z", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "enu2aer", "(", "xEast", ",", "yNorth", ",", "zUp", ",", "deg", "=", "deg", ")" ]
gives azimuth, elevation and slant range from an Observer to a Point with ECEF coordinates. ECEF input location is with units of meters Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters]
[ "gives", "azimuth", "elevation", "and", "slant", "range", "from", "an", "Observer", "to", "a", "Point", "with", "ECEF", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L10-L49
train
237,006
scivision/pymap3d
pymap3d/aer.py
geodetic2aer
def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters] """ e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg) return enu2aer(e, n, u, deg=deg)
python
def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters] """ e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg) return enu2aer(e, n, u, deg=deg)
[ "def", "geodetic2aer", "(", "lat", ":", "float", ",", "lon", ":", "float", ",", "h", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", "geodetic2enu", "(", "lat", ",", "lon", ",", "h", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", "=", "deg", ")", "return", "enu2aer", "(", "e", ",", "n", ",", "u", ",", "deg", "=", "deg", ")" ]
gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates. Parameters ---------- lat : float or numpy.ndarray of float target geodetic latitude lon : float or numpy.ndarray of float target geodetic longitude h : float or numpy.ndarray of float target altitude above geodetic ellipsoid (meters) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- az : float or numpy.ndarray of float azimuth el : float or numpy.ndarray of float elevation srange : float or numpy.ndarray of float slant range [meters]
[ "gives", "azimuth", "elevation", "and", "slant", "range", "from", "an", "Observer", "to", "a", "Point", "with", "geodetic", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L52-L90
train
237,007
scivision/pymap3d
pymap3d/aer.py
aer2geodetic
def aer2geodetic(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell=ell, deg=deg) return ecef2geodetic(x, y, z, ell=ell, deg=deg)
python
def aer2geodetic(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell=ell, deg=deg) return ecef2geodetic(x, y, z, ell=ell, deg=deg)
[ "def", "aer2geodetic", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "x", ",", "y", ",", "z", "=", "aer2ecef", "(", "az", ",", "el", ",", "srange", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", "=", "ell", ",", "deg", "=", "deg", ")", "return", "ecef2geodetic", "(", "x", ",", "y", ",", "z", ",", "ell", "=", "ell", ",", "deg", "=", "deg", ")" ]
gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- In reference ellipsoid system: lat : float or numpy.ndarray of float geodetic latitude lon : float or numpy.ndarray of float geodetic longitude alt : float or numpy.ndarray of float altitude above ellipsoid (meters)
[ "gives", "geodetic", "coordinates", "of", "a", "point", "with", "az", "el", "range", "from", "an", "observer", "at", "lat0", "lon0", "h0" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L93-L134
train
237,008
scivision/pymap3d
pymap3d/aer.py
eci2aer
def eci2aer(eci: Tuple[float, float, float], lat0: float, lon0: float, h0: float, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters] """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy)) return ecef2aer(ecef[:, 0], ecef[:, 1], ecef[:, 2], lat0, lon0, h0)
python
def eci2aer(eci: Tuple[float, float, float], lat0: float, lon0: float, h0: float, t: datetime, useastropy: bool = True) -> Tuple[float, float, float]: """ takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters] """ ecef = np.atleast_2d(eci2ecef(eci, t, useastropy)) return ecef2aer(ecef[:, 0], ecef[:, 1], ecef[:, 2], lat0, lon0, h0)
[ "def", "eci2aer", "(", "eci", ":", "Tuple", "[", "float", ",", "float", ",", "float", "]", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "t", ":", "datetime", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "ecef", "=", "np", ".", "atleast_2d", "(", "eci2ecef", "(", "eci", ",", "t", ",", "useastropy", ")", ")", "return", "ecef2aer", "(", "ecef", "[", ":", ",", "0", "]", ",", "ecef", "[", ":", ",", "1", "]", ",", "ecef", "[", ":", ",", "2", "]", ",", "lat0", ",", "lon0", ",", "h0", ")" ]
takes ECI coordinates of point and gives az, el, slant range from Observer Parameters ---------- eci : tuple [meters] Nx3 target ECI location (x,y,z) lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) t : datetime.datetime Observation time Returns ------- az : float azimuth to target el : float elevation to target srange : float slant range [meters]
[ "takes", "ECI", "coordinates", "of", "point", "and", "gives", "az", "el", "slant", "range", "from", "Observer" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L137-L170
train
237,009
scivision/pymap3d
pymap3d/aer.py
aer2eci
def aer2eci(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, t: datetime, ell=None, deg: bool = True, useastropy: bool = True) -> np.ndarray: """ gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell, deg) return ecef2eci(np.column_stack((x, y, z)), t, useastropy)
python
def aer2eci(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, t: datetime, ell=None, deg: bool = True, useastropy: bool = True) -> np.ndarray: """ gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) """ x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell, deg) return ecef2eci(np.column_stack((x, y, z)), t, useastropy)
[ "def", "aer2eci", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "h0", ":", "float", ",", "t", ":", "datetime", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "np", ".", "ndarray", ":", "x", ",", "y", ",", "z", "=", "aer2ecef", "(", "az", ",", "el", ",", "srange", ",", "lat0", ",", "lon0", ",", "h0", ",", "ell", ",", "deg", ")", "return", "ecef2eci", "(", "np", ".", "column_stack", "(", "(", "x", ",", "y", ",", "z", ")", ")", ",", "t", ",", "useastropy", ")" ]
gives ECI of a point from an observer at az, el, slant range Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) t : datetime.datetime Observation time Returns ------- Earth Centered Inertial x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters)
[ "gives", "ECI", "of", "a", "point", "from", "an", "observer", "at", "az", "el", "slant", "range" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L173-L215
train
237,010
scivision/pymap3d
pymap3d/aer.py
aer2ecef
def aer2ecef(az: float, el: float, srange: float, lat0: float, lon0: float, alt0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN """ # Origin of the local system in geocentric coordinates. x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg) # Convert Local Spherical AER to ENU e1, n1, u1 = aer2enu(az, el, srange, deg=deg) # Rotating ENU to ECEF dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) # Origin + offset from origin equals position in ECEF return x0 + dx, y0 + dy, z0 + dz
python
def aer2ecef(az: float, el: float, srange: float, lat0: float, lon0: float, alt0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN """ # Origin of the local system in geocentric coordinates. x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg) # Convert Local Spherical AER to ENU e1, n1, u1 = aer2enu(az, el, srange, deg=deg) # Rotating ENU to ECEF dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg) # Origin + offset from origin equals position in ECEF return x0 + dx, y0 + dy, z0 + dz
[ "def", "aer2ecef", "(", "az", ":", "float", ",", "el", ":", "float", ",", "srange", ":", "float", ",", "lat0", ":", "float", ",", "lon0", ":", "float", ",", "alt0", ":", "float", ",", "ell", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "# Origin of the local system in geocentric coordinates.", "x0", ",", "y0", ",", "z0", "=", "geodetic2ecef", "(", "lat0", ",", "lon0", ",", "alt0", ",", "ell", ",", "deg", "=", "deg", ")", "# Convert Local Spherical AER to ENU", "e1", ",", "n1", ",", "u1", "=", "aer2enu", "(", "az", ",", "el", ",", "srange", ",", "deg", "=", "deg", ")", "# Rotating ENU to ECEF", "dx", ",", "dy", ",", "dz", "=", "enu2uvw", "(", "e1", ",", "n1", ",", "u1", ",", "lat0", ",", "lon0", ",", "deg", "=", "deg", ")", "# Origin + offset from origin equals position in ECEF", "return", "x0", "+", "dx", ",", "y0", "+", "dy", ",", "z0", "+", "dz" ]
converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates. Parameters ---------- az : float or numpy.ndarray of float azimuth to target el : float or numpy.ndarray of float elevation to target srange : float or numpy.ndarray of float slant range [meters] lat0 : float Observer geodetic latitude lon0 : float Observer geodetic longitude h0 : float observer altitude above geodetic ellipsoid (meters) ell : Ellipsoid, optional reference ellipsoid deg : bool, optional degrees input/output (False: radians in/out) Returns ------- ECEF (Earth centered, Earth fixed) x,y,z x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.ndarray of float ECEF y coordinate (meters) z : float or numpy.ndarray of float ECEF z coordinate (meters) Notes ------ if srange==NaN, z=NaN
[ "converts", "target", "azimuth", "elevation", "range", "from", "observer", "at", "lat0", "lon0", "alt0", "to", "ECEF", "coordinates", "." ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/aer.py#L218-L267
train
237,011
scivision/pymap3d
pymap3d/lox.py
isometric
def isometric(lat: float, ell: Ellipsoid = None, deg: bool = True): """ computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 """ if ell is None: ell = Ellipsoid() f = ell.f # flattening of ellipsoid if deg is True: lat = np.deg2rad(lat) e2 = f * (2 - f) # eccentricity-squared e = np.sqrt(e2) # eccentricity of ellipsoid x = e * np.sin(lat) y = (1 - x) / (1 + x) z = np.pi / 4 + lat / 2 # calculate the isometric latitude isolat = np.log(np.tan(z) * (y**(e / 2))) if deg is True: isolat = np.degrees(isolat) return isolat
python
def isometric(lat: float, ell: Ellipsoid = None, deg: bool = True): """ computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 """ if ell is None: ell = Ellipsoid() f = ell.f # flattening of ellipsoid if deg is True: lat = np.deg2rad(lat) e2 = f * (2 - f) # eccentricity-squared e = np.sqrt(e2) # eccentricity of ellipsoid x = e * np.sin(lat) y = (1 - x) / (1 + x) z = np.pi / 4 + lat / 2 # calculate the isometric latitude isolat = np.log(np.tan(z) * (y**(e / 2))) if deg is True: isolat = np.degrees(isolat) return isolat
[ "def", "isometric", "(", "lat", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", ":", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "f", "=", "ell", ".", "f", "# flattening of ellipsoid", "if", "deg", "is", "True", ":", "lat", "=", "np", ".", "deg2rad", "(", "lat", ")", "e2", "=", "f", "*", "(", "2", "-", "f", ")", "# eccentricity-squared", "e", "=", "np", ".", "sqrt", "(", "e2", ")", "# eccentricity of ellipsoid", "x", "=", "e", "*", "np", ".", "sin", "(", "lat", ")", "y", "=", "(", "1", "-", "x", ")", "/", "(", "1", "+", "x", ")", "z", "=", "np", ".", "pi", "/", "4", "+", "lat", "/", "2", "# calculate the isometric latitude", "isolat", "=", "np", ".", "log", "(", "np", ".", "tan", "(", "z", ")", "*", "(", "y", "**", "(", "e", "/", "2", ")", ")", ")", "if", "deg", "is", "True", ":", "isolat", "=", "np", ".", "degrees", "(", "isolat", ")", "return", "isolat" ]
computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Returns ------- isolat : float or numpy.ndarray of float isometric latiude Notes ----- Isometric latitude is an auxiliary latitude proportional to the spacing of parallels of latitude on an ellipsoidal mercator projection. Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010
[ "computes", "isometric", "latitude", "of", "a", "point", "on", "an", "ellipsoid" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/lox.py#L6-L58
train
237,012
scivision/pymap3d
pymap3d/lox.py
loxodrome_inverse
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66. """ # set ellipsoid parameters if ell is None: ell = Ellipsoid() if deg is True: lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2]) # compute isometric latitude of P1 and P2 isolat1 = isometric(lat1, deg=False, ell=ell) isolat2 = isometric(lat2, deg=False, ell=ell) # compute changes in isometric latitude and longitude between points disolat = isolat2 - isolat1 dlon = lon2 - lon1 # compute azimuth az12 = np.arctan2(dlon, disolat) # compute distance along loxodromic curve m1 = meridian_dist(lat1, deg=False, ell=ell) m2 = meridian_dist(lat2, deg=False, ell=ell) dm = m2 - m1 lox_s = dm / np.cos(az12) if deg is True: az12 = np.degrees(az12) % 360. return lox_s, az12
python
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66. """ # set ellipsoid parameters if ell is None: ell = Ellipsoid() if deg is True: lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2]) # compute isometric latitude of P1 and P2 isolat1 = isometric(lat1, deg=False, ell=ell) isolat2 = isometric(lat2, deg=False, ell=ell) # compute changes in isometric latitude and longitude between points disolat = isolat2 - isolat1 dlon = lon2 - lon1 # compute azimuth az12 = np.arctan2(dlon, disolat) # compute distance along loxodromic curve m1 = meridian_dist(lat1, deg=False, ell=ell) m2 = meridian_dist(lat2, deg=False, ell=ell) dm = m2 - m1 lox_s = dm / np.cos(az12) if deg is True: az12 = np.degrees(az12) % 360. return lox_s, az12
[ "def", "loxodrome_inverse", "(", "lat1", ":", "float", ",", "lon1", ":", "float", ",", "lat2", ":", "float", ",", "lon2", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", ":", "# set ellipsoid parameters", "if", "ell", "is", "None", ":", "ell", "=", "Ellipsoid", "(", ")", "if", "deg", "is", "True", ":", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "=", "np", ".", "radians", "(", "[", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "]", ")", "# compute isometric latitude of P1 and P2", "isolat1", "=", "isometric", "(", "lat1", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "isolat2", "=", "isometric", "(", "lat2", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "# compute changes in isometric latitude and longitude between points", "disolat", "=", "isolat2", "-", "isolat1", "dlon", "=", "lon2", "-", "lon1", "# compute azimuth", "az12", "=", "np", ".", "arctan2", "(", "dlon", ",", "disolat", ")", "# compute distance along loxodromic curve", "m1", "=", "meridian_dist", "(", "lat1", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "m2", "=", "meridian_dist", "(", "lat2", ",", "deg", "=", "False", ",", "ell", "=", "ell", ")", "dm", "=", "m2", "-", "m1", "lox_s", "=", "dm", "/", "np", ".", "cos", "(", "az12", ")", "if", "deg", "is", "True", ":", "az12", "=", "np", ".", "degrees", "(", "az12", ")", "%", "360.", "return", "lox_s", ",", "az12" ]
computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or numpy.ndarray of float geodetic latitude of first point lon1 : float or numpy.ndarray of float geodetic longitude of first point lat2 : float or numpy.ndarray of float geodetic latitude of second point lon2 : float or numpy.ndarray of float geodetic longitude of second point ell : Ellipsoid, optional reference ellipsoid (default WGS84) deg : bool, optional degrees input/output (False: radians in/out) Results ------- lox_s : float or numpy.ndarray of float distance along loxodrome az12 : float or numpy.ndarray of float azimuth of loxodrome (degrees/radians) Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes, School of Mathematical and Geospatial Sciences, RMIT University, January 2010 [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985, pp.223-230. [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S. Geological Survey Professional Paper 1395. Washington, DC: U.S. Government Printing Office, pp.15-16 and pp. 44-45. [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and Cartography, Special Publication No. 251, Coast and Geodetic Survey, U.S. Department of Commerce, Washington, DC: U.S. Government Printing Office, p. 66.
[ "computes", "the", "arc", "length", "and", "azimuth", "of", "the", "loxodrome", "between", "two", "points", "on", "the", "surface", "of", "the", "reference", "ellipsoid" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/lox.py#L130-L202
train
237,013
scivision/pymap3d
pymap3d/eci.py
eci2ecef
def eci2ecef(eci: np.ndarray, time: datetime, useastropy: bool = True) -> np.ndarray: """ Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate """ useastropy = useastropy and Time if useastropy: gst = Time(time).sidereal_time('apparent', 'greenwich').radian else: gst = datetime2sidereal(time, 0.) gst = np.atleast_1d(gst) assert gst.ndim == 1 and isinstance(gst[0], float) # must be in radians! eci = np.atleast_2d(eci) assert eci.shape[0] == gst.size, 'length of time does not match number of ECI positions' N, trip = eci.shape if eci.ndim > 2 or trip != 3: raise ValueError('eci triplets must be shape (N,3)') ecef = np.empty_like(eci) for i in range(N): ecef[i, :] = _rottrip(gst[i]) @ eci[i, :] return ecef.squeeze()
python
def eci2ecef(eci: np.ndarray, time: datetime, useastropy: bool = True) -> np.ndarray: """ Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate """ useastropy = useastropy and Time if useastropy: gst = Time(time).sidereal_time('apparent', 'greenwich').radian else: gst = datetime2sidereal(time, 0.) gst = np.atleast_1d(gst) assert gst.ndim == 1 and isinstance(gst[0], float) # must be in radians! eci = np.atleast_2d(eci) assert eci.shape[0] == gst.size, 'length of time does not match number of ECI positions' N, trip = eci.shape if eci.ndim > 2 or trip != 3: raise ValueError('eci triplets must be shape (N,3)') ecef = np.empty_like(eci) for i in range(N): ecef[i, :] = _rottrip(gst[i]) @ eci[i, :] return ecef.squeeze()
[ "def", "eci2ecef", "(", "eci", ":", "np", ".", "ndarray", ",", "time", ":", "datetime", ",", "useastropy", ":", "bool", "=", "True", ")", "->", "np", ".", "ndarray", ":", "useastropy", "=", "useastropy", "and", "Time", "if", "useastropy", ":", "gst", "=", "Time", "(", "time", ")", ".", "sidereal_time", "(", "'apparent'", ",", "'greenwich'", ")", ".", "radian", "else", ":", "gst", "=", "datetime2sidereal", "(", "time", ",", "0.", ")", "gst", "=", "np", ".", "atleast_1d", "(", "gst", ")", "assert", "gst", ".", "ndim", "==", "1", "and", "isinstance", "(", "gst", "[", "0", "]", ",", "float", ")", "# must be in radians!", "eci", "=", "np", ".", "atleast_2d", "(", "eci", ")", "assert", "eci", ".", "shape", "[", "0", "]", "==", "gst", ".", "size", ",", "'length of time does not match number of ECI positions'", "N", ",", "trip", "=", "eci", ".", "shape", "if", "eci", ".", "ndim", ">", "2", "or", "trip", "!=", "3", ":", "raise", "ValueError", "(", "'eci triplets must be shape (N,3)'", ")", "ecef", "=", "np", ".", "empty_like", "(", "eci", ")", "for", "i", "in", "range", "(", "N", ")", ":", "ecef", "[", "i", ",", ":", "]", "=", "_rottrip", "(", "gst", "[", "i", "]", ")", "@", "eci", "[", "i", ",", ":", "]", "return", "ecef", ".", "squeeze", "(", ")" ]
Observer => Point ECI => ECEF Parameters ---------- eci : tuple of float Nx3 target ECI location (x,y,z) [meters] time : datetime.datetime time of obsevation (UTC) useastropy : bool, optional use AstroPy for conversion Results ------- x : float target x ECEF coordinate y : float target y ECEF coordinate z : float target z ECEF coordinate
[ "Observer", "=", ">", "Point", "ECI", "=", ">", "ECEF" ]
c9cf676594611cdb52ff7e0eca6388c80ed4f63f
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/eci.py#L12-L58
train
237,014
Netflix-Skunkworks/historical
historical/vpc/collector.py
describe_vpc
def describe_vpc(record): """Attempts to describe vpc ids.""" account_id = record['account'] vpc_name = cloudwatch.filter_request_parameters('vpcName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) try: if vpc_id and vpc_name: # pylint: disable=R1705 return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, Filters=[ { 'Name': 'vpc-id', 'Values': [vpc_id] } ] ) elif vpc_id: return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, VpcIds=[vpc_id] ) else: raise Exception('[X] Describe requires VpcId.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidVpc.NotFound': return [] raise exc
python
def describe_vpc(record): """Attempts to describe vpc ids.""" account_id = record['account'] vpc_name = cloudwatch.filter_request_parameters('vpcName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) try: if vpc_id and vpc_name: # pylint: disable=R1705 return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, Filters=[ { 'Name': 'vpc-id', 'Values': [vpc_id] } ] ) elif vpc_id: return describe_vpcs( account_number=account_id, assume_role=HISTORICAL_ROLE, region=CURRENT_REGION, VpcIds=[vpc_id] ) else: raise Exception('[X] Describe requires VpcId.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidVpc.NotFound': return [] raise exc
[ "def", "describe_vpc", "(", "record", ")", ":", "account_id", "=", "record", "[", "'account'", "]", "vpc_name", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcName'", ",", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "try", ":", "if", "vpc_id", "and", "vpc_name", ":", "# pylint: disable=R1705", "return", "describe_vpcs", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ",", "Filters", "=", "[", "{", "'Name'", ":", "'vpc-id'", ",", "'Values'", ":", "[", "vpc_id", "]", "}", "]", ")", "elif", "vpc_id", ":", "return", "describe_vpcs", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ",", "VpcIds", "=", "[", "vpc_id", "]", ")", "else", ":", "raise", "Exception", "(", "'[X] Describe requires VpcId.'", ")", "except", "ClientError", "as", "exc", ":", "if", "exc", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'InvalidVpc.NotFound'", ":", "return", "[", "]", "raise", "exc" ]
Attempts to describe vpc ids.
[ "Attempts", "to", "describe", "vpc", "ids", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L44-L75
train
237,015
Netflix-Skunkworks/historical
historical/vpc/collector.py
create_delete_model
def create_delete_model(record): """Create a vpc model from a record.""" data = cloudwatch.get_historical_base_info(record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) arn = get_arn(vpc_id, cloudwatch.get_region(record), record['account']) LOG.debug(F'[-] Deleting Dynamodb Records. Hash Key: {arn}') # tombstone these records so that the deletion event time can be accurately tracked. data.update({ 'configuration': {} }) items = list(CurrentVPCModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentVPCModel(**model_dict) model.save() return model return None
python
def create_delete_model(record): """Create a vpc model from a record.""" data = cloudwatch.get_historical_base_info(record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) arn = get_arn(vpc_id, cloudwatch.get_region(record), record['account']) LOG.debug(F'[-] Deleting Dynamodb Records. Hash Key: {arn}') # tombstone these records so that the deletion event time can be accurately tracked. data.update({ 'configuration': {} }) items = list(CurrentVPCModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentVPCModel(**model_dict) model.save() return model return None
[ "def", "create_delete_model", "(", "record", ")", ":", "data", "=", "cloudwatch", ".", "get_historical_base_info", "(", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "arn", "=", "get_arn", "(", "vpc_id", ",", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "record", "[", "'account'", "]", ")", "LOG", ".", "debug", "(", "F'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "# tombstone these records so that the deletion event time can be accurately tracked.", "data", ".", "update", "(", "{", "'configuration'", ":", "{", "}", "}", ")", "items", "=", "list", "(", "CurrentVPCModel", ".", "query", "(", "arn", ",", "limit", "=", "1", ")", ")", "if", "items", ":", "model_dict", "=", "items", "[", "0", "]", ".", "__dict__", "[", "'attribute_values'", "]", ".", "copy", "(", ")", "model_dict", ".", "update", "(", "data", ")", "model", "=", "CurrentVPCModel", "(", "*", "*", "model_dict", ")", "model", ".", "save", "(", ")", "return", "model", "return", "None" ]
Create a vpc model from a record.
[ "Create", "a", "vpc", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L78-L102
train
237,016
Netflix-Skunkworks/historical
historical/vpc/collector.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) capture_delete_records(delete_records) # filter out error events update_records = [e for e in update_records if not e['detail'].get('errorCode')] # pylint: disable=C0103 # group records by account for more efficient processing LOG.debug(f'[@] Update Records: {records}') capture_update_records(update_records)
python
def handler(event, context): # pylint: disable=W0613 """ Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) capture_delete_records(delete_records) # filter out error events update_records = [e for e in update_records if not e['detail'].get('errorCode')] # pylint: disable=C0103 # group records by account for more efficient processing LOG.debug(f'[@] Update Records: {records}') capture_update_records(update_records)
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "# Split records into two groups, update and delete.", "# We don't want to query for deleted records.", "update_records", ",", "delete_records", "=", "group_records_by_type", "(", "records", ",", "UPDATE_EVENTS", ")", "capture_delete_records", "(", "delete_records", ")", "# filter out error events", "update_records", "=", "[", "e", "for", "e", "in", "update_records", "if", "not", "e", "[", "'detail'", "]", ".", "get", "(", "'errorCode'", ")", "]", "# pylint: disable=C0103", "# group records by account for more efficient processing", "LOG", ".", "debug", "(", "f'[@] Update Records: {records}'", ")", "capture_update_records", "(", "update_records", ")" ]
Historical vpc event collector. This collector is responsible for processing Cloudwatch events and polling events.
[ "Historical", "vpc", "event", "collector", ".", "This", "collector", "is", "responsible", "for", "processing", "Cloudwatch", "events", "and", "polling", "events", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/collector.py#L165-L183
train
237,017
Netflix-Skunkworks/historical
historical/common/dynamodb.py
default_diff
def default_diff(latest_config, current_config): """Determine if two revisions have actually changed.""" # Pop off the fields we don't care about: pop_no_diff_fields(latest_config, current_config) diff = DeepDiff( latest_config, current_config, ignore_order=True ) return diff
python
def default_diff(latest_config, current_config): """Determine if two revisions have actually changed.""" # Pop off the fields we don't care about: pop_no_diff_fields(latest_config, current_config) diff = DeepDiff( latest_config, current_config, ignore_order=True ) return diff
[ "def", "default_diff", "(", "latest_config", ",", "current_config", ")", ":", "# Pop off the fields we don't care about:", "pop_no_diff_fields", "(", "latest_config", ",", "current_config", ")", "diff", "=", "DeepDiff", "(", "latest_config", ",", "current_config", ",", "ignore_order", "=", "True", ")", "return", "diff" ]
Determine if two revisions have actually changed.
[ "Determine", "if", "two", "revisions", "have", "actually", "changed", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L33-L43
train
237,018
Netflix-Skunkworks/historical
historical/common/dynamodb.py
pop_no_diff_fields
def pop_no_diff_fields(latest_config, current_config): """Pops off fields that should not be included in the diff.""" for field in ['userIdentity', 'principalId', 'userAgent', 'sourceIpAddress', 'requestParameters', 'eventName']: latest_config.pop(field, None) current_config.pop(field, None)
python
def pop_no_diff_fields(latest_config, current_config): """Pops off fields that should not be included in the diff.""" for field in ['userIdentity', 'principalId', 'userAgent', 'sourceIpAddress', 'requestParameters', 'eventName']: latest_config.pop(field, None) current_config.pop(field, None)
[ "def", "pop_no_diff_fields", "(", "latest_config", ",", "current_config", ")", ":", "for", "field", "in", "[", "'userIdentity'", ",", "'principalId'", ",", "'userAgent'", ",", "'sourceIpAddress'", ",", "'requestParameters'", ",", "'eventName'", "]", ":", "latest_config", ".", "pop", "(", "field", ",", "None", ")", "current_config", ".", "pop", "(", "field", ",", "None", ")" ]
Pops off fields that should not be included in the diff.
[ "Pops", "off", "fields", "that", "should", "not", "be", "included", "in", "the", "diff", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L46-L50
train
237,019
Netflix-Skunkworks/historical
historical/common/dynamodb.py
modify_record
def modify_record(durable_model, current_revision, arn, event_time, diff_func): """Handles a DynamoDB MODIFY event type.""" # We want the newest items first. # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html items = list(durable_model.query( arn, (durable_model.eventTime <= event_time), scan_index_forward=False, limit=1, consistent_read=True)) if items: latest_revision = items[0] latest_config = latest_revision._get_json()[1]['attributes'] # pylint: disable=W0212 current_config = current_revision._get_json()[1]['attributes'] # pylint: disable=W0212 # Determine if there is truly a difference, disregarding Ephemeral Paths diff = diff_func(latest_config, current_config) if diff: LOG.debug( f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} ' f'CurrentConfig: {json.dumps(current_config)}') current_revision.save() else: current_revision.save() LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
python
def modify_record(durable_model, current_revision, arn, event_time, diff_func): """Handles a DynamoDB MODIFY event type.""" # We want the newest items first. # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html items = list(durable_model.query( arn, (durable_model.eventTime <= event_time), scan_index_forward=False, limit=1, consistent_read=True)) if items: latest_revision = items[0] latest_config = latest_revision._get_json()[1]['attributes'] # pylint: disable=W0212 current_config = current_revision._get_json()[1]['attributes'] # pylint: disable=W0212 # Determine if there is truly a difference, disregarding Ephemeral Paths diff = diff_func(latest_config, current_config) if diff: LOG.debug( f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} ' f'CurrentConfig: {json.dumps(current_config)}') current_revision.save() else: current_revision.save() LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
[ "def", "modify_record", "(", "durable_model", ",", "current_revision", ",", "arn", ",", "event_time", ",", "diff_func", ")", ":", "# We want the newest items first.", "# See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html", "items", "=", "list", "(", "durable_model", ".", "query", "(", "arn", ",", "(", "durable_model", ".", "eventTime", "<=", "event_time", ")", ",", "scan_index_forward", "=", "False", ",", "limit", "=", "1", ",", "consistent_read", "=", "True", ")", ")", "if", "items", ":", "latest_revision", "=", "items", "[", "0", "]", "latest_config", "=", "latest_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "current_config", "=", "current_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "# Determine if there is truly a difference, disregarding Ephemeral Paths", "diff", "=", "diff_func", "(", "latest_config", ",", "current_config", ")", "if", "diff", ":", "LOG", ".", "debug", "(", "f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '", "f'CurrentConfig: {json.dumps(current_config)}'", ")", "current_revision", ".", "save", "(", ")", "else", ":", "current_revision", ".", "save", "(", ")", "LOG", ".", "info", "(", "f'[?] Got modify event but no current revision found. Arn: {arn}'", ")" ]
Handles a DynamoDB MODIFY event type.
[ "Handles", "a", "DynamoDB", "MODIFY", "event", "type", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L82-L108
train
237,020
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_current_record_to_durable_model
def deserialize_current_record_to_durable_model(record, current_model, durable_model): """ Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): record = get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) if not record: return None serialized = record._serialize() # pylint: disable=W0212 record = { 'dynamodb': { 'NewImage': serialized['attributes'] } } # The ARN isn't added because it's in the HASH key section: record['dynamodb']['NewImage']['arn'] = {'S': serialized['HASH']} new_image = remove_current_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
python
def deserialize_current_record_to_durable_model(record, current_model, durable_model): """ Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): record = get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) if not record: return None serialized = record._serialize() # pylint: disable=W0212 record = { 'dynamodb': { 'NewImage': serialized['attributes'] } } # The ARN isn't added because it's in the HASH key section: record['dynamodb']['NewImage']['arn'] = {'S': serialized['HASH']} new_image = remove_current_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
[ "def", "deserialize_current_record_to_durable_model", "(", "record", ",", "current_model", ",", "durable_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "record", "=", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "if", "not", "record", ":", "return", "None", "serialized", "=", "record", ".", "_serialize", "(", ")", "# pylint: disable=W0212", "record", "=", "{", "'dynamodb'", ":", "{", "'NewImage'", ":", "serialized", "[", "'attributes'", "]", "}", "}", "# The ARN isn't added because it's in the HASH key section:", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", "[", "'arn'", "]", "=", "{", "'S'", ":", "serialized", "[", "'HASH'", "]", "}", "new_image", "=", "remove_current_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "durable_model", "(", "*", "*", "data", ")" ]
Utility function that will take a dynamo event record and turn it into the proper pynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :param durable_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "pynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L168-L203
train
237,021
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_current_record_to_current_model
def deserialize_current_record_to_current_model(record, current_model): """ Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
python
def deserialize_current_record_to_current_model(record, current_model): """ Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
[ "def", "deserialize_current_record_to_current_model", "(", "record", ",", "current_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "return", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "current_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object. This will remove the "current table" specific fields, and properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Current", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L206-L226
train
237,022
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_durable_record_to_durable_model
def deserialize_durable_record_to_durable_model(record, durable_model): """ Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_durable_object(record['dynamodb']['Keys']['arn']['S'], record['dynamodb']['NewImage']['eventTime']['S'], durable_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
python
def deserialize_durable_record_to_durable_model(record, durable_model): """ Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): return get_full_durable_object(record['dynamodb']['Keys']['arn']['S'], record['dynamodb']['NewImage']['eventTime']['S'], durable_model) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return durable_model(**data)
[ "def", "deserialize_durable_record_to_durable_model", "(", "record", ",", "durable_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "return", "get_full_durable_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", "[", "'eventTime'", "]", "[", "'S'", "]", ",", "durable_model", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "durable_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param durable_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Durable", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L229-L251
train
237,023
Netflix-Skunkworks/historical
historical/common/dynamodb.py
deserialize_durable_record_to_current_model
def deserialize_durable_record_to_current_model(record, current_model): """ Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): # Try to get the data from the current table vs. grabbing the data from the Durable table: return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_durable_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
python
def deserialize_durable_record_to_current_model(record, current_model): """ Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return: """ # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record.get(EVENT_TOO_BIG_FLAG): # Try to get the data from the current table vs. grabbing the data from the Durable table: return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model) new_image = remove_durable_specific_fields(record['dynamodb']['NewImage']) data = {} for item, value in new_image.items(): # This could end up as loss of precision data[item] = DESER.deserialize(value) return current_model(**data)
[ "def", "deserialize_durable_record_to_current_model", "(", "record", ",", "current_model", ")", ":", "# Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:", "if", "record", ".", "get", "(", "EVENT_TOO_BIG_FLAG", ")", ":", "# Try to get the data from the current table vs. grabbing the data from the Durable table:", "return", "get_full_current_object", "(", "record", "[", "'dynamodb'", "]", "[", "'Keys'", "]", "[", "'arn'", "]", "[", "'S'", "]", ",", "current_model", ")", "new_image", "=", "remove_durable_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "data", "=", "{", "}", "for", "item", ",", "value", "in", "new_image", ".", "items", "(", ")", ":", "# This could end up as loss of precision", "data", "[", "item", "]", "=", "DESER", ".", "deserialize", "(", "value", ")", "return", "current_model", "(", "*", "*", "data", ")" ]
Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object. This will properly deserialize the ugly Dynamo datatypes away. :param record: :param current_model: :return:
[ "Utility", "function", "that", "will", "take", "a", "Durable", "Dynamo", "event", "record", "and", "turn", "it", "into", "the", "proper", "Current", "Dynamo", "object", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L254-L275
train
237,024
Netflix-Skunkworks/historical
historical/models.py
HistoricalPollerTaskEventModel.serialize_me
def serialize_me(self, account_id, region, next_token=None): """Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return: """ payload = { 'account_id': account_id, 'region': region } if next_token: payload['next_token'] = next_token return self.dumps(payload).data
python
def serialize_me(self, account_id, region, next_token=None): """Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return: """ payload = { 'account_id': account_id, 'region': region } if next_token: payload['next_token'] = next_token return self.dumps(payload).data
[ "def", "serialize_me", "(", "self", ",", "account_id", ",", "region", ",", "next_token", "=", "None", ")", ":", "payload", "=", "{", "'account_id'", ":", "account_id", ",", "'region'", ":", "region", "}", "if", "next_token", ":", "payload", "[", "'next_token'", "]", "=", "next_token", "return", "self", ".", "dumps", "(", "payload", ")", ".", "data" ]
Dumps the proper JSON for the schema. :param account_id: :param region: :param next_token: :return:
[ "Dumps", "the", "proper", "JSON", "for", "the", "schema", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/models.py#L136-L152
train
237,025
Netflix-Skunkworks/historical
historical/models.py
SimpleDurableSchema.serialize_me
def serialize_me(self, arn, event_time, tech, item=None): """Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return: """ payload = { 'arn': arn, 'event_time': event_time, 'tech': tech } if item: payload['item'] = item else: payload['event_too_big'] = True return self.dumps(payload).data.replace('<empty>', '')
python
def serialize_me(self, arn, event_time, tech, item=None): """Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return: """ payload = { 'arn': arn, 'event_time': event_time, 'tech': tech } if item: payload['item'] = item else: payload['event_too_big'] = True return self.dumps(payload).data.replace('<empty>', '')
[ "def", "serialize_me", "(", "self", ",", "arn", ",", "event_time", ",", "tech", ",", "item", "=", "None", ")", ":", "payload", "=", "{", "'arn'", ":", "arn", ",", "'event_time'", ":", "event_time", ",", "'tech'", ":", "tech", "}", "if", "item", ":", "payload", "[", "'item'", "]", "=", "item", "else", ":", "payload", "[", "'event_too_big'", "]", "=", "True", "return", "self", ".", "dumps", "(", "payload", ")", ".", "data", ".", "replace", "(", "'<empty>'", ",", "''", ")" ]
Dumps the proper JSON for the schema. If the event is too big, then don't include the item. :param arn: :param event_time: :param tech: :param item: :return:
[ "Dumps", "the", "proper", "JSON", "for", "the", "schema", ".", "If", "the", "event", "is", "too", "big", "then", "don", "t", "include", "the", "item", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/models.py#L169-L190
train
237,026
Netflix-Skunkworks/historical
historical/attributes.py
fix_decimals
def fix_decimals(obj): """Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290 """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = fix_decimals(obj[i]) return obj elif isinstance(obj, dict): for key, value in obj.items(): obj[key] = fix_decimals(value) return obj elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) else: return obj
python
def fix_decimals(obj): """Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290 """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = fix_decimals(obj[i]) return obj elif isinstance(obj, dict): for key, value in obj.items(): obj[key] = fix_decimals(value) return obj elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) else: return obj
[ "def", "fix_decimals", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "i", "in", "range", "(", "len", "(", "obj", ")", ")", ":", "obj", "[", "i", "]", "=", "fix_decimals", "(", "obj", "[", "i", "]", ")", "return", "obj", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "obj", "[", "key", "]", "=", "fix_decimals", "(", "value", ")", "return", "obj", "elif", "isinstance", "(", "obj", ",", "decimal", ".", "Decimal", ")", ":", "if", "obj", "%", "1", "==", "0", ":", "return", "int", "(", "obj", ")", "else", ":", "return", "float", "(", "obj", ")", "else", ":", "return", "obj" ]
Removes the stupid Decimals See: https://github.com/boto/boto3/issues/369#issuecomment-302137290
[ "Removes", "the", "stupid", "Decimals" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/attributes.py#L62-L84
train
237,027
Netflix-Skunkworks/historical
historical/attributes.py
EventTimeAttribute.serialize
def serialize(self, value): """Takes a datetime object and returns a string""" if isinstance(value, str): return value return value.strftime(DATETIME_FORMAT)
python
def serialize(self, value): """Takes a datetime object and returns a string""" if isinstance(value, str): return value return value.strftime(DATETIME_FORMAT)
[ "def", "serialize", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "return", "value", ".", "strftime", "(", "DATETIME_FORMAT", ")" ]
Takes a datetime object and returns a string
[ "Takes", "a", "datetime", "object", "and", "returns", "a", "string" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/attributes.py#L45-L49
train
237,028
Netflix-Skunkworks/historical
historical/common/util.py
pull_tag_dict
def pull_tag_dict(data): """This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values. """ # If there are tags, set them to a normal dict, vs. a list of dicts: tags = data.pop('Tags', {}) or {} if tags: proper_tags = {} for tag in tags: proper_tags[tag['Key']] = tag['Value'] tags = proper_tags return tags
python
def pull_tag_dict(data): """This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values. """ # If there are tags, set them to a normal dict, vs. a list of dicts: tags = data.pop('Tags', {}) or {} if tags: proper_tags = {} for tag in tags: proper_tags[tag['Key']] = tag['Value'] tags = proper_tags return tags
[ "def", "pull_tag_dict", "(", "data", ")", ":", "# If there are tags, set them to a normal dict, vs. a list of dicts:", "tags", "=", "data", ".", "pop", "(", "'Tags'", ",", "{", "}", ")", "or", "{", "}", "if", "tags", ":", "proper_tags", "=", "{", "}", "for", "tag", "in", "tags", ":", "proper_tags", "[", "tag", "[", "'Key'", "]", "]", "=", "tag", "[", "'Value'", "]", "tags", "=", "proper_tags", "return", "tags" ]
This will pull out a list of Tag Name-Value objects, and return it as a dictionary. :param data: The dict collected from the collector. :returns dict: A dict of the tag names and their corresponding values.
[ "This", "will", "pull", "out", "a", "list", "of", "Tag", "Name", "-", "Value", "objects", "and", "return", "it", "as", "a", "dictionary", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/util.py#L39-L54
train
237,029
Netflix-Skunkworks/historical
historical/s3/collector.py
create_delete_model
def create_delete_model(record): """Create an S3 model from a record.""" arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') data = { 'arn': arn, 'principalId': cloudwatch.get_principal(record), 'userIdentity': cloudwatch.get_user_identity(record), 'accountId': record['account'], 'eventTime': record['detail']['eventTime'], 'BucketName': cloudwatch.filter_request_parameters('bucketName', record), 'Region': cloudwatch.get_region(record), 'Tags': {}, 'configuration': {}, 'eventSource': record['detail']['eventSource'], 'version': VERSION } return CurrentS3Model(**data)
python
def create_delete_model(record): """Create an S3 model from a record.""" arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') data = { 'arn': arn, 'principalId': cloudwatch.get_principal(record), 'userIdentity': cloudwatch.get_user_identity(record), 'accountId': record['account'], 'eventTime': record['detail']['eventTime'], 'BucketName': cloudwatch.filter_request_parameters('bucketName', record), 'Region': cloudwatch.get_region(record), 'Tags': {}, 'configuration': {}, 'eventSource': record['detail']['eventSource'], 'version': VERSION } return CurrentS3Model(**data)
[ "def", "create_delete_model", "(", "record", ")", ":", "arn", "=", "f\"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}\"", "LOG", ".", "debug", "(", "f'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "data", "=", "{", "'arn'", ":", "arn", ",", "'principalId'", ":", "cloudwatch", ".", "get_principal", "(", "record", ")", ",", "'userIdentity'", ":", "cloudwatch", ".", "get_user_identity", "(", "record", ")", ",", "'accountId'", ":", "record", "[", "'account'", "]", ",", "'eventTime'", ":", "record", "[", "'detail'", "]", "[", "'eventTime'", "]", ",", "'BucketName'", ":", "cloudwatch", ".", "filter_request_parameters", "(", "'bucketName'", ",", "record", ")", ",", "'Region'", ":", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "'Tags'", ":", "{", "}", ",", "'configuration'", ":", "{", "}", ",", "'eventSource'", ":", "record", "[", "'detail'", "]", "[", "'eventSource'", "]", ",", "'version'", ":", "VERSION", "}", "return", "CurrentS3Model", "(", "*", "*", "data", ")" ]
Create an S3 model from a record.
[ "Create", "an", "S3", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L55-L74
train
237,030
Netflix-Skunkworks/historical
historical/s3/collector.py
process_delete_records
def process_delete_records(delete_records): """Process the requests for S3 bucket deletions""" for rec in delete_records: arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" # Need to check if the event is NEWER than the previous event in case # events are out of order. This could *possibly* happen if something # was deleted, and then quickly re-created. It could be *possible* for the # deletion event to arrive after the creation event. Thus, this will check # if the current event timestamp is newer and will only delete if the deletion # event is newer. try: LOG.debug(f'[-] Deleting bucket: {arn}') model = create_delete_model(rec) model.save(condition=(CurrentS3Model.eventTime <= rec['detail']['eventTime'])) model.delete() except PynamoDBConnectionError as pdce: LOG.warning(f"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale " f"(arrived before a NEWER creation/update). The specific exception is: {pdce}")
python
def process_delete_records(delete_records): """Process the requests for S3 bucket deletions""" for rec in delete_records: arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" # Need to check if the event is NEWER than the previous event in case # events are out of order. This could *possibly* happen if something # was deleted, and then quickly re-created. It could be *possible* for the # deletion event to arrive after the creation event. Thus, this will check # if the current event timestamp is newer and will only delete if the deletion # event is newer. try: LOG.debug(f'[-] Deleting bucket: {arn}') model = create_delete_model(rec) model.save(condition=(CurrentS3Model.eventTime <= rec['detail']['eventTime'])) model.delete() except PynamoDBConnectionError as pdce: LOG.warning(f"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale " f"(arrived before a NEWER creation/update). The specific exception is: {pdce}")
[ "def", "process_delete_records", "(", "delete_records", ")", ":", "for", "rec", "in", "delete_records", ":", "arn", "=", "f\"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}\"", "# Need to check if the event is NEWER than the previous event in case", "# events are out of order. This could *possibly* happen if something", "# was deleted, and then quickly re-created. It could be *possible* for the", "# deletion event to arrive after the creation event. Thus, this will check", "# if the current event timestamp is newer and will only delete if the deletion", "# event is newer.", "try", ":", "LOG", ".", "debug", "(", "f'[-] Deleting bucket: {arn}'", ")", "model", "=", "create_delete_model", "(", "rec", ")", "model", ".", "save", "(", "condition", "=", "(", "CurrentS3Model", ".", "eventTime", "<=", "rec", "[", "'detail'", "]", "[", "'eventTime'", "]", ")", ")", "model", ".", "delete", "(", ")", "except", "PynamoDBConnectionError", "as", "pdce", ":", "LOG", ".", "warning", "(", "f\"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale \"", "f\"(arrived before a NEWER creation/update). The specific exception is: {pdce}\"", ")" ]
Process the requests for S3 bucket deletions
[ "Process", "the", "requests", "for", "S3", "bucket", "deletions" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L77-L96
train
237,031
Netflix-Skunkworks/historical
historical/s3/collector.py
process_update_records
def process_update_records(update_records): """Process the requests for S3 bucket update requests""" events = sorted(update_records, key=lambda x: x['account']) # Group records by account for more efficient processing for account_id, events in groupby(events, lambda x: x['account']): events = list(events) # Grab the bucket names (de-dupe events): buckets = {} for event in events: # If the creation date is present, then use it: bucket_event = buckets.get(event['detail']['requestParameters']['bucketName'], { 'creationDate': event['detail']['requestParameters'].get('creationDate') }) bucket_event.update(event['detail']['requestParameters']) buckets[event['detail']['requestParameters']['bucketName']] = bucket_event buckets[event['detail']['requestParameters']['bucketName']]['eventDetails'] = event # Query AWS for current configuration for b_name, item in buckets.items(): LOG.debug(f'[~] Processing Create/Update for: {b_name}') # If the bucket does not exist, then simply drop the request -- # If this happens, there is likely a Delete event that has occurred and will be processed soon. try: bucket_details = get_bucket(b_name, account_number=account_id, include_created=(item.get('creationDate') is None), assume_role=HISTORICAL_ROLE, region=CURRENT_REGION) if bucket_details.get('Error'): LOG.error(f"[X] Unable to fetch details about bucket: {b_name}. " f"The error details are: {bucket_details['Error']}") continue except ClientError as cerr: if cerr.response['Error']['Code'] == 'NoSuchBucket': LOG.warning(f'[?] Received update request for bucket: {b_name} that does not ' 'currently exist. Skipping.') continue # Catch Access Denied exceptions as well: if cerr.response['Error']['Code'] == 'AccessDenied': LOG.error(f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. ' 'Skipping...') continue raise Exception(cerr) # Pull out the fields we want: data = { 'arn': f'arn:aws:s3:::{b_name}', 'principalId': cloudwatch.get_principal(item['eventDetails']), 'userIdentity': cloudwatch.get_user_identity(item['eventDetails']), 'userAgent': item['eventDetails']['detail'].get('userAgent'), 'sourceIpAddress': item['eventDetails']['detail'].get('sourceIPAddress'), 'requestParameters': item['eventDetails']['detail'].get('requestParameters'), 'accountId': account_id, 'eventTime': item['eventDetails']['detail']['eventTime'], 'BucketName': b_name, 'Region': bucket_details.pop('Region'), # Duplicated in top level and configuration for secondary index 'Tags': bucket_details.pop('Tags', {}) or {}, 'eventSource': item['eventDetails']['detail']['eventSource'], 'eventName': item['eventDetails']['detail']['eventName'], 'version': VERSION } # Remove the fields we don't care about: del bucket_details['Arn'] del bucket_details['GrantReferences'] del bucket_details['_version'] del bucket_details['Name'] if not bucket_details.get('CreationDate'): bucket_details['CreationDate'] = item['creationDate'] data['configuration'] = bucket_details current_revision = CurrentS3Model(**data) current_revision.save()
python
def process_update_records(update_records): """Process the requests for S3 bucket update requests""" events = sorted(update_records, key=lambda x: x['account']) # Group records by account for more efficient processing for account_id, events in groupby(events, lambda x: x['account']): events = list(events) # Grab the bucket names (de-dupe events): buckets = {} for event in events: # If the creation date is present, then use it: bucket_event = buckets.get(event['detail']['requestParameters']['bucketName'], { 'creationDate': event['detail']['requestParameters'].get('creationDate') }) bucket_event.update(event['detail']['requestParameters']) buckets[event['detail']['requestParameters']['bucketName']] = bucket_event buckets[event['detail']['requestParameters']['bucketName']]['eventDetails'] = event # Query AWS for current configuration for b_name, item in buckets.items(): LOG.debug(f'[~] Processing Create/Update for: {b_name}') # If the bucket does not exist, then simply drop the request -- # If this happens, there is likely a Delete event that has occurred and will be processed soon. try: bucket_details = get_bucket(b_name, account_number=account_id, include_created=(item.get('creationDate') is None), assume_role=HISTORICAL_ROLE, region=CURRENT_REGION) if bucket_details.get('Error'): LOG.error(f"[X] Unable to fetch details about bucket: {b_name}. " f"The error details are: {bucket_details['Error']}") continue except ClientError as cerr: if cerr.response['Error']['Code'] == 'NoSuchBucket': LOG.warning(f'[?] Received update request for bucket: {b_name} that does not ' 'currently exist. Skipping.') continue # Catch Access Denied exceptions as well: if cerr.response['Error']['Code'] == 'AccessDenied': LOG.error(f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. ' 'Skipping...') continue raise Exception(cerr) # Pull out the fields we want: data = { 'arn': f'arn:aws:s3:::{b_name}', 'principalId': cloudwatch.get_principal(item['eventDetails']), 'userIdentity': cloudwatch.get_user_identity(item['eventDetails']), 'userAgent': item['eventDetails']['detail'].get('userAgent'), 'sourceIpAddress': item['eventDetails']['detail'].get('sourceIPAddress'), 'requestParameters': item['eventDetails']['detail'].get('requestParameters'), 'accountId': account_id, 'eventTime': item['eventDetails']['detail']['eventTime'], 'BucketName': b_name, 'Region': bucket_details.pop('Region'), # Duplicated in top level and configuration for secondary index 'Tags': bucket_details.pop('Tags', {}) or {}, 'eventSource': item['eventDetails']['detail']['eventSource'], 'eventName': item['eventDetails']['detail']['eventName'], 'version': VERSION } # Remove the fields we don't care about: del bucket_details['Arn'] del bucket_details['GrantReferences'] del bucket_details['_version'] del bucket_details['Name'] if not bucket_details.get('CreationDate'): bucket_details['CreationDate'] = item['creationDate'] data['configuration'] = bucket_details current_revision = CurrentS3Model(**data) current_revision.save()
[ "def", "process_update_records", "(", "update_records", ")", ":", "events", "=", "sorted", "(", "update_records", ",", "key", "=", "lambda", "x", ":", "x", "[", "'account'", "]", ")", "# Group records by account for more efficient processing", "for", "account_id", ",", "events", "in", "groupby", "(", "events", ",", "lambda", "x", ":", "x", "[", "'account'", "]", ")", ":", "events", "=", "list", "(", "events", ")", "# Grab the bucket names (de-dupe events):", "buckets", "=", "{", "}", "for", "event", "in", "events", ":", "# If the creation date is present, then use it:", "bucket_event", "=", "buckets", ".", "get", "(", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", ",", "{", "'creationDate'", ":", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", ".", "get", "(", "'creationDate'", ")", "}", ")", "bucket_event", ".", "update", "(", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", ")", "buckets", "[", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", "]", "=", "bucket_event", "buckets", "[", "event", "[", "'detail'", "]", "[", "'requestParameters'", "]", "[", "'bucketName'", "]", "]", "[", "'eventDetails'", "]", "=", "event", "# Query AWS for current configuration", "for", "b_name", ",", "item", "in", "buckets", ".", "items", "(", ")", ":", "LOG", ".", "debug", "(", "f'[~] Processing Create/Update for: {b_name}'", ")", "# If the bucket does not exist, then simply drop the request --", "# If this happens, there is likely a Delete event that has occurred and will be processed soon.", "try", ":", "bucket_details", "=", "get_bucket", "(", "b_name", ",", "account_number", "=", "account_id", ",", "include_created", "=", "(", "item", ".", "get", "(", "'creationDate'", ")", "is", "None", ")", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "CURRENT_REGION", ")", "if", "bucket_details", ".", "get", "(", "'Error'", ")", ":", "LOG", ".", "error", "(", "f\"[X] Unable to fetch details about bucket: {b_name}. \"", "f\"The error details are: {bucket_details['Error']}\"", ")", "continue", "except", "ClientError", "as", "cerr", ":", "if", "cerr", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'NoSuchBucket'", ":", "LOG", ".", "warning", "(", "f'[?] Received update request for bucket: {b_name} that does not '", "'currently exist. Skipping.'", ")", "continue", "# Catch Access Denied exceptions as well:", "if", "cerr", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'AccessDenied'", ":", "LOG", ".", "error", "(", "f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. '", "'Skipping...'", ")", "continue", "raise", "Exception", "(", "cerr", ")", "# Pull out the fields we want:", "data", "=", "{", "'arn'", ":", "f'arn:aws:s3:::{b_name}'", ",", "'principalId'", ":", "cloudwatch", ".", "get_principal", "(", "item", "[", "'eventDetails'", "]", ")", ",", "'userIdentity'", ":", "cloudwatch", ".", "get_user_identity", "(", "item", "[", "'eventDetails'", "]", ")", ",", "'userAgent'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'userAgent'", ")", ",", "'sourceIpAddress'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'sourceIPAddress'", ")", ",", "'requestParameters'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ")", ",", "'accountId'", ":", "account_id", ",", "'eventTime'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventTime'", "]", ",", "'BucketName'", ":", "b_name", ",", "'Region'", ":", "bucket_details", ".", "pop", "(", "'Region'", ")", ",", "# Duplicated in top level and configuration for secondary index", "'Tags'", ":", "bucket_details", ".", "pop", "(", "'Tags'", ",", "{", "}", ")", "or", "{", "}", ",", "'eventSource'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventSource'", "]", ",", "'eventName'", ":", "item", "[", "'eventDetails'", "]", "[", "'detail'", "]", "[", "'eventName'", "]", ",", "'version'", ":", "VERSION", "}", "# Remove the fields we don't care about:", "del", "bucket_details", "[", "'Arn'", "]", "del", "bucket_details", "[", "'GrantReferences'", "]", "del", "bucket_details", "[", "'_version'", "]", "del", "bucket_details", "[", "'Name'", "]", "if", "not", "bucket_details", ".", "get", "(", "'CreationDate'", ")", ":", "bucket_details", "[", "'CreationDate'", "]", "=", "item", "[", "'creationDate'", "]", "data", "[", "'configuration'", "]", "=", "bucket_details", "current_revision", "=", "CurrentS3Model", "(", "*", "*", "data", ")", "current_revision", ".", "save", "(", ")" ]
Process the requests for S3 bucket update requests
[ "Process", "the", "requests", "for", "S3", "bucket", "update", "requests" ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L99-L179
train
237,032
Netflix-Skunkworks/historical
historical/s3/collector.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) LOG.debug('[@] Processing update records...') process_update_records(update_records) LOG.debug('[@] Completed processing of update records.') LOG.debug('[@] Processing delete records...') process_delete_records(delete_records) LOG.debug('[@] Completed processing of delete records.') LOG.debug('[@] Successfully updated current Historical table')
python
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS) LOG.debug('[@] Processing update records...') process_update_records(update_records) LOG.debug('[@] Completed processing of update records.') LOG.debug('[@] Processing delete records...') process_delete_records(delete_records) LOG.debug('[@] Completed processing of delete records.') LOG.debug('[@] Successfully updated current Historical table')
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "# Split records into two groups, update and delete.", "# We don't want to query for deleted records.", "update_records", ",", "delete_records", "=", "group_records_by_type", "(", "records", ",", "UPDATE_EVENTS", ")", "LOG", ".", "debug", "(", "'[@] Processing update records...'", ")", "process_update_records", "(", "update_records", ")", "LOG", ".", "debug", "(", "'[@] Completed processing of update records.'", ")", "LOG", ".", "debug", "(", "'[@] Processing delete records...'", ")", "process_delete_records", "(", "delete_records", ")", "LOG", ".", "debug", "(", "'[@] Completed processing of delete records.'", ")", "LOG", ".", "debug", "(", "'[@] Successfully updated current Historical table'", ")" ]
Historical S3 event collector. This collector is responsible for processing CloudWatch events and polling events.
[ "Historical", "S3", "event", "collector", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/collector.py#L183-L203
train
237,033
Netflix-Skunkworks/historical
historical/common/accounts.py
get_historical_accounts
def get_historical_accounts(): """Fetches valid accounts from SWAG if enabled or a list accounts.""" if os.environ.get('SWAG_BUCKET', False): swag_opts = { 'swag.type': 's3', 'swag.bucket_name': os.environ['SWAG_BUCKET'], 'swag.data_file': os.environ.get('SWAG_DATA_FILE', 'accounts.json'), 'swag.region': os.environ.get('SWAG_REGION', 'us-east-1') } swag = SWAGManager(**parse_swag_config_options(swag_opts)) search_filter = f"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'" if parse_boolean(os.environ.get('TEST_ACCOUNTS_ONLY')): search_filter += " && environment=='test'" search_filter += ']' accounts = swag.get_service_enabled('historical', search_filter=search_filter) else: accounts = [{'id': account_id} for account_id in os.environ['ENABLED_ACCOUNTS'].split(',')] return accounts
python
def get_historical_accounts(): """Fetches valid accounts from SWAG if enabled or a list accounts.""" if os.environ.get('SWAG_BUCKET', False): swag_opts = { 'swag.type': 's3', 'swag.bucket_name': os.environ['SWAG_BUCKET'], 'swag.data_file': os.environ.get('SWAG_DATA_FILE', 'accounts.json'), 'swag.region': os.environ.get('SWAG_REGION', 'us-east-1') } swag = SWAGManager(**parse_swag_config_options(swag_opts)) search_filter = f"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'" if parse_boolean(os.environ.get('TEST_ACCOUNTS_ONLY')): search_filter += " && environment=='test'" search_filter += ']' accounts = swag.get_service_enabled('historical', search_filter=search_filter) else: accounts = [{'id': account_id} for account_id in os.environ['ENABLED_ACCOUNTS'].split(',')] return accounts
[ "def", "get_historical_accounts", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'SWAG_BUCKET'", ",", "False", ")", ":", "swag_opts", "=", "{", "'swag.type'", ":", "'s3'", ",", "'swag.bucket_name'", ":", "os", ".", "environ", "[", "'SWAG_BUCKET'", "]", ",", "'swag.data_file'", ":", "os", ".", "environ", ".", "get", "(", "'SWAG_DATA_FILE'", ",", "'accounts.json'", ")", ",", "'swag.region'", ":", "os", ".", "environ", ".", "get", "(", "'SWAG_REGION'", ",", "'us-east-1'", ")", "}", "swag", "=", "SWAGManager", "(", "*", "*", "parse_swag_config_options", "(", "swag_opts", ")", ")", "search_filter", "=", "f\"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'\"", "if", "parse_boolean", "(", "os", ".", "environ", ".", "get", "(", "'TEST_ACCOUNTS_ONLY'", ")", ")", ":", "search_filter", "+=", "\" && environment=='test'\"", "search_filter", "+=", "']'", "accounts", "=", "swag", ".", "get_service_enabled", "(", "'historical'", ",", "search_filter", "=", "search_filter", ")", "else", ":", "accounts", "=", "[", "{", "'id'", ":", "account_id", "}", "for", "account_id", "in", "os", ".", "environ", "[", "'ENABLED_ACCOUNTS'", "]", ".", "split", "(", "','", ")", "]", "return", "accounts" ]
Fetches valid accounts from SWAG if enabled or a list accounts.
[ "Fetches", "valid", "accounts", "from", "SWAG", "if", "enabled", "or", "a", "list", "accounts", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/accounts.py#L26-L47
train
237,034
Netflix-Skunkworks/historical
historical/s3/poller.py
poller_processor_handler
def poller_processor_handler(event, context): # pylint: disable=W0613 """ Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. """ LOG.debug('[@] Running Poller...') queue_url = get_queue_url(os.environ.get('POLLER_QUEUE_NAME', 'HistoricalS3Poller')) records = deserialize_records(event['Records']) for record in records: # Skip accounts that have role assumption errors: try: # List all buckets in the account: all_buckets = list_buckets(account_number=record['account_id'], assume_role=HISTORICAL_ROLE, session_name="historical-cloudwatch-s3list", region=record['region'])["Buckets"] events = [S3_POLLING_SCHEMA.serialize_me(record['account_id'], bucket) for bucket in all_buckets] produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}") LOG.debug(f"[@] Finished generating polling events for account: {record['account_id']}. Events Created:" f" {len(record['account_id'])}")
python
def poller_processor_handler(event, context): # pylint: disable=W0613 """ Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. """ LOG.debug('[@] Running Poller...') queue_url = get_queue_url(os.environ.get('POLLER_QUEUE_NAME', 'HistoricalS3Poller')) records = deserialize_records(event['Records']) for record in records: # Skip accounts that have role assumption errors: try: # List all buckets in the account: all_buckets = list_buckets(account_number=record['account_id'], assume_role=HISTORICAL_ROLE, session_name="historical-cloudwatch-s3list", region=record['region'])["Buckets"] events = [S3_POLLING_SCHEMA.serialize_me(record['account_id'], bucket) for bucket in all_buckets] produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}") LOG.debug(f"[@] Finished generating polling events for account: {record['account_id']}. Events Created:" f" {len(record['account_id'])}")
[ "def", "poller_processor_handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "LOG", ".", "debug", "(", "'[@] Running Poller...'", ")", "queue_url", "=", "get_queue_url", "(", "os", ".", "environ", ".", "get", "(", "'POLLER_QUEUE_NAME'", ",", "'HistoricalS3Poller'", ")", ")", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "for", "record", "in", "records", ":", "# Skip accounts that have role assumption errors:", "try", ":", "# List all buckets in the account:", "all_buckets", "=", "list_buckets", "(", "account_number", "=", "record", "[", "'account_id'", "]", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "session_name", "=", "\"historical-cloudwatch-s3list\"", ",", "region", "=", "record", "[", "'region'", "]", ")", "[", "\"Buckets\"", "]", "events", "=", "[", "S3_POLLING_SCHEMA", ".", "serialize_me", "(", "record", "[", "'account_id'", "]", ",", "bucket", ")", "for", "bucket", "in", "all_buckets", "]", "produce_events", "(", "events", ",", "queue_url", ",", "randomize_delay", "=", "RANDOMIZE_POLLER", ")", "except", "ClientError", "as", "exc", ":", "LOG", ".", "error", "(", "f\"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}\"", ")", "LOG", ".", "debug", "(", "f\"[@] Finished generating polling events for account: {record['account_id']}. Events Created:\"", "f\" {len(record['account_id'])}\"", ")" ]
Historical S3 Poller Processor. This will receive events from the Poller Tasker, and will list all objects of a given technology for an account/region pair. This will generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from.
[ "Historical", "S3", "Poller", "Processor", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/poller.py#L58-L87
train
237,035
Netflix-Skunkworks/historical
historical/common/proxy.py
detect_global_table_updates
def detect_global_table_updates(record): """This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return: """ # This only affects MODIFY events. if record['eventName'] == 'MODIFY': # Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields) old_image = remove_global_dynamo_specific_fields(record['dynamodb']['OldImage']) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) if json.dumps(old_image, sort_keys=True) == json.dumps(new_image, sort_keys=True): return True return False
python
def detect_global_table_updates(record): """This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return: """ # This only affects MODIFY events. if record['eventName'] == 'MODIFY': # Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields) old_image = remove_global_dynamo_specific_fields(record['dynamodb']['OldImage']) new_image = remove_global_dynamo_specific_fields(record['dynamodb']['NewImage']) if json.dumps(old_image, sort_keys=True) == json.dumps(new_image, sort_keys=True): return True return False
[ "def", "detect_global_table_updates", "(", "record", ")", ":", "# This only affects MODIFY events.", "if", "record", "[", "'eventName'", "]", "==", "'MODIFY'", ":", "# Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields)", "old_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'OldImage'", "]", ")", "new_image", "=", "remove_global_dynamo_specific_fields", "(", "record", "[", "'dynamodb'", "]", "[", "'NewImage'", "]", ")", "if", "json", ".", "dumps", "(", "old_image", ",", "sort_keys", "=", "True", ")", "==", "json", ".", "dumps", "(", "new_image", ",", "sort_keys", "=", "True", ")", ":", "return", "True", "return", "False" ]
This will detect DDB Global Table updates that are not relevant to application data updates. These need to be skipped over as they are pure noise. :param record: :return:
[ "This", "will", "detect", "DDB", "Global", "Table", "updates", "that", "are", "not", "relevant", "to", "application", "data", "updates", ".", "These", "need", "to", "be", "skipped", "over", "as", "they", "are", "pure", "noise", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/proxy.py#L126-L142
train
237,036
Netflix-Skunkworks/historical
historical/s3/differ.py
handler
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. """ # De-serialize the records: records = deserialize_records(event['Records']) for record in records: process_dynamodb_differ_record(record, CurrentS3Model, DurableS3Model)
python
def handler(event, context): # pylint: disable=W0613 """ Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record. """ # De-serialize the records: records = deserialize_records(event['Records']) for record in records: process_dynamodb_differ_record(record, CurrentS3Model, DurableS3Model)
[ "def", "handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "# De-serialize the records:", "records", "=", "deserialize_records", "(", "event", "[", "'Records'", "]", ")", "for", "record", "in", "records", ":", "process_dynamodb_differ_record", "(", "record", ",", "CurrentS3Model", ",", "DurableS3Model", ")" ]
Historical S3 event differ. Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record.
[ "Historical", "S3", "event", "differ", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/s3/differ.py#L26-L37
train
237,037
Netflix-Skunkworks/historical
historical/cli.py
new
def new(): """Creates a new historical technology.""" dir_path = os.path.dirname(os.path.realpath(__file__)) cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
python
def new(): """Creates a new historical technology.""" dir_path = os.path.dirname(os.path.realpath(__file__)) cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
[ "def", "new", "(", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "cookiecutter", "(", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'historical-cookiecutter/'", ")", ")" ]
Creates a new historical technology.
[ "Creates", "a", "new", "historical", "technology", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/cli.py#L30-L33
train
237,038
Netflix-Skunkworks/historical
historical/vpc/poller.py
poller_tasker_handler
def poller_tasker_handler(event, context): # pylint: disable=W0613 """ Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts. """ LOG.debug('[@] Running Poller Tasker...') queue_url = get_queue_url(os.environ.get('POLLER_TASKER_QUEUE_NAME', 'HistoricalVPCPollerTasker')) poller_task_schema = HistoricalPollerTaskEventModel() events = [] for account in get_historical_accounts(): for region in POLL_REGIONS: events.append(poller_task_schema.serialize_me(account['id'], region)) try: produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f'[X] Unable to generate poller tasker events! Reason: {exc}') LOG.debug('[@] Finished tasking the pollers.')
python
def poller_tasker_handler(event, context): # pylint: disable=W0613 """ Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts. """ LOG.debug('[@] Running Poller Tasker...') queue_url = get_queue_url(os.environ.get('POLLER_TASKER_QUEUE_NAME', 'HistoricalVPCPollerTasker')) poller_task_schema = HistoricalPollerTaskEventModel() events = [] for account in get_historical_accounts(): for region in POLL_REGIONS: events.append(poller_task_schema.serialize_me(account['id'], region)) try: produce_events(events, queue_url, randomize_delay=RANDOMIZE_POLLER) except ClientError as exc: LOG.error(f'[X] Unable to generate poller tasker events! Reason: {exc}') LOG.debug('[@] Finished tasking the pollers.')
[ "def", "poller_tasker_handler", "(", "event", ",", "context", ")", ":", "# pylint: disable=W0613", "LOG", ".", "debug", "(", "'[@] Running Poller Tasker...'", ")", "queue_url", "=", "get_queue_url", "(", "os", ".", "environ", ".", "get", "(", "'POLLER_TASKER_QUEUE_NAME'", ",", "'HistoricalVPCPollerTasker'", ")", ")", "poller_task_schema", "=", "HistoricalPollerTaskEventModel", "(", ")", "events", "=", "[", "]", "for", "account", "in", "get_historical_accounts", "(", ")", ":", "for", "region", "in", "POLL_REGIONS", ":", "events", ".", "append", "(", "poller_task_schema", ".", "serialize_me", "(", "account", "[", "'id'", "]", ",", "region", ")", ")", "try", ":", "produce_events", "(", "events", ",", "queue_url", ",", "randomize_delay", "=", "RANDOMIZE_POLLER", ")", "except", "ClientError", "as", "exc", ":", "LOG", ".", "error", "(", "f'[X] Unable to generate poller tasker events! Reason: {exc}'", ")", "LOG", ".", "debug", "(", "'[@] Finished tasking the pollers.'", ")" ]
Historical VPC Poller Tasker. The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical. Historical pollers generate `polling events` which simulate changes. These polling events contain configuration data such as the account/region defining where the collector should attempt to gather data from. This is the entry point. This will task subsequent Poller lambdas to list all of a given resource in a select few AWS accounts.
[ "Historical", "VPC", "Poller", "Tasker", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/vpc/poller.py#L30-L57
train
237,039
Netflix-Skunkworks/historical
historical/common/sqs.py
chunks
def chunks(event_list, chunk_size): """Yield successive n-sized chunks from the event list.""" for i in range(0, len(event_list), chunk_size): yield event_list[i:i + chunk_size]
python
def chunks(event_list, chunk_size): """Yield successive n-sized chunks from the event list.""" for i in range(0, len(event_list), chunk_size): yield event_list[i:i + chunk_size]
[ "def", "chunks", "(", "event_list", ",", "chunk_size", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "event_list", ")", ",", "chunk_size", ")", ":", "yield", "event_list", "[", "i", ":", "i", "+", "chunk_size", "]" ]
Yield successive n-sized chunks from the event list.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "the", "event", "list", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L21-L24
train
237,040
Netflix-Skunkworks/historical
historical/common/sqs.py
get_queue_url
def get_queue_url(queue_name): """Get the URL of the SQS queue to send events to.""" client = boto3.client("sqs", CURRENT_REGION) queue = client.get_queue_url(QueueName=queue_name) return queue["QueueUrl"]
python
def get_queue_url(queue_name): """Get the URL of the SQS queue to send events to.""" client = boto3.client("sqs", CURRENT_REGION) queue = client.get_queue_url(QueueName=queue_name) return queue["QueueUrl"]
[ "def", "get_queue_url", "(", "queue_name", ")", ":", "client", "=", "boto3", ".", "client", "(", "\"sqs\"", ",", "CURRENT_REGION", ")", "queue", "=", "client", ".", "get_queue_url", "(", "QueueName", "=", "queue_name", ")", "return", "queue", "[", "\"QueueUrl\"", "]" ]
Get the URL of the SQS queue to send events to.
[ "Get", "the", "URL", "of", "the", "SQS", "queue", "to", "send", "events", "to", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L27-L32
train
237,041
Netflix-Skunkworks/historical
historical/common/sqs.py
produce_events
def produce_events(events, queue_url, batch_size=10, randomize_delay=0): """ Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay: """ client = boto3.client('sqs', region_name=CURRENT_REGION) for chunk in chunks(events, batch_size): records = [make_sqs_record(event, delay_seconds=get_random_delay(randomize_delay)) for event in chunk] client.send_message_batch(Entries=records, QueueUrl=queue_url)
python
def produce_events(events, queue_url, batch_size=10, randomize_delay=0): """ Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay: """ client = boto3.client('sqs', region_name=CURRENT_REGION) for chunk in chunks(events, batch_size): records = [make_sqs_record(event, delay_seconds=get_random_delay(randomize_delay)) for event in chunk] client.send_message_batch(Entries=records, QueueUrl=queue_url)
[ "def", "produce_events", "(", "events", ",", "queue_url", ",", "batch_size", "=", "10", ",", "randomize_delay", "=", "0", ")", ":", "client", "=", "boto3", ".", "client", "(", "'sqs'", ",", "region_name", "=", "CURRENT_REGION", ")", "for", "chunk", "in", "chunks", "(", "events", ",", "batch_size", ")", ":", "records", "=", "[", "make_sqs_record", "(", "event", ",", "delay_seconds", "=", "get_random_delay", "(", "randomize_delay", ")", ")", "for", "event", "in", "chunk", "]", "client", ".", "send_message_batch", "(", "Entries", "=", "records", ",", "QueueUrl", "=", "queue_url", ")" ]
Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maximum of 900 seconds. Set that in `randomize_delay` :param events: :param queue_url: :param batch_size: :param randomize_delay:
[ "Efficiently", "sends", "events", "to", "the", "SQS", "event", "queue", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/sqs.py#L55-L73
train
237,042
Netflix-Skunkworks/historical
historical/security_group/collector.py
describe_group
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True) # Did this get collected already by the poller? if cloudwatch.get_collected_details(record): LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}") return [record['detail']['collected']] try: # Always depend on Group ID first: if group_id: # pylint: disable=R1705 return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, GroupIds=[group_id] )['SecurityGroups'] elif vpc_id and group_name: return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, Filters=[ { 'Name': 'group-name', 'Values': [group_name] }, { 'Name': 'vpc-id', 'Values': [vpc_id] } ] )['SecurityGroups'] else: raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. ' f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidGroup.NotFound': return [] raise exc
python
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True) # Did this get collected already by the poller? if cloudwatch.get_collected_details(record): LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}") return [record['detail']['collected']] try: # Always depend on Group ID first: if group_id: # pylint: disable=R1705 return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, GroupIds=[group_id] )['SecurityGroups'] elif vpc_id and group_name: return describe_security_groups( account_number=account_id, assume_role=HISTORICAL_ROLE, region=region, Filters=[ { 'Name': 'group-name', 'Values': [group_name] }, { 'Name': 'vpc-id', 'Values': [vpc_id] } ] )['SecurityGroups'] else: raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. ' f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.') except ClientError as exc: if exc.response['Error']['Code'] == 'InvalidGroup.NotFound': return [] raise exc
[ "def", "describe_group", "(", "record", ",", "region", ")", ":", "account_id", "=", "record", "[", "'account'", "]", "group_name", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupName'", ",", "record", ")", "vpc_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'vpcId'", ",", "record", ")", "group_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupId'", ",", "record", ",", "look_in_response", "=", "True", ")", "# Did this get collected already by the poller?", "if", "cloudwatch", ".", "get_collected_details", "(", "record", ")", ":", "LOG", ".", "debug", "(", "f\"[<--] Received already collected security group data: {record['detail']['collected']}\"", ")", "return", "[", "record", "[", "'detail'", "]", "[", "'collected'", "]", "]", "try", ":", "# Always depend on Group ID first:", "if", "group_id", ":", "# pylint: disable=R1705", "return", "describe_security_groups", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "region", ",", "GroupIds", "=", "[", "group_id", "]", ")", "[", "'SecurityGroups'", "]", "elif", "vpc_id", "and", "group_name", ":", "return", "describe_security_groups", "(", "account_number", "=", "account_id", ",", "assume_role", "=", "HISTORICAL_ROLE", ",", "region", "=", "region", ",", "Filters", "=", "[", "{", "'Name'", ":", "'group-name'", ",", "'Values'", ":", "[", "group_name", "]", "}", ",", "{", "'Name'", ":", "'vpc-id'", ",", "'Values'", ":", "[", "vpc_id", "]", "}", "]", ")", "[", "'SecurityGroups'", "]", "else", ":", "raise", "Exception", "(", "'[X] Did not receive Group ID or VPC/Group Name pairs. '", "f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.'", ")", "except", "ClientError", "as", "exc", ":", "if", "exc", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "==", "'InvalidGroup.NotFound'", ":", "return", "[", "]", "raise", "exc" ]
Attempts to describe group ids.
[ "Attempts", "to", "describe", "group", "ids", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L47-L92
train
237,043
Netflix-Skunkworks/historical
historical/security_group/collector.py
create_delete_model
def create_delete_model(record): """Create a security group model from a record.""" data = cloudwatch.get_historical_base_info(record) group_id = cloudwatch.filter_request_parameters('groupId', record) # vpc_id = cloudwatch.filter_request_parameters('vpcId', record) # group_name = cloudwatch.filter_request_parameters('groupName', record) arn = get_arn(group_id, cloudwatch.get_region(record), record['account']) LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') # Tombstone these records so that the deletion event time can be accurately tracked. data.update({'configuration': {}}) items = list(CurrentSecurityGroupModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentSecurityGroupModel(**model_dict) model.save() return model return None
python
def create_delete_model(record): """Create a security group model from a record.""" data = cloudwatch.get_historical_base_info(record) group_id = cloudwatch.filter_request_parameters('groupId', record) # vpc_id = cloudwatch.filter_request_parameters('vpcId', record) # group_name = cloudwatch.filter_request_parameters('groupName', record) arn = get_arn(group_id, cloudwatch.get_region(record), record['account']) LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}') # Tombstone these records so that the deletion event time can be accurately tracked. data.update({'configuration': {}}) items = list(CurrentSecurityGroupModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentSecurityGroupModel(**model_dict) model.save() return model return None
[ "def", "create_delete_model", "(", "record", ")", ":", "data", "=", "cloudwatch", ".", "get_historical_base_info", "(", "record", ")", "group_id", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupId'", ",", "record", ")", "# vpc_id = cloudwatch.filter_request_parameters('vpcId', record)", "# group_name = cloudwatch.filter_request_parameters('groupName', record)", "arn", "=", "get_arn", "(", "group_id", ",", "cloudwatch", ".", "get_region", "(", "record", ")", ",", "record", "[", "'account'", "]", ")", "LOG", ".", "debug", "(", "f'[-] Deleting Dynamodb Records. Hash Key: {arn}'", ")", "# Tombstone these records so that the deletion event time can be accurately tracked.", "data", ".", "update", "(", "{", "'configuration'", ":", "{", "}", "}", ")", "items", "=", "list", "(", "CurrentSecurityGroupModel", ".", "query", "(", "arn", ",", "limit", "=", "1", ")", ")", "if", "items", ":", "model_dict", "=", "items", "[", "0", "]", ".", "__dict__", "[", "'attribute_values'", "]", ".", "copy", "(", ")", "model_dict", ".", "update", "(", "data", ")", "model", "=", "CurrentSecurityGroupModel", "(", "*", "*", "model_dict", ")", "model", ".", "save", "(", ")", "return", "model", "return", "None" ]
Create a security group model from a record.
[ "Create", "a", "security", "group", "model", "from", "a", "record", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L95-L119
train
237,044
Netflix-Skunkworks/historical
historical/constants.py
extract_log_level_from_environment
def extract_log_level_from_environment(k, default): """Gets the log level from the environment variable.""" return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))
python
def extract_log_level_from_environment(k, default): """Gets the log level from the environment variable.""" return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))
[ "def", "extract_log_level_from_environment", "(", "k", ",", "default", ")", ":", "return", "LOG_LEVELS", ".", "get", "(", "os", ".", "environ", ".", "get", "(", "k", ")", ")", "or", "int", "(", "os", ".", "environ", ".", "get", "(", "k", ",", "default", ")", ")" ]
Gets the log level from the environment variable.
[ "Gets", "the", "log", "level", "from", "the", "environment", "variable", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/constants.py#L21-L23
train
237,045
Netflix-Skunkworks/historical
historical/common/cloudwatch.py
filter_request_parameters
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: val = msg['detail'].get('requestParameters', {}).get(field_name, None) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response: if msg['detail'].get('responseElements'): val = msg['detail']['responseElements'].get(field_name, None) # Just in case... We didn't find the value, so just make it None: except AttributeError: val = None return val
python
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: val = msg['detail'].get('requestParameters', {}).get(field_name, None) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response: if msg['detail'].get('responseElements'): val = msg['detail']['responseElements'].get(field_name, None) # Just in case... We didn't find the value, so just make it None: except AttributeError: val = None return val
[ "def", "filter_request_parameters", "(", "field_name", ",", "msg", ",", "look_in_response", "=", "False", ")", ":", "val", "=", "msg", "[", "'detail'", "]", ".", "get", "(", "field_name", ",", "None", ")", "try", ":", "if", "not", "val", ":", "val", "=", "msg", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ",", "{", "}", ")", ".", "get", "(", "field_name", ",", "None", ")", "# If we STILL didn't find it -- check if it's in the response element (default off)", "if", "not", "val", "and", "look_in_response", ":", "if", "msg", "[", "'detail'", "]", ".", "get", "(", "'responseElements'", ")", ":", "val", "=", "msg", "[", "'detail'", "]", "[", "'responseElements'", "]", ".", "get", "(", "field_name", ",", "None", ")", "# Just in case... We didn't find the value, so just make it None:", "except", "AttributeError", ":", "val", "=", "None", "return", "val" ]
From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places.
[ "From", "an", "event", "extract", "the", "field", "name", "from", "the", "message", ".", "Different", "API", "calls", "put", "this", "information", "in", "different", "places", "so", "check", "a", "few", "places", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/cloudwatch.py#L14-L33
train
237,046
Netflix-Skunkworks/historical
historical/common/cloudwatch.py
get_historical_base_info
def get_historical_base_info(event): """Gets the base details from the CloudWatch Event.""" data = { 'principalId': get_principal(event), 'userIdentity': get_user_identity(event), 'accountId': event['account'], 'userAgent': event['detail'].get('userAgent'), 'sourceIpAddress': event['detail'].get('sourceIPAddress'), 'requestParameters': event['detail'].get('requestParameters') } if event['detail'].get('eventTime'): data['eventTime'] = event['detail']['eventTime'] if event['detail'].get('eventSource'): data['eventSource'] = event['detail']['eventSource'] if event['detail'].get('eventName'): data['eventName'] = event['detail']['eventName'] return data
python
def get_historical_base_info(event): """Gets the base details from the CloudWatch Event.""" data = { 'principalId': get_principal(event), 'userIdentity': get_user_identity(event), 'accountId': event['account'], 'userAgent': event['detail'].get('userAgent'), 'sourceIpAddress': event['detail'].get('sourceIPAddress'), 'requestParameters': event['detail'].get('requestParameters') } if event['detail'].get('eventTime'): data['eventTime'] = event['detail']['eventTime'] if event['detail'].get('eventSource'): data['eventSource'] = event['detail']['eventSource'] if event['detail'].get('eventName'): data['eventName'] = event['detail']['eventName'] return data
[ "def", "get_historical_base_info", "(", "event", ")", ":", "data", "=", "{", "'principalId'", ":", "get_principal", "(", "event", ")", ",", "'userIdentity'", ":", "get_user_identity", "(", "event", ")", ",", "'accountId'", ":", "event", "[", "'account'", "]", ",", "'userAgent'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'userAgent'", ")", ",", "'sourceIpAddress'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'sourceIPAddress'", ")", ",", "'requestParameters'", ":", "event", "[", "'detail'", "]", ".", "get", "(", "'requestParameters'", ")", "}", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventTime'", ")", ":", "data", "[", "'eventTime'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventTime'", "]", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventSource'", ")", ":", "data", "[", "'eventSource'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventSource'", "]", "if", "event", "[", "'detail'", "]", ".", "get", "(", "'eventName'", ")", ":", "data", "[", "'eventName'", "]", "=", "event", "[", "'detail'", "]", "[", "'eventName'", "]", "return", "data" ]
Gets the base details from the CloudWatch Event.
[ "Gets", "the", "base", "details", "from", "the", "CloudWatch", "Event", "." ]
c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/cloudwatch.py#L67-L87
train
237,047
desbma/GoogleSpeech
google_speech/__init__.py
Speech.splitText
def splitText(text): """ Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE. """ segments = [] remaining_text = __class__.cleanSpaces(text) while len(remaining_text) > __class__.MAX_SEGMENT_SIZE: cur_text = remaining_text[:__class__.MAX_SEGMENT_SIZE] # try to split at punctuation split_idx = __class__.findLastCharIndexMatching(cur_text, # https://en.wikipedia.org/wiki/Unicode_character_property#General_Category lambda x: unicodedata.category(x) in ("Ps", "Pe", "Pi", "Pf", "Po")) if split_idx is None: # try to split at whitespace split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: unicodedata.category(x).startswith("Z")) if split_idx is None: # try to split at anything not a letter or number split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: not (unicodedata.category(x)[0] in ("L", "N"))) if split_idx is None: # split at the last char split_idx = __class__.MAX_SEGMENT_SIZE - 1 new_segment = cur_text[:split_idx + 1].rstrip() segments.append(new_segment) remaining_text = remaining_text[split_idx + 1:].lstrip(string.whitespace + string.punctuation) if remaining_text: segments.append(remaining_text) return segments
python
def splitText(text): """ Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE. """ segments = [] remaining_text = __class__.cleanSpaces(text) while len(remaining_text) > __class__.MAX_SEGMENT_SIZE: cur_text = remaining_text[:__class__.MAX_SEGMENT_SIZE] # try to split at punctuation split_idx = __class__.findLastCharIndexMatching(cur_text, # https://en.wikipedia.org/wiki/Unicode_character_property#General_Category lambda x: unicodedata.category(x) in ("Ps", "Pe", "Pi", "Pf", "Po")) if split_idx is None: # try to split at whitespace split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: unicodedata.category(x).startswith("Z")) if split_idx is None: # try to split at anything not a letter or number split_idx = __class__.findLastCharIndexMatching(cur_text, lambda x: not (unicodedata.category(x)[0] in ("L", "N"))) if split_idx is None: # split at the last char split_idx = __class__.MAX_SEGMENT_SIZE - 1 new_segment = cur_text[:split_idx + 1].rstrip() segments.append(new_segment) remaining_text = remaining_text[split_idx + 1:].lstrip(string.whitespace + string.punctuation) if remaining_text: segments.append(remaining_text) return segments
[ "def", "splitText", "(", "text", ")", ":", "segments", "=", "[", "]", "remaining_text", "=", "__class__", ".", "cleanSpaces", "(", "text", ")", "while", "len", "(", "remaining_text", ")", ">", "__class__", ".", "MAX_SEGMENT_SIZE", ":", "cur_text", "=", "remaining_text", "[", ":", "__class__", ".", "MAX_SEGMENT_SIZE", "]", "# try to split at punctuation", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "# https://en.wikipedia.org/wiki/Unicode_character_property#General_Category", "lambda", "x", ":", "unicodedata", ".", "category", "(", "x", ")", "in", "(", "\"Ps\"", ",", "\"Pe\"", ",", "\"Pi\"", ",", "\"Pf\"", ",", "\"Po\"", ")", ")", "if", "split_idx", "is", "None", ":", "# try to split at whitespace", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "lambda", "x", ":", "unicodedata", ".", "category", "(", "x", ")", ".", "startswith", "(", "\"Z\"", ")", ")", "if", "split_idx", "is", "None", ":", "# try to split at anything not a letter or number", "split_idx", "=", "__class__", ".", "findLastCharIndexMatching", "(", "cur_text", ",", "lambda", "x", ":", "not", "(", "unicodedata", ".", "category", "(", "x", ")", "[", "0", "]", "in", "(", "\"L\"", ",", "\"N\"", ")", ")", ")", "if", "split_idx", "is", "None", ":", "# split at the last char", "split_idx", "=", "__class__", ".", "MAX_SEGMENT_SIZE", "-", "1", "new_segment", "=", "cur_text", "[", ":", "split_idx", "+", "1", "]", ".", "rstrip", "(", ")", "segments", ".", "append", "(", "new_segment", ")", "remaining_text", "=", "remaining_text", "[", "split_idx", "+", "1", ":", "]", ".", "lstrip", "(", "string", ".", "whitespace", "+", "string", ".", "punctuation", ")", "if", "remaining_text", ":", "segments", ".", "append", "(", "remaining_text", ")", "return", "segments" ]
Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE.
[ "Split", "text", "into", "sub", "segments", "of", "size", "not", "bigger", "than", "MAX_SEGMENT_SIZE", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L99-L130
train
237,048
desbma/GoogleSpeech
google_speech/__init__.py
Speech.play
def play(self, sox_effects=()): """ Play a speech. """ # build the segments preloader_threads = [] if self.text != "-": segments = list(self) # start preloader thread(s) preloader_threads = [PreloaderThread(name="PreloaderThread-%u" % (i)) for i in range(PRELOADER_THREAD_COUNT)] for preloader_thread in preloader_threads: preloader_thread.segments = segments preloader_thread.start() else: segments = iter(self) # play segments for segment in segments: segment.play(sox_effects) if self.text != "-": # destroy preloader threads for preloader_thread in preloader_threads: preloader_thread.join()
python
def play(self, sox_effects=()): """ Play a speech. """ # build the segments preloader_threads = [] if self.text != "-": segments = list(self) # start preloader thread(s) preloader_threads = [PreloaderThread(name="PreloaderThread-%u" % (i)) for i in range(PRELOADER_THREAD_COUNT)] for preloader_thread in preloader_threads: preloader_thread.segments = segments preloader_thread.start() else: segments = iter(self) # play segments for segment in segments: segment.play(sox_effects) if self.text != "-": # destroy preloader threads for preloader_thread in preloader_threads: preloader_thread.join()
[ "def", "play", "(", "self", ",", "sox_effects", "=", "(", ")", ")", ":", "# build the segments", "preloader_threads", "=", "[", "]", "if", "self", ".", "text", "!=", "\"-\"", ":", "segments", "=", "list", "(", "self", ")", "# start preloader thread(s)", "preloader_threads", "=", "[", "PreloaderThread", "(", "name", "=", "\"PreloaderThread-%u\"", "%", "(", "i", ")", ")", "for", "i", "in", "range", "(", "PRELOADER_THREAD_COUNT", ")", "]", "for", "preloader_thread", "in", "preloader_threads", ":", "preloader_thread", ".", "segments", "=", "segments", "preloader_thread", ".", "start", "(", ")", "else", ":", "segments", "=", "iter", "(", "self", ")", "# play segments", "for", "segment", "in", "segments", ":", "segment", ".", "play", "(", "sox_effects", ")", "if", "self", ".", "text", "!=", "\"-\"", ":", "# destroy preloader threads", "for", "preloader_thread", "in", "preloader_threads", ":", "preloader_thread", ".", "join", "(", ")" ]
Play a speech.
[ "Play", "a", "speech", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L138-L160
train
237,049
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.isInCache
def isInCache(self): """ Return True if audio data for this segment is present in cache, False otherwise. """ url = self.buildUrl(cache_friendly=True) return url in __class__.cache
python
def isInCache(self): """ Return True if audio data for this segment is present in cache, False otherwise. """ url = self.buildUrl(cache_friendly=True) return url in __class__.cache
[ "def", "isInCache", "(", "self", ")", ":", "url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "return", "url", "in", "__class__", ".", "cache" ]
Return True if audio data for this segment is present in cache, False otherwise.
[ "Return", "True", "if", "audio", "data", "for", "this", "segment", "is", "present", "in", "cache", "False", "otherwise", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L207-L210
train
237,050
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.preLoad
def preLoad(self): """ Store audio data in cache for fast playback. """ logging.getLogger().debug("Preloading segment '%s'" % (self)) real_url = self.buildUrl() cache_url = self.buildUrl(cache_friendly=True) audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data
python
def preLoad(self): """ Store audio data in cache for fast playback. """ logging.getLogger().debug("Preloading segment '%s'" % (self)) real_url = self.buildUrl() cache_url = self.buildUrl(cache_friendly=True) audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data
[ "def", "preLoad", "(", "self", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Preloading segment '%s'\"", "%", "(", "self", ")", ")", "real_url", "=", "self", ".", "buildUrl", "(", ")", "cache_url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "audio_data", "=", "self", ".", "download", "(", "real_url", ")", "assert", "(", "audio_data", ")", "__class__", ".", "cache", "[", "cache_url", "]", "=", "audio_data" ]
Store audio data in cache for fast playback.
[ "Store", "audio", "data", "in", "cache", "for", "fast", "playback", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L212-L219
train
237,051
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.getAudioData
def getAudioData(self): """ Fetch the audio data. """ with self.preload_mutex: cache_url = self.buildUrl(cache_friendly=True) if cache_url in __class__.cache: logging.getLogger().debug("Got data for URL '%s' from cache" % (cache_url)) audio_data = __class__.cache[cache_url] assert(audio_data) else: real_url = self.buildUrl() audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data return audio_data
python
def getAudioData(self): """ Fetch the audio data. """ with self.preload_mutex: cache_url = self.buildUrl(cache_friendly=True) if cache_url in __class__.cache: logging.getLogger().debug("Got data for URL '%s' from cache" % (cache_url)) audio_data = __class__.cache[cache_url] assert(audio_data) else: real_url = self.buildUrl() audio_data = self.download(real_url) assert(audio_data) __class__.cache[cache_url] = audio_data return audio_data
[ "def", "getAudioData", "(", "self", ")", ":", "with", "self", ".", "preload_mutex", ":", "cache_url", "=", "self", ".", "buildUrl", "(", "cache_friendly", "=", "True", ")", "if", "cache_url", "in", "__class__", ".", "cache", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Got data for URL '%s' from cache\"", "%", "(", "cache_url", ")", ")", "audio_data", "=", "__class__", ".", "cache", "[", "cache_url", "]", "assert", "(", "audio_data", ")", "else", ":", "real_url", "=", "self", ".", "buildUrl", "(", ")", "audio_data", "=", "self", ".", "download", "(", "real_url", ")", "assert", "(", "audio_data", ")", "__class__", ".", "cache", "[", "cache_url", "]", "=", "audio_data", "return", "audio_data" ]
Fetch the audio data.
[ "Fetch", "the", "audio", "data", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L221-L234
train
237,052
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.play
def play(self, sox_effects=()): """ Play the segment. """ audio_data = self.getAudioData() logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self)) cmd = ["sox", "-q", "-t", "mp3", "-"] if sys.platform.startswith("win32"): cmd.extend(("-t", "waveaudio")) cmd.extend(("-d", "trim", "0.1", "reverse", "trim", "0.07", "reverse")) # "trim", "0.25", "-0.1" cmd.extend(sox_effects) logging.getLogger().debug("Start player process") p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) p.communicate(input=audio_data) if p.returncode != 0: raise RuntimeError() logging.getLogger().debug("Done playing")
python
def play(self, sox_effects=()): """ Play the segment. """ audio_data = self.getAudioData() logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self)) cmd = ["sox", "-q", "-t", "mp3", "-"] if sys.platform.startswith("win32"): cmd.extend(("-t", "waveaudio")) cmd.extend(("-d", "trim", "0.1", "reverse", "trim", "0.07", "reverse")) # "trim", "0.25", "-0.1" cmd.extend(sox_effects) logging.getLogger().debug("Start player process") p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) p.communicate(input=audio_data) if p.returncode != 0: raise RuntimeError() logging.getLogger().debug("Done playing")
[ "def", "play", "(", "self", ",", "sox_effects", "=", "(", ")", ")", ":", "audio_data", "=", "self", ".", "getAudioData", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "info", "(", "\"Playing speech segment (%s): '%s'\"", "%", "(", "self", ".", "lang", ",", "self", ")", ")", "cmd", "=", "[", "\"sox\"", ",", "\"-q\"", ",", "\"-t\"", ",", "\"mp3\"", ",", "\"-\"", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win32\"", ")", ":", "cmd", ".", "extend", "(", "(", "\"-t\"", ",", "\"waveaudio\"", ")", ")", "cmd", ".", "extend", "(", "(", "\"-d\"", ",", "\"trim\"", ",", "\"0.1\"", ",", "\"reverse\"", ",", "\"trim\"", ",", "\"0.07\"", ",", "\"reverse\"", ")", ")", "# \"trim\", \"0.25\", \"-0.1\"", "cmd", ".", "extend", "(", "sox_effects", ")", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Start player process\"", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ")", "p", ".", "communicate", "(", "input", "=", "audio_data", ")", "if", "p", ".", "returncode", "!=", "0", ":", "raise", "RuntimeError", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Done playing\"", ")" ]
Play the segment.
[ "Play", "the", "segment", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L236-L252
train
237,053
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.buildUrl
def buildUrl(self, cache_friendly=False): """ Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key. """ params = collections.OrderedDict() params["client"] = "tw-ob" params["ie"] = "UTF-8" params["idx"] = str(self.segment_num) if self.segment_count is not None: params["total"] = str(self.segment_count) params["textlen"] = str(len(self.text)) params["tl"] = self.lang lower_text = self.text.lower() params["q"] = lower_text return "%s?%s" % (__class__.BASE_URL, urllib.parse.urlencode(params))
python
def buildUrl(self, cache_friendly=False): """ Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key. """ params = collections.OrderedDict() params["client"] = "tw-ob" params["ie"] = "UTF-8" params["idx"] = str(self.segment_num) if self.segment_count is not None: params["total"] = str(self.segment_count) params["textlen"] = str(len(self.text)) params["tl"] = self.lang lower_text = self.text.lower() params["q"] = lower_text return "%s?%s" % (__class__.BASE_URL, urllib.parse.urlencode(params))
[ "def", "buildUrl", "(", "self", ",", "cache_friendly", "=", "False", ")", ":", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"client\"", "]", "=", "\"tw-ob\"", "params", "[", "\"ie\"", "]", "=", "\"UTF-8\"", "params", "[", "\"idx\"", "]", "=", "str", "(", "self", ".", "segment_num", ")", "if", "self", ".", "segment_count", "is", "not", "None", ":", "params", "[", "\"total\"", "]", "=", "str", "(", "self", ".", "segment_count", ")", "params", "[", "\"textlen\"", "]", "=", "str", "(", "len", "(", "self", ".", "text", ")", ")", "params", "[", "\"tl\"", "]", "=", "self", ".", "lang", "lower_text", "=", "self", ".", "text", ".", "lower", "(", ")", "params", "[", "\"q\"", "]", "=", "lower_text", "return", "\"%s?%s\"", "%", "(", "__class__", ".", "BASE_URL", ",", "urllib", ".", "parse", ".", "urlencode", "(", "params", ")", ")" ]
Construct the URL to get the sound from Goggle API. If cache_friendly is True, remove token from URL to use as a cache key.
[ "Construct", "the", "URL", "to", "get", "the", "sound", "from", "Goggle", "API", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L254-L270
train
237,054
desbma/GoogleSpeech
google_speech/__init__.py
SpeechSegment.download
def download(self, url): """ Download a sound file. """ logging.getLogger().debug("Downloading '%s'..." % (url)) response = __class__.session.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=3.1) response.raise_for_status() return response.content
python
def download(self, url): """ Download a sound file. """ logging.getLogger().debug("Downloading '%s'..." % (url)) response = __class__.session.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=3.1) response.raise_for_status() return response.content
[ "def", "download", "(", "self", ",", "url", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Downloading '%s'...\"", "%", "(", "url", ")", ")", "response", "=", "__class__", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "{", "\"User-Agent\"", ":", "\"Mozilla/5.0\"", "}", ",", "timeout", "=", "3.1", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "content" ]
Download a sound file.
[ "Download", "a", "sound", "file", "." ]
6d3ec62dc26400ccb4f2e77b8ccd4cb416141233
https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L272-L279
train
237,055
gtalarico/airtable-python-wrapper
airtable/params.py
_BaseObjectArrayParam.to_param_dict
def to_param_dict(self): """ Sorts to ensure Order is consistent for Testing """ param_dict = {} for index, dictionary in enumerate(self.value): for key, value in dictionary.items(): param_name = '{param_name}[{index}][{key}]'.format( param_name=self.param_name, index=index, key=key) param_dict[param_name] = value return OrderedDict(sorted(param_dict.items()))
python
def to_param_dict(self): """ Sorts to ensure Order is consistent for Testing """ param_dict = {} for index, dictionary in enumerate(self.value): for key, value in dictionary.items(): param_name = '{param_name}[{index}][{key}]'.format( param_name=self.param_name, index=index, key=key) param_dict[param_name] = value return OrderedDict(sorted(param_dict.items()))
[ "def", "to_param_dict", "(", "self", ")", ":", "param_dict", "=", "{", "}", "for", "index", ",", "dictionary", "in", "enumerate", "(", "self", ".", "value", ")", ":", "for", "key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ":", "param_name", "=", "'{param_name}[{index}][{key}]'", ".", "format", "(", "param_name", "=", "self", ".", "param_name", ",", "index", "=", "index", ",", "key", "=", "key", ")", "param_dict", "[", "param_name", "]", "=", "value", "return", "OrderedDict", "(", "sorted", "(", "param_dict", ".", "items", "(", ")", ")", ")" ]
Sorts to ensure Order is consistent for Testing
[ "Sorts", "to", "ensure", "Order", "is", "consistent", "for", "Testing" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L68-L78
train
237,056
gtalarico/airtable-python-wrapper
airtable/params.py
AirtableParams._get
def _get(cls, kwarg_name): """ Returns a Param Class Instance, by its kwarg or param name """ param_classes = cls._discover_params() try: param_class = param_classes[kwarg_name] except KeyError: raise ValueError('invalid param keyword {}'.format(kwarg_name)) else: return param_class
python
def _get(cls, kwarg_name): """ Returns a Param Class Instance, by its kwarg or param name """ param_classes = cls._discover_params() try: param_class = param_classes[kwarg_name] except KeyError: raise ValueError('invalid param keyword {}'.format(kwarg_name)) else: return param_class
[ "def", "_get", "(", "cls", ",", "kwarg_name", ")", ":", "param_classes", "=", "cls", ".", "_discover_params", "(", ")", "try", ":", "param_class", "=", "param_classes", "[", "kwarg_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'invalid param keyword {}'", ".", "format", "(", "kwarg_name", ")", ")", "else", ":", "return", "param_class" ]
Returns a Param Class Instance, by its kwarg or param name
[ "Returns", "a", "Param", "Class", "Instance", "by", "its", "kwarg", "or", "param", "name" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/params.py#L362-L370
train
237,057
gtalarico/airtable-python-wrapper
airtable/airtable.py
Airtable._process_params
def _process_params(self, params): """ Process params names or values as needed using filters """ new_params = OrderedDict() for param_name, param_value in sorted(params.items()): param_value = params[param_name] ParamClass = AirtableParams._get(param_name) new_params.update(ParamClass(param_value).to_param_dict()) return new_params
python
def _process_params(self, params): """ Process params names or values as needed using filters """ new_params = OrderedDict() for param_name, param_value in sorted(params.items()): param_value = params[param_name] ParamClass = AirtableParams._get(param_name) new_params.update(ParamClass(param_value).to_param_dict()) return new_params
[ "def", "_process_params", "(", "self", ",", "params", ")", ":", "new_params", "=", "OrderedDict", "(", ")", "for", "param_name", ",", "param_value", "in", "sorted", "(", "params", ".", "items", "(", ")", ")", ":", "param_value", "=", "params", "[", "param_name", "]", "ParamClass", "=", "AirtableParams", ".", "_get", "(", "param_name", ")", "new_params", ".", "update", "(", "ParamClass", "(", "param_value", ")", ".", "to_param_dict", "(", ")", ")", "return", "new_params" ]
Process params names or values as needed using filters
[ "Process", "params", "names", "or", "values", "as", "needed", "using", "filters" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L141-L150
train
237,058
gtalarico/airtable-python-wrapper
airtable/airtable.py
Airtable._batch_request
def _batch_request(self, func, iterable): """ Internal Function to limit batch calls to API limit """ responses = [] for item in iterable: responses.append(func(item)) time.sleep(self.API_LIMIT) return responses
python
def _batch_request(self, func, iterable): """ Internal Function to limit batch calls to API limit """ responses = [] for item in iterable: responses.append(func(item)) time.sleep(self.API_LIMIT) return responses
[ "def", "_batch_request", "(", "self", ",", "func", ",", "iterable", ")", ":", "responses", "=", "[", "]", "for", "item", "in", "iterable", ":", "responses", ".", "append", "(", "func", "(", "item", ")", ")", "time", ".", "sleep", "(", "self", ".", "API_LIMIT", ")", "return", "responses" ]
Internal Function to limit batch calls to API limit
[ "Internal", "Function", "to", "limit", "batch", "calls", "to", "API", "limit" ]
48b2d806178085b52a31817571e5a1fc3dce4045
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L372-L378
train
237,059
siznax/wptools
wptools/category.py
WPToolsCategory._add_members
def _add_members(self, catmembers): """ Adds category members and subcategories to data """ members = [x for x in catmembers if x['ns'] == 0] subcats = [x for x in catmembers if x['ns'] == 14] if 'members' in self.data: self.data['members'].extend(members) else: self.data.update({'members': members}) if subcats: if 'subcategories' in self.data: self.data['subcategories'].extend(subcats) else: self.data.update({'subcategories': subcats})
python
def _add_members(self, catmembers): """ Adds category members and subcategories to data """ members = [x for x in catmembers if x['ns'] == 0] subcats = [x for x in catmembers if x['ns'] == 14] if 'members' in self.data: self.data['members'].extend(members) else: self.data.update({'members': members}) if subcats: if 'subcategories' in self.data: self.data['subcategories'].extend(subcats) else: self.data.update({'subcategories': subcats})
[ "def", "_add_members", "(", "self", ",", "catmembers", ")", ":", "members", "=", "[", "x", "for", "x", "in", "catmembers", "if", "x", "[", "'ns'", "]", "==", "0", "]", "subcats", "=", "[", "x", "for", "x", "in", "catmembers", "if", "x", "[", "'ns'", "]", "==", "14", "]", "if", "'members'", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'members'", "]", ".", "extend", "(", "members", ")", "else", ":", "self", ".", "data", ".", "update", "(", "{", "'members'", ":", "members", "}", ")", "if", "subcats", ":", "if", "'subcategories'", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'subcategories'", "]", ".", "extend", "(", "subcats", ")", "else", ":", "self", ".", "data", ".", "update", "(", "{", "'subcategories'", ":", "subcats", "}", ")" ]
Adds category members and subcategories to data
[ "Adds", "category", "members", "and", "subcategories", "to", "data" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L74-L90
train
237,060
siznax/wptools
wptools/category.py
WPToolsCategory._query
def _query(self, action, qobj): """ Form query to enumerate category """ title = self.params.get('title') pageid = self.params.get('pageid') if action == 'random': return qobj.random(namespace=14) elif action == 'category': return qobj.category(title, pageid, self._continue_params())
python
def _query(self, action, qobj): """ Form query to enumerate category """ title = self.params.get('title') pageid = self.params.get('pageid') if action == 'random': return qobj.random(namespace=14) elif action == 'category': return qobj.category(title, pageid, self._continue_params())
[ "def", "_query", "(", "self", ",", "action", ",", "qobj", ")", ":", "title", "=", "self", ".", "params", ".", "get", "(", "'title'", ")", "pageid", "=", "self", ".", "params", ".", "get", "(", "'pageid'", ")", "if", "action", "==", "'random'", ":", "return", "qobj", ".", "random", "(", "namespace", "=", "14", ")", "elif", "action", "==", "'category'", ":", "return", "qobj", ".", "category", "(", "title", ",", "pageid", ",", "self", ".", "_continue_params", "(", ")", ")" ]
Form query to enumerate category
[ "Form", "query", "to", "enumerate", "category" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L92-L102
train
237,061
siznax/wptools
wptools/category.py
WPToolsCategory._set_data
def _set_data(self, action): """ Set category member data from API response """ data = self._load_response(action) self._handle_continuations(data, 'category') if action == 'category': members = data.get('query').get('categorymembers') if members: self._add_members(members) if action == 'random': rand = data['query']['random'][0] data = {'pageid': rand.get('id'), 'title': rand.get('title')} self.data.update(data) self.params.update(data)
python
def _set_data(self, action): """ Set category member data from API response """ data = self._load_response(action) self._handle_continuations(data, 'category') if action == 'category': members = data.get('query').get('categorymembers') if members: self._add_members(members) if action == 'random': rand = data['query']['random'][0] data = {'pageid': rand.get('id'), 'title': rand.get('title')} self.data.update(data) self.params.update(data)
[ "def", "_set_data", "(", "self", ",", "action", ")", ":", "data", "=", "self", ".", "_load_response", "(", "action", ")", "self", ".", "_handle_continuations", "(", "data", ",", "'category'", ")", "if", "action", "==", "'category'", ":", "members", "=", "data", ".", "get", "(", "'query'", ")", ".", "get", "(", "'categorymembers'", ")", "if", "members", ":", "self", ".", "_add_members", "(", "members", ")", "if", "action", "==", "'random'", ":", "rand", "=", "data", "[", "'query'", "]", "[", "'random'", "]", "[", "0", "]", "data", "=", "{", "'pageid'", ":", "rand", ".", "get", "(", "'id'", ")", ",", "'title'", ":", "rand", ".", "get", "(", "'title'", ")", "}", "self", ".", "data", ".", "update", "(", "data", ")", "self", ".", "params", ".", "update", "(", "data", ")" ]
Set category member data from API response
[ "Set", "category", "member", "data", "from", "API", "response" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L104-L122
train
237,062
siznax/wptools
wptools/site.py
WPToolsSite._sitelist
def _sitelist(self, matrix): """ Returns a list of sites from a SiteMatrix, optionally filtered by 'domain' param """ _list = [] for item in matrix: sites = [] if isinstance(matrix[item], list): sites = matrix[item] elif isinstance(matrix[item], dict): sites = matrix[item]['site'] for site in sites: if len(site.keys()) > 4: # closed, fishbowl, private continue domain = self.params.get('domain') if domain: if domain in site['url']: _list.append(site['url']) else: _list.append(site['url']) return _list
python
def _sitelist(self, matrix): """ Returns a list of sites from a SiteMatrix, optionally filtered by 'domain' param """ _list = [] for item in matrix: sites = [] if isinstance(matrix[item], list): sites = matrix[item] elif isinstance(matrix[item], dict): sites = matrix[item]['site'] for site in sites: if len(site.keys()) > 4: # closed, fishbowl, private continue domain = self.params.get('domain') if domain: if domain in site['url']: _list.append(site['url']) else: _list.append(site['url']) return _list
[ "def", "_sitelist", "(", "self", ",", "matrix", ")", ":", "_list", "=", "[", "]", "for", "item", "in", "matrix", ":", "sites", "=", "[", "]", "if", "isinstance", "(", "matrix", "[", "item", "]", ",", "list", ")", ":", "sites", "=", "matrix", "[", "item", "]", "elif", "isinstance", "(", "matrix", "[", "item", "]", ",", "dict", ")", ":", "sites", "=", "matrix", "[", "item", "]", "[", "'site'", "]", "for", "site", "in", "sites", ":", "if", "len", "(", "site", ".", "keys", "(", ")", ")", ">", "4", ":", "# closed, fishbowl, private", "continue", "domain", "=", "self", ".", "params", ".", "get", "(", "'domain'", ")", "if", "domain", ":", "if", "domain", "in", "site", "[", "'url'", "]", ":", "_list", ".", "append", "(", "site", "[", "'url'", "]", ")", "else", ":", "_list", ".", "append", "(", "site", "[", "'url'", "]", ")", "return", "_list" ]
Returns a list of sites from a SiteMatrix, optionally filtered by 'domain' param
[ "Returns", "a", "list", "of", "sites", "from", "a", "SiteMatrix", "optionally", "filtered", "by", "domain", "param" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/site.py#L125-L149
train
237,063
siznax/wptools
wptools/core.py
handle_wikidata_errors
def handle_wikidata_errors(data, query): """ Raises LookupError if wikidata error found """ entities = data.get('entities') if not entities: raise LookupError(query) elif '-1' in entities: raise LookupError(query) else: item = list(entities.values())[0] if 'missing' in item: errmsg = "wikidata item %s has been deleted" % item['id'] raise LookupError(errmsg)
python
def handle_wikidata_errors(data, query): """ Raises LookupError if wikidata error found """ entities = data.get('entities') if not entities: raise LookupError(query) elif '-1' in entities: raise LookupError(query) else: item = list(entities.values())[0] if 'missing' in item: errmsg = "wikidata item %s has been deleted" % item['id'] raise LookupError(errmsg)
[ "def", "handle_wikidata_errors", "(", "data", ",", "query", ")", ":", "entities", "=", "data", ".", "get", "(", "'entities'", ")", "if", "not", "entities", ":", "raise", "LookupError", "(", "query", ")", "elif", "'-1'", "in", "entities", ":", "raise", "LookupError", "(", "query", ")", "else", ":", "item", "=", "list", "(", "entities", ".", "values", "(", ")", ")", "[", "0", "]", "if", "'missing'", "in", "item", ":", "errmsg", "=", "\"wikidata item %s has been deleted\"", "%", "item", "[", "'id'", "]", "raise", "LookupError", "(", "errmsg", ")" ]
Raises LookupError if wikidata error found
[ "Raises", "LookupError", "if", "wikidata", "error", "found" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L294-L308
train
237,064
siznax/wptools
wptools/core.py
prettyprint
def prettyprint(datastr): """ Print page data strings to stderr """ maxwidth = WPToolsQuery.MAXWIDTH rpad = WPToolsQuery.RPAD extent = maxwidth - (rpad + 2) for line in datastr: if len(line) >= maxwidth: line = line[:extent] + '...' utils.stderr(line)
python
def prettyprint(datastr): """ Print page data strings to stderr """ maxwidth = WPToolsQuery.MAXWIDTH rpad = WPToolsQuery.RPAD extent = maxwidth - (rpad + 2) for line in datastr: if len(line) >= maxwidth: line = line[:extent] + '...' utils.stderr(line)
[ "def", "prettyprint", "(", "datastr", ")", ":", "maxwidth", "=", "WPToolsQuery", ".", "MAXWIDTH", "rpad", "=", "WPToolsQuery", ".", "RPAD", "extent", "=", "maxwidth", "-", "(", "rpad", "+", "2", ")", "for", "line", "in", "datastr", ":", "if", "len", "(", "line", ")", ">=", "maxwidth", ":", "line", "=", "line", "[", ":", "extent", "]", "+", "'...'", "utils", ".", "stderr", "(", "line", ")" ]
Print page data strings to stderr
[ "Print", "page", "data", "strings", "to", "stderr" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L311-L322
train
237,065
siznax/wptools
wptools/core.py
WPTools._continue_params
def _continue_params(self): """ Returns query string fragment continue parameters """ if not self.data.get('continue'): return params = [] for item in self.data['continue']: params.append("&%s=%s" % (item, self.data['continue'][item])) return ''.join(params)
python
def _continue_params(self): """ Returns query string fragment continue parameters """ if not self.data.get('continue'): return params = [] for item in self.data['continue']: params.append("&%s=%s" % (item, self.data['continue'][item])) return ''.join(params)
[ "def", "_continue_params", "(", "self", ")", ":", "if", "not", "self", ".", "data", ".", "get", "(", "'continue'", ")", ":", "return", "params", "=", "[", "]", "for", "item", "in", "self", ".", "data", "[", "'continue'", "]", ":", "params", ".", "append", "(", "\"&%s=%s\"", "%", "(", "item", ",", "self", ".", "data", "[", "'continue'", "]", "[", "item", "]", ")", ")", "return", "''", ".", "join", "(", "params", ")" ]
Returns query string fragment continue parameters
[ "Returns", "query", "string", "fragment", "continue", "parameters" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L107-L118
train
237,066
siznax/wptools
wptools/core.py
WPTools._handle_continuations
def _handle_continuations(self, response, cache_key): """ Select continue params and clear cache or last continue params """ rcontinue = response.get('continue') listen = ['blcontinue', 'cmcontinue', 'plcontinue'] cparams = {} if rcontinue: for flag in listen: if rcontinue.get(flag): cparams[flag] = rcontinue.get(flag) if cparams: self.data['continue'] = cparams del self.cache[cache_key] else: # no more continuations if 'continue' in self.data: del self.data['continue']
python
def _handle_continuations(self, response, cache_key): """ Select continue params and clear cache or last continue params """ rcontinue = response.get('continue') listen = ['blcontinue', 'cmcontinue', 'plcontinue'] cparams = {} if rcontinue: for flag in listen: if rcontinue.get(flag): cparams[flag] = rcontinue.get(flag) if cparams: self.data['continue'] = cparams del self.cache[cache_key] else: # no more continuations if 'continue' in self.data: del self.data['continue']
[ "def", "_handle_continuations", "(", "self", ",", "response", ",", "cache_key", ")", ":", "rcontinue", "=", "response", ".", "get", "(", "'continue'", ")", "listen", "=", "[", "'blcontinue'", ",", "'cmcontinue'", ",", "'plcontinue'", "]", "cparams", "=", "{", "}", "if", "rcontinue", ":", "for", "flag", "in", "listen", ":", "if", "rcontinue", ".", "get", "(", "flag", ")", ":", "cparams", "[", "flag", "]", "=", "rcontinue", ".", "get", "(", "flag", ")", "if", "cparams", ":", "self", ".", "data", "[", "'continue'", "]", "=", "cparams", "del", "self", ".", "cache", "[", "cache_key", "]", "else", ":", "# no more continuations", "if", "'continue'", "in", "self", ".", "data", ":", "del", "self", ".", "data", "[", "'continue'", "]" ]
Select continue params and clear cache or last continue params
[ "Select", "continue", "params", "and", "clear", "cache", "or", "last", "continue", "params" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L120-L138
train
237,067
siznax/wptools
wptools/core.py
WPTools._get
def _get(self, action, show, proxy, timeout): """ make HTTP request and cache response """ silent = self.flags['silent'] if action in self.cache: if action != 'imageinfo' and action != 'labels': utils.stderr("+ %s results in cache" % action, silent) return else: self.cache[action] = {} if self.flags.get('skip') and action in self.flags['skip']: if not self.flags['silent']: utils.stderr("+ skipping %s" % action) return if 'requests' not in self.data: self.data['requests'] = [] if len(self.data['requests']) >= self.REQUEST_LIMIT: raise StopIteration("Hit REQUEST_LIMIT = %d" % self.REQUEST_LIMIT) if self.data['requests'] and self.REQUEST_DELAY: utils.stderr("REQUEST_DELAY = %d seconds" % self.REQUEST_DELAY) sleep(self.REQUEST_DELAY) # make the request qobj = WPToolsQuery(lang=self.params['lang'], variant=self.params.get('variant'), wiki=self.params.get('wiki'), endpoint=self.params.get('endpoint')) qstr = self._query(action, qobj) req = self._request(proxy, timeout) response = req.get(qstr, qobj.status) self.cache[action]['query'] = qstr self.cache[action]['response'] = response self.cache[action]['info'] = req.info self.data['requests'].append(action) self._set_data(action) if show and not self.flags.get('silent'): self.show()
python
def _get(self, action, show, proxy, timeout): """ make HTTP request and cache response """ silent = self.flags['silent'] if action in self.cache: if action != 'imageinfo' and action != 'labels': utils.stderr("+ %s results in cache" % action, silent) return else: self.cache[action] = {} if self.flags.get('skip') and action in self.flags['skip']: if not self.flags['silent']: utils.stderr("+ skipping %s" % action) return if 'requests' not in self.data: self.data['requests'] = [] if len(self.data['requests']) >= self.REQUEST_LIMIT: raise StopIteration("Hit REQUEST_LIMIT = %d" % self.REQUEST_LIMIT) if self.data['requests'] and self.REQUEST_DELAY: utils.stderr("REQUEST_DELAY = %d seconds" % self.REQUEST_DELAY) sleep(self.REQUEST_DELAY) # make the request qobj = WPToolsQuery(lang=self.params['lang'], variant=self.params.get('variant'), wiki=self.params.get('wiki'), endpoint=self.params.get('endpoint')) qstr = self._query(action, qobj) req = self._request(proxy, timeout) response = req.get(qstr, qobj.status) self.cache[action]['query'] = qstr self.cache[action]['response'] = response self.cache[action]['info'] = req.info self.data['requests'].append(action) self._set_data(action) if show and not self.flags.get('silent'): self.show()
[ "def", "_get", "(", "self", ",", "action", ",", "show", ",", "proxy", ",", "timeout", ")", ":", "silent", "=", "self", ".", "flags", "[", "'silent'", "]", "if", "action", "in", "self", ".", "cache", ":", "if", "action", "!=", "'imageinfo'", "and", "action", "!=", "'labels'", ":", "utils", ".", "stderr", "(", "\"+ %s results in cache\"", "%", "action", ",", "silent", ")", "return", "else", ":", "self", ".", "cache", "[", "action", "]", "=", "{", "}", "if", "self", ".", "flags", ".", "get", "(", "'skip'", ")", "and", "action", "in", "self", ".", "flags", "[", "'skip'", "]", ":", "if", "not", "self", ".", "flags", "[", "'silent'", "]", ":", "utils", ".", "stderr", "(", "\"+ skipping %s\"", "%", "action", ")", "return", "if", "'requests'", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'requests'", "]", "=", "[", "]", "if", "len", "(", "self", ".", "data", "[", "'requests'", "]", ")", ">=", "self", ".", "REQUEST_LIMIT", ":", "raise", "StopIteration", "(", "\"Hit REQUEST_LIMIT = %d\"", "%", "self", ".", "REQUEST_LIMIT", ")", "if", "self", ".", "data", "[", "'requests'", "]", "and", "self", ".", "REQUEST_DELAY", ":", "utils", ".", "stderr", "(", "\"REQUEST_DELAY = %d seconds\"", "%", "self", ".", "REQUEST_DELAY", ")", "sleep", "(", "self", ".", "REQUEST_DELAY", ")", "# make the request", "qobj", "=", "WPToolsQuery", "(", "lang", "=", "self", ".", "params", "[", "'lang'", "]", ",", "variant", "=", "self", ".", "params", ".", "get", "(", "'variant'", ")", ",", "wiki", "=", "self", ".", "params", ".", "get", "(", "'wiki'", ")", ",", "endpoint", "=", "self", ".", "params", ".", "get", "(", "'endpoint'", ")", ")", "qstr", "=", "self", ".", "_query", "(", "action", ",", "qobj", ")", "req", "=", "self", ".", "_request", "(", "proxy", ",", "timeout", ")", "response", "=", "req", ".", "get", "(", "qstr", ",", "qobj", ".", "status", ")", "self", ".", "cache", "[", "action", "]", "[", "'query'", "]", "=", "qstr", "self", ".", "cache", "[", "action", "]", "[", "'response'", "]", "=", "response", "self", ".", "cache", "[", "action", "]", "[", "'info'", "]", "=", "req", ".", "info", "self", ".", "data", "[", "'requests'", "]", ".", "append", "(", "action", ")", "self", ".", "_set_data", "(", "action", ")", "if", "show", "and", "not", "self", ".", "flags", ".", "get", "(", "'silent'", ")", ":", "self", ".", "show", "(", ")" ]
make HTTP request and cache response
[ "make", "HTTP", "request", "and", "cache", "response" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L140-L186
train
237,068
siznax/wptools
wptools/core.py
WPTools._load_response
def _load_response(self, action): """ returns API reponse from cache or raises ValueError """ _query = self.cache[action]['query'].replace('&format=json', '') response = self.cache[action]['response'] if not response: raise ValueError("Empty response: %s" % self.params) try: data = utils.json_loads(response) except ValueError: raise ValueError(_query) if data.get('warnings'): if 'WARNINGS' in self.data: self.data['WARNINGS'].update(data['warnings']) else: self.data['WARNINGS'] = data['warnings'] if data.get('error'): utils.stderr("API error: %s" % data.get('error')) raise LookupError(_query) if 'query' in action and data.get('query'): if data['query'].get('pages'): if data['query']['pages'][0].get('missing'): raise LookupError(_query) if action == 'parse' and not data.get('parse'): raise LookupError(_query) if action == 'wikidata': handle_wikidata_errors(data, _query) return data
python
def _load_response(self, action): """ returns API reponse from cache or raises ValueError """ _query = self.cache[action]['query'].replace('&format=json', '') response = self.cache[action]['response'] if not response: raise ValueError("Empty response: %s" % self.params) try: data = utils.json_loads(response) except ValueError: raise ValueError(_query) if data.get('warnings'): if 'WARNINGS' in self.data: self.data['WARNINGS'].update(data['warnings']) else: self.data['WARNINGS'] = data['warnings'] if data.get('error'): utils.stderr("API error: %s" % data.get('error')) raise LookupError(_query) if 'query' in action and data.get('query'): if data['query'].get('pages'): if data['query']['pages'][0].get('missing'): raise LookupError(_query) if action == 'parse' and not data.get('parse'): raise LookupError(_query) if action == 'wikidata': handle_wikidata_errors(data, _query) return data
[ "def", "_load_response", "(", "self", ",", "action", ")", ":", "_query", "=", "self", ".", "cache", "[", "action", "]", "[", "'query'", "]", ".", "replace", "(", "'&format=json'", ",", "''", ")", "response", "=", "self", ".", "cache", "[", "action", "]", "[", "'response'", "]", "if", "not", "response", ":", "raise", "ValueError", "(", "\"Empty response: %s\"", "%", "self", ".", "params", ")", "try", ":", "data", "=", "utils", ".", "json_loads", "(", "response", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "_query", ")", "if", "data", ".", "get", "(", "'warnings'", ")", ":", "if", "'WARNINGS'", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'WARNINGS'", "]", ".", "update", "(", "data", "[", "'warnings'", "]", ")", "else", ":", "self", ".", "data", "[", "'WARNINGS'", "]", "=", "data", "[", "'warnings'", "]", "if", "data", ".", "get", "(", "'error'", ")", ":", "utils", ".", "stderr", "(", "\"API error: %s\"", "%", "data", ".", "get", "(", "'error'", ")", ")", "raise", "LookupError", "(", "_query", ")", "if", "'query'", "in", "action", "and", "data", ".", "get", "(", "'query'", ")", ":", "if", "data", "[", "'query'", "]", ".", "get", "(", "'pages'", ")", ":", "if", "data", "[", "'query'", "]", "[", "'pages'", "]", "[", "0", "]", ".", "get", "(", "'missing'", ")", ":", "raise", "LookupError", "(", "_query", ")", "if", "action", "==", "'parse'", "and", "not", "data", ".", "get", "(", "'parse'", ")", ":", "raise", "LookupError", "(", "_query", ")", "if", "action", "==", "'wikidata'", ":", "handle_wikidata_errors", "(", "data", ",", "_query", ")", "return", "data" ]
returns API reponse from cache or raises ValueError
[ "returns", "API", "reponse", "from", "cache", "or", "raises", "ValueError" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L188-L224
train
237,069
siznax/wptools
wptools/core.py
WPTools._request
def _request(self, proxy, timeout): """ Returns WPToolsRequest object """ return request.WPToolsRequest(self.flags['silent'], self.flags['verbose'], proxy, timeout)
python
def _request(self, proxy, timeout): """ Returns WPToolsRequest object """ return request.WPToolsRequest(self.flags['silent'], self.flags['verbose'], proxy, timeout)
[ "def", "_request", "(", "self", ",", "proxy", ",", "timeout", ")", ":", "return", "request", ".", "WPToolsRequest", "(", "self", ".", "flags", "[", "'silent'", "]", ",", "self", ".", "flags", "[", "'verbose'", "]", ",", "proxy", ",", "timeout", ")" ]
Returns WPToolsRequest object
[ "Returns", "WPToolsRequest", "object" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L232-L238
train
237,070
siznax/wptools
wptools/core.py
WPTools.info
def info(self, action=None): """ returns cached request info for given action, or list of cached actions """ if action in self.cache: return self.cache[action]['info'] return self.cache.keys() or None
python
def info(self, action=None): """ returns cached request info for given action, or list of cached actions """ if action in self.cache: return self.cache[action]['info'] return self.cache.keys() or None
[ "def", "info", "(", "self", ",", "action", "=", "None", ")", ":", "if", "action", "in", "self", ".", "cache", ":", "return", "self", ".", "cache", "[", "action", "]", "[", "'info'", "]", "return", "self", ".", "cache", ".", "keys", "(", ")", "or", "None" ]
returns cached request info for given action, or list of cached actions
[ "returns", "cached", "request", "info", "for", "given", "action", "or", "list", "of", "cached", "actions" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L246-L253
train
237,071
siznax/wptools
wptools/core.py
WPTools.show
def show(self): """ Pretty-print instance data """ if not self.data: return if self.data.get('continue'): return ptitle = self.params.get('title') dtitle = self.data.get('title') pageid = self.params.get('pageid') seed = dtitle or ptitle or pageid if utils.is_text(seed): seed = seed.replace('_', ' ') prettyprint(self._build_showstr(seed))
python
def show(self): """ Pretty-print instance data """ if not self.data: return if self.data.get('continue'): return ptitle = self.params.get('title') dtitle = self.data.get('title') pageid = self.params.get('pageid') seed = dtitle or ptitle or pageid if utils.is_text(seed): seed = seed.replace('_', ' ') prettyprint(self._build_showstr(seed))
[ "def", "show", "(", "self", ")", ":", "if", "not", "self", ".", "data", ":", "return", "if", "self", ".", "data", ".", "get", "(", "'continue'", ")", ":", "return", "ptitle", "=", "self", ".", "params", ".", "get", "(", "'title'", ")", "dtitle", "=", "self", ".", "data", ".", "get", "(", "'title'", ")", "pageid", "=", "self", ".", "params", ".", "get", "(", "'pageid'", ")", "seed", "=", "dtitle", "or", "ptitle", "or", "pageid", "if", "utils", ".", "is_text", "(", "seed", ")", ":", "seed", "=", "seed", ".", "replace", "(", "'_'", ",", "' '", ")", "prettyprint", "(", "self", ".", "_build_showstr", "(", "seed", ")", ")" ]
Pretty-print instance data
[ "Pretty", "-", "print", "instance", "data" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L273-L291
train
237,072
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._get_entity_prop
def _get_entity_prop(self, entity, prop): """ returns Wikidata entity property value """ variant = self.params.get('variant') lang = self.params.get('lang') if entity.get(prop): ent = entity[prop] try: return ent[variant or lang].get('value') except AttributeError: return ent.get('value')
python
def _get_entity_prop(self, entity, prop): """ returns Wikidata entity property value """ variant = self.params.get('variant') lang = self.params.get('lang') if entity.get(prop): ent = entity[prop] try: return ent[variant or lang].get('value') except AttributeError: return ent.get('value')
[ "def", "_get_entity_prop", "(", "self", ",", "entity", ",", "prop", ")", ":", "variant", "=", "self", ".", "params", ".", "get", "(", "'variant'", ")", "lang", "=", "self", ".", "params", ".", "get", "(", "'lang'", ")", "if", "entity", ".", "get", "(", "prop", ")", ":", "ent", "=", "entity", "[", "prop", "]", "try", ":", "return", "ent", "[", "variant", "or", "lang", "]", ".", "get", "(", "'value'", ")", "except", "AttributeError", ":", "return", "ent", ".", "get", "(", "'value'", ")" ]
returns Wikidata entity property value
[ "returns", "Wikidata", "entity", "property", "value" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L49-L61
train
237,073
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._marshal_claims
def _marshal_claims(self, query_claims): """ set Wikidata entities from query claims """ claims = reduce_claims(query_claims) # self.data['claimq'] = query_claims self.data['claims'] = claims entities = set() for eid in claims: if self.user_labels: if eid in self.user_labels or eid == 'P31': entities.add(eid) # P (property) else: continue # get only wanted entities else: entities.add(eid) # P (property) for val in claims[eid]: if utils.is_text(val) and re.match(r'^Q\d+$', val): entities.add(val) # Q (item) self.data['entities'] = list(entities)
python
def _marshal_claims(self, query_claims): """ set Wikidata entities from query claims """ claims = reduce_claims(query_claims) # self.data['claimq'] = query_claims self.data['claims'] = claims entities = set() for eid in claims: if self.user_labels: if eid in self.user_labels or eid == 'P31': entities.add(eid) # P (property) else: continue # get only wanted entities else: entities.add(eid) # P (property) for val in claims[eid]: if utils.is_text(val) and re.match(r'^Q\d+$', val): entities.add(val) # Q (item) self.data['entities'] = list(entities)
[ "def", "_marshal_claims", "(", "self", ",", "query_claims", ")", ":", "claims", "=", "reduce_claims", "(", "query_claims", ")", "# self.data['claimq'] = query_claims", "self", ".", "data", "[", "'claims'", "]", "=", "claims", "entities", "=", "set", "(", ")", "for", "eid", "in", "claims", ":", "if", "self", ".", "user_labels", ":", "if", "eid", "in", "self", ".", "user_labels", "or", "eid", "==", "'P31'", ":", "entities", ".", "add", "(", "eid", ")", "# P (property)", "else", ":", "continue", "# get only wanted entities", "else", ":", "entities", ".", "add", "(", "eid", ")", "# P (property)", "for", "val", "in", "claims", "[", "eid", "]", ":", "if", "utils", ".", "is_text", "(", "val", ")", "and", "re", ".", "match", "(", "r'^Q\\d+$'", ",", "val", ")", ":", "entities", ".", "add", "(", "val", ")", "# Q (item)", "self", ".", "data", "[", "'entities'", "]", "=", "list", "(", "entities", ")" ]
set Wikidata entities from query claims
[ "set", "Wikidata", "entities", "from", "query", "claims" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L63-L85
train
237,074
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._pop_entities
def _pop_entities(self, limit=50): """ returns up to limit entities and pops them off the list """ pop = self.data['entities'][:limit] del self.data['entities'][:limit] return pop
python
def _pop_entities(self, limit=50): """ returns up to limit entities and pops them off the list """ pop = self.data['entities'][:limit] del self.data['entities'][:limit] return pop
[ "def", "_pop_entities", "(", "self", ",", "limit", "=", "50", ")", ":", "pop", "=", "self", ".", "data", "[", "'entities'", "]", "[", ":", "limit", "]", "del", "self", ".", "data", "[", "'entities'", "]", "[", ":", "limit", "]", "return", "pop" ]
returns up to limit entities and pops them off the list
[ "returns", "up", "to", "limit", "entities", "and", "pops", "them", "off", "the", "list" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L87-L93
train
237,075
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._query
def _query(self, action, qobj): """ returns wikidata query string """ if action == 'labels': return qobj.labels(self._pop_entities()) elif action == 'wikidata': return qobj.wikidata(self.params.get('title'), self.params.get('wikibase'))
python
def _query(self, action, qobj): """ returns wikidata query string """ if action == 'labels': return qobj.labels(self._pop_entities()) elif action == 'wikidata': return qobj.wikidata(self.params.get('title'), self.params.get('wikibase'))
[ "def", "_query", "(", "self", ",", "action", ",", "qobj", ")", ":", "if", "action", "==", "'labels'", ":", "return", "qobj", ".", "labels", "(", "self", ".", "_pop_entities", "(", ")", ")", "elif", "action", "==", "'wikidata'", ":", "return", "qobj", ".", "wikidata", "(", "self", ".", "params", ".", "get", "(", "'title'", ")", ",", "self", ".", "params", ".", "get", "(", "'wikibase'", ")", ")" ]
returns wikidata query string
[ "returns", "wikidata", "query", "string" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L103-L111
train
237,076
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._set_title
def _set_title(self, item): """ attempt to set title from wikidata """ title = None lang = self.params['lang'] label = self.data['label'] if item.get('sitelinks'): for link in item['sitelinks']: if link == "%swiki" % lang: title = item['sitelinks'][link]['title'] self.data['title'] = title.replace(' ', '_') if not self.data.get('title') and label: self.data['title'] = label.replace(' ', '_') if self.data.get('title') and not self.params.get('title'): self.params['title'] = self.data['title']
python
def _set_title(self, item): """ attempt to set title from wikidata """ title = None lang = self.params['lang'] label = self.data['label'] if item.get('sitelinks'): for link in item['sitelinks']: if link == "%swiki" % lang: title = item['sitelinks'][link]['title'] self.data['title'] = title.replace(' ', '_') if not self.data.get('title') and label: self.data['title'] = label.replace(' ', '_') if self.data.get('title') and not self.params.get('title'): self.params['title'] = self.data['title']
[ "def", "_set_title", "(", "self", ",", "item", ")", ":", "title", "=", "None", "lang", "=", "self", ".", "params", "[", "'lang'", "]", "label", "=", "self", ".", "data", "[", "'label'", "]", "if", "item", ".", "get", "(", "'sitelinks'", ")", ":", "for", "link", "in", "item", "[", "'sitelinks'", "]", ":", "if", "link", "==", "\"%swiki\"", "%", "lang", ":", "title", "=", "item", "[", "'sitelinks'", "]", "[", "link", "]", "[", "'title'", "]", "self", ".", "data", "[", "'title'", "]", "=", "title", ".", "replace", "(", "' '", ",", "'_'", ")", "if", "not", "self", ".", "data", ".", "get", "(", "'title'", ")", "and", "label", ":", "self", ".", "data", "[", "'title'", "]", "=", "label", ".", "replace", "(", "' '", ",", "'_'", ")", "if", "self", ".", "data", ".", "get", "(", "'title'", ")", "and", "not", "self", ".", "params", ".", "get", "(", "'title'", ")", ":", "self", ".", "params", "[", "'title'", "]", "=", "self", ".", "data", "[", "'title'", "]" ]
attempt to set title from wikidata
[ "attempt", "to", "set", "title", "from", "wikidata" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L135-L153
train
237,077
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._update_images
def _update_images(self): """ add images from Wikidata """ wd_images = self.data['claims'].get('P18') # image if wd_images: if not isinstance(wd_images, list): wd_images = [wd_images] if 'image' not in self.data: self.data['image'] = [] for img_file in wd_images: self.data['image'].append({'file': img_file, 'kind': 'wikidata-image'})
python
def _update_images(self): """ add images from Wikidata """ wd_images = self.data['claims'].get('P18') # image if wd_images: if not isinstance(wd_images, list): wd_images = [wd_images] if 'image' not in self.data: self.data['image'] = [] for img_file in wd_images: self.data['image'].append({'file': img_file, 'kind': 'wikidata-image'})
[ "def", "_update_images", "(", "self", ")", ":", "wd_images", "=", "self", ".", "data", "[", "'claims'", "]", ".", "get", "(", "'P18'", ")", "# image", "if", "wd_images", ":", "if", "not", "isinstance", "(", "wd_images", ",", "list", ")", ":", "wd_images", "=", "[", "wd_images", "]", "if", "'image'", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'image'", "]", "=", "[", "]", "for", "img_file", "in", "wd_images", ":", "self", ".", "data", "[", "'image'", "]", ".", "append", "(", "{", "'file'", ":", "img_file", ",", "'kind'", ":", "'wikidata-image'", "}", ")" ]
add images from Wikidata
[ "add", "images", "from", "Wikidata" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L190-L205
train
237,078
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._update_wikidata
def _update_wikidata(self): """ set wikidata from claims and labels """ claims = self.data['claims'] for ent in claims: plabel = self.data['labels'].get(ent) # P (property) label if plabel: plabel = "%s (%s)" % (plabel, ent) claim = [] for item in claims[ent]: ilabel = item if utils.is_text(item) and re.match(r'^Q\d+$', item): ilabel = self.data['labels'].get(item) # Q (item) label if ilabel: ilabel = "%s (%s)" % (ilabel, item) if len(claims[ent]) == 1: claim = ilabel else: claim.append(ilabel) if plabel and ilabel: self.data['wikidata'][plabel] = claim
python
def _update_wikidata(self): """ set wikidata from claims and labels """ claims = self.data['claims'] for ent in claims: plabel = self.data['labels'].get(ent) # P (property) label if plabel: plabel = "%s (%s)" % (plabel, ent) claim = [] for item in claims[ent]: ilabel = item if utils.is_text(item) and re.match(r'^Q\d+$', item): ilabel = self.data['labels'].get(item) # Q (item) label if ilabel: ilabel = "%s (%s)" % (ilabel, item) if len(claims[ent]) == 1: claim = ilabel else: claim.append(ilabel) if plabel and ilabel: self.data['wikidata'][plabel] = claim
[ "def", "_update_wikidata", "(", "self", ")", ":", "claims", "=", "self", ".", "data", "[", "'claims'", "]", "for", "ent", "in", "claims", ":", "plabel", "=", "self", ".", "data", "[", "'labels'", "]", ".", "get", "(", "ent", ")", "# P (property) label", "if", "plabel", ":", "plabel", "=", "\"%s (%s)\"", "%", "(", "plabel", ",", "ent", ")", "claim", "=", "[", "]", "for", "item", "in", "claims", "[", "ent", "]", ":", "ilabel", "=", "item", "if", "utils", ".", "is_text", "(", "item", ")", "and", "re", ".", "match", "(", "r'^Q\\d+$'", ",", "item", ")", ":", "ilabel", "=", "self", ".", "data", "[", "'labels'", "]", ".", "get", "(", "item", ")", "# Q (item) label", "if", "ilabel", ":", "ilabel", "=", "\"%s (%s)\"", "%", "(", "ilabel", ",", "item", ")", "if", "len", "(", "claims", "[", "ent", "]", ")", "==", "1", ":", "claim", "=", "ilabel", "else", ":", "claim", ".", "append", "(", "ilabel", ")", "if", "plabel", "and", "ilabel", ":", "self", ".", "data", "[", "'wikidata'", "]", "[", "plabel", "]", "=", "claim" ]
set wikidata from claims and labels
[ "set", "wikidata", "from", "claims", "and", "labels" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L223-L249
train
237,079
siznax/wptools
scripts/wptool.py
_html_image
def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return alt = page.data.get('label') or page.data.get('title') img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % (alt, alt) img += "align=\"right\" width=\"240\">" return img
python
def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return alt = page.data.get('label') or page.data.get('title') img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % (alt, alt) img += "align=\"right\" width=\"240\">" return img
[ "def", "_html_image", "(", "page", ")", ":", "source", "=", "_image", "(", "page", ")", "if", "not", "source", ":", "return", "alt", "=", "page", ".", "data", ".", "get", "(", "'label'", ")", "or", "page", ".", "data", ".", "get", "(", "'title'", ")", "img", "=", "\"<img src=\\\"%s\\\"\"", "%", "source", "img", "+=", "\" alt=\\\"%s\\\" title=\\\"%s\\\" \"", "%", "(", "alt", ",", "alt", ")", "img", "+=", "\"align=\\\"right\\\" width=\\\"240\\\">\"", "return", "img" ]
returns HTML img tag
[ "returns", "HTML", "img", "tag" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L19-L30
train
237,080
siznax/wptools
scripts/wptool.py
_html_title
def _html_title(page): """ returns Wiki-linked HTML title """ link = "<a href=\"%s\">%s</a>" % (page.data.get('url'), page.data.get('title')) desc = page.data.get('description') if desc: link += "&mdash;<i>%s</i>" % desc else: link += "&mdash;<i>description</i>" if link: return "<p>%s</p>" % link
python
def _html_title(page): """ returns Wiki-linked HTML title """ link = "<a href=\"%s\">%s</a>" % (page.data.get('url'), page.data.get('title')) desc = page.data.get('description') if desc: link += "&mdash;<i>%s</i>" % desc else: link += "&mdash;<i>description</i>" if link: return "<p>%s</p>" % link
[ "def", "_html_title", "(", "page", ")", ":", "link", "=", "\"<a href=\\\"%s\\\">%s</a>\"", "%", "(", "page", ".", "data", ".", "get", "(", "'url'", ")", ",", "page", ".", "data", ".", "get", "(", "'title'", ")", ")", "desc", "=", "page", ".", "data", ".", "get", "(", "'description'", ")", "if", "desc", ":", "link", "+=", "\"&mdash;<i>%s</i>\"", "%", "desc", "else", ":", "link", "+=", "\"&mdash;<i>description</i>\"", "if", "link", ":", "return", "\"<p>%s</p>\"", "%", "link" ]
returns Wiki-linked HTML title
[ "returns", "Wiki", "-", "linked", "HTML", "title" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L33-L45
train
237,081
siznax/wptools
scripts/wptool.py
_page_html
def _page_html(page): """ returns assembled HTML output """ out = [] out.append(_html_title(page)) out.append(_html_image(page)) out.append(page.data.get('extract')) return "\n".join([x for x in out if x])
python
def _page_html(page): """ returns assembled HTML output """ out = [] out.append(_html_title(page)) out.append(_html_image(page)) out.append(page.data.get('extract')) return "\n".join([x for x in out if x])
[ "def", "_page_html", "(", "page", ")", ":", "out", "=", "[", "]", "out", ".", "append", "(", "_html_title", "(", "page", ")", ")", "out", ".", "append", "(", "_html_image", "(", "page", ")", ")", "out", ".", "append", "(", "page", ".", "data", ".", "get", "(", "'extract'", ")", ")", "return", "\"\\n\"", ".", "join", "(", "[", "x", "for", "x", "in", "out", "if", "x", "]", ")" ]
returns assembled HTML output
[ "returns", "assembled", "HTML", "output" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L57-L65
train
237,082
siznax/wptools
scripts/wptool.py
_page_text
def _page_text(page, nowrap=False): """ returns assembled text output """ title = page.data['title'] title = "%s\n%s" % (title, "=" * len(title)) desc = page.data.get('description') if desc: desc = "_%s_" % desc img = _text_image(page) pars = page.data.get('extext') if pars: # pars = pars.replace(' * ', '\n * ') pars = re.sub(r'[ ]+\*[ ]+', '* ', pars) if pars and not nowrap: parlist = [] for par in pars.split("\n\n"): parlist.append("\n".join(textwrap.wrap(par))) disambiguation = page.data.get('disambiguation') if disambiguation: parlist.append(' * ' + "\n * ".join(page.data.get('links'))) pars = "\n\n".join(parlist) url = '<%s>' % page.data['url'] txt = [] txt.append(title) txt.append(desc) txt.append(url) txt.append(pars) txt.append(img) return "\n\n".join([x for x in txt if x])
python
def _page_text(page, nowrap=False): """ returns assembled text output """ title = page.data['title'] title = "%s\n%s" % (title, "=" * len(title)) desc = page.data.get('description') if desc: desc = "_%s_" % desc img = _text_image(page) pars = page.data.get('extext') if pars: # pars = pars.replace(' * ', '\n * ') pars = re.sub(r'[ ]+\*[ ]+', '* ', pars) if pars and not nowrap: parlist = [] for par in pars.split("\n\n"): parlist.append("\n".join(textwrap.wrap(par))) disambiguation = page.data.get('disambiguation') if disambiguation: parlist.append(' * ' + "\n * ".join(page.data.get('links'))) pars = "\n\n".join(parlist) url = '<%s>' % page.data['url'] txt = [] txt.append(title) txt.append(desc) txt.append(url) txt.append(pars) txt.append(img) return "\n\n".join([x for x in txt if x])
[ "def", "_page_text", "(", "page", ",", "nowrap", "=", "False", ")", ":", "title", "=", "page", ".", "data", "[", "'title'", "]", "title", "=", "\"%s\\n%s\"", "%", "(", "title", ",", "\"=\"", "*", "len", "(", "title", ")", ")", "desc", "=", "page", ".", "data", ".", "get", "(", "'description'", ")", "if", "desc", ":", "desc", "=", "\"_%s_\"", "%", "desc", "img", "=", "_text_image", "(", "page", ")", "pars", "=", "page", ".", "data", ".", "get", "(", "'extext'", ")", "if", "pars", ":", "# pars = pars.replace(' * ', '\\n * ')", "pars", "=", "re", ".", "sub", "(", "r'[ ]+\\*[ ]+'", ",", "'* '", ",", "pars", ")", "if", "pars", "and", "not", "nowrap", ":", "parlist", "=", "[", "]", "for", "par", "in", "pars", ".", "split", "(", "\"\\n\\n\"", ")", ":", "parlist", ".", "append", "(", "\"\\n\"", ".", "join", "(", "textwrap", ".", "wrap", "(", "par", ")", ")", ")", "disambiguation", "=", "page", ".", "data", ".", "get", "(", "'disambiguation'", ")", "if", "disambiguation", ":", "parlist", ".", "append", "(", "' * '", "+", "\"\\n * \"", ".", "join", "(", "page", ".", "data", ".", "get", "(", "'links'", ")", ")", ")", "pars", "=", "\"\\n\\n\"", ".", "join", "(", "parlist", ")", "url", "=", "'<%s>'", "%", "page", ".", "data", "[", "'url'", "]", "txt", "=", "[", "]", "txt", ".", "append", "(", "title", ")", "txt", ".", "append", "(", "desc", ")", "txt", ".", "append", "(", "url", ")", "txt", ".", "append", "(", "pars", ")", "txt", ".", "append", "(", "img", ")", "return", "\"\\n\\n\"", ".", "join", "(", "[", "x", "for", "x", "in", "txt", "if", "x", "]", ")" ]
returns assembled text output
[ "returns", "assembled", "text", "output" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L68-L107
train
237,083
siznax/wptools
scripts/wptool.py
_safe_exit
def _safe_exit(start, output): """ exit without breaking pipes """ try: sys.stdout.write(output) sys.stdout.flush() except TypeError: # python3 sys.stdout.write(str(output, 'utf-8')) sys.stdout.flush() except IOError: pass seconds = time.time() - start print("\n\n%5.3f seconds" % (seconds), file=sys.stderr)
python
def _safe_exit(start, output): """ exit without breaking pipes """ try: sys.stdout.write(output) sys.stdout.flush() except TypeError: # python3 sys.stdout.write(str(output, 'utf-8')) sys.stdout.flush() except IOError: pass seconds = time.time() - start print("\n\n%5.3f seconds" % (seconds), file=sys.stderr)
[ "def", "_safe_exit", "(", "start", ",", "output", ")", ":", "try", ":", "sys", ".", "stdout", ".", "write", "(", "output", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "except", "TypeError", ":", "# python3", "sys", ".", "stdout", ".", "write", "(", "str", "(", "output", ",", "'utf-8'", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "except", "IOError", ":", "pass", "seconds", "=", "time", ".", "time", "(", ")", "-", "start", "print", "(", "\"\\n\\n%5.3f seconds\"", "%", "(", "seconds", ")", ",", "file", "=", "sys", ".", "stderr", ")" ]
exit without breaking pipes
[ "exit", "without", "breaking", "pipes" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L110-L124
train
237,084
siznax/wptools
scripts/wptool.py
_text_image
def _text_image(page): """ returns text image URL """ img = None alt = page.data.get('label') or page.data.get('title') source = _image(page) if source: img = "![%s](%s)" % (alt, source) return img
python
def _text_image(page): """ returns text image URL """ img = None alt = page.data.get('label') or page.data.get('title') source = _image(page) if source: img = "![%s](%s)" % (alt, source) return img
[ "def", "_text_image", "(", "page", ")", ":", "img", "=", "None", "alt", "=", "page", ".", "data", ".", "get", "(", "'label'", ")", "or", "page", ".", "data", ".", "get", "(", "'title'", ")", "source", "=", "_image", "(", "page", ")", "if", "source", ":", "img", "=", "\"![%s](%s)\"", "%", "(", "alt", ",", "source", ")", "return", "img" ]
returns text image URL
[ "returns", "text", "image", "URL" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L127-L136
train
237,085
siznax/wptools
scripts/wptool.py
get
def get(args): """ invoke wptools and assemble selected output """ html = args.H lang = args.l nowrap = args.n query = args.q silent = args.s title = args.t verbose = args.v wiki = args.w if query: qobj = WPToolsQuery(lang=lang, wiki=wiki) if title: return qobj.query(title) return qobj.random() page = wptools.page(title, lang=lang, silent=silent, verbose=verbose, wiki=wiki) try: page.get_query() except (StandardError, ValueError, LookupError): return "NOT_FOUND" if not page.data.get('extext'): out = page.cache['query']['query'] out = _page_text(page, nowrap) if html: out = _page_html(page) try: return out.encode('utf-8') except KeyError: return out
python
def get(args): """ invoke wptools and assemble selected output """ html = args.H lang = args.l nowrap = args.n query = args.q silent = args.s title = args.t verbose = args.v wiki = args.w if query: qobj = WPToolsQuery(lang=lang, wiki=wiki) if title: return qobj.query(title) return qobj.random() page = wptools.page(title, lang=lang, silent=silent, verbose=verbose, wiki=wiki) try: page.get_query() except (StandardError, ValueError, LookupError): return "NOT_FOUND" if not page.data.get('extext'): out = page.cache['query']['query'] out = _page_text(page, nowrap) if html: out = _page_html(page) try: return out.encode('utf-8') except KeyError: return out
[ "def", "get", "(", "args", ")", ":", "html", "=", "args", ".", "H", "lang", "=", "args", ".", "l", "nowrap", "=", "args", ".", "n", "query", "=", "args", ".", "q", "silent", "=", "args", ".", "s", "title", "=", "args", ".", "t", "verbose", "=", "args", ".", "v", "wiki", "=", "args", ".", "w", "if", "query", ":", "qobj", "=", "WPToolsQuery", "(", "lang", "=", "lang", ",", "wiki", "=", "wiki", ")", "if", "title", ":", "return", "qobj", ".", "query", "(", "title", ")", "return", "qobj", ".", "random", "(", ")", "page", "=", "wptools", ".", "page", "(", "title", ",", "lang", "=", "lang", ",", "silent", "=", "silent", ",", "verbose", "=", "verbose", ",", "wiki", "=", "wiki", ")", "try", ":", "page", ".", "get_query", "(", ")", "except", "(", "StandardError", ",", "ValueError", ",", "LookupError", ")", ":", "return", "\"NOT_FOUND\"", "if", "not", "page", ".", "data", ".", "get", "(", "'extext'", ")", ":", "out", "=", "page", ".", "cache", "[", "'query'", "]", "[", "'query'", "]", "out", "=", "_page_text", "(", "page", ",", "nowrap", ")", "if", "html", ":", "out", "=", "_page_html", "(", "page", ")", "try", ":", "return", "out", ".", "encode", "(", "'utf-8'", ")", "except", "KeyError", ":", "return", "out" ]
invoke wptools and assemble selected output
[ "invoke", "wptools", "and", "assemble", "selected", "output" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L139-L177
train
237,086
siznax/wptools
scripts/wptool.py
main
def main(args): """ invoke wptools and exit safely """ start = time.time() output = get(args) _safe_exit(start, output)
python
def main(args): """ invoke wptools and exit safely """ start = time.time() output = get(args) _safe_exit(start, output)
[ "def", "main", "(", "args", ")", ":", "start", "=", "time", ".", "time", "(", ")", "output", "=", "get", "(", "args", ")", "_safe_exit", "(", "start", ",", "output", ")" ]
invoke wptools and exit safely
[ "invoke", "wptools", "and", "exit", "safely" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L213-L219
train
237,087
siznax/wptools
wptools/page.py
WPToolsPage.__insert_image_info
def __insert_image_info(self, title, _from, info): """ Insert API image INFO into matching image dict We make one imageinfo request containing only unique image filenames. We reduce duplication by asking for image data per file, instead of per "kind" or source (Wikipedia, Wikidata, etc.), because some sources reference the same image file. We match API imageinfo response data to existing image filenames by API title or normalized "from" title. So, some imageinfo data will be applied to more than one image "kind" (source) if they share the same filename. """ for img in self.data['image']: if 'url' not in img: if title == img['file']: # matching title/file img.update(info) elif _from == img['file']: # matching from/file img.update(info)
python
def __insert_image_info(self, title, _from, info): """ Insert API image INFO into matching image dict We make one imageinfo request containing only unique image filenames. We reduce duplication by asking for image data per file, instead of per "kind" or source (Wikipedia, Wikidata, etc.), because some sources reference the same image file. We match API imageinfo response data to existing image filenames by API title or normalized "from" title. So, some imageinfo data will be applied to more than one image "kind" (source) if they share the same filename. """ for img in self.data['image']: if 'url' not in img: if title == img['file']: # matching title/file img.update(info) elif _from == img['file']: # matching from/file img.update(info)
[ "def", "__insert_image_info", "(", "self", ",", "title", ",", "_from", ",", "info", ")", ":", "for", "img", "in", "self", ".", "data", "[", "'image'", "]", ":", "if", "'url'", "not", "in", "img", ":", "if", "title", "==", "img", "[", "'file'", "]", ":", "# matching title/file", "img", ".", "update", "(", "info", ")", "elif", "_from", "==", "img", "[", "'file'", "]", ":", "# matching from/file", "img", ".", "update", "(", "info", ")" ]
Insert API image INFO into matching image dict We make one imageinfo request containing only unique image filenames. We reduce duplication by asking for image data per file, instead of per "kind" or source (Wikipedia, Wikidata, etc.), because some sources reference the same image file. We match API imageinfo response data to existing image filenames by API title or normalized "from" title. So, some imageinfo data will be applied to more than one image "kind" (source) if they share the same filename.
[ "Insert", "API", "image", "INFO", "into", "matching", "image", "dict" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L84-L102
train
237,088
siznax/wptools
wptools/page.py
WPToolsPage.__pull_image_info
def __pull_image_info(self, title, imageinfo, normalized): """ Pull image INFO from API response and insert """ for info in imageinfo: info.update({'title': title}) # get API normalized "from" filename for matching _from = None for norm in normalized: if title == norm['to']: _from = norm['from'] # let's put all "metadata" in one member info['metadata'] = {} extmetadata = info.get('extmetadata') if extmetadata: info['metadata'].update(extmetadata) del info['extmetadata'] self.__insert_image_info(title, _from, info)
python
def __pull_image_info(self, title, imageinfo, normalized): """ Pull image INFO from API response and insert """ for info in imageinfo: info.update({'title': title}) # get API normalized "from" filename for matching _from = None for norm in normalized: if title == norm['to']: _from = norm['from'] # let's put all "metadata" in one member info['metadata'] = {} extmetadata = info.get('extmetadata') if extmetadata: info['metadata'].update(extmetadata) del info['extmetadata'] self.__insert_image_info(title, _from, info)
[ "def", "__pull_image_info", "(", "self", ",", "title", ",", "imageinfo", ",", "normalized", ")", ":", "for", "info", "in", "imageinfo", ":", "info", ".", "update", "(", "{", "'title'", ":", "title", "}", ")", "# get API normalized \"from\" filename for matching", "_from", "=", "None", "for", "norm", "in", "normalized", ":", "if", "title", "==", "norm", "[", "'to'", "]", ":", "_from", "=", "norm", "[", "'from'", "]", "# let's put all \"metadata\" in one member", "info", "[", "'metadata'", "]", "=", "{", "}", "extmetadata", "=", "info", ".", "get", "(", "'extmetadata'", ")", "if", "extmetadata", ":", "info", "[", "'metadata'", "]", ".", "update", "(", "extmetadata", ")", "del", "info", "[", "'extmetadata'", "]", "self", ".", "__insert_image_info", "(", "title", ",", "_from", ",", "info", ")" ]
Pull image INFO from API response and insert
[ "Pull", "image", "INFO", "from", "API", "response", "and", "insert" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L104-L124
train
237,089
siznax/wptools
wptools/page.py
WPToolsPage._extend_data
def _extend_data(self, datapoint, new_data): """ extend or assign new data to datapoint """ if new_data: try: self.data[datapoint].extend(new_data) except KeyError: self.data[datapoint] = new_data
python
def _extend_data(self, datapoint, new_data): """ extend or assign new data to datapoint """ if new_data: try: self.data[datapoint].extend(new_data) except KeyError: self.data[datapoint] = new_data
[ "def", "_extend_data", "(", "self", ",", "datapoint", ",", "new_data", ")", ":", "if", "new_data", ":", "try", ":", "self", ".", "data", "[", "datapoint", "]", ".", "extend", "(", "new_data", ")", "except", "KeyError", ":", "self", ".", "data", "[", "datapoint", "]", "=", "new_data" ]
extend or assign new data to datapoint
[ "extend", "or", "assign", "new", "data", "to", "datapoint" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L126-L134
train
237,090
siznax/wptools
wptools/page.py
WPToolsPage._missing_imageinfo
def _missing_imageinfo(self): """ returns list of image filenames that are missing info """ if 'image' not in self.data: return missing = [] for img in self.data['image']: if 'url' not in img: missing.append(img['file']) return list(set(missing))
python
def _missing_imageinfo(self): """ returns list of image filenames that are missing info """ if 'image' not in self.data: return missing = [] for img in self.data['image']: if 'url' not in img: missing.append(img['file']) return list(set(missing))
[ "def", "_missing_imageinfo", "(", "self", ")", ":", "if", "'image'", "not", "in", "self", ".", "data", ":", "return", "missing", "=", "[", "]", "for", "img", "in", "self", ".", "data", "[", "'image'", "]", ":", "if", "'url'", "not", "in", "img", ":", "missing", ".", "append", "(", "img", "[", "'file'", "]", ")", "return", "list", "(", "set", "(", "missing", ")", ")" ]
returns list of image filenames that are missing info
[ "returns", "list", "of", "image", "filenames", "that", "are", "missing", "info" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L136-L146
train
237,091
siznax/wptools
wptools/page.py
WPToolsPage._query
def _query(self, action, qobj): """ returns WPToolsQuery string """ title = self.params.get('title') pageid = self.params.get('pageid') wikibase = self.params.get('wikibase') qstr = None if action == 'random': qstr = qobj.random() elif action == 'query': qstr = qobj.query(title, pageid, self._continue_params()) elif action == 'querymore': qstr = qobj.querymore(title, pageid, self._continue_params()) elif action == 'parse': qstr = qobj.parse(title, pageid) elif action == 'imageinfo': qstr = qobj.imageinfo(self._missing_imageinfo()) elif action == 'labels': qstr = qobj.labels(self._pop_entities()) elif action == 'wikidata': qstr = qobj.wikidata(title, wikibase) elif action == 'restbase': qstr = qobj.restbase(self.params.get('rest_endpoint'), title) if qstr is None: raise ValueError("Unknown action: %s" % action) return qstr
python
def _query(self, action, qobj): """ returns WPToolsQuery string """ title = self.params.get('title') pageid = self.params.get('pageid') wikibase = self.params.get('wikibase') qstr = None if action == 'random': qstr = qobj.random() elif action == 'query': qstr = qobj.query(title, pageid, self._continue_params()) elif action == 'querymore': qstr = qobj.querymore(title, pageid, self._continue_params()) elif action == 'parse': qstr = qobj.parse(title, pageid) elif action == 'imageinfo': qstr = qobj.imageinfo(self._missing_imageinfo()) elif action == 'labels': qstr = qobj.labels(self._pop_entities()) elif action == 'wikidata': qstr = qobj.wikidata(title, wikibase) elif action == 'restbase': qstr = qobj.restbase(self.params.get('rest_endpoint'), title) if qstr is None: raise ValueError("Unknown action: %s" % action) return qstr
[ "def", "_query", "(", "self", ",", "action", ",", "qobj", ")", ":", "title", "=", "self", ".", "params", ".", "get", "(", "'title'", ")", "pageid", "=", "self", ".", "params", ".", "get", "(", "'pageid'", ")", "wikibase", "=", "self", ".", "params", ".", "get", "(", "'wikibase'", ")", "qstr", "=", "None", "if", "action", "==", "'random'", ":", "qstr", "=", "qobj", ".", "random", "(", ")", "elif", "action", "==", "'query'", ":", "qstr", "=", "qobj", ".", "query", "(", "title", ",", "pageid", ",", "self", ".", "_continue_params", "(", ")", ")", "elif", "action", "==", "'querymore'", ":", "qstr", "=", "qobj", ".", "querymore", "(", "title", ",", "pageid", ",", "self", ".", "_continue_params", "(", ")", ")", "elif", "action", "==", "'parse'", ":", "qstr", "=", "qobj", ".", "parse", "(", "title", ",", "pageid", ")", "elif", "action", "==", "'imageinfo'", ":", "qstr", "=", "qobj", ".", "imageinfo", "(", "self", ".", "_missing_imageinfo", "(", ")", ")", "elif", "action", "==", "'labels'", ":", "qstr", "=", "qobj", ".", "labels", "(", "self", ".", "_pop_entities", "(", ")", ")", "elif", "action", "==", "'wikidata'", ":", "qstr", "=", "qobj", ".", "wikidata", "(", "title", ",", "wikibase", ")", "elif", "action", "==", "'restbase'", ":", "qstr", "=", "qobj", ".", "restbase", "(", "self", ".", "params", ".", "get", "(", "'rest_endpoint'", ")", ",", "title", ")", "if", "qstr", "is", "None", ":", "raise", "ValueError", "(", "\"Unknown action: %s\"", "%", "action", ")", "return", "qstr" ]
returns WPToolsQuery string
[ "returns", "WPToolsQuery", "string" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L163-L193
train
237,092
siznax/wptools
wptools/page.py
WPToolsPage._set_data
def _set_data(self, action): """ marshals response data into page data """ if 'query' in action: self._set_query_data(action) elif action == 'imageinfo': self._set_imageinfo_data() elif action == 'parse': self._set_parse_data() elif action == 'random': self._set_random_data() elif action == 'labels': self._set_labels() elif action == 'wikidata': self._set_wikidata() self.get_labels() elif action == 'restbase': self._set_restbase_data() self._update_imageinfo() self._update_params()
python
def _set_data(self, action): """ marshals response data into page data """ if 'query' in action: self._set_query_data(action) elif action == 'imageinfo': self._set_imageinfo_data() elif action == 'parse': self._set_parse_data() elif action == 'random': self._set_random_data() elif action == 'labels': self._set_labels() elif action == 'wikidata': self._set_wikidata() self.get_labels() elif action == 'restbase': self._set_restbase_data() self._update_imageinfo() self._update_params()
[ "def", "_set_data", "(", "self", ",", "action", ")", ":", "if", "'query'", "in", "action", ":", "self", ".", "_set_query_data", "(", "action", ")", "elif", "action", "==", "'imageinfo'", ":", "self", ".", "_set_imageinfo_data", "(", ")", "elif", "action", "==", "'parse'", ":", "self", ".", "_set_parse_data", "(", ")", "elif", "action", "==", "'random'", ":", "self", ".", "_set_random_data", "(", ")", "elif", "action", "==", "'labels'", ":", "self", ".", "_set_labels", "(", ")", "elif", "action", "==", "'wikidata'", ":", "self", ".", "_set_wikidata", "(", ")", "self", ".", "get_labels", "(", ")", "elif", "action", "==", "'restbase'", ":", "self", ".", "_set_restbase_data", "(", ")", "self", ".", "_update_imageinfo", "(", ")", "self", ".", "_update_params", "(", ")" ]
marshals response data into page data
[ "marshals", "response", "data", "into", "page", "data" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L195-L216
train
237,093
siznax/wptools
wptools/page.py
WPToolsPage._set_parse_image
def _set_parse_image(self, infobox): """ set image data from action=parse response """ image = infobox.get('image') cover = infobox.get('Cover') or infobox.get('cover') if image or cover: if 'image' not in self.data: self.data['image'] = [] if image and utils.isfilename(image): self.data['image'].append({'kind': 'parse-image', 'file': image}) if cover and utils.isfilename(cover): self.data['image'].append({'kind': 'parse-cover', 'file': cover})
python
def _set_parse_image(self, infobox): """ set image data from action=parse response """ image = infobox.get('image') cover = infobox.get('Cover') or infobox.get('cover') if image or cover: if 'image' not in self.data: self.data['image'] = [] if image and utils.isfilename(image): self.data['image'].append({'kind': 'parse-image', 'file': image}) if cover and utils.isfilename(cover): self.data['image'].append({'kind': 'parse-cover', 'file': cover})
[ "def", "_set_parse_image", "(", "self", ",", "infobox", ")", ":", "image", "=", "infobox", ".", "get", "(", "'image'", ")", "cover", "=", "infobox", ".", "get", "(", "'Cover'", ")", "or", "infobox", ".", "get", "(", "'cover'", ")", "if", "image", "or", "cover", ":", "if", "'image'", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'image'", "]", "=", "[", "]", "if", "image", "and", "utils", ".", "isfilename", "(", "image", ")", ":", "self", ".", "data", "[", "'image'", "]", ".", "append", "(", "{", "'kind'", ":", "'parse-image'", ",", "'file'", ":", "image", "}", ")", "if", "cover", "and", "utils", ".", "isfilename", "(", "cover", ")", ":", "self", ".", "data", "[", "'image'", "]", ".", "append", "(", "{", "'kind'", ":", "'parse-cover'", ",", "'file'", ":", "cover", "}", ")" ]
set image data from action=parse response
[ "set", "image", "data", "from", "action", "=", "parse", "response" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L274-L289
train
237,094
siznax/wptools
wptools/page.py
WPToolsPage._set_query_data_fast_1
def _set_query_data_fast_1(self, page): """ set less expensive action=query response data PART 1 """ self.data['pageid'] = page.get('pageid') assessments = page.get('pageassessments') if assessments: self.data['assessments'] = assessments extract = page.get('extract') if extract: self.data['extract'] = extract extext = html2text.html2text(extract) if extext: self.data['extext'] = extext.strip() fullurl = page.get('fullurl') if fullurl: self.data['url'] = fullurl self.data['url_raw'] = fullurl + '?action=raw' length = page.get('length') if length: self.data['length'] = length self._extend_data('links', utils.get_links(page.get('links'))) self._update_data('modified', 'page', page.get('touched')) pageprops = page.get('pageprops') if pageprops: wikibase = pageprops.get('wikibase_item') if wikibase: self.data['wikibase'] = wikibase self.data['wikidata_url'] = utils.wikidata_url(wikibase) if 'disambiguation' in pageprops: self.data['disambiguation'] = len(self.data['links'])
python
def _set_query_data_fast_1(self, page): """ set less expensive action=query response data PART 1 """ self.data['pageid'] = page.get('pageid') assessments = page.get('pageassessments') if assessments: self.data['assessments'] = assessments extract = page.get('extract') if extract: self.data['extract'] = extract extext = html2text.html2text(extract) if extext: self.data['extext'] = extext.strip() fullurl = page.get('fullurl') if fullurl: self.data['url'] = fullurl self.data['url_raw'] = fullurl + '?action=raw' length = page.get('length') if length: self.data['length'] = length self._extend_data('links', utils.get_links(page.get('links'))) self._update_data('modified', 'page', page.get('touched')) pageprops = page.get('pageprops') if pageprops: wikibase = pageprops.get('wikibase_item') if wikibase: self.data['wikibase'] = wikibase self.data['wikidata_url'] = utils.wikidata_url(wikibase) if 'disambiguation' in pageprops: self.data['disambiguation'] = len(self.data['links'])
[ "def", "_set_query_data_fast_1", "(", "self", ",", "page", ")", ":", "self", ".", "data", "[", "'pageid'", "]", "=", "page", ".", "get", "(", "'pageid'", ")", "assessments", "=", "page", ".", "get", "(", "'pageassessments'", ")", "if", "assessments", ":", "self", ".", "data", "[", "'assessments'", "]", "=", "assessments", "extract", "=", "page", ".", "get", "(", "'extract'", ")", "if", "extract", ":", "self", ".", "data", "[", "'extract'", "]", "=", "extract", "extext", "=", "html2text", ".", "html2text", "(", "extract", ")", "if", "extext", ":", "self", ".", "data", "[", "'extext'", "]", "=", "extext", ".", "strip", "(", ")", "fullurl", "=", "page", ".", "get", "(", "'fullurl'", ")", "if", "fullurl", ":", "self", ".", "data", "[", "'url'", "]", "=", "fullurl", "self", ".", "data", "[", "'url_raw'", "]", "=", "fullurl", "+", "'?action=raw'", "length", "=", "page", ".", "get", "(", "'length'", ")", "if", "length", ":", "self", ".", "data", "[", "'length'", "]", "=", "length", "self", ".", "_extend_data", "(", "'links'", ",", "utils", ".", "get_links", "(", "page", ".", "get", "(", "'links'", ")", ")", ")", "self", ".", "_update_data", "(", "'modified'", ",", "'page'", ",", "page", ".", "get", "(", "'touched'", ")", ")", "pageprops", "=", "page", ".", "get", "(", "'pageprops'", ")", "if", "pageprops", ":", "wikibase", "=", "pageprops", ".", "get", "(", "'wikibase_item'", ")", "if", "wikibase", ":", "self", ".", "data", "[", "'wikibase'", "]", "=", "wikibase", "self", ".", "data", "[", "'wikidata_url'", "]", "=", "utils", ".", "wikidata_url", "(", "wikibase", ")", "if", "'disambiguation'", "in", "pageprops", ":", "self", ".", "data", "[", "'disambiguation'", "]", "=", "len", "(", "self", ".", "data", "[", "'links'", "]", ")" ]
set less expensive action=query response data PART 1
[ "set", "less", "expensive", "action", "=", "query", "response", "data", "PART", "1" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L311-L349
train
237,095
siznax/wptools
wptools/page.py
WPToolsPage._set_query_data_fast_2
def _set_query_data_fast_2(self, page): """ set less expensive action=query response data PART 2 """ self.data['pageid'] = page.get('pageid') redirects = page.get('redirects') if redirects: self.data['redirects'] = redirects terms = page.get('terms') if terms: if terms.get('alias'): self.data['aliases'] = terms['alias'] if terms.get('description'): self.data['description'] = next(iter(terms['description']), None) if terms.get('label'): self.data['label'] = next(iter(terms['label']), None) title = page.get('title') self.data['title'] = title if not self.params.get('title'): self.params['title'] = title watchers = page.get('watchers') if watchers: self.data['watchers'] = watchers self._set_query_image(page)
python
def _set_query_data_fast_2(self, page): """ set less expensive action=query response data PART 2 """ self.data['pageid'] = page.get('pageid') redirects = page.get('redirects') if redirects: self.data['redirects'] = redirects terms = page.get('terms') if terms: if terms.get('alias'): self.data['aliases'] = terms['alias'] if terms.get('description'): self.data['description'] = next(iter(terms['description']), None) if terms.get('label'): self.data['label'] = next(iter(terms['label']), None) title = page.get('title') self.data['title'] = title if not self.params.get('title'): self.params['title'] = title watchers = page.get('watchers') if watchers: self.data['watchers'] = watchers self._set_query_image(page)
[ "def", "_set_query_data_fast_2", "(", "self", ",", "page", ")", ":", "self", ".", "data", "[", "'pageid'", "]", "=", "page", ".", "get", "(", "'pageid'", ")", "redirects", "=", "page", ".", "get", "(", "'redirects'", ")", "if", "redirects", ":", "self", ".", "data", "[", "'redirects'", "]", "=", "redirects", "terms", "=", "page", ".", "get", "(", "'terms'", ")", "if", "terms", ":", "if", "terms", ".", "get", "(", "'alias'", ")", ":", "self", ".", "data", "[", "'aliases'", "]", "=", "terms", "[", "'alias'", "]", "if", "terms", ".", "get", "(", "'description'", ")", ":", "self", ".", "data", "[", "'description'", "]", "=", "next", "(", "iter", "(", "terms", "[", "'description'", "]", ")", ",", "None", ")", "if", "terms", ".", "get", "(", "'label'", ")", ":", "self", ".", "data", "[", "'label'", "]", "=", "next", "(", "iter", "(", "terms", "[", "'label'", "]", ")", ",", "None", ")", "title", "=", "page", ".", "get", "(", "'title'", ")", "self", ".", "data", "[", "'title'", "]", "=", "title", "if", "not", "self", ".", "params", ".", "get", "(", "'title'", ")", ":", "self", ".", "params", "[", "'title'", "]", "=", "title", "watchers", "=", "page", ".", "get", "(", "'watchers'", ")", "if", "watchers", ":", "self", ".", "data", "[", "'watchers'", "]", "=", "watchers", "self", ".", "_set_query_image", "(", "page", ")" ]
set less expensive action=query response data PART 2
[ "set", "less", "expensive", "action", "=", "query", "response", "data", "PART", "2" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L351-L381
train
237,096
siznax/wptools
wptools/page.py
WPToolsPage._set_query_data_slow
def _set_query_data_slow(self, page): """ set more expensive action=query response data """ categories = page.get('categories') if categories: self.data['categories'] = [x['title'] for x in categories] if page.get('contributors'): contributors = page.get('contributors') or 0 anoncontributors = page.get('anoncontributors') or 0 if isinstance(contributors, list): contributors = len(contributors) self.data['contributors'] = contributors + anoncontributors files = page.get('images') # really, these are FILES if files: self.data['files'] = [x['title'] for x in files] languages = page.get('langlinks') if languages: self.data['languages'] = languages pageviews = page.get('pageviews') if pageviews: values = [x for x in pageviews.values() if x] if values: self.data['views'] = int(sum(values) / len(values)) else: self.data['views'] = 0
python
def _set_query_data_slow(self, page): """ set more expensive action=query response data """ categories = page.get('categories') if categories: self.data['categories'] = [x['title'] for x in categories] if page.get('contributors'): contributors = page.get('contributors') or 0 anoncontributors = page.get('anoncontributors') or 0 if isinstance(contributors, list): contributors = len(contributors) self.data['contributors'] = contributors + anoncontributors files = page.get('images') # really, these are FILES if files: self.data['files'] = [x['title'] for x in files] languages = page.get('langlinks') if languages: self.data['languages'] = languages pageviews = page.get('pageviews') if pageviews: values = [x for x in pageviews.values() if x] if values: self.data['views'] = int(sum(values) / len(values)) else: self.data['views'] = 0
[ "def", "_set_query_data_slow", "(", "self", ",", "page", ")", ":", "categories", "=", "page", ".", "get", "(", "'categories'", ")", "if", "categories", ":", "self", ".", "data", "[", "'categories'", "]", "=", "[", "x", "[", "'title'", "]", "for", "x", "in", "categories", "]", "if", "page", ".", "get", "(", "'contributors'", ")", ":", "contributors", "=", "page", ".", "get", "(", "'contributors'", ")", "or", "0", "anoncontributors", "=", "page", ".", "get", "(", "'anoncontributors'", ")", "or", "0", "if", "isinstance", "(", "contributors", ",", "list", ")", ":", "contributors", "=", "len", "(", "contributors", ")", "self", ".", "data", "[", "'contributors'", "]", "=", "contributors", "+", "anoncontributors", "files", "=", "page", ".", "get", "(", "'images'", ")", "# really, these are FILES", "if", "files", ":", "self", ".", "data", "[", "'files'", "]", "=", "[", "x", "[", "'title'", "]", "for", "x", "in", "files", "]", "languages", "=", "page", ".", "get", "(", "'langlinks'", ")", "if", "languages", ":", "self", ".", "data", "[", "'languages'", "]", "=", "languages", "pageviews", "=", "page", ".", "get", "(", "'pageviews'", ")", "if", "pageviews", ":", "values", "=", "[", "x", "for", "x", "in", "pageviews", ".", "values", "(", ")", "if", "x", "]", "if", "values", ":", "self", ".", "data", "[", "'views'", "]", "=", "int", "(", "sum", "(", "values", ")", "/", "len", "(", "values", ")", ")", "else", ":", "self", ".", "data", "[", "'views'", "]", "=", "0" ]
set more expensive action=query response data
[ "set", "more", "expensive", "action", "=", "query", "response", "data" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L383-L412
train
237,097
siznax/wptools
wptools/page.py
WPToolsPage._set_query_image
def _set_query_image(self, page): """ set image data from action=query response """ pageimage = page.get('pageimage') thumbnail = page.get('thumbnail') if pageimage or thumbnail: if 'image' not in self.data: self.data['image'] = [] if pageimage: self.data['image'].append({ 'kind': 'query-pageimage', 'file': pageimage}) if thumbnail: qthumb = {'kind': 'query-thumbnail'} qthumb.update(thumbnail) qthumb['url'] = thumbnail.get('source') del qthumb['source'] qthumb['file'] = qthumb['url'].split('/')[-2] self.data['image'].append(qthumb)
python
def _set_query_image(self, page): """ set image data from action=query response """ pageimage = page.get('pageimage') thumbnail = page.get('thumbnail') if pageimage or thumbnail: if 'image' not in self.data: self.data['image'] = [] if pageimage: self.data['image'].append({ 'kind': 'query-pageimage', 'file': pageimage}) if thumbnail: qthumb = {'kind': 'query-thumbnail'} qthumb.update(thumbnail) qthumb['url'] = thumbnail.get('source') del qthumb['source'] qthumb['file'] = qthumb['url'].split('/')[-2] self.data['image'].append(qthumb)
[ "def", "_set_query_image", "(", "self", ",", "page", ")", ":", "pageimage", "=", "page", ".", "get", "(", "'pageimage'", ")", "thumbnail", "=", "page", ".", "get", "(", "'thumbnail'", ")", "if", "pageimage", "or", "thumbnail", ":", "if", "'image'", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "'image'", "]", "=", "[", "]", "if", "pageimage", ":", "self", ".", "data", "[", "'image'", "]", ".", "append", "(", "{", "'kind'", ":", "'query-pageimage'", ",", "'file'", ":", "pageimage", "}", ")", "if", "thumbnail", ":", "qthumb", "=", "{", "'kind'", ":", "'query-thumbnail'", "}", "qthumb", ".", "update", "(", "thumbnail", ")", "qthumb", "[", "'url'", "]", "=", "thumbnail", ".", "get", "(", "'source'", ")", "del", "qthumb", "[", "'source'", "]", "qthumb", "[", "'file'", "]", "=", "qthumb", "[", "'url'", "]", ".", "split", "(", "'/'", ")", "[", "-", "2", "]", "self", ".", "data", "[", "'image'", "]", ".", "append", "(", "qthumb", ")" ]
set image data from action=query response
[ "set", "image", "data", "from", "action", "=", "query", "response" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L414-L436
train
237,098
siznax/wptools
wptools/page.py
WPToolsPage._set_random_data
def _set_random_data(self): """ sets page data from random request """ rdata = self._load_response('random') rdata = rdata['query']['random'][0] pageid = rdata.get('id') title = rdata.get('title') self.data.update({'pageid': pageid, 'title': title})
python
def _set_random_data(self): """ sets page data from random request """ rdata = self._load_response('random') rdata = rdata['query']['random'][0] pageid = rdata.get('id') title = rdata.get('title') self.data.update({'pageid': pageid, 'title': title})
[ "def", "_set_random_data", "(", "self", ")", ":", "rdata", "=", "self", ".", "_load_response", "(", "'random'", ")", "rdata", "=", "rdata", "[", "'query'", "]", "[", "'random'", "]", "[", "0", "]", "pageid", "=", "rdata", ".", "get", "(", "'id'", ")", "title", "=", "rdata", ".", "get", "(", "'title'", ")", "self", ".", "data", ".", "update", "(", "{", "'pageid'", ":", "pageid", ",", "'title'", ":", "title", "}", ")" ]
sets page data from random request
[ "sets", "page", "data", "from", "random", "request" ]
100eaea585c34aa9ad87a9eda8982bb4898f6ec9
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L438-L449
train
237,099