text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_image_id(self, image_id):
"""Query OPUS via the image_id. This is a query using the 'primaryfilespec' field of the OPUS database. It returns a list of ... |
myquery = {"primaryfilespec": image_id}
self.create_files_request(myquery, fmt="json")
self.unpack_json_response()
return self.obsids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_between_times(self, t1, t2, target=None):
""" Query for OPUS data between times t1 and t2. Parameters t1, t2 : datetime.datetime, strings Start and end t... |
try:
# checking if times have isoformat() method (datetimes have)
t1 = t1.isoformat()
t2 = t2.isoformat()
except AttributeError:
# if not, should already be a string, so do nothing.
pass
myquery = self._get_time_query(t1, t2)
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_images(self, size="small"):
"""Shows preview images using the Jupyter notebook HTML display. Parameters ========== size : {'small', 'med', 'thumb', 'ful... |
d = dict(small=256, med=512, thumb=100, full=1024)
try:
width = d[size]
except KeyError:
print("Allowed keys:", d.keys())
return
img_urls = [i._get_img_url(size) for i in self.obsids]
imagesList = "".join(
[
"<img s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_results(self, savedir=None, raw=True, calib=False, index=None):
"""Download the previously found and stored Opus obsids. Parameters ========== saved... |
obsids = self.obsids if index is None else [self.obsids[index]]
for obsid in obsids:
pm = io.PathManager(obsid.img_id, savedir=savedir)
pm.basepath.mkdir(exist_ok=True)
to_download = []
if raw is True:
to_download.extend(obsid.raw_urls)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_previews(self, savedir=None):
"""Download preview files for the previously found and stored Opus obsids. Parameters ========== savedir: str or pathl... |
for obsid in self.obsids:
pm = io.PathManager(obsid.img_id, savedir=savedir)
pm.basepath.mkdir(exist_ok=True)
basename = Path(obsid.medium_img_url).name
print("Downloading", basename)
urlretrieve(obsid.medium_img_url, str(pm.basepath / basename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which_epi_janus_resonance(name, time):
"""Find which swap situtation we are in by time. Starting from 2006-01-21 where a Janus-Epimetheus swap occured, and d... |
t1 = Time('2002-01-21').to_datetime()
delta = Time(time).to_datetime() - t1
yearfraction = delta.days / 365
if int(yearfraction / 4) % 2 == 0:
return name + '2'
else:
return name + '1' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(self, layer_id, version_id, expand=[]):
""" Get a specific version of a layer. """ |
target_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
return self._get(target_url, expand=expand) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_draft(self, layer_id):
""" Creates a new draft version. If anything in the data object has changed then an import will begin immediately. Otherwise to... |
target_url = self.client.get_url('VERSION', 'POST', 'create', {'layer_id': layer_id})
r = self.client.request('POST', target_url, json={})
return self.create_from_result(r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_metadata(self, layer_id, version_id, fp):
""" Set the XML metadata on a layer draft version. :param file fp: file-like object to read the XML metadata fr... |
base_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
self._metadata.set(base_url, fp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_published_version(self):
""" Return if this version is the published version of a layer """ |
pub_ver = getattr(self, 'published_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and pub_ver and (this_ver == pub_ver) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_draft_version(self):
""" Return if this version is the draft version of a layer """ |
pub_ver = getattr(self, 'published_version', None)
latest_ver = getattr(self, 'latest_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and latest_ver and (this_ver == latest_ver) and (latest_ver != pub_ver) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(self, version_id, expand=[]):
""" Get a specific version of this layer """ |
target_url = self._client.get_url('VERSION', 'GET', 'single', {'layer_id': self.id, 'version_id': version_id})
return self._manager._get(target_url, expand=expand) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, version_id=None):
""" Creates a publish task just for this version, which publishes as soon as any import is complete. :return: the publish tas... |
if not version_id:
version_id = self.version.id
target_url = self._client.get_url('VERSION', 'POST', 'publish', {'layer_id': self.id, 'version_id': version_id})
r = self._client.request('POST', target_url, json={})
return self._client.get_manager(Publish).create_from_result... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_item_class(self, url):
""" Return the model class matching a URL """ |
if '/layers/' in url:
return Layer
elif '/tables/' in url:
return Table
elif '/sets/' in url:
return Set
# elif '/documents/' in url:
# return Document
else:
raise NotImplementedError("No support for catalog results of ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_year_since_resonance(ringcube):
"Calculate the fraction of the year since moon swap."
t0 = dt(2006, 1, 21)
td = ringcube.imagetime - t0
return td.days / 365.25 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_polynoms():
"""Create and return poly1d objects. Uses the parameters from Morgan to create poly1d objects for calculations. """ |
fname = pr.resource_filename('pyciss', 'data/soliton_prediction_parameters.csv')
res_df = pd.read_csv(fname)
polys = {}
for resorder, row in zip('65 54 43 21'.split(),
range(4)):
p = poly1d([res_df.loc[row, 'Slope (km/yr)'], res_df.loc[row, 'Intercept (km)']])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_for_soliton(img_id):
"""Workhorse function. Creates the polynom. Calculates radius constraints from attributes in `ringcube` object. Parameters ringcub... |
pm = io.PathManager(img_id)
try:
ringcube = RingCube(pm.cubepath)
except FileNotFoundError:
ringcube = RingCube(pm.undestriped)
polys = create_polynoms()
minrad = ringcube.minrad.to(u.km)
maxrad = ringcube.maxrad.to(u.km)
delta_years = get_year_since_resonance(ringcube)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assemble_headers(self, method, user_headers=None):
""" Takes the supplied headers and adds in any which are defined at a client level and then returns the r... |
headers = copy.deepcopy(user_headers or {})
if method not in ('GET', 'HEAD'):
headers.setdefault('Content-Type', 'application/json')
return headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reverse_url(self, datatype, url, verb='GET', urltype='single', api_version=None):
""" Extracts parameters from a populated URL :param datatype: a string iden... |
api_version = api_version or 'v1'
templates = getattr(self, 'URL_TEMPLATES__%s' % api_version)
# this is fairly simplistic, if necessary we could use the parse lib
template_url = r"https://(?P<api_host>.+)/services/api/(?P<api_version>.+)"
template_url += re.sub(r'{([^}]+)}', r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_url(self, datatype, verb, urltype, params={}, api_host=None, api_version=None):
"""Returns a fully formed url :param datatype: a string identifying the d... |
api_version = api_version or 'v1'
api_host = api_host or self.host
subst = params.copy()
subst['api_host'] = api_host
subst['api_version'] = api_version
url = "https://{api_host}/services/api/{api_version}"
url += self.get_url_path(datatype, verb, urltype, para... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_store_variable(self, name, var):
"""Turn CDMRemote variable into something like a numpy.ndarray.""" |
data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))
return Variable(var.dimensions, data, {a: getattr(var, a) for a in var.ncattrs()}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_attrs(self):
"""Get the global attributes from underlying data set.""" |
return FrozenOrderedDict((a, getattr(self.ds, a)) for a in self.ds.ncattrs()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dimensions(self):
"""Get the dimensions from underlying data set.""" |
return FrozenOrderedDict((k, len(v)) for k, v in self.ds.dimensions.items()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_base_tds_url(catalog_url):
"""Identify the base URL of the THREDDS server from the catalog URL. Will retain URL scheme, host, port and username/passwor... |
url_components = urlparse(catalog_url)
if url_components.path:
return catalog_url.split(url_components.path)[0]
else:
return catalog_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_time_nearest(self, time, regex=None):
"""Filter keys for an item closest to the desired time. Loops over all keys in the collection and uses `regex` t... |
return min(self._get_datasets_with_times(regex),
key=lambda i: abs((i[0] - time).total_seconds()))[-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_time_range(self, start, end, regex=None):
"""Filter keys for all items within the desired time range. Loops over all keys in the collection and uses `... |
return [item[-1] for item in self._get_datasets_with_times(regex)
if start <= item[0] <= end] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self, key, *args, **kwargs):
"""Remove and return the value associated with case-insensitive ``key``.""" |
return super(CaseInsensitiveDict, self).pop(CaseInsensitiveStr(key)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _keys_to_lower(self):
"""Convert key set to lowercase.""" |
for k in list(self.keys()):
val = super(CaseInsensitiveDict, self).__getitem__(k)
super(CaseInsensitiveDict, self).__delitem__(k)
self.__setitem__(CaseInsensitiveStr(k), val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_url(self, catalog_url):
"""Resolve the url of the dataset when reading latest.xml. Parameters catalog_url : str The catalog url to be resolved """ |
if catalog_url != '':
resolver_base = catalog_url.split('catalog.xml')[0]
resolver_url = resolver_base + self.url_path
resolver_xml = session_manager.urlopen(resolver_url)
tree = ET.parse(resolver_xml)
root = tree.getroot()
if 'name' in ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_access_urls(self, catalog_url, all_services, metadata=None):
"""Make fully qualified urls for the access methods enabled on the dataset. Parameters cata... |
all_service_dict = CaseInsensitiveDict({})
for service in all_services:
all_service_dict[service.name] = service
if isinstance(service, CompoundService):
for subservice in service.services:
all_service_dict[subservice.name] = subservice
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_access_element_info(self, access_element):
"""Create an access method from a catalog element.""" |
service_name = access_element.attrib['serviceName']
url_path = access_element.attrib['urlPath']
self.access_element_info[service_name] = url_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, filename=None):
"""Download the dataset to a local file. Parameters filename : str, optional The full path to which the dataset will be saved ... |
if filename is None:
filename = self.name
with self.remote_open() as infile:
with open(filename, 'wb') as outfile:
outfile.write(infile.read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remote_access(self, service=None, use_xarray=None):
"""Access the remote dataset. Open the remote dataset and get a netCDF4-compatible `Dataset` object provi... |
if service is None:
service = 'CdmRemote' if 'CdmRemote' in self.access_urls else 'OPENDAP'
if service not in (CaseInsensitiveStr('CdmRemote'), CaseInsensitiveStr('OPENDAP')):
raise ValueError(service + ' is not a valid service for remote_access')
return self.access_wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subset(self, service=None):
"""Subset the dataset. Open the remote dataset and get a client for talking to ``service``. Parameters service : str, optional Th... |
if service is None:
for serviceName in self.ncssServiceNames:
if serviceName in self.access_urls:
service = serviceName
break
else:
raise RuntimeError('Subset access is not available for this dataset.')
elif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def access_with_service(self, service, use_xarray=None):
"""Access the dataset using a particular service. Return an Python object capable of communicating with ... |
service = CaseInsensitiveStr(service)
if service == 'CdmRemote':
if use_xarray:
from .cdmr.xarray_support import CDMRemoteStore
try:
import xarray as xr
provider = lambda url: xr.open_dataset(CDMRemoteStore(url)) # noq... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_metadata(self):
"""Get header information and store as metadata for the endpoint.""" |
self.metadata = self.fetch_header()
self.variables = {g.name for g in self.metadata.grids} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_header(self):
"""Make a header request to the endpoint.""" |
query = self.query().add_query_parameter(req='header')
return self._parse_messages(self.get_query(query).content)[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_feature_type(self):
"""Request the featureType from the endpoint.""" |
query = self.query().add_query_parameter(req='featureType')
return self.get_query(query).content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_coords(self, query):
"""Pull down coordinate data from the endpoint.""" |
q = query.add_query_parameter(req='coord')
return self._parse_messages(self.get_query(q).content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_data(cls, time, site_id, derived=False):
"""Retreive IGRA version 2 data for one station. Parameters -------- site_id : str 11-character IGRA2 statio... |
igra2 = cls()
# Set parameters for data query
if derived:
igra2.ftpsite = igra2.ftpsite + 'derived/derived-por/'
igra2.suffix = igra2.suffix + '-drvd.txt'
else:
igra2.ftpsite = igra2.ftpsite + 'data/data-por/'
igra2.suffix = igra2.suffix ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data(self):
"""Process the IGRA2 text file for observations at site_id matching time. Return: ------- :class: `pandas.DataFrame` containing the body dat... |
# Split the list of times into begin and end dates. If only
# one date is supplied, set both begin and end dates equal to that date.
body, header, dates_long, dates = self._get_data_raw()
params = self._get_fwf_params()
df_body = pd.read_fwf(StringIO(body), **params['body'])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data_raw(self):
"""Download observations matching the time range. Returns a tuple with a string for the body, string for the headers, and a list of date... |
# Import need to be here so we can monkeypatch urlopen for testing and avoid
# downloading live data for testing
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
with closing(urlopen(self.ftpsite + self.site_id + se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _select_date_range(self, lines):
"""Identify lines containing headers within the range begin_date to end_date. Parameters ----- lines: list list of lines fro... |
headers = []
num_lev = []
dates = []
# Get indices of headers, and make a list of dates and num_lev
for idx, line in enumerate(lines):
if line[0] == '#':
year, month, day, hour = map(int, line[13:26].split())
# All soundings have YMD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_body_df(self, df):
"""Format the dataframe, remove empty rows, and add units attribute.""" |
if self.suffix == '-drvd.txt':
df = df.dropna(subset=('temperature', 'reported_relative_humidity',
'u_wind', 'v_wind'), how='all').reset_index(drop=True)
df.units = {'pressure': 'hPa',
'reported_height': 'meter',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_header_df(self, df):
"""Format the header dataframe and add units.""" |
if self.suffix == '-drvd.txt':
df.units = {'release_time': 'second',
'precipitable_water': 'millimeter',
'inv_pressure': 'hPa',
'inv_height': 'meter',
'inv_strength': 'Kelvin',
'm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def realtime_observations(cls, buoy, data_type='txt'):
"""Retrieve the realtime buoy data from NDBC. Parameters buoy : str Name of buoy data_type : str Type of d... |
endpoint = cls()
parsers = {'txt': endpoint._parse_met,
'drift': endpoint._parse_drift,
'cwind': endpoint._parse_cwind,
'spec': endpoint._parse_spec,
'ocean': endpoint._parse_ocean,
'srad': endpoint._parse_sr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_met(content):
"""Parse standard meteorological data from NDBC buoys. Parameters content : str Data to parse Returns ------- :class:`pandas.DataFrame` ... |
col_names = ['year', 'month', 'day', 'hour', 'minute',
'wind_direction', 'wind_speed', 'wind_gust',
'wave_height', 'dominant_wave_period', 'average_wave_period',
'dominant_wave_direction', 'pressure',
'air_temperature', 'water_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_supl(content):
"""Parse supplemental measurements data. Parameters content : str Data to parse Returns ------- :class:`pandas.DataFrame` containing th... |
col_names = ['year', 'month', 'day', 'hour', 'minute',
'hourly_low_pressure', 'hourly_low_pressure_time',
'hourly_high_wind', 'hourly_high_wind_direction',
'hourly_high_wind_time']
col_units = {'hourly_low_pressure': 'hPa',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buoy_data_types(cls, buoy):
"""Determine which types of data are available for a given buoy. Parameters buoy : str Buoy name Returns ------- dict of valid fi... |
endpoint = cls()
file_types = {'txt': 'standard meteorological data',
'drift': 'meteorological data from drifting buoys and limited moored'
'buoy data mainly from international partners',
'cwind': 'continuous wind data (10 minut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_buoy_data(cls, buoy, data_type='txt'):
"""Retrieve the raw buoy data contents from NDBC. Parameters buoy : str Name of buoy data_type : str Type of data ... |
endpoint = cls()
resp = endpoint.get_path('data/realtime2/{}.{}'.format(buoy, data_type))
return resp.text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_session(self):
"""Create a new HTTP session with our user-agent set. Returns ------- session : requests.Session The created session See Also -------- ... |
ret = requests.Session()
ret.headers['User-Agent'] = self.user_agent
for k, v in self.options.items():
setattr(ret, k, v)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def urlopen(self, url, **kwargs):
"""GET a file-like object for a URL using HTTP. This is a thin wrapper around :meth:`requests.Session.get` that returns a file-... |
return BytesIO(self.create_session().get(url, **kwargs).content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time(self, time):
"""Add a request for a specific time to the query. This modifies the query in-place, but returns `self` so that multiple queries can be cha... |
self._set_query(self.time_query, time=self._format_time(time))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_range(self, start, end):
"""Add a request for a time range to the query. This modifies the query in-place, but returns `self` so that multiple queries c... |
self._set_query(self.time_query, time_start=self._format_time(start),
time_end=self._format_time(end))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_query(self, query):
"""Make a GET request, including a query, to the endpoint. The path of the request is to the base URL assigned to the endpoint. Param... |
url = self._base[:-1] if self._base[-1] == '/' else self._base
return self.get(url, query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_path(self, path, query=None):
"""Make a GET request, optionally including a query, to a relative path. The path of the request includes a path on top of ... |
return self.get(self.url_path(path), query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, path, params=None):
"""Make a GET request, optionally including a parameters, to a path. The path of the request is the full URL. Parameters path :... |
resp = self._session.get(path, params=params)
if resp.status_code != 200:
if resp.headers.get('Content-Type', '').startswith('text/html'):
text = resp.reason
else:
text = resp.text
raise requests.HTTPError('Error accessing {0}\n'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path(self):
"""Return the full path to the Group, including any parent Groups.""" |
# If root, return '/'
if self.dataset is self:
return ''
else: # Otherwise recurse
return self.dataset.path + '/' + self.name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_stream(self, group):
"""Load a Group from an NCStream object.""" |
self._unpack_attrs(group.atts)
self.name = group.name
for dim in group.dims:
new_dim = Dimension(self, dim.name)
self.dimensions[dim.name] = new_dim
new_dim.load_from_stream(dim)
for var in group.vars:
new_var = Variable(self, var.name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_stream(self, var):
"""Populate the Variable from an NCStream object.""" |
dims = []
for d in var.shape:
dim = Dimension(None, d.name)
dim.load_from_stream(d)
dims.append(dim)
self.dimensions = tuple(dim.name for dim in dims)
self.shape = tuple(dim.size for dim in dims)
self.ndim = len(var.shape)
self._unpac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_stream(self, dim):
"""Load from an NCStream object.""" |
self.unlimited = dim.isUnlimited
self.private = dim.isPrivate
self.vlen = dim.isVlen
if not self.vlen:
self.size = dim.length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_header(self):
"""Get the needed header information to initialize dataset.""" |
self._header = self.cdmrf.fetch_header()
self.load_from_stream(self._header) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_stream(self, header):
"""Populate the CoverageDataset from the protobuf information.""" |
self._unpack_attrs(header.atts)
self.name = header.name
self.lon_lat_domain = header.latlonRect
self.proj_domain = header.projRect
self.date_range = header.dateRange
self.type = header.coverageType
for sys in header.coordSys:
self.coord_systems[sys.n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_data(cls, time, site_id, **kwargs):
"""Retrieve upper air observations from Iowa State's archive for a single station. Parameters time : datetime The... |
endpoint = cls()
df = endpoint._get_data(time, site_id, None, **kwargs)
return df |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_all_data(cls, time, pressure=None, **kwargs):
"""Retrieve upper air observations from Iowa State's archive for all stations. Parameters time : dateti... |
endpoint = cls()
df = endpoint._get_data(time, None, pressure, **kwargs)
return df |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data(self, time, site_id, pressure=None):
"""Download data from Iowa State's upper air archive. Parameters time : datetime Date and time for which data ... |
json_data = self._get_data_raw(time, site_id, pressure)
data = {}
for profile in json_data['profiles']:
for pt in profile['profile']:
for field in ('drct', 'dwpc', 'hght', 'pres', 'sknt', 'tmpc'):
data.setdefault(field, []).append(np.nan if pt[fie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data_raw(self, time, site_id, pressure=None):
r"""Download data from the Iowa State's upper air archive. Parameters time : datetime Date and time for wh... |
query = {'ts': time.strftime('%Y%m%d%H00')}
if site_id is not None:
query['station'] = site_id
if pressure is not None:
query['pressure'] = pressure
resp = self.get_path('raob.py', query)
json_data = json.loads(resp.text)
# See if the return is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_station_table(root):
"""Parse station list XML file.""" |
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stations(self, *stns):
"""Specify one or more stations for the query. This modifies the query in-place, but returns `self` so that multiple queries can be ch... |
self._set_query(self.spatial_query, stn=stns)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_catalog(self, query):
"""Fetch a parsed THREDDS catalog from the radar server. Requests a catalog of radar data files data from the radar server given th... |
# TODO: Refactor TDSCatalog so we don't need two requests, or to do URL munging
try:
url = self._base[:-1] if self._base[-1] == '/' else self._base
url += '?' + str(query)
return TDSCatalog(url)
except ET.ParseError:
raise BadQueryError(self.get_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acis_request(method, params):
"""Request data from the ACIS Web Services API. Makes a request from the ACIS Web Services API for data based on a given method... |
base_url = 'http://data.rcc-acis.org/' # ACIS Web API URL
timeout = 300 if method == 'MultiStnData' else 60
try:
response = session_manager.create_session().post(base_url + method, json=params,
timeout=timeout)
return response.json... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS.""" |
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_xml_point(elem):
"""Parse an XML point tag.""" |
point = {}
units = {}
for data in elem.findall('data'):
name = data.get('name')
unit = data.get('units')
point[name] = float(data.text) if name != 'date' else parse_iso_date(data.text)
if unit:
units[name] = unit
return point, units |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array.""" |
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key != 'date':
ret[key] = handle_units(value, units.get(key, None))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_xml_dataset(elem, handle_units):
"""Create a netCDF-like dataset from XML data.""" |
points, units = zip(*[parse_xml_point(p) for p in elem.findall('point')])
# Group points by the contents of each point
datasets = {}
for p in points:
datasets.setdefault(tuple(p), []).append(p)
all_units = combine_dicts(units)
return [combine_xml_points(d, all_units, handle_units) for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_csv_response(data, unit_handler):
"""Handle CSV-formatted HTTP responses.""" |
return squish([parse_csv_dataset(d, unit_handler) for d in data.split(b'\n\n')]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_csv_header(line):
"""Parse the CSV header returned by TDS.""" |
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var.find(']', start)
unitstr = var[start + 1:end]
eq = unitstr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_csv_dataset(data, handle_units):
"""Parse CSV data into a netCDF-like dataset.""" |
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode('utf-8'))
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=',', unpack=True,
converters={'date': lambda s: parse_iso_date(s.decode('utf-8'))})
d = {}
for f in arrs.dtype.fields:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_data(self, query):
"""Fetch parsed data from a THREDDS server using NCSS. Requests data from the NCSS endpoint given the parameters in `query` and handle... |
resp = self.get_query(query)
return response_handlers(resp, self.unit_handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, mimetype):
"""Register a function to handle a particular mimetype.""" |
def dec(func):
self._reg[mimetype] = func
return func
return dec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_typed_values(val, type_name, value_type):
"""Translate typed values into the appropriate python object. Takes an element name, value, and type and ret... |
if value_type in ['byte', 'short', 'int', 'long']:
try:
val = [int(v) for v in re.split('[ ,]', val) if v]
except ValueError:
log.warning('Cannot convert "%s" to int. Keeping type as str.', val)
elif value_type in ['float', 'double']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data(self, time, site_id):
r"""Download and parse upper air observations from an online archive. Parameters time : datetime The date and time of the des... |
raw_data = self._get_data_raw(time, site_id)
soup = BeautifulSoup(raw_data, 'html.parser')
tabular_data = StringIO(soup.find_all('pre')[0].contents[0])
col_names = ['pressure', 'height', 'temperature', 'dewpoint', 'direction', 'speed']
df = pd.read_fwf(tabular_data, skiprows=5, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_data_raw(self, time, site_id):
"""Download data from the University of Wyoming's upper air archive. Parameters time : datetime Date and time for which d... |
path = ('?region=naconf&TYPE=TEXT%3ALIST'
'&YEAR={time:%Y}&MONTH={time:%m}&FROM={time:%d%H}&TO={time:%d%H}'
'&STNM={stid}').format(time=time, stid=site_id)
resp = self.get_path(path)
# See if the return is valid, but has no data
if resp.text.find('Can\'t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ncstream_data(fobj):
"""Handle reading an NcStream v1 data block from a file-like object.""" |
data = read_proto_object(fobj, stream.Data)
if data.dataType in (stream.STRING, stream.OPAQUE) or data.vdata:
log.debug('Reading string/opaque/vlen')
num_obj = read_var_int(fobj)
log.debug('Num objects: %d', num_obj)
blocks = [read_block(fobj) for _ in range(num_obj)]
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ncstream_err(fobj):
"""Handle reading an NcStream error from a file-like object and raise as error.""" |
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_messages(fobj, magic_table):
"""Read messages from a file-like object until stream is exhausted.""" |
messages = []
while True:
magic = read_magic(fobj)
if not magic:
break
func = magic_table.get(magic)
if func is not None:
messages.append(func(fobj))
else:
log.error('Unknown magic: ' + str(' '.join('{0:02x}'.format(b)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_proto_object(fobj, klass):
"""Read a block of data and parse using the given protobuf object.""" |
log.debug('%s chunk', klass.__name__)
obj = klass()
obj.ParseFromString(read_block(fobj))
log.debug('Header: %s', str(obj))
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_block(fobj):
"""Read a block. Reads a block from a file object by first reading the number of bytes to read, which must be encoded as a variable-byte le... |
num = read_var_int(fobj)
log.debug('Next block: %d bytes', num)
return fobj.read(num) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_vlen(data_header, array):
"""Process vlen coming back from NCStream v2. This takes the array of values and slices into an object array, with entries ... |
source = iter(array)
return np.array([np.fromiter(itertools.islice(source, size), dtype=array.dtype)
for size in data_header.vlens]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datacol_to_array(datacol):
"""Convert DataCol from NCStream v2 into an array with appropriate type. Depending on the data type specified, this extracts data ... |
if datacol.dataType == stream.STRING:
arr = np.array(datacol.stringdata, dtype=np.object)
elif datacol.dataType == stream.OPAQUE:
arr = np.array(datacol.opaquedata, dtype=np.object)
elif datacol.dataType == stream.STRUCTURE:
members = OrderedDict((mem.name, datacol_to_array(mem))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reshape_array(data_header, array):
"""Extract the appropriate array shape from the header. Can handle taking a data header and either bytes containing data o... |
shape = tuple(r.size for r in data_header.section.range)
if shape:
return array.reshape(*shape)
else:
return array |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_type_to_numpy(datatype, unsigned=False):
"""Convert an ncstream datatype to a numpy one.""" |
basic_type = _dtypeLookup[datatype]
if datatype in (stream.STRING, stream.OPAQUE):
return np.dtype(basic_type)
if unsigned:
basic_type = basic_type.replace('i', 'u')
return np.dtype('=' + basic_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def struct_to_dtype(struct):
"""Convert a Structure specification to a numpy structured dtype.""" |
# str() around name necessary because protobuf gives unicode names, but dtype doesn't
# support them on Python 2
fields = [(str(var.name), data_type_to_numpy(var.dataType, var.unsigned))
for var in struct.vars]
for s in struct.structs:
fields.append((str(s.name), struct_to_dtype(s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_variable(var):
"""Unpack an NCStream Variable into information we can use.""" |
# If we actually get a structure instance, handle turning that into a variable
if var.dataType == stream.STRUCTURE:
return None, struct_to_dtype(var), 'Structure'
elif var.dataType == stream.SEQUENCE:
log.warning('Sequence support not implemented!')
dt = data_type_to_numpy(var.dataType... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_attribute(att):
"""Unpack an embedded attribute into a python or numpy object.""" |
if att.unsigned:
log.warning('Unsupported unsigned attribute!')
# TDS 5.0 now has a dataType attribute that takes precedence
if att.len == 0: # Empty
val = None
elif att.dataType == stream.STRING: # Then look for new datatype string
val = att.sdata
elif att.dataType: # T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_var_int(file_obj):
"""Read a variable-length integer. Parameters file_obj : file-like object The file to read from. Returns ------- int the variable-len... |
# Read all bytes from here, stopping with the first one that does not have
# the MSB set. Save the lower 7 bits, and keep stacking to the *left*.
val = 0
shift = 0
while True:
# Read next byte
next_val = ord(file_obj.read(1))
val |= ((next_val & 0x7F) << shift)
shift... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_data(self, **var):
"""Retrieve data from CDMRemote for one or more variables.""" |
varstr = ','.join(name + self._convert_indices(ind)
for name, ind in var.items())
query = self.query().add_query_parameter(req='data', var=varstr)
return self._fetch(query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self):
"""Generate a new query for CDMRemote. This handles turning on compression if necessary. Returns ------- HTTPQuery The created query. """ |
q = super(CDMRemote, self).query()
# Turn on compression if it's been set on the object
if self.deflate:
q.add_query_parameter(deflate=self.deflate)
return q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
""" Login to verisure app api Login before calling any read or write commands """ |
if os.path.exists(self._cookieFileName):
with open(self._cookieFileName, 'r') as cookieFile:
self._vid = cookieFile.read().strip()
try:
self._get_installations()
except ResponseError:
self._vid = None
os.remove... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_installations(self):
""" Get information about installations """ |
response = None
for base_url in urls.BASE_URLS:
urls.BASE_URL = base_url
try:
response = requests.get(
urls.get_installations(self._username),
headers={
'Cookie': 'vid={}'.format(self._vid),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.