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 string_is_url(test_str):
""" Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component False Tr... |
parsed = urlparse.urlparse(test_str)
return parsed.scheme is not None and parsed.scheme != '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def item_transaction(self, item) -> Transaction: """Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for per... |
items = self.__build_transaction_items(item)
transaction = Transaction(self, item, items)
self.__transactions.append(transaction)
return transaction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_data_item(self, before_index, data_item, auto_display: bool = True) -> None: """Insert a new data item into document model. This method is NOT threadsa... |
assert data_item is not None
assert data_item not in self.data_items
assert before_index <= len(self.data_items) and before_index >= 0
assert data_item.uuid not in self.__uuid_to_data_item
# update the session
data_item.session_id = self.session_id
# insert in in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_data_item(self, data_item: DataItem.DataItem, *, safe: bool=False) -> typing.Optional[typing.Sequence]: """Remove data item from document model. This m... |
# remove data item from any computations
return self.__cascade_delete(data_item, safe=safe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transaction_context(self):
"""Return a context object for a document-wide transaction.""" |
class DocumentModelTransaction:
def __init__(self, document_model):
self.__document_model = document_model
def __enter__(self):
self.__document_model.persistent_object_context.enter_write_delay(self.__document_model)
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 data_item_live(self, data_item):
""" Return a context manager to put the data item in a 'live state'. """ |
class LiveContextManager:
def __init__(self, manager, object):
self.__manager = manager
self.__object = object
def __enter__(self):
self.__manager.begin_data_item_live(self.__object)
return self
def __exit__(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin_data_item_live(self, data_item):
"""Begins a live state for the data item. The live state is propagated to dependent data items. This method is thread ... |
with self.__live_data_items_lock:
old_live_count = self.__live_data_items.get(data_item.uuid, 0)
self.__live_data_items[data_item.uuid] = old_live_count + 1
if old_live_count == 0:
data_item._enter_live_state()
for dependent_data_item in self.get_dependen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_data_item_live(self, data_item):
"""Ends a live state for the data item. The live-ness property is propagated to dependent data items, similar to the tra... |
with self.__live_data_items_lock:
live_count = self.__live_data_items.get(data_item.uuid, 0) - 1
assert live_count >= 0
self.__live_data_items[data_item.uuid] = live_count
if live_count == 0:
data_item._exit_live_state()
for dependent_data_ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __construct_data_item_reference(self, hardware_source: HardwareSource.HardwareSource, data_channel: HardwareSource.DataChannel):
"""Construct a data item ref... |
session_id = self.session_id
key = self.make_data_item_reference_key(hardware_source.hardware_source_id, data_channel.channel_id)
data_item_reference = self.get_data_item_reference(key)
with data_item_reference.mutex:
data_item = data_item_reference.data_item
# 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 load_data_old(self):
""" Loads time series of 2D data grids from each opened file. The code handles loading a full time series from one file or individual ti... |
units = ""
if len(self.file_objects) == 1 and self.file_objects[0] is not None:
data = self.file_objects[0].variables[self.variable][self.forecast_hours]
if hasattr(self.file_objects[0].variables[self.variable], "units"):
units = self.file_objects[0].variables[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 load_data(self):
""" Load data from netCDF file objects or list of netCDF file objects. Handles special variable name formats. Returns: Array of data loaded ... |
units = ""
if self.file_objects[0] is None:
raise IOError()
var_name, z_index = self.format_var_name(self.variable, list(self.file_objects[0].variables.keys()))
ntimes = 0
if 'time' in self.file_objects[0].variables[var_name].dimensions:
ntimes = len(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 format_var_name(variable, var_list):
""" Searches var list for variable name, checks other variable name format options. Args: variable (str):
Variable bein... |
z_index = None
if variable in var_list:
var_name = variable
elif variable.ljust(6, "_") in var_list:
var_name = variable.ljust(6, "_")
elif any([variable in v_sub.split("_") for v_sub in var_list]):
var_name = var_list[[variable in v_sub.split("_") fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_models(self, model_path):
""" Save machine learning models to pickle files. """ |
for group, condition_model_set in self.condition_models.items():
for model_name, model_obj in condition_model_set.items():
out_filename = model_path + \
"{0}_{1}_condition.pkl".format(group,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_forecasts_csv(self, forecasts, mode, csv_path, run_date_format="%Y%m%d-%H%M"):
""" Output hail forecast values to csv files by run date and ensemble m... |
merged_forecasts = pd.merge(forecasts["condition"],
forecasts["dist"],
on=["Step_ID","Track_ID","Ensemble_Member","Forecast_Hour"])
all_members = self.data[mode]["combo"]["Ensemble_Member"]
members = np.unique(all_members)
... |
<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_forecasts(self):
""" Loads the forecast files and gathers the forecast information into pandas DataFrames. """ |
forecast_path = self.forecast_json_path + "/{0}/{1}/".format(self.run_date.strftime("%Y%m%d"),
self.ensemble_member)
forecast_files = sorted(glob(forecast_path + "*.json"))
for forecast_file in forecast_files:
file... |
<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_obs(self):
""" Loads the track total and step files and merges the information into a single data frame. """ |
track_total_file = self.track_data_csv_path + \
"track_total_{0}_{1}_{2}.csv".format(self.ensemble_name,
self.ensemble_member,
self.run_date.strftime("%Y%m%d"))
track_step_file = self.track_dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_obs(self):
""" Match forecasts and observations. """ |
for model_type in self.model_types:
self.matched_forecasts[model_type] = {}
for model_name in self.model_names[model_type]:
self.matched_forecasts[model_type][model_name] = pd.merge(self.forecasts[model_type][model_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 roc(self, model_type, model_name, intensity_threshold, prob_thresholds, query=None):
""" Calculates a ROC curve at a specified intensity threshold. Args: mod... |
roc_obj = DistributedROC(prob_thresholds, 0.5)
if query is not None:
sub_forecasts = self.matched_forecasts[model_type][model_name].query(query)
sub_forecasts = sub_forecasts.reset_index(drop=True)
else:
sub_forecasts = self.matched_forecasts[model_type][mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_forecast_max_hail(self, dist_model_name, condition_model_name, num_samples, condition_threshold=0.5, query=None):
""" Samples every forecast hail obje... |
if query is not None:
dist_forecasts = self.matched_forecasts["dist"][dist_model_name].query(query)
dist_forecasts = dist_forecasts.reset_index(drop=True)
condition_forecasts = self.matched_forecasts["condition"][condition_model_name].query(query)
condition_forec... |
<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_params(self):
"""Get signature and params """ |
params = {
'key': self.get_app_key(),
'uid': self.user_id,
'widget': self.widget_code
}
products_number = len(self.products)
if self.get_api_type() == self.API_GOODS:
if isinstance(self.products, list):
if products_numb... |
<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_forecasts(self):
""" Load the forecast files into memory. """ |
run_date_str = self.run_date.strftime("%Y%m%d")
for model_name in self.model_names:
self.raw_forecasts[model_name] = {}
forecast_file = self.forecast_path + run_date_str + "/" + \
model_name.replace(" ", "-") + "_hailprobs_{0}_{1}.nc".format(self.ensemble_member,... |
<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_window_forecasts(self):
""" Aggregate the forecasts within the specified time windows. """ |
for model_name in self.model_names:
self.window_forecasts[model_name] = {}
for size_threshold in self.size_thresholds:
self.window_forecasts[model_name][size_threshold] = \
np.array([self.raw_forecasts[model_name][size_threshold][sl].sum(axis=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 dilate_obs(self, dilation_radius):
""" Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: ... |
for s in self.size_thresholds:
self.dilated_obs[s] = np.zeros(self.window_obs[self.mrms_variable].shape)
for t in range(self.dilated_obs[s].shape[0]):
self.dilated_obs[s][t][binary_dilation(self.window_obs[self.mrms_variable][t] >= s, iterations=dilation_radius)] = 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 roc_curves(self, prob_thresholds):
""" Generate ROC Curve objects for each machine learning model, size threshold, and time window. :param prob_thresholds: P... |
all_roc_curves = {}
for model_name in self.model_names:
all_roc_curves[model_name] = {}
for size_threshold in self.size_thresholds:
all_roc_curves[model_name][size_threshold] = {}
for h, hour_window in enumerate(self.hour_windows):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reliability_curves(self, prob_thresholds):
""" Output reliability curves for each machine learning model, size threshold, and time window. :param prob_thresh... |
all_rel_curves = {}
for model_name in self.model_names:
all_rel_curves[model_name] = {}
for size_threshold in self.size_thresholds:
all_rel_curves[model_name][size_threshold] = {}
for h, hour_window in enumerate(self.hour_windows):
... |
<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_map_coordinates(map_file):
""" Loads map coordinates from netCDF or pickle file created by util.makeMapGrids. Args: map_file: Filename for the file cont... |
if map_file[-4:] == ".pkl":
map_data = pickle.load(open(map_file))
lon = map_data['lon']
lat = map_data['lat']
else:
map_data = Dataset(map_file)
if "lon" in map_data.variables.keys():
lon = map_data.variables['lon'][:]
lat = map_data.variables['l... |
<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_data(self):
""" Loads data from MRMS GRIB2 files and handles compression duties if files are compressed. """ |
data = []
loaded_dates = []
loaded_indices = []
for t, timestamp in enumerate(self.all_dates):
date_str = timestamp.date().strftime("%Y%m%d")
full_path = self.path_start + date_str + "/"
if self.variable in os.listdir(full_path):
full_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpolate_grid(self, in_lon, in_lat):
""" Interpolates MRMS data to a different grid using cubic bivariate splines """ |
out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1]))
for d in range(self.data.shape[0]):
print("Loading ", d, self.variable, self.start_date)
if self.data[d].max() > -999:
step = self.data[d]
step[step < 0] = 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 max_neighbor(self, in_lon, in_lat, radius=0.05):
""" Finds the largest value within a given radius of a point on the interpolated grid. Args: in_lon: 2D arra... |
out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1]))
in_tree = cKDTree(np.vstack((in_lat.ravel(), in_lon.ravel())).T)
out_indices = np.indices(out_data.shape[1:])
out_rows = out_indices[0].ravel()
out_cols = out_indices[1].ravel()
for d in range(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 interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00", interp_type="spline"):
""" Calls the interpolation function... |
if interp_type == "spline":
out_data = self.interpolate_grid(in_lon, in_lat)
else:
out_data = self.max_neighbor(in_lon, in_lat)
if not os.access(out_path + self.variable, os.R_OK):
try:
os.mkdir(out_path + self.variable)
except OSE... |
<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_generator_by_id(hardware_source_id, sync=True):
""" Return a generator for data. :param bool sync: whether to wait for current frame to finish then ... |
hardware_source = HardwareSourceManager().get_hardware_source_for_hardware_source_id(hardware_source_id)
def get_last_data():
return hardware_source.get_next_xdatas_to_finish()[0].data.copy()
yield get_last_data |
<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_hardware_aliases_config_file(config_path):
""" Parse config file for aliases and automatically register them. Returns True if alias file was found and ... |
if os.path.exists(config_path):
logging.info("Parsing alias file {:s}".format(config_path))
try:
config = configparser.ConfigParser()
config.read(config_path)
for section in config.sections():
device = config.get(section, "device")
... |
<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_instrument_alias(self, instrument_id, alias_instrument_id, display_name):
""" Configure an alias. Callers can use the alias to refer to the instrument o... |
self.__aliases[alias_instrument_id] = (instrument_id, display_name)
for f in self.aliases_updated:
f() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, data_and_metadata: DataAndMetadata.DataAndMetadata, state: str, sub_area, view_id) -> None: """Called from hardware source when new data arrives.... |
self.__state = state
self.__sub_area = sub_area
hardware_source_id = self.__hardware_source.hardware_source_id
channel_index = self.index
channel_id = self.channel_id
channel_name = self.name
metadata = copy.deepcopy(data_and_metadata.metadata)
hardware_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Called from hardware source when data starts streaming.""" |
old_start_count = self.__start_count
self.__start_count += 1
if old_start_count == 0:
self.data_channel_start_event.fire() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_data_item_reference(self, data_item_reference):
"""Connect to the data item reference, creating a crop graphic if necessary. If the data item referen... |
display_item = data_item_reference.display_item
data_item = display_item.data_item if display_item else None
if data_item and display_item:
self.__connect_display(display_item)
else:
def data_item_reference_changed():
self.__data_item_reference_ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_earliest(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the earliest data from the buffer, blocking until one is ava... |
timeout = timeout if timeout is not None else 10.0
with self.__buffer_lock:
if len(self.__buffer) == 0:
done_event = threading.Event()
self.__done_events.append(done_event)
self.__buffer_lock.release()
done = done_event.wait(ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_next(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to finish from the buffer, blocking until one is a... |
with self.__buffer_lock:
self.__buffer = list()
return self.grab_latest(timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_following(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to start from the buffer, blocking until one ... |
self.grab_next(timeout)
return self.grab_next(timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" |
with self.__state_lock:
if self.__state == DataChannelBuffer.State.started:
self.__state = DataChannelBuffer.State.paused |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resume(self) -> None: """Resume recording after pause. Thread safe and UI safe.""" |
with self.__state_lock:
if self.__state == DataChannelBuffer.State.paused:
self.__state = DataChannelBuffer.State.started |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlargest(n, mapping):
""" Takes a mapping and returns the n keys associated with the largest values in descending order. If the mapping has fewer than n item... |
try:
it = mapping.iteritems()
except AttributeError:
it = iter(mapping.items())
pq = minpq()
try:
for i in range(n):
pq.additem(*next(it))
except StopIteration:
pass
try:
while it:
pq.pushpopitem(*next(it))
except StopIteration... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromkeys(cls, iterable, value, **kwargs):
""" Return a new pqict mapping keys from an iterable to the same value. """ |
return cls(((k, value) for k in iterable), **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
""" Return a shallow copy of a pqdict. """ |
return self.__class__(self, key=self._keyfn, precedes=self._precedes) |
<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=__marker, default=__marker):
""" If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` ... |
heap = self._heap
position = self._position
# pq semantics: remove and return top *key* (value is discarded)
if key is self.__marker:
if not heap:
raise KeyError('pqdict is empty')
key = heap[0].key
del self[key]
return 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 popitem(self):
""" Remove and return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ |
heap = self._heap
position = self._position
try:
end = heap.pop(-1)
except IndexError:
raise KeyError('pqdict is empty')
if heap:
node = heap[0]
heap[0] = end
position[end.key] = 0
self._sink(0)
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def topitem(self):
""" Return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ |
try:
node = self._heap[0]
except IndexError:
raise KeyError('pqdict is empty')
return node.key, node.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def additem(self, key, value):
""" Add a new item. Raises ``KeyError`` if key is already in the pqdict. """ |
if key in self._position:
raise KeyError('%s is already in the queue' % repr(key))
self[key] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pushpopitem(self, key, value, node_factory=_Node):
""" Equivalent to inserting a new item followed by removing the top priority item, but faster. Raises ``Ke... |
heap = self._heap
position = self._position
precedes = self._precedes
prio = self._keyfn(value) if self._keyfn else value
node = node_factory(key, value, prio)
if key in self:
raise KeyError('%s is already in the queue' % repr(key))
if heap and preced... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateitem(self, key, new_val):
""" Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict. """ |
if key not in self._position:
raise KeyError(key)
self[key] = new_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 replace_key(self, key, new_key):
""" Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to replace does not exist or if the ne... |
heap = self._heap
position = self._position
if new_key in self:
raise KeyError('%s is already in the queue' % repr(new_key))
pos = position.pop(key) # raises appropriate KeyError
position[new_key] = pos
heap[pos].key = new_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 swap_priority(self, key1, key2):
""" Fast way to swap the priority level of two items in the pqdict. Raises ``KeyError`` if either key does not exist. """ |
heap = self._heap
position = self._position
if key1 not in self or key2 not in self:
raise KeyError
pos1, pos2 = position[key1], position[key2]
heap[pos1].key, heap[pos2].key = key2, key1
position[key1], position[key2] = pos2, pos1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def heapify(self, key=__marker):
""" Repair a broken heap. If the state of an item's priority value changes you can re-sort the relevant item only by providing `... |
if key is self.__marker:
n = len(self._heap)
for pos in reversed(range(n//2)):
self._sink(pos)
else:
try:
pos = self._position[key]
except KeyError:
raise KeyError(key)
self._reheapify(pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package_has_version_file(package_name):
""" Check to make sure _version.py is contained in the package """ |
version_file_path = helpers.package_file_path('_version.py', package_name)
return os.path.isfile(version_file_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 get_project_name():
""" Grab the project name out of setup.py """ |
setup_py_content = helpers.get_file_content('setup.py')
ret = helpers.value_of_named_argument_in_function(
'name', 'setup', setup_py_content, resolve_varname=True
)
if ret and ret[0] == ret[-1] in ('"', "'"):
ret = ret[1:-1]
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 get_version(package_name, ignore_cache=False):
""" Get the version which is currently configured by the package """ |
if ignore_cache:
with microcache.temporarily_disabled():
found = helpers.regex_in_package_file(
VERSION_SET_REGEX, '_version.py', package_name, return_match=True
)
else:
found = helpers.regex_in_package_file(
VERSION_SET_REGEX, '_version.py', ... |
<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_version(package_name, version_str):
""" Set the version in _version.py to version_str """ |
current_version = get_version(package_name)
version_file_path = helpers.package_file_path('_version.py', package_name)
version_file_content = helpers.get_file_content(version_file_path)
version_file_content = version_file_content.replace(current_version, version_str)
with open(version_file_path, 'w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_is_valid(version_str):
""" Check to see if the version specified is a valid as far as pkg_resources is concerned False True """ |
try:
packaging.version.Version(version_str)
except packaging.version.InvalidVersion:
return False
return True |
<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_uploaded_versions_warehouse(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using warehouse api to find all of the... |
url = '/'.join((index_url, project_name, 'json'))
response = requests.get(url, verify=requests_verify)
if response.status_code == 200:
return response.json()['releases'].keys()
return None |
<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_uploaded_versions_pypicloud(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using pypicloud api to find all versio... |
api_url = index_url
for suffix in ('/pypi', '/pypi/', '/simple', '/simple/'):
if api_url.endswith(suffix):
api_url = api_url[:len(suffix) * -1] + '/api/package'
break
url = '/'.join((api_url, project_name))
response = requests.get(url, verify=requests_verify)
if resp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_already_uploaded(project_name, version_str, index_url, requests_verify=True):
""" Check to see if the version specified has already been uploaded to ... |
all_versions = _get_uploaded_versions(project_name, index_url, requests_verify)
return version_str in all_versions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_readme_to_rst():
""" Attempt to convert a README.md file into README.rst """ |
project_files = os.listdir('.')
for filename in project_files:
if filename.lower() == 'readme':
raise ProjectError(
'found {} in project directory...'.format(filename) +
'not sure what to do with it, refusing to convert'
)
elif filename.lo... |
<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_packaged_files(package_name):
""" Collect relative paths to all files which have already been packaged """ |
if not os.path.isdir('dist'):
return []
return [os.path.join('dist', filename) for filename in os.listdir('dist')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multiple_packaged_versions(package_name):
""" Look through built package directory and see if there are multiple versions there """ |
dist_files = os.listdir('dist')
versions = set()
for filename in dist_files:
version = funcy.re_find(r'{}-(.+).tar.gz'.format(package_name), filename)
if version:
versions.add(version)
return len(versions) > 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 period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time):
""" Calculate the neighborhood probability over the full per... |
neighbor_x = self.x[::stride, ::stride]
neighbor_y = self.y[::stride, ::stride]
neighbor_kd_tree = cKDTree(np.vstack((neighbor_x.ravel(), neighbor_y.ravel())).T)
neighbor_prob = np.zeros((self.data.shape[0], neighbor_x.shape[0], neighbor_x.shape[1]))
print('Forecast Hours: {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 load_map_info(self, map_file):
""" Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection. Args: map_file: F... |
if self.ensemble_name.upper() == "SSEF":
proj_dict, grid_dict = read_arps_map_file(map_file)
self.dx = int(grid_dict["dx"])
mapping_data = make_proj_grids(proj_dict, grid_dict)
for m, v in mapping_data.items():
setattr(self, m, v)
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 read_geojson(filename):
""" Reads a geojson file containing an STObject and initializes a new STObject from the information in the file. Args: filename: Name... |
json_file = open(filename)
data = json.load(json_file)
json_file.close()
times = data["properties"]["times"]
main_data = dict(timesteps=[], masks=[], x=[], y=[], i=[], j=[])
attribute_data = dict()
for feature in data["features"]:
for main_name in main_data.keys():
main_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_of_mass(self, time):
""" Calculate the center of mass at a given timestep. Args: time: Time at which the center of mass calculation is performed Retur... |
if self.start_time <= time <= self.end_time:
diff = time - self.start_time
valid = np.flatnonzero(self.masks[diff] != 0)
if valid.size > 0:
com_x = 1.0 / self.timesteps[diff].ravel()[valid].sum() * np.sum(self.timesteps[diff].ravel()[valid] *
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trajectory(self):
""" Calculates the center of mass for each time step and outputs an array Returns: """ |
traj = np.zeros((2, self.times.size))
for t, time in enumerate(self.times):
traj[:, t] = self.center_of_mass(time)
return traj |
<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_corner(self, time):
""" Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for t... |
if self.start_time <= time <= self.end_time:
diff = time - self.start_time
return self.i[diff][0, 0], self.j[diff][0, 0]
else:
return -1, -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 size(self, time):
""" Gets the size of the object at a given time. Args: time: Time value being queried. Returns: size of the object in pixels """ |
if self.start_time <= time <= self.end_time:
return self.masks[time - self.start_time].sum()
else:
return 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 max_intensity(self, time):
""" Calculate the maximum intensity found at a timestep. """ |
ti = np.where(time == self.times)[0][0]
return self.timesteps[ti].max() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def boundary_polygon(self, time):
""" Get coordinates of object boundary in counter-clockwise order """ |
ti = np.where(time == self.times)[0][0]
com_x, com_y = self.center_of_mass(time)
# If at least one point along perimeter of the mask rectangle is unmasked, find_boundaries() works.
# But if all perimeter points are masked, find_boundaries() does not find the object.
# Therefore,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate_motion(self, time, intensity_grid, max_u, max_v):
""" Estimate the motion of the object with cross-correlation on the intensity values from the prev... |
ti = np.where(time == self.times)[0][0]
mask_vals = np.where(self.masks[ti].ravel() == 1)
i_vals = self.i[ti].ravel()[mask_vals]
j_vals = self.j[ti].ravel()[mask_vals]
obj_vals = self.timesteps[ti].ravel()[mask_vals]
u_shifts = np.arange(-max_u, max_u + 1)
v_shif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_overlap(self, time, other_object, other_time):
""" Counts the number of points that overlap between this STObject and another STObject. Used for tracki... |
ti = np.where(time == self.times)[0][0]
ma = np.where(self.masks[ti].ravel() == 1)
oti = np.where(other_time == other_object.times)[0]
obj_coords = np.zeros(self.masks[ti].sum(), dtype=[('x', int), ('y', int)])
other_obj_coords = np.zeros(other_object.masks[oti].sum(), dtype=[('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_attribute_array(self, data_array, var_name):
""" Extracts data from a 2D array that has the same dimensions as the grid used to identify the object. ... |
if var_name not in self.attributes.keys():
self.attributes[var_name] = []
for t in range(self.times.size):
self.attributes[var_name].append(data_array[self.i[t], self.j[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 extract_tendency_grid(self, model_grid):
""" Extracts the difference in model outputs Args: model_grid: ModelOutput or ModelGrid object. """ |
var_name = model_grid.variable + "-tendency"
self.attributes[var_name] = []
timesteps = np.arange(self.start_time, self.end_time + 1)
for ti, t in enumerate(timesteps):
t_index = t - model_grid.start_hour
self.attributes[var_name].append(
model_gr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_timestep_statistic(self, statistic, time):
""" Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calcula... |
ti = np.where(self.times == time)[0][0]
ma = np.where(self.masks[ti].ravel() == 1)
if statistic in ['mean', 'max', 'min', 'std', 'ptp']:
stat_val = getattr(self.timesteps[ti].ravel()[ma], statistic)()
elif statistic == 'median':
stat_val = np.median(self.timestep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_shape_step(self, stat_names, time):
""" Calculate shape statistics for a single time step Args: stat_names: List of shape statistics calculated from reg... |
ti = np.where(self.times == time)[0][0]
props = regionprops(self.masks[ti], self.timesteps[ti])[0]
shape_stats = []
for stat_name in stat_names:
if "moments_hu" in stat_name:
hu_index = int(stat_name.split("_")[-1])
hu_name = "_".join(stat_nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_geojson(self, filename, proj, metadata=None):
""" Output the data in the STObject to a geoJSON file. Args: filename: Name of the file proj: PyProj object ... |
if metadata is None:
metadata = {}
json_obj = {"type": "FeatureCollection", "features": [], "properties": {}}
json_obj['properties']['times'] = self.times.tolist()
json_obj['properties']['dx'] = self.dx
json_obj['properties']['step'] = self.step
json_obj['pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def model(self, v=None):
"Returns the model of node v"
if v is None:
v = self.estopping
hist = self.hist
trace = self.trace(v)
ins = None
if self._base._probability_calibration is not None:
node = hist[-1]
node.normalize()
X... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def trace(self, n):
"Restore the position in the history of individual v's nodes"
trace_map = {}
self._trace(n, trace_map)
s = list(trace_map.keys())
s.sort()
return 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 tournament(self, negative=False):
"""Tournament selection and when negative is True it performs negative tournament selection""" |
if self.generation <= self._random_generations and not negative:
return self.random_selection()
if not self._negative_selection and negative:
return self.random_selection(negative=negative)
vars = self.random()
fit = [(k, self.population[x].fitness) for k, x in e... |
<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_population(self):
"Create the initial population"
base = self._base
if base._share_inputs:
used_inputs_var = SelectNumbers([x for x in range(base.nvar)])
used_inputs_naive = used_inputs_var
if base._pr_variable == 0:
used_inputs_var = Select... |
<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(self, v):
"Add an individual to the population"
self.population.append(v)
self._current_popsize += 1
v.position = len(self._hist)
self._hist.append(v)
self.bsf = v
self.estopping = v
self._density += self.get_density(v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, v):
"""Replace an individual selected by negative tournament selection with individual v""" |
if self.popsize < self._popsize:
return self.add(v)
k = self.tournament(negative=True)
self.clean(self.population[k])
self.population[k] = v
v.position = len(self._hist)
self._hist.append(v)
self.bsf = v
self.estopping = v
self._inds_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 make_directory_if_needed(directory_path):
""" Make the directory path, if needed. """ |
if os.path.exists(directory_path):
if not os.path.isdir(directory_path):
raise OSError("Path is not a directory:", directory_path)
else:
os.makedirs(directory_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 hatchery():
""" Main entry point for the hatchery program """ |
args = docopt.docopt(__doc__)
task_list = args['<task>']
if not task_list or 'help' in task_list or args['--help']:
print(__doc__.format(version=_version.__version__, config_files=config.CONFIG_LOCATIONS))
return 0
level_str = args['--log-level']
try:
level_const = getattr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(cmd_args, suppress_output=False):
""" Call an arbitary command and return the exit value, stdout, and stderr as a tuple Command can be passed in as eith... |
if not funcy.is_list(cmd_args) and not funcy.is_tuple(cmd_args):
cmd_args = shlex.split(cmd_args)
logger.info('executing `{}`'.format(' '.join(cmd_args)))
call_request = CallRequest(cmd_args, suppress_output=suppress_output)
call_result = call_request.run()
if call_result.exitval:
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(cmd_args, suppress_output=False):
""" Call a setup.py command or list of commands 0 1 """ |
if not funcy.is_list(cmd_args) and not funcy.is_tuple(cmd_args):
cmd_args = shlex.split(cmd_args)
cmd_args = [sys.executable, 'setup.py'] + [x for x in cmd_args]
return call(cmd_args, suppress_output=suppress_output) |
<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_data(self):
""" Loads data files and stores the output in the data attribute. """ |
data = []
valid_dates = []
mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/")))
mrms_file_dates = np.array([m_file.split("_")[-2].split("-")[0]
for m_file in mrms_files])
old_mrms_file = None
file_obj = None
for t in range(self.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rescale_data(data, data_min, data_max, out_min=0.0, out_max=100.0):
""" Rescale your input data so that is ranges over integer values, which will perform bet... |
return (out_max - out_min) / (data_max - data_min) * (data - data_min) + out_min |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def label(self, input_grid):
""" Labels input grid using enhanced watershed algorithm. Args: input_grid (numpy.ndarray):
Grid to be labeled. Returns: Array of l... |
marked = self.find_local_maxima(input_grid)
marked = np.where(marked >= 0, 1, 0)
# splabel returns two things in a tuple: an array and an integer
# assign the first thing (array) to markers
markers = splabel(marked)[0]
return markers |
<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_local_maxima(self, input_grid):
""" Finds the local maxima in the inputGrid and perform region growing to identify objects. Args: input_grid: Raw input ... |
pixels, q_data = self.quantize(input_grid)
centers = OrderedDict()
for p in pixels.keys():
centers[p] = []
marked = np.ones(q_data.shape, dtype=int) * self.UNMARKED
MIN_INFL = int(np.round(1 + 0.5 * np.sqrt(self.max_size)))
MAX_INFL = 2 * MIN_INFL
mar... |
<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_maximum(self, q_data, marked, center, bin_lower, foothills):
""" Grow a region at a certain bin level and check if the region has reached the maximum siz... |
as_bin = [] # pixels to be included in peak
as_glob = [] # pixels to be globbed up as part of foothills
marked_so_far = [] # pixels that have already been marked
will_be_considered_again = False
as_bin.append(center)
center_data = q_data[center]
while len(as_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 remove_foothills(self, q_data, marked, bin_num, bin_lower, centers, foothills):
""" Mark points determined to be foothills as globbed, so that they are not i... |
hills = []
for foot in foothills:
center = foot[0]
hills[:] = foot[1][:]
# remove all foothills
while len(hills) > 0:
# mark this point
pt = hills.pop(-1)
marked[pt] = self.GLOBBED
for s_inde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quantize(self, input_grid):
""" Quantize a grid into discrete steps based on input parameters. Args: input_grid: 2-d array of values Returns: Dictionary of v... |
pixels = {}
for i in range(self.max_bin+1):
pixels[i] = []
data = (np.array(input_grid, dtype=int) - self.min_thresh) / self.data_increment
data[data < 0] = -1
data[data > self.max_bin] = self.max_bin
good_points = np.where(data >= 0)
for g in np.ara... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def content(self, **args):
'''
Doesn't require manual fetching of gistID of a gist
passing gistName will return the content of gist. In case,
names are ambigious, provide GistID or it will return the contents
of recent ambigious gistname
'''
self.gist_name = ''
if 'name' in args:
self.gist_name = arg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def edit(self, **args):
'''
Doesn't require manual fetching of gistID of a gist
passing gistName will return edit the gist
'''
self.gist_name = ''
if 'description' in args:
self.description = args['description']
else:
self.description = ''
if 'name' in args and 'id' in args:
self.gist_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 starred(self, **args):
'''
List the authenticated user's starred gists
'''
ids =[]
r = requests.get(
'%s/gists/starred'%BASE_URL,
headers=self.gist.header
)
if 'limit' in args:
limit = args['limit']
else:
limit = len(r.json())
if (r.status_code == 200):
for g in range(0,limit ):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.