_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q27100 | DependencyTree._find_reader_dataset | train | def _find_reader_dataset(self, dataset_key, **dfilter):
"""Attempt to find a `DatasetID` in the available readers.
Args:
dataset_key (str, float, DatasetID):
Dataset name, wavelength, or a combination of `DatasetID`
parameters to use in searching for the data... | python | {
"resource": ""
} |
q27101 | DependencyTree._get_compositor_prereqs | train | def _get_compositor_prereqs(self, parent, prereq_names, skip=False,
**dfilter):
"""Determine prerequisite Nodes for a composite.
Args:
parent (Node): Compositor node to add these prerequisites under
prereq_names (sequence): Strings (names), floats... | python | {
"resource": ""
} |
q27102 | DependencyTree._find_compositor | train | def _find_compositor(self, dataset_key, **dfilter):
"""Find the compositor object for the given dataset_key."""
# NOTE: This function can not find a modifier that performs
# one or more modifications if it has modifiers see if we can find
# the unmodified version first
src_node =... | python | {
"resource": ""
} |
q27103 | DependencyTree.find_dependencies | train | def find_dependencies(self, dataset_keys, **dfilter):
"""Create the dependency tree.
Args:
dataset_keys (iterable): Strings or DatasetIDs to find dependencies for
**dfilter (dict): Additional filter parameters. See
`satpy.readers.get_key` for more d... | python | {
"resource": ""
} |
q27104 | average_datetimes | train | def average_datetimes(dt_list):
"""Average a series of datetime objects.
.. note::
This function assumes all datetime objects are naive and in the same
time zone (UTC).
Args:
dt_list (iterable): Datetime objects to average
Returns: Average | python | {
"resource": ""
} |
q27105 | combine_metadata | train | def combine_metadata(*metadata_objects, **kwargs):
"""Combine the metadata of two or more Datasets.
If any keys are not equal or do not exist in all provided dictionaries
then they are not included in the returned dictionary.
By default any keys with the word 'time' in them and consisting
of dateti... | python | {
"resource": ""
} |
q27106 | DatasetID.wavelength_match | train | def wavelength_match(a, b):
"""Return if two wavelengths are equal.
Args:
a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
"""
if type(a) == (type(b) or
isinstance... | python | {
"resource": ""
} |
q27107 | DatasetID._comparable | train | def _comparable(self):
"""Get a comparable version of the DatasetID.
Without this DatasetIDs often raise an exception when compared in
Python 3 due to None not being comparable with other types.
"""
return self._replace(
name='' if self.name is None else self.name,
... | python | {
"resource": ""
} |
q27108 | DatasetID.from_dict | train | def from_dict(cls, d, **kwargs):
"""Convert a dict to an ID."""
args = []
for k in DATASET_KEYS:
val = kwargs.get(k, d.get(k))
# force modifiers to tuple
if k == 'modifiers' and | python | {
"resource": ""
} |
q27109 | DatasetID.to_dict | train | def to_dict(self, trim=True):
"""Convert the ID to a dict."""
if trim:
return self._to_trimmed_dict()
| python | {
"resource": ""
} |
q27110 | NUCAPSFileHandler.sensor_names | train | def sensor_names(self):
"""Return standard sensor or instrument name for the file's data.
"""
res = self['/attr/instrument_name']
if isinstance(res, np.ndarray):
res = str(res.astype(str))
res = | python | {
"resource": ""
} |
q27111 | NUCAPSFileHandler.get_shape | train | def get_shape(self, ds_id, ds_info):
"""Return data array shape for item specified.
"""
var_path = ds_info.get('file_key', '{}'.format(ds_id.name))
if var_path + '/shape' not in self:
# loading a scalar value
shape = 1
else:
shape = self[var_pa... | python | {
"resource": ""
} |
q27112 | NUCAPSFileHandler.get_dataset | train | def get_dataset(self, dataset_id, ds_info):
"""Load data array and metadata for specified dataset"""
var_path = ds_info.get('file_key', '{}'.format(dataset_id.name))
metadata = self.get_metadata(dataset_id, ds_info)
valid_min, valid_max = self[var_path + '/attr/valid_range']
fill... | python | {
"resource": ""
} |
q27113 | NUCAPSReader.load_ds_ids_from_config | train | def load_ds_ids_from_config(self):
"""Convert config dataset entries to DatasetIDs
Special handling is done to provide level specific datasets
for any pressured based datasets. For example, a dataset is
added for each pressure level of 'Temperature' with each
new dataset being n... | python | {
"resource": ""
} |
q27114 | AHIHSDFileHandler.scheduled_time | train | def scheduled_time(self):
"""Time this band was scheduled to be recorded."""
timeline = "{:04d}".format(self.basic_info['observation_timeline'][0])
return | python | {
"resource": ""
} |
q27115 | AHIHSDFileHandler._check_fpos | train | def _check_fpos(self, fp_, fpos, offset, block):
"""Check file position matches blocksize"""
if (fp_.tell() + offset != fpos):
| python | {
"resource": ""
} |
q27116 | AHIHSDFileHandler._read_data | train | def _read_data(self, fp_, header):
"""Read data block"""
nlines = int(header["block2"]['number_of_lines'][0])
ncols = int(header["block2"]['number_of_columns'][0])
return da.from_array(np.memmap(self.filename, offset=fp_.tell(),
| python | {
"resource": ""
} |
q27117 | AHIHSDFileHandler._mask_invalid | train | def _mask_invalid(self, data, header):
"""Mask invalid data"""
invalid = da.logical_or(data == header['block5']["count_value_outside_scan_pixels"][0],
| python | {
"resource": ""
} |
q27118 | AHIHSDFileHandler.convert_to_radiance | train | def convert_to_radiance(self, data):
"""Calibrate to radiance."""
bnum = self._header["block5"]['band_number'][0]
# Check calibration mode and select corresponding coefficients
if self.calib_mode == "UPDATE" and bnum < 7:
gain = self._header['calibration']["cali_gain_count2r... | python | {
"resource": ""
} |
q27119 | AHIHSDFileHandler._ir_calibrate | train | def _ir_calibrate(self, data):
"""IR calibration."""
# No radiance -> no temperature
data = da.where(data == 0, np.float32(np.nan), data)
cwl = self._header['block5']["central_wave_length"][0] * 1e-6
c__ = self._header['calibration']["speed_of_light"][0]
h__ = self._head... | python | {
"resource": ""
} |
q27120 | process_field | train | def process_field(elt, ascii=False):
"""Process a 'field' tag.
"""
# NOTE: if there is a variable defined in this field and it is different
# from the default, we could change the value and restart.
scale = np.uint8(1)
if elt.get("type") == "bitfield" and not ascii:
current_type = ">u"... | python | {
"resource": ""
} |
q27121 | process_array | train | def process_array(elt, ascii=False):
"""Process an 'array' tag.
"""
del ascii
chld = elt.getchildren()
if len(chld) > 1:
raise ValueError()
chld = chld[0]
try:
name, current_type, scale = CASES[chld.tag](chld)
size = None
except ValueError:
name, current_t... | python | {
"resource": ""
} |
q27122 | parse_format | train | def parse_format(xml_file):
"""Parse the xml file to create types, scaling factor types, and scales.
"""
tree = ElementTree()
tree.parse(xml_file)
for param in tree.find("parameters").getchildren():
VARIABLES[param.get("name")] = param.get("value")
types_scales = {}
for prod in tr... | python | {
"resource": ""
} |
q27123 | _apply_scales | train | def _apply_scales(array, scales, dtype):
"""Apply scales to the array.
"""
new_array = np.empty(array.shape, dtype)
for i in array.dtype.names:
try:
new_array[i] = array[i] * scales[i]
except TypeError: | python | {
"resource": ""
} |
q27124 | get_coeffs | train | def get_coeffs(page):
'''Parse coefficients from the page.'''
coeffs = {}
coeffs['datetime'] = []
coeffs['slope1'] = []
coeffs['intercept1'] = []
coeffs['slope2'] = []
coeffs['intercept2'] = []
slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \
None, None, None, None
... | python | {
"resource": ""
} |
q27125 | get_all_coeffs | train | def get_all_coeffs():
'''Get all available calibration coefficients for the satellites.'''
coeffs = {}
for platform in URLS.keys():
if platform not in coeffs:
coeffs[platform] = {}
for chan in URLS[platform].keys():
| python | {
"resource": ""
} |
q27126 | save_coeffs | train | def save_coeffs(coeffs, out_dir=''):
'''Save calibration coefficients to HDF5 files.'''
for platform in coeffs.keys():
fname = os.path.join(out_dir, "%s_calibration_data.h5" % platform)
fid = h5py.File(fname, 'w')
for chan in coeffs[platform].keys():
fid.create_group... | python | {
"resource": ""
} |
q27127 | main | train | def main():
'''Create calibration coefficient files for AVHRR'''
out_dir = sys.argv[1]
| python | {
"resource": ""
} |
q27128 | NcNWCSAF.remove_timedim | train | def remove_timedim(self, var):
"""Remove time dimension from dataset"""
if self.pps and var.dims[0] == 'time':
data = | python | {
"resource": ""
} |
q27129 | NcNWCSAF.scale_dataset | train | def scale_dataset(self, dsid, variable, info):
"""Scale the data set, applying the attributes from the netCDF file"""
variable = remove_empties(variable)
scale = variable.attrs.get('scale_factor', np.array(1))
offset = variable.attrs.get('add_offset', np.array(0))
if np.issubdty... | python | {
"resource": ""
} |
q27130 | NcNWCSAF.get_area_def | train | def get_area_def(self, dsid):
"""Get the area definition of the datasets in the file.
Only applicable for MSG products!
"""
if self.pps:
# PPS:
raise NotImplementedError
if dsid.name.endswith('_pal'):
raise NotImplementedError
| python | {
"resource": ""
} |
q27131 | NcNWCSAF.end_time | train | def end_time(self):
"""Return the end time of the object."""
try:
# MSG:
try:
return datetime.strptime(self.nc.attrs['time_coverage_end'],
'%Y-%m-%dT%H:%M:%SZ')
except TypeError:
return datetime.... | python | {
"resource": ""
} |
q27132 | NcNWCSAF._get_projection | train | def _get_projection(self):
"""Get projection from the NetCDF4 attributes"""
try:
proj_str = self.nc.attrs['gdal_projection']
except TypeError:
proj_str = self.nc.attrs['gdal_projection'].decode()
# Check the a/b/h units
radius_a = proj_str.split('+a=')[-1... | python | {
"resource": ""
} |
q27133 | get_geotiff_area_def | train | def get_geotiff_area_def(filename, crs):
"""Read area definition from a geotiff."""
from osgeo import gdal
from pyresample.geometry import AreaDefinition
from pyresample.utils import proj4_str_to_dict
fid = gdal.Open(filename)
geo_transform = fid.GetGeoTransform()
pcs_id = fid.GetProjection(... | python | {
"resource": ""
} |
q27134 | mask_image_data | train | def mask_image_data(data):
"""Mask image data if alpha channel is present."""
if data.bands.size in (2, 4):
if not np.issubdtype(data.dtype, np.integer):
raise ValueError("Only integer datatypes can be used as a mask.")
mask = data.data[-1, :, :] == np.iinfo(data.dtype).min
d... | python | {
"resource": ""
} |
q27135 | GenericImageFileHandler.read | train | def read(self):
"""Read the image"""
data = xr.open_rasterio(self.finfo["filename"],
chunks=(1, CHUNK_SIZE, CHUNK_SIZE))
attrs = data.attrs.copy()
# Create area definition
if hasattr(data, 'crs'):
self.area = self.get_geotiff_area_def(d... | python | {
"resource": ""
} |
q27136 | GRIBFileHandler.get_area_def | train | def get_area_def(self, dsid):
"""Get area definition for message.
If latlong grid then convert to valid eqc grid.
"""
msg = self._get_message(self._msg_datasets[dsid])
try:
| python | {
"resource": ""
} |
q27137 | GRIBFileHandler.get_dataset | train | def get_dataset(self, dataset_id, ds_info):
"""Read a GRIB message into an xarray DataArray."""
msg = self._get_message(ds_info)
ds_info = self.get_metadata(msg, ds_info)
fill = msg['missingValue']
data = msg.values.astype(np.float32)
if msg.valid_key('jScansPositively') ... | python | {
"resource": ""
} |
q27138 | stack | train | def stack(datasets):
"""First dataset at the bottom."""
base = datasets[0].copy()
| python | {
"resource": ""
} |
q27139 | timeseries | train | def timeseries(datasets):
"""Expands dataset with and concats by time dimension"""
expanded_ds = []
for ds in datasets:
tmp = ds.expand_dims("time")
tmp.coords["time"] = pd.DatetimeIndex([ds.attrs["start_time"]])
| python | {
"resource": ""
} |
q27140 | _SceneGenerator._create_cached_iter | train | def _create_cached_iter(self):
"""Iterate over the provided scenes, caching them for later."""
for scn in self._scene_gen:
| python | {
"resource": ""
} |
q27141 | MultiScene.from_files | train | def from_files(cls, files_to_sort, reader=None, **kwargs):
"""Create multiple Scene objects from multiple files.
This uses the :func:`satpy.readers.group_files` function to group
files. See this function for more details on possible keyword
arguments.
.. versionadded:: 0.12
... | python | {
"resource": ""
} |
q27142 | MultiScene.scenes | train | def scenes(self):
"""Get list of Scene objects contained in this MultiScene.
.. note::
If the Scenes contained in this object are stored in a
generator (not list or tuple) then accessing this property
will load/iterate through the generator possibly
"""
| python | {
"resource": ""
} |
q27143 | MultiScene.loaded_dataset_ids | train | def loaded_dataset_ids(self):
"""Union of all Dataset IDs loaded by all children."""
| python | {
"resource": ""
} |
q27144 | MultiScene.shared_dataset_ids | train | def shared_dataset_ids(self):
"""Dataset IDs shared by all children."""
shared_ids = set(self.scenes[0].keys())
| python | {
"resource": ""
} |
q27145 | MultiScene._all_same_area | train | def _all_same_area(self, dataset_ids):
"""Return True if all areas for the provided IDs are equal."""
all_areas = []
for ds_id in dataset_ids:
for scn in self.scenes:
ds = scn.get(ds_id)
if ds is None:
continue
| python | {
"resource": ""
} |
q27146 | MultiScene.load | train | def load(self, *args, **kwargs):
"""Load the required datasets from the multiple scenes."""
| python | {
"resource": ""
} |
q27147 | MultiScene.crop | train | def crop(self, *args, **kwargs):
"""Crop the multiscene and return a new cropped multiscene."""
| python | {
"resource": ""
} |
q27148 | MultiScene.resample | train | def resample(self, destination=None, **kwargs):
"""Resample the multiscene."""
return | python | {
"resource": ""
} |
q27149 | MultiScene.blend | train | def blend(self, blend_function=stack):
"""Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene.
"""
new_scn = Scene()
common_datasets = self.shared_dataset_ids
| python | {
"resource": ""
} |
q27150 | MultiScene._distribute_save_datasets | train | def _distribute_save_datasets(self, scenes_iter, client, batch_size=1, **kwargs):
"""Distribute save_datasets across a cluster."""
def load_data(q):
idx = 0
while True:
future_list = q.get()
if future_list is None:
break
... | python | {
"resource": ""
} |
q27151 | MultiScene.save_datasets | train | def save_datasets(self, client=True, batch_size=1, **kwargs):
"""Run save_datasets on each Scene.
Note that some writers may not be multi-process friendly and may
produce unexpected results or fail by raising an exception. In
these cases ``client`` should be set to ``False``.
Th... | python | {
"resource": ""
} |
q27152 | MultiScene._get_animation_info | train | def _get_animation_info(self, all_datasets, filename, fill_value=None):
"""Determine filename and shape of animation to be created."""
valid_datasets = [ds for ds in all_datasets if ds is not None]
first_dataset = valid_datasets[0]
last_dataset = valid_datasets[-1]
first_img = ge... | python | {
"resource": ""
} |
q27153 | MultiScene._get_animation_frames | train | def _get_animation_frames(self, all_datasets, shape, fill_value=None,
ignore_missing=False):
"""Create enhanced image frames to save to a file."""
for idx, ds in enumerate(all_datasets):
if ds is None and ignore_missing:
continue
elif... | python | {
"resource": ""
} |
q27154 | MultiScene._get_client | train | def _get_client(self, client=True):
"""Determine what dask distributed client to use."""
client = client or None # convert False/None to None
if client is True and get_client is None:
log.debug("'dask.distributed' library was not found, will "
"use simple seria... | python | {
"resource": ""
} |
q27155 | MultiScene._distribute_frame_compute | train | def _distribute_frame_compute(self, writers, frame_keys, frames_to_write, client, batch_size=1):
"""Use ``dask.distributed`` to compute multiple frames at a time."""
def load_data(frame_gen, q):
for frame_arrays in frame_gen:
future_list = client.compute(frame_arrays)
... | python | {
"resource": ""
} |
q27156 | MultiScene._simple_frame_compute | train | def _simple_frame_compute(self, writers, frame_keys, frames_to_write):
"""Compute frames the plain dask way."""
for frame_arrays in frames_to_write:
for frame_key, product_frame in | python | {
"resource": ""
} |
q27157 | get_bucket_files | train | def get_bucket_files(glob_pattern, base_dir, force=False, pattern_slice=slice(None)):
"""Helper function to download files from Google Cloud Storage.
Args:
glob_pattern (str or list): Glob pattern string or series of patterns
used to search for on Google Cloud Storage. The pattern should
... | python | {
"resource": ""
} |
q27158 | HRITGOESPrologueFileHandler.process_prologue | train | def process_prologue(self):
"""Reprocess prologue to correct types."""
for key in ['TCurr', 'TCHED', 'TCTRL', 'TLHED', 'TLTRL', 'TIPFS',
'TINFS', 'TISPC', 'TIECL', 'TIBBC', 'TISTR', 'TLRAN',
'TIIRT', 'TIVIT', 'TCLMT', 'TIONA']:
try:
se... | python | {
"resource": ""
} |
q27159 | HRITGOESFileHandler._get_calibration_params | train | def _get_calibration_params(self):
"""Get the calibration parameters from the metadata."""
params = {}
idx_table = []
val_table = []
for elt in self.mda['image_data_function'].split(b'\r\n'):
try:
key, val = elt.split(b':=')
try:
... | python | {
"resource": ""
} |
q27160 | NCOLCI1B._get_solar_flux | train | def _get_solar_flux(self, band):
"""Get the solar flux for the band."""
solar_flux = self.cal['solar_flux'].isel(bands=band).values
d_index = self.cal['detector_index'].fillna(0).astype(int)
| python | {
"resource": ""
} |
q27161 | GOESNCBaseFileHandler._get_platform_name | train | def _get_platform_name(ncattr):
"""Determine name of the platform"""
match = re.match(r'G-(\d+)', ncattr)
if match:
| python | {
"resource": ""
} |
q27162 | GOESNCBaseFileHandler._get_sector | train | def _get_sector(self, channel, nlines, ncols):
"""Determine which sector was scanned"""
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
else:
margin = 50
sectors_ref = self.ir_sectors
| python | {
"resource": ""
} |
q27163 | GOESNCBaseFileHandler._is_vis | train | def _is_vis(channel):
"""Determine whether the given channel is a visible channel"""
if isinstance(channel, str):
| python | {
"resource": ""
} |
q27164 | GOESNCBaseFileHandler._get_nadir_pixel | train | def _get_nadir_pixel(earth_mask, sector):
"""Find the nadir pixel
Args:
earth_mask: Mask identifying earth and space pixels
sector: Specifies the scanned sector
Returns:
nadir row, nadir column
"""
if sector == FULL_DISC:
logger.de... | python | {
"resource": ""
} |
q27165 | GOESNCBaseFileHandler._get_area_def_uniform_sampling | train | def _get_area_def_uniform_sampling(self, lon0, channel):
"""Get area definition with uniform sampling"""
logger.debug('Computing area definition')
if lon0 is not None:
# Define proj4 projection parameters
proj_dict = {'a': EQUATOR_RADIUS,
'b': PO... | python | {
"resource": ""
} |
q27166 | GOESNCBaseFileHandler.start_time | train | def start_time(self):
"""Start timestamp of the dataset"""
dt = self.nc['time'].dt
return datetime(year=dt.year, month=dt.month, day=dt.day,
| python | {
"resource": ""
} |
q27167 | GOESNCBaseFileHandler.end_time | train | def end_time(self):
"""End timestamp of the dataset"""
try:
return | python | {
"resource": ""
} |
q27168 | GOESNCBaseFileHandler.meta | train | def meta(self):
"""Derive metadata from the coordinates"""
# Use buffered data if available
if self._meta is None:
lat = self.geo_data['lat']
earth_mask = self._get_earth_mask(lat)
crow, ccol = self._get_nadir_pixel(earth_mask=earth_mask,
... | python | {
"resource": ""
} |
q27169 | GOESNCBaseFileHandler._counts2radiance | train | def _counts2radiance(self, counts, coefs, channel):
"""Convert raw detector counts to radiance"""
logger.debug('Converting counts to radiance')
if self._is_vis(channel):
# Since the scanline-detector assignment is unknown, use the average
# coefficients for all scanlines... | python | {
"resource": ""
} |
q27170 | GOESNCBaseFileHandler._calibrate | train | def _calibrate(self, radiance, coefs, channel, calibration):
"""Convert radiance to reflectance or brightness temperature"""
if self._is_vis(channel):
if not calibration == 'reflectance':
raise ValueError('Cannot calibrate VIS channel to '
'{}... | python | {
"resource": ""
} |
q27171 | GOESNCBaseFileHandler._ircounts2radiance | train | def _ircounts2radiance(counts, scale, offset):
"""Convert IR counts to radiance
Reference: [IR].
Args:
counts: Raw detector counts
scale: Scale [mW-1 m2 cm sr]
offset: Offset [1]
| python | {
"resource": ""
} |
q27172 | GOESNCBaseFileHandler._calibrate_ir | train | def _calibrate_ir(radiance, coefs):
"""Convert IR radiance to brightness temperature
Reference: [IR]
Args:
radiance: Radiance [mW m-2 cm-1 sr-1]
coefs: Dictionary of calibration coefficients. Keys:
n: The channel's central wavenumber [cm-1]
... | python | {
"resource": ""
} |
q27173 | GOESNCBaseFileHandler._viscounts2radiance | train | def _viscounts2radiance(counts, slope, offset):
"""Convert VIS counts to radiance
References: [VIS]
Args:
counts: Raw detector counts
slope: Slope [W m-2 um-1 sr-1]
offset: Offset [W m-2 um-1 | python | {
"resource": ""
} |
q27174 | GOESNCBaseFileHandler._calibrate_vis | train | def _calibrate_vis(radiance, k):
"""Convert VIS radiance to reflectance
Note: Angle of incident radiation and annual variation of the
earth-sun distance is not taken into account. A value of 100%
corresponds to the radiance of a perfectly reflecting diffuse surface
illuminated a... | python | {
"resource": ""
} |
q27175 | GOESNCBaseFileHandler._update_metadata | train | def _update_metadata(self, data, ds_info):
"""Update metadata of the given DataArray"""
# Metadata from the dataset definition
data.attrs.update(ds_info)
# If the file_type attribute is a list and the data is xarray
# the concat of the dataset will not work. As the file_type is
... | python | {
"resource": ""
} |
q27176 | GOESCoefficientReader._float | train | def _float(self, string):
"""Convert string to float
Take care of numbers in exponential format
"""
string = self._denoise(string)
exp_match = re.match(r'^[-.\d]+x10-(\d)$', string)
if exp_match:
exp = int(exp_match.groups()[0])
| python | {
"resource": ""
} |
q27177 | NC_ABI_L1B._vis_calibrate | train | def _vis_calibrate(self, data):
"""Calibrate visible channels to reflectance."""
solar_irradiance = self['esun']
esd = self["earth_sun_distance_anomaly_in_AU"].astype(float)
factor = np.pi * esd * esd / solar_irradiance
res = data * factor
| python | {
"resource": ""
} |
q27178 | NC_ABI_L1B._ir_calibrate | train | def _ir_calibrate(self, data):
"""Calibrate IR channels to BT."""
fk1 = float(self["planck_fk1"])
fk2 = float(self["planck_fk2"])
bc1 = float(self["planck_bc1"])
bc2 = float(self["planck_bc2"])
res = (fk2 / xu.log(fk1 / data + 1) - bc1) / bc2
| python | {
"resource": ""
} |
q27179 | time_seconds | train | def time_seconds(tc_array, year):
"""Return the time object from the timecodes
"""
tc_array = np.array(tc_array, copy=True)
word = tc_array[:, 0]
day = word >> 1
word = tc_array[:, 1].astype(np.uint64)
msecs = ((127) & word) * 1024
word = tc_array[:, 2]
msecs += word & 1023
msecs... | python | {
"resource": ""
} |
q27180 | apply_enhancement | train | def apply_enhancement(data, func, exclude=None, separate=False,
pass_dask=False):
"""Apply `func` to the provided data.
Args:
data (xarray.DataArray): Data to be modified inplace.
func (callable): Function to be applied to an xarray
exclude (iterable): Bands in the... | python | {
"resource": ""
} |
q27181 | cira_stretch | train | def cira_stretch(img, **kwargs):
"""Logarithmic stretch adapted to human vision.
Applicable only for visible channels.
"""
LOG.debug("Applying the cira-stretch")
def func(band_data):
log_root = np.log10(0.0223)
denom = (1.0 - log_root) * 0.75
band_data *= 0.01
| python | {
"resource": ""
} |
q27182 | lookup | train | def lookup(img, **kwargs):
"""Assign values to channels based on a table."""
luts = np.array(kwargs['luts'], dtype=np.float32) / 255.0
def func(band_data, luts=luts, index=-1):
# NaN/null values will become 0
lut = luts[:, index] if len(luts.shape) == 2 else luts
band_data = band_da... | python | {
"resource": ""
} |
q27183 | _merge_colormaps | train | def _merge_colormaps(kwargs):
"""Merge colormaps listed in kwargs."""
from trollimage.colormap import Colormap
full_cmap = None
palette = kwargs['palettes']
if isinstance(palette, Colormap):
full_cmap = palette
else:
for itm in palette:
| python | {
"resource": ""
} |
q27184 | create_colormap | train | def create_colormap(palette):
"""Create colormap of the given numpy file, color vector or colormap."""
from trollimage.colormap import Colormap
fname = palette.get('filename', None)
if fname:
data = np.load(fname)
cmap = []
num = 1.0 * data.shape[0]
for i in range(int(num... | python | {
"resource": ""
} |
q27185 | three_d_effect | train | def three_d_effect(img, **kwargs):
"""Create 3D effect using convolution"""
w = kwargs.get('weight', 1)
LOG.debug("Applying 3D effect with weight %.2f", w)
kernel = np.array([[-w, 0, w],
[-w, 1, w],
[-w, 0, w]])
mode = kwargs.get('convolve_mode', 'same')... | python | {
"resource": ""
} |
q27186 | btemp_threshold | train | def btemp_threshold(img, min_in, max_in, threshold, threshold_out=None, **kwargs):
"""Scale data linearly in two separate regions.
This enhancement scales the input data linearly by splitting the data
into two regions; min_in to threshold and threshold to max_in. These
regions are mapped to 1 to thresh... | python | {
"resource": ""
} |
q27187 | API._make_request | train | def _make_request(self, path, method='GET', params_=None):
"""Make a request to the API"""
uri = self.api_root + path
if params_:
params_['text_format'] = self.response_format
else:
params_ = {'text_format': self.response_format}
# Make the request
... | python | {
"resource": ""
} |
q27188 | API.get_song | train | def get_song(self, id_):
"""Data for a specific song."""
endpoint | python | {
"resource": ""
} |
q27189 | API.get_artist | train | def get_artist(self, id_):
"""Data for a specific artist."""
endpoint | python | {
"resource": ""
} |
q27190 | API.search_genius | train | def search_genius(self, search_term):
"""Search documents hosted on Genius."""
endpoint = "search/"
| python | {
"resource": ""
} |
q27191 | API.search_genius_web | train | def search_genius_web(self, search_term, per_page=5):
"""Use the web-version of Genius search"""
endpoint = "search/multi?"
params = {'per_page': per_page, 'q': search_term}
# This endpoint is | python | {
"resource": ""
} |
q27192 | API.get_annotation | train | def get_annotation(self, id_):
"""Data for a specific annotation."""
endpoint | python | {
"resource": ""
} |
q27193 | Genius._result_is_lyrics | train | def _result_is_lyrics(self, song_title):
""" Returns False if result from Genius is not actually song lyrics
Set the `excluded_terms` and `replace_default_terms` as
instance variables within the Genius class.
"""
default_terms = ['track\\s?list', 'album art(work)?', 'lin... | python | {
"resource": ""
} |
q27194 | Genius._get_item_from_search_response | train | def _get_item_from_search_response(self, response, type_):
""" Returns either a Song or Artist result from search_genius_web """
sections = sorted(response['sections'],
| python | {
"resource": ""
} |
q27195 | Genius._result_is_match | train | def _result_is_match(self, result, title, artist=None):
""" Returns True if search result matches searched song """
result_title = self._clean_str(result['title'])
title_is_match = result_title == self._clean_str(title)
if not artist:
| python | {
"resource": ""
} |
q27196 | Song.to_dict | train | def to_dict(self):
"""
Create a dictionary from the song object
Used in save_lyrics to create json object
:return: Dictionary
| python | {
"resource": ""
} |
q27197 | Song.save_lyrics | train | def save_lyrics(self, filename=None, extension='json', verbose=True,
overwrite=None, binary_encoding=False):
"""Allows user to save song lyrics from Song object to a .json or .txt file."""
extension = extension.lstrip(".")
assert (extension == 'json') or (extension == 'txt'),... | python | {
"resource": ""
} |
q27198 | Artist.add_song | train | def add_song(self, new_song, verbose=True):
"""Add a Song object to the Artist object"""
if any([song.title == new_song.title for song in self._songs]):
if verbose:
print('{s} already in {a}, not adding song.'.format(s=new_song.title,
... | python | {
"resource": ""
} |
q27199 | Artist.save_lyrics | train | def save_lyrics(self, extension='json', overwrite=False,
verbose=True, binary_encoding=False):
"""Allows user to save all lyrics within an Artist object"""
extension = extension.lstrip(".")
assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT"
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.