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 calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args...
morning_dawn = None sunrise = None evening_dawn = None sunset = None latitude, longitude = locator_to_latlong(locator) if type(calc_date) != datetime: raise ValueError sun = ephem.Sun() home = ephem.Observer() home.lat = str(latitude) home.long = str(longitude) h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloudpickle_dumps(obj, dumper=cloudpickle.dumps): """ Encode Python objects into a byte stream using cloudpickle. """
return dumper(obj, protocol=serialization.pickle_protocol)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_celery(): """ Monkey patch Celery to use cloudpickle instead of pickle. """
registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x-python-serialize', content_encoding='binary') import celery.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 connect(self): """ Connects to the redis database. """
self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(self): """ Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Return...
pickled_request = self._connection.connection.lpop(self._request_key) return pickle.loads(pickled_request) if pickled_request is not None else 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 send(self, response): """ Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should ...
self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, request): """ Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the...
self._connection.connection.rpush(self._request_key, pickle.dumps(request))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the ...
self._connection.connection.rpush(self._request_key, pickle.dumps(request)) resp_key = '{}:{}'.format(SIGNAL_REDIS_PREFIX, request.uid) while True: if self._connection.polling_time > 0.0: sleep(self._connection.polling_time) response_data = self._connec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_pattern(pattern): """Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True i...
regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pattern__): if not __pattern__: return False elif __pattern__[0] == "!": return __verify_pattern__(__pattern__[1:]) elif __pattern__[0] == "[" and __pattern__[-1] == "]": return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_tree(sentence, pattern): """Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sen...
if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p): pat_node = p.pop(0) if p else "" return not pat_node or (_match_token(t, pat_node, False) and _match_edge(t.children,p)) def _match_edge(edges,p): pat_edge = p.pop(0) if p else ""...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `de...
ret = [] special1 = ['(', ')', '[', ']', '{', '}'] special2 = ['\'', '"'] special3 = '\\' flags1 = [0, 0, 0] flags2 = [False, False] flags3 = False start = 0 nlim = 0 for i, c in enumerate(s): if c == special3: # next char is escaped flags3 = not flags3 elif not flags3: # no ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. ...
# Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(self.code), None, localns) return localns[Liquid.COMPLIED_RENDERED_STR] except Exception: stacks = list(reversed(traceback.format_exc().splitlines())) for stack in stacks: stack = stack.st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The...
if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
<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_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """
from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %s' % (currency, )) return rate.rate
<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_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """
reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency reverse_rate = True else: rate_currency = to_currency rate = get_rate_from_db(rate_currency) if reverse_rate: ...
<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_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating h...
if months is None: months = [np.arange(12) + 1] self.precip.months = months self.precip.stats = melodist.build_casc(self.data, months=months, avg_stats=avg_stats, percentile=percentile)
<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_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """
a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_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 calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """
a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hour_precip_mean = melodist.calculate_month_hour_precip_mean(self.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 calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """
self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=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 to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters filename: output file that holds statistics data """
def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series): if isinstance(obj.index, pd.core.index.MultiIndex): obj = obj.reset_index() # convert MultiIndex to columns return json.loads(obj.to_json(date_format='iso')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters filename: input file that holds statistics data """
def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatistics object return melodist.cascade.CascadeStatistics.from_dict(d) return d with open(filename) as f: d = json.load(f, object_hook=json_decoder) stats = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canonical(self): """Return a tuple containing a canonicalized version of this location's country, state, county, and city names."""
try: return tuple(map(lambda x: x.lower(), self.name())) except: return tuple([x.lower() for x in 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 name(self): """Return a tuple containing this location's country, state, county, and city names."""
try: return tuple( getattr(self, x) if getattr(self, x) else u'' for x in ('country', 'state', 'county', 'city')) except: return tuple( getattr(self, x) if getattr(self, x) else '' for x in ('country', 'state', 'cou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self): """Return a location representing the administrative unit above the one represented by this location."""
if self.city: return Location( country=self.country, state=self.state, county=self.county) if self.county: return Location(country=self.country, state=self.state) if self.state: return Location(country=self.country) return Location()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None, preserve_daily_mean=False): """general f...
assert method in ('equal', 'minimal', 'dewpoint_regression', 'min_max', 'linear_dewpoint_variation', 'month_hour_precip_mean'), 'Invalid option' if method == 'equal': hum_disagg = melodist.dis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cosine_function(x, a, b, t_shift): """genrates a diurnal course of windspeed accroding to the cosine function Args: x: series of euqally distributed windspe...
mean_wind, t = x return a * mean_wind * np.cos(np.pi * (t - t_shift) / 12) + b * mean_wind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None): """general function for windspeed disaggregation Args: wind_daily: daily values ...
assert method in ('equal', 'cosine', 'random'), 'Invalid method' wind_eq = melodist.distribute_equally(wind_daily) if method == 'equal': wind_disagg = wind_eq elif method == 'cosine': assert None not in (a, b, t_shift) wind_disagg = _cosine_function(np.array([wind_eq.values, 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 fit_cosine_function(wind): """fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed ...
wind_daily = wind.groupby(wind.index.date).mean() wind_daily_hourly = pd.Series(index=wind.index, data=wind_daily.loc[wind.index.date].values) # daily values evenly distributed over the hours df = pd.DataFrame(data=dict(daily=wind_daily_hourly, hourly=wind)).dropna(how='any') x = np.array([df.daily, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """writes smet files Parameters ---- filename : filename/loction of output...
# dictionary # based on smet spec V.1.1 and selfdefined # daily data dict_d= {'tmean':'TA', 'tmin':'TMAX', #no spec 'tmax':'TMIN', #no spec 'precip':'PSUM', 'glob':'ISWR', #no spec 'hum':'RH', 'wind':'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 read_single_knmi_file(filename): """reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgege...
hourly_data_obs_raw = pd.read_csv( filename, parse_dates=[['YYYYMMDD', 'HH']], date_parser=lambda yyyymmdd, hh: pd.datetime(int(str(yyyymmdd)[0:4]), int(str(yyyymmdd)[4:6]), int(str(yyy...
<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_knmi_dataset(directory): """Reads files from a directory and merges the time series Please note: For each station, a separate directory must be provided...
filemask = '%s*.txt' % directory filelist = glob.glob(filemask) columns_hourly = ['temp', 'precip', 'glob', 'hum', 'wind', 'ssd'] ts = pd.DataFrame(columns=columns_hourly) first_call = True for file_i in filelist: print(file_i) current = read_single_knmi_file(file_i) 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 disaggregate_wind(self, method='equal'): """ Disaggregate wind speed. Parameters method : str, optional Disaggregation method. ``equal`` Mean daily wind spee...
self.data_disagg.wind = melodist.disaggregate_wind(self.data_daily.wind, method=method, **self.statistics.wind)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disaggregate_humidity(self, method='equal', preserve_daily_mean=False): """ Disaggregate relative humidity. Parameters method : str, optional Disaggregation ...
self.data_disagg.hum = melodist.disaggregate_humidity( self.data_daily, temp=self.data_disagg.temp, method=method, preserve_daily_mean=preserve_daily_mean, **self.statistics.hum )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disaggregate_temperature(self, method='sine_min_max', min_max_time='fix', mod_nighttime=False): """ Disaggregate air temperature. Parameters method : str, op...
self.data_disagg.temp = melodist.disaggregate_temperature( self.data_daily, method=method, min_max_time=min_max_time, max_delta=self.statistics.temp.max_delta, mean_course=self.statistics.temp.mean_course, sun_times=self.sun_times, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disaggregate_precipitation(self, method='equal', zerodiv='uniform', shift=0, master_precip=None): """ Disaggregate precipitation. Parameters method : str, op...
if method == 'equal': precip_disagg = melodist.disagg_prec(self.data_daily, method=method, shift=shift) elif method == 'cascade': precip_disagg = pd.Series(index=self.data_disagg.index) for months, stats in zip(self.statistics.precip.months, self.statistics.precip.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 disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters method : str, optional Disaggregation method. ``po...
if self.sun_times is None: self.calc_sun_times() if pot_rad is None and method != 'mean_course': pot_rad = melodist.potential_radiation(self.data_disagg.index, self.lon, self.lat, self.timezone) self.data_disagg.glob = melodist.disaggregate_radiation( 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 interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs): """ Wrapper function for ``pandas.Series.interpolate`` that can...
kwargs = dict(kwargs, method=method, limit=limit, limit_direction=limit_direction) data = melodist.util.prepare_interpolation_data(self.data_daily, column_hours) return data.interpolate(**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 _query_helper(self, by=None): """ Internal helper for preparing queries. """
if by is None: primary_keys = self.table.primary_key.columns.keys() if len(primary_keys) > 1: warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. " "USING THE FIRST KEY %s." % (self.table.name, primar...
<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, sql_query, return_as="dataframe"): """ Execute a raw SQL query against the the SQL DB. Args: sql_query (str): A raw SQL query to execute. Kwargs...
if isinstance(sql_query, str): pass elif isinstance(sql_query, unicode): sql_query = str(sql_query) else: raise QueryDbError("query() requires a str or unicode input.") query = sqlalchemy.sql.text(sql_query) if return_as.upper() in ["DF", "D...
<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): """ Internal helper to set metadata attributes. """
meta = QueryDbMeta() with self._engine.connect() as conn: meta.bind = conn meta.reflect() self._meta = meta # Set an inspect attribute, whose subattributes # return individual tables / columns. Tables and columns # are special classes with .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 _to_df(self, query, conn, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None): """ Internal convert-to-DataFrame convenience wrap...
return pd.io.sql.read_sql(str(query), conn, index_col=index_col, coerce_float=coerce_float, params=params, parse_dates=parse_dates, columns=columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distribute_equally(daily_data, divide=False): """Obtains hourly values by equally distributing the daily values. Args: daily_data: daily values divide: if Tr...
index = hourly_index(daily_data.index) hourly_data = daily_data.reindex(index) hourly_data = hourly_data.groupby(hourly_data.index.day).transform( lambda x: x.fillna(method='ffill', limit=23)) if divide: hourly_data /= 24 return hourly_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 dewpoint_temperature(temp, hum): """computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint tempera...
assert(temp.shape == hum.shape) vap_press = vapor_pressure(temp, hum) positives = np.array(temp >= 273.15) dewpoint_temp = temp.copy() * np.nan dewpoint_temp[positives] = 243.12 * np.log(vap_press[positives] / 6.112) / (17.62 - np.log(vap_press[positives] / 6.112)) dewpoint_temp[~positives] =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linregress(x, y, return_stats=False): """linear regression calculation Parameters ---- x : independent variable (series) y : dependent variable (series) retu...
a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y) retval = a1, a0 if return_stats: retval += r_value, p_value, stderr return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_gaps(dataframe, timestep, print_all=False, print_max=5, verbose=True): """checks if a given dataframe contains gaps and returns the number of gaps Thi...
gcount = 0 msg_counter = 0 warning_printed = False try: n = len(dataframe.index) except: print('Error: Invalid dataframe.') return -1 for i in range(0, n): if(i > 0): time_diff = dataframe.index[i] - dataframe.index[i-1] if(time_diff.delta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_incomplete_days(dataframe, shift=0): """truncates a given dataframe to full days only This funtion truncates a given pandas dataframe (time series) to f...
dropped = 0 if shift > 23 or shift < 0: print("Invalid shift parameter setting! Using defaults.") shift = 0 first = shift last = first - 1 if last < 0: last += 24 try: # todo: move this checks to a separate function n = len(dataframe.index) except: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disagg_prec(dailyData, method='equal', cascade_options=None, hourly_data_obs=None, zerodiv="uniform", shift=0): """The disaggregation function for precipitat...
if method not in ('equal', 'cascade', 'masterstation'): raise ValueError('Invalid option') if method == 'equal': precip_disagg = melodist.distribute_equally(dailyData.precip, divide=True) elif method == 'masterstation': precip_di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precip_master_station(precip_daily, master_precip_hourly, zerodiv): """Disaggregate precipitation based on the patterns of a master station Parameters precip...
precip_hourly = pd.Series(index=melodist.util.hourly_index(precip_daily.index)) # set some parameters for cosine function for index_d, precip in precip_daily.iteritems(): # get hourly data of the day index = index_d.date().isoformat() precip_h = master_precip_hourly[index] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def seasonal_subset(dataframe, months='all'): '''Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all') ''' if isinstance(months, str) and months == 'all': mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build_casc(ObsData, hourly=True,level=9, months=None, avg_stats=True, percentile=50): '''Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 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 fill_with_sample_data(self): """This function fills the corresponding object with sample data."""
# replace these sample data with another dataset later # this function is deprecated as soon as a common file format for this # type of data will be available self.p01 = np.array([[0.576724636119866, 0.238722774405744, 0.166532122130638, 0.393474644666218], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def names(cls): """A list of all emoji names without file extension."""
if not cls._files: for f in os.listdir(cls._image_path): if(not f.startswith('.') and os.path.isfile(os.path.join(cls._image_path, f))): cls._files.append(os.path.splitext(f)[0]) return cls._files
<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_unicode(cls, replacement_string): """This method will iterate over every character in ``replacement_string`` and see if it mathces any of the unicode...
e = cls() output = [] surrogate_character = None if settings.EMOJI_REPLACE_HTML_ENTITIES: replacement_string = cls.replace_html_entities(replacement_string) for i, character in enumerate(replacement_string): if character in cls._unicode_modifiers: ...
<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_to_unicode(string): """This method should work with both Python 2 and 3 with the caveat that they need to be compiled with wide unicode character su...
codepoints = [] for character in string.split('-'): if character in BLACKLIST_UNICODE: next codepoints.append( '\U{0:0>8}'.format(character).decode('unicode-escape') ) return codepoints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _delete_file(configurator, path): """ remove file and remove it's directories if empty """
path = os.path.join(configurator.target_directory, path) os.remove(path) try: os.removedirs(os.path.dirname(path)) except OSError: pass
<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_requirements(filename): """Parses a file for pip installation requirements."""
with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_perm(perm, group): """ Assigns a permission to a group """
if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argument must be in" " format: 'app_label.codename' (is %r)" % perm) perm = Permission.o...
<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_perm(perm, group): """ Removes a permission from a group """
if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argument must be in" " format: 'app_label.codename' (is %r)" % perm) perm = Permission.o...
<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_list_class(context, list): """ Returns the class to use for the passed in list. We just build something up from the object type for the list. """
return "list_%s_%s" % (list.model._meta.app_label, list.model._meta.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 format_datetime(time): """ Formats a date, converting the time to the user timezone if one is specified """
user_time_zone = timezone.get_current_timezone() if time.tzinfo is None: time = time.replace(tzinfo=pytz.utc) user_time_zone = pytz.timezone(getattr(settings, 'USER_TIME_ZONE', 'GMT')) time = time.astimezone(user_time_zone) return time.strftime("%b %d, %Y %H:%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 get_value_from_view(context, field): """ Responsible for deriving the displayed value for the passed in 'field'. This first checks for a particular method on...
view = context['view'] obj = None if 'object' in context: obj = context['object'] value = view.lookup_field_value(context, obj, field) # it's a date if type(value) == datetime: return format_datetime(value) return 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 get_class(context, field, obj=None): """ Looks up the class for this field """
view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
<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_label(context, field, obj=None): """ Responsible for figuring out the right label for the passed in field. The order of precedence is: 1) if the view has...
view = context['view'] return view.lookup_field_label(context, field, 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 get_field_link(context, field, obj=None): """ Determine what the field link should be for the given field, object pair """
view = context['view'] return view.lookup_field_link(context, field, 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 get_permissions_app_name(): """ Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the Django set...
global permissions_app_name if not permissions_app_name: permissions_app_name = getattr(settings, 'PERMISSIONS_APP', None) if not permissions_app_name: app_names_with_models = [a.name for a in apps.get_app_configs() if a.models_module is not None] if app_names_with_mod...
<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_all_group_permissions(sender, **kwargs): """ Checks that all the permissions specified in our settings.py are set for our groups. """
if not is_permissions_app(sender): return config = getattr(settings, 'GROUP_PERMISSIONS', dict()) # for each of our items for name, permissions in config.items(): # get or create the group (group, created) = Group.objects.get_or_create(name=name) if created: ...
<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_permission(content_type, permission): """ Adds the passed in permission to that content type. Note that the permission passed in should be a single word,...
# build our permission slug codename = "%s_%s" % (content_type.model, permission) # sys.stderr.write("Checking %s permission for %s\n" % (permission, content_type.name)) # does it already exist if not Permission.objects.filter(content_type=content_type, codename=codename): Permission.obje...
<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_all_permissions(sender, **kwargs): """ This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit. ""...
if not is_permissions_app(sender): return config = getattr(settings, 'PERMISSIONS', dict()) # for each of our items for natural_key, permissions in config.items(): # if the natural key '*' then that means add to all objects if natural_key == '*': # for each of our ...
<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(self, commit=True): """ Overloaded so we can save any new password that is included. """
is_new_user = self.instance.pk is None user = super(UserForm, self).save(commit) # new users should be made active by default if is_new_user: user.is_active = True # if we had a new password set, use it new_pass = self.cleaned_data['new_password'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_single_object_url_pattern(slug_url_kwarg, path, action): """ Utility function called by class methods for single object views """
if slug_url_kwarg: return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg) else: return r'^%s/%s/(?P<pk>\d+)/$' % (path, action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, request, *args, **kwargs): """ Overloaded to check permissions if appropriate """
def wrapper(request, *args, **kwargs): if not self.has_permission(request, *args, **kwargs): path = urlquote(request.get_full_path()) login_url = kwargs.pop('login_url', settings.LOGIN_URL) redirect_field_name = kwargs.pop('redirect_field_name', REDIR...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_obj_attribute(self, obj, field): """ Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal with subel...
curr_field = field.encode('ascii', 'ignore').decode("utf-8") rest = None if field.find('.') >= 0: curr_field = field.split('.')[0] rest = '.'.join(field.split('.')[1:]) # next up is the object itself obj_field = getattr(obj, curr_field, 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 lookup_field_value(self, context, obj, field): """ Looks up the field value for the passed in object and field name. Note that this method is actually called...
curr_field = field.encode('ascii', 'ignore').decode("utf-8") # if this isn't a subfield, check the view to see if it has a get_ method if field.find('.') == -1: # view supercedes all, does it have a 'get_' method for this obj view_method = getattr(self, 'get_%s' % curr_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_field_class(self, field, obj=None, default=None): """ Looks up any additional class we should include when rendering this field """
css = "" # is there a class specified for this field if field in self.field_config and 'class' in self.field_config[field]: css = self.field_config[field]['class'] # if we were given a default, use that elif default: css = default return css
<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_template_names(self): """ Returns the name of the template to use to render this request. Smartmin provides default templates as fallbacks, so appends it...
templates = [] if getattr(self, 'template_name', None): templates.append(self.template_name) if getattr(self, 'default_template', None): templates.append(self.default_template) else: templates = super(SmartView, self).get_template_names() re...
<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_context_data(self, **kwargs): """ We supplement the normal context data by adding our fields and labels. """
context = super(SmartView, self).get_context_data(**kwargs) # derive our field config self.field_config = self.derive_field_config() # add our fields self.fields = self.derive_fields() # build up our current parameter string, EXCLUSIVE of our page. These # ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_fields(self): """ Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object. """
if self.fields: return list(self.fields) else: fields = [] for field in self.object._meta.fields: fields.append(field.name) # only exclude? then remove those items there exclude = self.derive_exclude() # 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_context_data(self, **kwargs): """ Add in the field to use for the name field """
context = super(SmartDeleteView, self).get_context_data(**kwargs) context['name_field'] = self.name_field context['cancel_url'] = self.get_cancel_url() return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_title(self): """ Derives our title from our list """
title = super(SmartListView, self).derive_title() if not title: return force_text(self.model._meta.verbose_name_plural).title() else: return title
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_field_orderable(self, field): """ Returns whether the passed in field is sortable or not, by default all 'raw' fields, that is fields that are part of...
try: self.model._meta.get_field_by_name(field) return True except Exception: # that field doesn't exist, so not sortable return False
<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_context_data(self, **kwargs): """ Add in what fields are linkable """
context = super(SmartListView, self).get_context_data(**kwargs) # our linkable fields self.link_fields = self.derive_link_fields(context) # stuff it all in our context context['link_fields'] = self.link_fields # our search term if any if 'search' in self.reque...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_queryset(self, **kwargs): """ Derives our queryset. """
# get our parent queryset queryset = super(SmartListView, self).get_queryset(**kwargs) # apply any filtering search_fields = self.derive_search_fields() search_query = self.request.GET.get('search') if search_fields and search_query: term_queries = [] ...
<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_queryset(self, **kwargs): """ Gets our queryset. This takes care of filtering if there are any fields to filter by. """
queryset = self.derive_queryset(**kwargs) return self.order_queryset(queryset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. """
order = self.derive_ordering() # if we get our order from the request # make sure it is a valid field in the list if '_order' in self.request.GET: if order.lstrip('-') not in self.derive_fields(): order = None if order: # if our order 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 customize_form_field(self, name, field): """ Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it'...
if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.widgets.DateInput): field.widget = widgets.DatePickerWidget() field.input_formats = [field.widget.input_format[1]] + list(field.input_formats) if isinstance(field, forms.fields.ImageField) and isins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_readonly(self): """ Figures out what fields should be readonly. We iterate our field_config to find all that have a readonly of true """
readonly = list(self.readonly) for key, value in self.field_config.items(): if 'readonly' in value and value['readonly']: readonly.append(key) return readonly
<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_form_class(self): """ Returns the form class to use in this view """
if self.form_class: form_class = self.form_class else: if self.model is not None: # If a model has been explicitly provided, use it model = self.model elif hasattr(self, 'object') and self.object is not None: # If this...
<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_factory_kwargs(self): """ Let's us specify any extra parameters we might want to call for our form factory. These can include: 'form', 'fields', 'exclude...
params = dict() exclude = self.derive_exclude() exclude += self.derive_readonly() if self.fields: fields = list(self.fields) for ex in exclude: if ex in fields: fields.remove(ex) params['fields'] = 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_success_url(self): """ By default we use the referer that was stuffed in our form when it was created """
if self.success_url: # if our smart url references an object, pass that in if self.success_url.find('@') > 0: return smart_url(self.success_url, self.object) else: return smart_url(self.success_url, None) elif 'loc' in self.form.clean...
<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_form_kwargs(self): """ We override this, using only those fields specified if they are specified. Otherwise we include all fields in a standard ModelForm...
kwargs = super(SmartFormMixin, self).get_form_kwargs() kwargs['initial'] = self.derive_initial() return 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 derive_title(self): """ Derives our title from our object """
if not self.title: return _("Create %s") % force_text(self.model._meta.verbose_name).title() else: return self.title
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_for_action(self, action): """ Returns the permission to use for the passed in action """
return "%s.%s_%s" % (self.app_name.lower(), self.model_name.lower(), action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_for_action(self, action): """ Returns the template to use for the passed in action """
return "%s/%s_%s.html" % (self.module_name.lower(), self.model_name.lower(), action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_name_for_action(self, action): """ Returns the reverse name for this action """
return "%s.%s_%s" % (self.module_name.lower(), self.model_name.lower(), action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern_for_view(self, view, action): """ Returns the URL pattern for the passed in action. """
# if this view knows how to define a URL pattern, call that if getattr(view, 'derive_url_pattern', None): return view.derive_url_pattern(self.path, action) # otherwise take our best guess else: return r'^%s/%s/$' % (self.path, action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_urlpatterns(self): """ Creates the appropriate URLs for this object. """
urls = [] # for each of our actions for action in self.actions: view_class = self.view_for_action(action) view_pattern = self.pattern_for_view(view_class, action) name = self.url_name_for_action(action) urls.append(url(view_pattern, view_class.as...
<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_migrations(self): # pragma: no cover """ Loads all migrations in the order they would be applied to a clean database """
executor = MigrationExecutor(connection=None) # create the forwards plan Django would follow on an empty database plan = executor.migration_plan(executor.loader.graph.leaf_nodes(), clean_start=True) if self.verbosity >= 2: for migration, _ in plan: self.std...
<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_operations(self, migrations): """ Extract SQL operations from the given migrations """
operations = [] for migration in migrations: for operation in migration.operations: if isinstance(operation, RunSQL): statements = sqlparse.parse(dedent(operation.sql)) for statement in statements: operation =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_type_dumps(self, operations, preserve_order, output_dir): """ Splits the list of SQL operations by type and dumps these to separate files """
by_type = {SqlType.INDEX: [], SqlType.FUNCTION: [], SqlType.TRIGGER: []} for operation in operations: by_type[operation.sql_type].append(operation) # optionally sort each operation list by the object name if not preserve_order: for obj_type, ops in by_type.items...