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 from_model(cls, model_name, **kwargs):
""" Define a grid using the specifications of a given model. Parameters model_name : string Name the model (see :func:... |
settings = _get_model_info(model_name)
model = settings.pop('model_name')
for k, v in list(kwargs.items()):
if k in ('resolution', 'Psurf'):
settings[k] = v
return cls(model, **settings) |
<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_from_model(cls, model_name, reference, **kwargs):
""" Set-up a user-defined grid using specifications of a reference grid model. Parameters model_name :... |
if isinstance(reference, cls):
settings = reference.__dict__.copy()
settings.pop('model')
else:
settings = _get_model_info(reference)
settings.pop('model_name')
settings.update(kwargs)
settings['reference'] = reference
return cls... |
<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_layers(self, Psurf=1013.25, Ptop=0.01, **kwargs):
""" Compute scalars or coordinates associated to the vertical layers. Parameters grid_spec : CTMGrid ob... |
Psurf = np.asarray(Psurf)
output_ndims = Psurf.ndim + 1
if output_ndims > 3:
raise ValueError("`Psurf` argument must be a float or an array"
" with <= 2 dimensions (or None)")
# Compute all variables: takes not much memory, fast
# and 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 _get_template_dirs():
"""existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir... |
return filter(lambda x: os.path.exists(x), [
# user dir
os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'),
# system wide dir
os.path.join('/', 'usr', 'share', 'py2pack', 'templates'),
# usually inside the site-packages dir
os.path.join(os.path.dirname(os... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _license_from_classifiers(data):
"""try to get a license from the classifiers""" |
classifiers = data.get('classifiers', [])
found_license = None
for c in classifiers:
if c.startswith("License :: OSI Approved :: "):
found_license = c.replace("License :: OSI Approved :: ", "")
return found_license |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalize_license(data):
"""try to get SDPX license""" |
license = data.get('license', None)
if not license:
# try to get license from classifiers
license = _license_from_classifiers(data)
if license:
if license in SDPX_LICENSES.keys():
data['license'] = SDPX_LICENSES[license]
else:
data['license'] = "%s (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 wrap_prompts_class(Klass):
""" Wrap an IPython's Prompt class This is needed in order for Prompt to inject the correct escape sequences at the right position... |
try:
from prompt_toolkit.token import ZeroWidthEscape
except ImportError:
return Klass
class ITerm2IPythonPrompt(Klass):
def in_prompt_tokens(self, cli=None):
return [
(ZeroWidthEscape, last_status(self.shell)+BEFORE_PROMPT),
... |
<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_all_keys(self, start=None):
""" A generator which yields a list of all valid keys starting at the given `start` offset. If `start` is `None`, we will sta... |
s = self.stream
if not start:
start = HEADER_SIZE + self.block_size * self.root_block
s.seek(start)
block_type = s.read(2)
if block_type == LEAF:
reader = LeafReader(self)
num_keys = struct.unpack('>i', reader.read(4))[0]
for _ 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 readline(self, fmt=None):
""" Return next unformatted "line". If format is given, unpack content, otherwise return byte string. """ |
prefix_size = self._fix()
if fmt is None:
content = self.read(prefix_size)
else:
fmt = self.endian + fmt
fmt = _replace_star(fmt, prefix_size)
content = struct.unpack(fmt, self.read(prefix_size))
try:
suffix_size = self._fix(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skipline(self):
""" Skip the next line and returns position and size of line. Raises IOError if pre- and suffix of line do not match. """ |
position = self.tell()
prefix = self._fix()
self.seek(prefix, 1) # skip content
suffix = self._fix()
if prefix != suffix:
raise IOError(_FIX_ERROR)
return position, prefix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writelines(self, lines, fmt):
""" Write `lines` with given `format`. """ |
if isinstance(fmt, basestring):
fmt = [fmt] * len(lines)
for f, line in zip(fmt, lines):
self.writeline(f, line, self.endian) |
<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_varint(stream):
"""Read while the most significant bit is set, then put the 7 least significant bits of all read bytes together to create a number. """ |
value = 0
while True:
byte = ord(stream.read(1))
if not byte & 0b10000000:
return value << 7 | byte
value = value << 7 | (byte & 0b01111111) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_bpchdataset(filename, fields=[], categories=[], tracerinfo_file='tracerinfo.dat', diaginfo_file='diaginfo.dat', endian=">", decode_cf=True, memmap=True, ... |
store = BPCHDataStore(
filename, fields=fields, categories=categories,
tracerinfo_file=tracerinfo_file,
diaginfo_file=diaginfo_file, endian=endian,
use_mmap=memmap, dask_delayed=dask
)
ds = xr.Dataset.load_store(store)
# Record what the file object underlying the store ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_mfbpchdataset(paths, concat_dim='time', compat='no_conflicts', preprocess=None, lock=None, **kwargs):
""" Open multiple bpch files as a single dataset. ... |
from xarray.backends.api import _MultiFileCloser
# TODO: Include file locks?
# Check for dask
dask = kwargs.pop('dask', False)
if not dask:
raise ValueError("Reading multiple files without dask is not supported")
kwargs['dask'] = True
# Add th
if isinstance(paths, basestrin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None):
""" Return a bytes string that displays image given by byte... |
if preserve_aspect_ratio is None:
if width != 'auto' and height != 'auto':
preserve_aspect_ratio = False
else:
preserve_aspect_ratio = True
data = {
'name': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None):
""" Display the image given by the bytes b in the t... |
sys.stdout.buffer.write(image_bytes(b, filename=filename, inline=inline,
width=width, height=height, preserve_aspect_ratio=preserve_aspect_ratio))
sys.stdout.write('\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_image_file(fn, width='auto', height='auto', preserve_aspect_ratio=None):
""" Display an image in the terminal. A newline is not printed. width and he... |
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.buffer.write(image_bytes(f.read(), filename=fn,
width=width, height=height,
preserve_aspect_ratio=preserve_aspect_ratio)) |
<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_entity_uuid_coords(self, uuid):
""" Returns the coordinates of the given entity UUID inside this world, or `None` if the UUID is not found. """ |
if uuid in self._entity_to_region_map:
coords = self._entity_to_region_map[uuid]
entities = self.get_entities(*coords)
for entity in entities:
if 'uniqueId' in entity.data and entity.data['uniqueId'] == uuid:
return tuple(entity.data['tile... |
<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_fuzzy_pattern(pattern):
""" Convert a string into a fuzzy regular expression pattern. :param pattern: The input pattern (a string). :returns: A compil... |
return re.compile(".*".join(map(re.escape, pattern)), re.IGNORECASE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fuzzy_search(self, *filters):
""" Perform a "fuzzy" search that matches the given characters in the given order. :param filters: The pattern(s) to search for... |
matches = []
logger.verbose(
"Performing fuzzy search on %s (%s) ..", pluralize(len(filters), "pattern"), concatenate(map(repr, filters))
)
patterns = list(map(create_fuzzy_pattern, filters))
for entry in self.filtered_entries:
if all(p.search(entry.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 select_entry(self, *arguments):
""" Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a ... |
matches = self.smart_search(*arguments)
if len(matches) > 1:
logger.info("More than one match, prompting for choice ..")
labels = [entry.name for entry in matches]
return matches[labels.index(prompt_for_choice(labels))]
else:
logger.info("Matched ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_search(self, *keywords):
""" Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: T... |
matches = []
keywords = [kw.lower() for kw in keywords]
logger.verbose(
"Performing simple search on %s (%s) ..",
pluralize(len(keywords), "keyword"),
concatenate(map(repr, keywords)),
)
for entry in self.filtered_entries:
normaliz... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smart_search(self, *arguments):
""" Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :retu... |
matches = self.simple_search(*arguments)
if not matches:
logger.verbose("Falling back from substring search to fuzzy search ..")
matches = self.fuzzy_search(*arguments)
if not matches:
if len(self.filtered_entries) > 0:
raise NoMatchingPasswor... |
<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_diaginfo(diaginfo_file):
""" Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters diagin... |
widths = [rec.width for rec in diag_recs]
col_names = [rec.name for rec in diag_recs]
dtypes = [rec.type for rec in diag_recs]
usecols = [name for name in col_names if not name.startswith('-')]
diag_df = pd.read_fwf(diaginfo_file, widths=widths, names=col_names,
dtypes=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 get_tracerinfo(tracerinfo_file):
""" Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ... |
widths = [rec.width for rec in tracer_recs]
col_names = [rec.name for rec in tracer_recs]
dtypes = [rec.type for rec in tracer_recs]
usecols = [name for name in col_names if not name.startswith('-')]
tracer_df = pd.read_fwf(tracerinfo_file, widths=widths, names=col_names,
... |
<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_from_bpch(filename, file_position, shape, dtype, endian, use_mmap=False):
""" Read a chunk of data from a bpch output file. Parameters filename : str Pa... |
offset = file_position + 4
if use_mmap:
d = np.memmap(filename, dtype=dtype, mode='r', shape=shape,
offset=offset, order='F')
else:
with FortranFile(filename, 'rb', endian) as ff:
ff.seek(file_position)
d = np.array(ff.readline('*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 _read(self):
""" Helper function to load the data referenced by this bundle. """ |
if self._dask:
d = da.from_delayed(
delayed(read_from_bpch, )(
self.filename, self.file_position, self.shape,
self.dtype, self.endian, use_mmap=self._mmap
),
self.shape, self.dtype
)
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 close(self):
""" Close this bpch file. """ |
if not self.fp.closed:
for v in list(self.var_data):
del self.var_data[v]
self.fp.close() |
<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_metadata(self):
""" Read the main metadata packaged within a bpch file, indicating the output filetype and its title. """ |
filetype = self.fp.readline().strip()
filetitle = self.fp.readline().strip()
# Decode to UTF string, if possible
try:
filetype = str(filetype, 'utf-8')
filetitle = str(filetitle, 'utf-8')
except:
# TODO: Handle this edge-case of converting fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_var_data(self):
""" Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained ther... |
var_bundles = OrderedDict()
var_attrs = OrderedDict()
n_vars = 0
while self.fp.tell() < self.fsize:
var_attr = OrderedDict()
# read first and second header lines
line = self.fp.readline('20sffii')
modelname, res0, res1, halfpolar, cen... |
<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_timestamp(time=True, date=True, fmt=None):
""" Return the current timestamp in machine local time. Parameters: time, date : Boolean Flag to include the t... |
time_format = "%H:%M:%S"
date_format = "%m-%d-%Y"
if fmt is None:
if time and date:
fmt = time_format + " " + date_format
elif time:
fmt = time_format
elif date:
fmt = date_format
else:
raise ValueError("One of `date` or `tim... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_attr_encoding(ds):
""" This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scal... |
def _maybe_del_attr(da, attr):
""" Possibly delete an attribute on a DataArray if it's present """
if attr in da.attrs:
del da.attrs[attr]
return da
def _maybe_decode_attr(da, attr):
# TODO: Fix this so that bools get written as attributes just fine
""" 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 after_output(command_status):
""" Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ |
if command_status not in range(256):
raise ValueError("command_status must be an integer in the range 0-255")
sys.stdout.write(AFTER_OUTPUT.format(command_status=command_status))
# Flushing is important as the command timing feature maybe based on
# AFTER_OUTPUT in the future.
sys.stdout.fl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enforce_cf_variable(var, mask_and_scale=True):
""" Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a ... |
var = as_variable(var)
data = var._data # avoid loading by accessing _data instead of data
dims = var.dims
attrs = var.attrs.copy()
encoding = var.encoding.copy()
orig_dtype = data.dtype
# Process masking/scaling coordinates. We only expect a "scale" value
# for the units with this ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None):
""" Returns all entries, which publication date has been hit or which ... |
if check_language:
qs = NewsEntry.objects.language(language or get_language()).filter(
is_published=True)
else:
qs = self.get_queryset()
qs = qs.filter(
models.Q(pub_date__lte=now()) | models.Q(pub_date__isnull=True)
)
if kwarg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recent(self, check_language=True, language=None, limit=3, exclude=None, kwargs=None, category=None):
""" Returns recently published new entries. """ |
if category:
if not kwargs:
kwargs = {}
kwargs['categories__in'] = [category]
qs = self.published(check_language=check_language, language=language,
kwargs=kwargs)
if exclude:
qs = qs.exclude(pk=exclude.pk)
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_newsentry_meta_description(newsentry):
"""Returns the meta description for the given entry.""" |
if newsentry.meta_description:
return newsentry.meta_description
# If there is no seo addon found, take the info from the placeholders
text = newsentry.get_description()
if len(text) > 160:
return u'{}...'.format(text[:160])
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _requirement_filter_by_marker(req):
# type: (pkg_resources.Requirement) -> bool """Check if the requirement is satisfied by the marker. This function checks ... |
if hasattr(req, 'marker') and req.marker:
marker_env = {
'python_version': '.'.join(map(str, sys.version_info[:2])),
'sys_platform': sys.platform
}
if not req.marker.evaluate(environment=marker_env):
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 _requirement_find_lowest_possible(req):
# type: (pkg_resources.Requirement) -> List[str] """Find lowest required version. Given a single Requirement, this fu... |
version_dep = None # type: Optional[str]
version_comp = None # type: Optional[str]
for dep in req.specs:
version = pkg_resources.parse_version(dep[1])
# we don't want to have a not supported version as minimal version
if dep[0] == '!=':
continue
# try to use th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ensure_coroutine_function(func):
"""Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a ... |
if asyncio.iscoroutinefunction(func):
return func
else:
@asyncio.coroutine
def coroutine_function(evt):
func(evt)
yield
return coroutine_function |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def location(self):
"""Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which i... |
if self._location is None:
self._location = "{}/{}-{}".format(
self.stream,
self.type,
self.sequence,
)
return self._location |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def find_backwards(self, stream_name, predicate, predicate_label='predicate'):
"""Return first event matching predicate, or None if none exists. Note: 'bac... |
logger = self._logger.getChild(predicate_label)
logger.info('Fetching first matching event')
uri = self._head_uri
try:
page = await self._fetcher.fetch(uri)
except HttpNotFoundError as e:
raise StreamNotFoundError() from e
while 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 main():
"""Command line interface for the ``qpass`` program.""" |
# Initialize logging to the terminal.
coloredlogs.install()
# Prepare for command line argument parsing.
action = show_matching_entry
program_opts = dict(exclude_list=[])
show_opts = dict(filters=[], use_clipboard=is_clipboard_supported())
verbosity = 0
# Parse the command line argument... |
<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_matching_entry(program, arguments):
"""Edit the matching entry.""" |
entry = program.select_entry(*arguments)
entry.context.execute("pass", "edit", entry.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 SVGdocument():
"Create default SVG document"
import xml.dom.minidom
implementation = xml.dom.minidom.getDOMImplementation()
doctype = implementation.createDocumentType(
"svg", "-//W3C//DTD SVG 1.1//EN",
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
)
document= implementation.createDocument(None, "sv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def polyline(document, coords):
"polyline with more then 2 vertices"
points = []
for i in range(0, len(coords), 2):
points.append("%s,%s" % (coords[i], coords[i+1]))
return setattribs(
document.createElement('polyline'),
points = ' '.join(points),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cubic_bezier(document, coords):
"cubic bezier polyline"
element = document.createElement('path')
points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)]
path = ["M%s %s" %points[0]]
for n in xrange(1, len(points), 3):
A, B, C = points[n:n+3]
path.append("C%s,%s %s,%s %s,%s" % (A[0], A[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 smoothpolygon(document, coords):
"smoothed filled polygon"
element = document.createElement('path')
path = []
points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)]
def pt(points):
p = points
n = len(points)
for i in range(0, len(points)):
a = p[(i-1) % n]
b = p[i]
c = p[(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 font_actual(tkapp, font):
"actual font parameters"
tmp = tkapp.call('font', 'actual', font)
return dict(
(tmp[i][1:], tmp[i+1]) for i in range(0, len(tmp), 2)
) |
<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_dash(string, width):
"parse dash pattern specified with string"
# DashConvert from {tk-sources}/generic/tkCanvUtil.c
w = max(1, int(width + 0.5))
n = len(string)
result = []
for i, c in enumerate(string):
if c == " " and len(result):
result[-1] += w + 1
elif c == "_":
result.append(8*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 prof_altitude(pressure, p_coef=(-0.028389, -0.0493698, 0.485718, 0.278656, -17.5703, 48.0926)):
""" Return altitude for given pressure. This function evaluat... |
pressure = np.asarray(pressure)
altitude = np.polyval(p_coef, np.log10(pressure.flatten()))
return altitude.reshape(pressure.shape) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prof_pressure(altitude, z_coef=(1.94170e-9, -5.14580e-7, 4.57018e-5, -1.55620e-3, -4.61994e-2, 2.99955)):
""" Return pressure for given altitude. This functi... |
altitude = np.asarray(altitude)
pressure = np.power(10, np.polyval(z_coef, altitude.flatten()))
return pressure.reshape(altitude.shape) |
<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_model_info(model_name):
""" Get the grid specifications for a given model. Parameters model_name : string Name of the model. Supports multiple formats (... |
# trying to get as much as possible a valid model name from the given
# `model_name`, using regular expressions.
split_name = re.split(r'[\-_\s]', model_name.strip().upper())
sep_chars = ('', ' ', '-', '_')
gen_seps = itertools.combinations_with_replacement(
sep_chars, len(split_name) - 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_archive_filelist(filename):
# type: (str) -> List[str] """Extract the list of files from a tar or zip archive. Args: filename: name of the archive Retur... |
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
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 _augment_book(self, uuid, event):
""" Checks if the newly created object is a book and only has an ISBN. If so, tries to fetch the book data off the internet... |
try:
if not isbnmeta:
self.log(
"No isbntools found! Install it to get full "
"functionality!",
lvl=warn)
return
new_book = objectmodels['book'].find_one({'uuid': uuid})
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opened(self, *args):
"""Initiates communication with the remote controlled device. :param args: """ |
self._serial_open = True
self.log("Opened: ", args, lvl=debug)
self._send_command(b'l,1') # Saying hello, shortly
self.log("Turning off engine, pump and neutralizing rudder")
self._send_command(b'v')
self._handle_servo(self._machine_channel, 0)
self._handle_ser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_machinerequest(self, event):
""" Sets a new machine speed. :param event: """ |
self.log("Updating new machine power: ", event.controlvalue)
self._handle_servo(self._machine_channel, event.controlvalue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_rudderrequest(self, event):
""" Sets a new rudder angle. :param event: """ |
self.log("Updating new rudder angle: ", event.controlvalue)
self._handle_servo(self._rudder_channel, event.controlvalue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_pumprequest(self, event):
""" Activates or deactivates a connected pump. :param event: """ |
self.log("Updating pump status: ", event.controlvalue)
self._set_digital_pin(self._pump_channel, event.controlvalue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def provisionList(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions a list of items according to their schema :param item... |
log('Provisioning', items, database_name, lvl=debug)
system_user = None
def get_system_user():
"""Retrieves the node local system user"""
user = objectmodels['user'].find_one({'name': 'System'})
try:
log('System user uuid: ', user.uuid, lvl=verbose)
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DefaultExtension(schema_obj, form_obj, schemata=None):
"""Create a default field""" |
if schemata is None:
schemata = ['systemconfig', 'profile', 'client']
DefaultExtends = {
'schema': {
"properties/modules": [
schema_obj
]
},
'form': {
'modules': {
'items/': form_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 copytree(root_src_dir, root_dst_dir, hardlink=True):
"""Copies a whole directory tree""" |
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, ... |
<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(ctx, componentname):
"""Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.""" |
col = ctx.obj['col']
if col.count({'name': componentname}) > 1:
log('More than one component configuration of this name! Try '
'one of the uuids as argument. Get a list with "config '
'list"')
return
log('Deleting component configuration', componentname,
em... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(ctx, component):
"""Show the stored, active configuration of a component.""" |
col = ctx.obj['col']
if col.count({'name': component}) > 1:
log('More than one component configuration of this name! Try '
'one of the uuids as argument. Get a list with "config '
'list"')
return
if component is None:
configurations = col.find()
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 debugrequest(self, event):
"""Handler for client-side debug requests""" |
try:
self.log("Event: ", event.__dict__, lvl=critical)
if event.data == "storejson":
self.log("Storing received object to /tmp", lvl=critical)
fp = open('/tmp/hfosdebugger_' + str(
event.user.useruuid) + "_" + str(uuid4()), "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 register_event(self, event):
"""Registers a new command line interface event hook as command""" |
self.log('Registering event hook:', event.cmd, event.thing,
pretty=True, lvl=verbose)
self.hooks[event.cmd] = event.thing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate_user_events():
"""Generate a list of all registered authorized and anonymous events""" |
global AuthorizedEvents
global AnonymousEvents
def inheritors(klass):
"""Find inheritors of a specified object class"""
subclasses = {}
subclasses_set = set()
work = [klass]
while work:
parent = work.pop()
for child in parent.__subclasses__... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(ctx, schema):
"""Clears an entire database collection irrevocably. Use with caution!""" |
response = _ask('Are you sure you want to delete the collection "%s"' % (
schema), default='N', data_type='bool')
if response is True:
host, port = ctx.obj['dbhost'].split(':')
client = pymongo.MongoClient(host=host, port=int(port))
database = client[ctx.obj['dbname']]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def provision_system_config(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provision a basic system configuration""" |
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
default_system_config_count = objectmodels['systemconfig'].count({
'name': 'Default System Configuration'})
if default_system_config_count == 0 or (clear or overwrite):
provisionList([SystemConfigur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def userlogin(self, event):
"""Provides the newly authenticated user with a backlog and general channel status information""" |
try:
user_uuid = event.useruuid
user = objectmodels['user'].find_one({'uuid': user_uuid})
if user_uuid not in self.lastlogs:
self.log('Setting up lastlog for a new user.', lvl=debug)
lastlog = objectmodels['chatlastlog']({
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_docs(instance, clear_target):
"""Builds and installs the complete HFOS documentation.""" |
_check_root()
def make_docs():
"""Trigger a Sphinx make command to build the documentation."""
log("Generating HTML documentation")
try:
build = Popen(
[
'make',
'html'
],
cwd='docs/'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_modules(wip):
"""Install the plugin modules""" |
def install_module(hfos_module):
"""Install a single module via setuptools"""
try:
setup = Popen(
[
sys.executable,
'setup.py',
'develop'
],
cwd='modules/' + hfos_module + "/"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_cert(selfsigned):
"""Install a local SSL certificate""" |
_check_root()
if selfsigned:
log('Generating self signed (insecure) certificate/key '
'combination')
try:
os.mkdir('/etc/ssl/certs/hfos')
except FileExistsError:
pass
except PermissionError:
log("Need root (e.g. via sudo) to gen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frontend(ctx, dev, rebuild, no_install, build_type):
"""Build and install frontend""" |
install_frontend(instance=ctx.obj['instance'],
forcerebuild=rebuild,
development=dev,
install=not no_install,
build_type=build_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_all(ctx, clear_all):
"""Default-Install everything installable \b This includes * System user (hfos.hfos) * Self signed certificate * Variable data l... |
_check_root()
instance = ctx.obj['instance']
dbhost = ctx.obj['dbhost']
dbname = ctx.obj['dbname']
port = ctx.obj['port']
install_system_user()
install_cert(selfsigned=True)
install_var(instance, clear_target=clear_all, clear_all=clear_all)
install_modules(wip=False)
install... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall():
"""Uninstall data and resource locations""" |
_check_root()
response = _ask("This will delete all data of your HFOS installations! Type"
"YES to continue:", default="N", show_hint=False)
if response == 'YES':
shutil.rmtree('/var/lib/hfos')
shutil.rmtree('/var/cache/hfos') |
<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(ctx, no_restart, no_rebuild):
"""Update a HFOS node""" |
# 0. (NOT YET! MAKE A BACKUP OF EVERYTHING)
# 1. update repository
# 2. update frontend repository
# 3. (Not yet: update venv)
# 4. rebuild frontend
# 5. restart service
instance = ctx.obj['instance']
log('Pulling github updates')
run_process('.', ['git', 'pull', 'origin', 'maste... |
<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_model_factories(store):
"""Generate factories to construct objects from schemata""" |
result = {}
for schemaname in store:
schema = None
try:
schema = store[schemaname]['schema']
except KeyError:
schemata_log("No schema found for ", schemaname, lvl=critical, exc=True)
try:
result[schemaname] = warmongo.model_factory(schema... |
<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_collections(store):
"""Generate database collections with indices from the schemastore""" |
result = {}
client = pymongo.MongoClient(host=dbhost, port=dbport)
db = client[dbname]
for schemaname in store:
schema = None
indices = None
try:
schema = store[schemaname]['schema']
indices = store[schemaname].get('indices', None)
except 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 initialize(address='127.0.0.1:27017', database_name='hfos', instance_name="default", reload=False):
"""Initializes the database connectivity, schemata and fi... |
global schemastore
global l10n_schemastore
global objectmodels
global collections
global dbhost
global dbport
global dbname
global instance
global initialized
if initialized and not reload:
hfoslog('Already initialized and not reloading.', lvl=warn, emitter="DB", frame... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(schemaname='sensordata', profiletype='pjs'):
"""Profiles object model handling with a very simple benchmarking test""" |
db_log("Profiling ", schemaname)
schema = schemastore[schemaname]['schema']
db_log("Schema: ", schema, lvl=debug)
testclass = None
if profiletype == 'warmongo':
db_log("Running Warmongo benchmark")
testclass = warmongo.model_factory(schema)
elif profiletype == 'pjs':
... |
<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_collections(self):
"""Checks node local collection storage sizes""" |
self.collection_sizes = {}
self.collection_total = 0
for col in self.db.collection_names(include_system_collections=False):
self.collection_sizes[col] = self.db.command('collstats', col).get(
'storageSize', 0)
self.collection_total += self.collection_siz... |
<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_free_space(self):
"""Checks used filesystem storage sizes""" |
def get_folder_size(path):
"""Aggregates used size of a specified path, recursively"""
total_size = 0
for item in walk(path):
for file in item[2]:
try:
total_size = total_size + getsize(join(item[0], 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 send_mail_worker(config, mail, event):
"""Worker task to send out an email, which blocks the process unless it is threaded""" |
log = ""
try:
if config.mail_ssl:
server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30)
else:
server = SMTP(config.mail_server, port=config.mail_server_port, timeout=30)
if config.mail_tls:
log += 'Starting TLS\n'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload_configuration(self, event):
"""Reload the current configuration and set up everything depending on it""" |
super(EnrolManager, self).reload_configuration(event)
self.log('Reloaded configuration.')
self._setup() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change(self, event):
"""An admin user requests a change to an enrolment""" |
uuid = event.data['uuid']
status = event.data['status']
if status not in ['Open', 'Pending', 'Accepted', 'Denied', 'Resend']:
self.log('Erroneous status for enrollment requested!', lvl=warn)
return
self.log('Changing status of an enrollment', uuid, 'to', statu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changepassword(self, event):
"""An enrolled user wants to change their password""" |
old = event.data['old']
new = event.data['new']
uuid = event.user.uuid
# TODO: Write email to notify user of password change
user = objectmodels['user'].find_one({'uuid': uuid})
if std_hash(old, self.salt) == user.passhash:
user.passhash = std_hash(new, 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 invite(self, event):
"""A new user has been invited to enrol by an admin user""" |
self.log('Inviting new user to enrol')
name = event.data['name']
email = event.data['email']
method = event.data['method']
self._invite(name, method, email, event.client.uuid, event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enrol(self, event):
"""A user tries to self-enrol with the enrolment form""" |
if self.config.allow_registration is False:
self.log('Someone tried to register although enrolment is closed.')
return
self.log('Client trying to register a new account:', event, pretty=True)
# self.log(event.data, pretty=True)
uuid = event.client.uuid
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self, event):
"""An anonymous client wants to know if we're open for enrollment""" |
self.log('Registration status requested')
response = {
'component': 'hfos.enrol.enrolmanager',
'action': 'status',
'data': self.config.allow_registration
}
self.fire(send(event.client.uuid, 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 request_reset(self, event):
"""An anonymous client requests a password reset""" |
self.log('Password reset request received:', event.__dict__, lvl=hilight)
user_object = objectmodels['user']
email = event.data.get('email', None)
email_user = None
if email is not None and user_object.count({'mail': email}) > 0:
email_user = user_object.find_one... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def captcha_transmit(self, captcha, uuid):
"""Delayed transmission of a requested captcha""" |
self.log('Transmitting captcha')
response = {
'component': 'hfos.enrol.enrolmanager',
'action': 'captcha',
'data': b64encode(captcha['image'].getvalue()).decode('utf-8')
}
self.fire(send(uuid, 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 _invite(self, name, method, email, uuid, event, password=""):
"""Actually invite a given user""" |
props = {
'uuid': std_uuid(),
'status': 'Open',
'name': name,
'method': method,
'email': email,
'password': password,
'timestamp': std_now()
}
enrollment = objectmodels['enrollment'](props)
enrollment.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 _create_user(self, username, password, mail, method, uuid):
"""Create a new user and all initial data""" |
try:
if method == 'Invited':
config_role = self.config.group_accept_invited
else:
config_role = self.config.group_accept_enrolled
roles = []
if ',' in config_role:
for item in config_role.split(','):
... |
<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_invitation(self, enrollment, event):
"""Send an invitation mail to an open enrolment""" |
self.log('Sending enrollment status mail to user')
self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event) |
<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_acceptance(self, enrollment, password, event):
"""Send an acceptance mail to an open enrolment""" |
self.log('Sending acceptance status mail to user')
if password is not "":
password_hint = '\n\nPS: Your new password is ' + password + ' - please change it after your first login!'
acceptance_text = self.config.acceptance_mail + password_hint
else:
accepta... |
<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_auth_hook(self, event):
"""Register event hook on reception of add_auth_hook-event""" |
self.log('Adding authentication hook for', event.authenticator_name)
self.auth_hooks[event.authenticator_name] = event.event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fail(self, event, message='Invalid credentials'):
"""Sends a failure message to the requesting client""" |
notification = {
'component': 'auth',
'action': 'fail',
'data': message
}
ip = event.sock.getpeername()[0]
self.failing_clients[ip] = event
Timer(3, Event.create('notify_fail', event.clientuuid, notification, ip)).register(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 _login(self, event, user_account, user_profile, client_config):
"""Send login notification to client""" |
user_account.lastlogin = std_now()
user_account.save()
user_account.passhash = ""
self.fireEvent(
authentication(user_account.name, (
user_account, user_profile, client_config),
event.clientuuid,
user_ac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_autologin(self, event):
"""Automatic logins for client configurations that allow it""" |
self.log("Verifying automatic login request")
# TODO: Check for a common secret
# noinspection PyBroadException
try:
client_config = objectmodels['client'].find_one({
'uuid': event.requestedclientuuid
})
except Exception:
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.