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 _es_text(settings, text_formating = {}):
""" Extract text formating related subset of widget settings. """ |
s = {k: settings[k] for k in (ConsoleWidget.SETTING_FLAG_PLAIN,)}
s.update(text_formating)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _es_margin(settings):
""" Extract margin formating related subset of widget settings. """ |
return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN,
ConsoleWidget.SETTING_MARGIN_LEFT,
ConsoleWidget.SETTING_MARGIN_RIGHT,
ConsoleWidget.SETTING_MARGIN_CHAR)} |
<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_width_widget(width, margin = None, margin_left = None, margin_right = None):
""" Calculate actual widget width based on given margins. """ |
if margin_left is None:
margin_left = margin
if margin_right is None:
margin_right = margin
if margin_left is not None:
width -= int(margin_left)
if margin_right is not None:
width -= int(margin_right)
return width if width > 0 els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmt_data(text, data_formating = None, data_type = None):
""" Format given text according to given data formating pattern or data type. """ |
if data_type:
return DATA_TYPES[data_type](text)
elif data_formating:
return str(data_formating).format(text)
return str(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 fmt_content(text, width = 0, align = '<', padding = None, padding_left = None, padding_right = None, padding_char = ' '):
""" Pad given text with given paddi... |
if padding_left is None:
padding_left = padding
if padding_right is None:
padding_right = padding
if padding_left is not None:
text = '{}{}'.format(str(padding_char)[0] * int(padding_left), text)
if padding_right is not None:
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 fmt_text(text, bg = None, fg = None, attr = None, plain = False):
""" Apply given console formating around given text. """ |
if not plain:
if fg is not None:
text = TEXT_FORMATING['fg'][fg] + text
if bg is not None:
text = TEXT_FORMATING['bg'][bg] + text
if attr is not None:
text = TEXT_FORMATING['attr'][attr] + text
if (fg is not None) 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 fmt_margin(text, margin = None, margin_left = None, margin_right = None, margin_char = ' '):
""" Surround given text with given margin characters. """ |
if margin_left is None:
margin_left = margin
if margin_right is None:
margin_right = margin
if margin_left is not None:
text = '{}{}'.format(str(margin_char)[0] * int(margin_left), text)
if margin_right is not None:
text = '{}{}'.format(te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bchar(posh, posv, border_style):
""" Retrieve table border style for particular box border piece. """ |
index = '{}{}'.format(posv, posh).lower()
return BORDER_STYLES[border_style][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 _render_item(self, depth, key, value = None, **settings):
""" Format single list item. """ |
strptrn = self.INDENT * depth
lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
lchar = self.fmt_text(lchar, **s)
strptrn = "{}"
if value is not None:
strptrn += ": {}"
s = 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 tchar(tree_style, cur_level, level, item, size):
""" Retrieve tree character for particular tree node. """ |
if (cur_level == level):
i1 = '1' if level == 0 else 'x'
i2 = '1' if item == 0 else 'x'
i3 = 'x'
if size == 1:
i3 = '1'
elif item == (size - 1):
i3 = 'l'
index = '{}{}{}'.format(i1, i2, i3)
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 _render_item(self, dstack, key, value = None, **settings):
""" Format single tree line. """ |
cur_depth = len(dstack) - 1
treeptrn = ''
s = self._es_text(settings, settings[self.SETTING_TREE_FORMATING])
for ds in dstack:
treeptrn += ' ' + self.fmt_text(self.tchar(settings[self.SETTING_TREE_STYLE], cur_depth, *ds), **s) + ''
strptrn = "{}"
if value 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 _render_content_list(self, content, depth, dstack, **settings):
""" Render the list. """ |
result = []
i = 0
size = len(content)
for value in content:
ds = [(depth, i, size)]
ds = dstack + ds
if isinstance(value, dict):
result.append(self._render_item(ds, "[{}]".format(i), **settings))
result += self._render_... |
<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_content_dict(self, content, depth, dstack, **settings):
""" Render the dict. """ |
result = []
i = 0
size = len(content)
for key in sorted(content):
ds = [(depth, i, size)]
ds = dstack + ds
if isinstance(content[key], dict):
result.append(self._render_item(ds, key, **settings))
result += self._render_... |
<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_content(self, content, **settings):
""" Render the tree widget. """ |
if isinstance(content, dict):
return self._render_content_dict(content, 0, [], **settings)
elif isinstance(content, list):
return self._render_content_list(content, 0, [], **settings)
else:
raise Exception("Received invalid data tree for rendering.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmt_border(self, width, t = 'm', border_style = 'utf8.a', border_formating = {}):
""" Format box separator line. """ |
border = self.bchar('l', t, border_style) + (self.bchar('h', t, border_style) * (width-2)) + self.bchar('r', t, border_style)
return self.fmt_text(border, **border_formating) |
<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_content(content, width):
""" Wrap given content into lines of given width. """ |
data = []
if isinstance(content, list):
data += content
else:
data.append(content)
lines = []
for d in data:
l = textwrap.wrap(d, width)
lines += l
return lines |
<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_border_line(self, t, settings):
""" Render box border line. """ |
s = self._es(settings, self.SETTING_WIDTH, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT)
w = self.calculate_width_widget(**s)
s = self._es(settings, self.SETTING_BORDER_STYLE, self.SETTING_BORDER_FORMATING)
border_line = self.fmt_border(w, t, **s)
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 _render_line(self, line, settings):
""" Render single box line. """ |
s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT)
width_content = self.calculate_width_widget_int(**s)
s = self._es_content(settings)
s[self.SETTING_WIDTH] = width_content
line = self.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 fmt_border(self, dimensions, t = 'm', border_style = 'utf8.a', border_formating = {}):
""" Format table separator line. """ |
cells = []
for column in dimensions:
cells.append(self.bchar('h', t, border_style) * (dimensions[column] + 2))
border = '{}{}{}'.format(self.bchar('l', t, border_style), self.bchar('m', t, border_style).join(cells), self.bchar('r', t, border_style))
return self.fmt_text(bor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmt_cell(self, value, width, cell_formating, **text_formating):
""" Format sigle table cell. """ |
strptrn = " {:" + '{:s}{:d}'.format(cell_formating.get('align', '<'), width) + "s} "
strptrn = self.fmt_text(strptrn, **text_formating)
return strptrn.format(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 fmt_row(self, columns, dimensions, row, **settings):
""" Format single table row. """ |
cells = []
i = 0
for column in columns:
cells.append(self.fmt_cell(
row[i],
dimensions[i],
column,
**settings[self.SETTING_TEXT_FORMATING]
)
)
i += 1
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 fmt_row_header(self, columns, dimensions, **settings):
""" Format table header row. """ |
row = list(map(lambda x: x['label'], columns))
return self.fmt_row(columns, dimensions, row, **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 _render_bar(self, bar, value, max_value, label_width, bar_width, **settings):
""" Render single chart bar. """ |
percent = value / max_value
barstr = ""
barstr += str(settings[self.SETTING_BAR_CHAR]) * int(bar_width * percent)
s = {k: settings[k] for k in (self.SETTING_FLAG_PLAIN,)}
s.update(settings[self.SETTING_BAR_FORMATING])
barstr = self.fmt_text(barstr, **s)
barstr +=... |
<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_select(query_obj):
""" Given a Query obj, return the corresponding sql """ |
return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \
limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct) |
<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_insert(table_name, attributes):
""" Given the table_name and the data, return the sql to insert the data """ |
sql = "INSERT INTO %s" %(table_name)
column_str = u""
value_str = u""
for index, (key, value) in enumerate(attributes.items()):
if index > 0:
column_str += u","
value_str += u","
column_str += key
value_str += value_to_sql_str(value)
sql = sql + u"(%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 make_gatherer(cls, cell, source_tiers, gatherby):
""" Produce a single source tier that gathers from a set of tiers when the key function returns a unique re... |
pending = collections.defaultdict(dict)
tier_hashes = [hash(x) for x in source_tiers]
@asyncio.coroutine
def organize(route, *args):
srchash = hash(route.source)
key = gatherby(*args)
group = pending[key]
assert srchash not in group
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enqueue_task(self, source, *args):
""" Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so. """ |
yield from self.cell.coord.enqueue(self)
route = Route(source, self.cell, self.spec, self.emit)
self.cell.loop.create_task(self.coord_wrap(route, *args))
# To guarantee that the event loop works fluidly, we manually yield
# once. The coordinator enqueue coroutine is not required... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coord_wrap(self, *args):
""" Wrap the coroutine with coordination throttles. """ |
yield from self.cell.coord.start(self)
yield from self.coro(*args)
yield from self.cell.coord.finish(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 flush(self):
""" Flush the buffer of buffered tiers to our destination tiers. """ |
if self.buffer is None:
return
data = self.buffer
self.buffer = []
for x in self.dests:
yield from x.enqueue_task(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 add_source(self, tier):
""" Schedule this tier to be called when another tier emits. """ |
tier.add_dest(self)
self.sources.append(tier) |
<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):
""" Free any potential cycles. """ |
self.cell = None
self.coro = None
self.buffer = None
del self.dests[:]
del self.sources[:] |
<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_arguments(parser):
'''Add command-line arguments for yakonfig proper.
This is part of the :class:`~yakonfig.Configurable` interface, and
is usually run by including :mod:`yakonfig` in the
:func:`parse_args()` module list.
:param argparse.ArgumentParser parser: command-line argument
p... |
<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_args(parser, modules, args=None):
"""Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` obj... |
collect_add_argparse(parser, modules)
namespace = parser.parse_args(args)
try:
do_dump_config = getattr(namespace, 'dump_config', None)
set_default_config(modules, params=vars(namespace),
validate=not do_dump_config)
if do_dump_config:
if 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 set_default_config(modules, params=None, yaml=None, filename=None, config=None, validate=True):
"""Set up global configuration for tests and noninteractive t... |
if params is None:
params = {}
# Get the configuration from the file, or from params['config']
file_config = {}
if yaml is None and filename is None and config is None:
if 'config' in params and params['config'] is not None:
filename = params['config']
if yaml is not 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 check_toplevel_config(what, who):
"""Verify that some dependent configuration is present and correct. This will generally be called from a :meth:`~yakonfig.C... |
config_name = what.config_name
config = get_global_config()
if config_name not in config:
raise ConfigurationError(
'{0} requires top-level configuration for {1}'
.format(who, config_name))
checker = getattr(what, 'check_config', None)
if checker:
checker(con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _recurse_config(parent_config, modules, f, prefix=''):
'''Walk through the module tree.
This is a helper function for :func:`create_config_tree` and
:func:`_walk_config`. It calls `f` once for each module in the
configuration tree with parameters `parent_config`, `config_name`,
`prefix`, and `... |
<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_config_tree(config, modules, prefix=''):
'''Cause every possible configuration sub-dictionary to exist.
This is intended to be called very early in the configuration
sequence. For each module, it checks that the corresponding
configuration item exists in `config` and creates it as an empty
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _walk_config(config, modules, f, prefix=''):
"""Recursively walk through a module list. For every module, calls ``f(config, module, name)`` where `config` is... |
def work_in(parent_config, config_name, prefix, module):
# create_config_tree() needs to have been called by now
# and you should never hit either of these asserts
if config_name not in parent_config:
raise ProgrammerError('{0} not present in configuration'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_add_argparse(parser, modules):
"""Add all command-line options. `modules` is an iterable of :class:`yakonfig.configurable.Configurable` objects, or a... |
def work_in(parent_config, config_name, prefix, module):
f = getattr(module, 'add_arguments', None)
if f is not None:
f(parser)
_recurse_config(dict(), modules, work_in)
return parser |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assemble_default_config(modules):
"""Build the default configuration from a set of modules. `modules` is an iterable of :class:`yakonfig.configurable.Configu... |
def work_in(parent_config, config_name, prefix, module):
my_config = dict(getattr(module, 'default_config', {}))
if config_name in parent_config:
extra_config = parent_config[config_name]
raise ProgrammerError(
'config for {0} already present when about to fe... |
<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_in_arguments(config, modules, args):
"""Fill in configuration fields from command-line arguments. `config` is a dictionary holding the initial configura... |
def work_in(config, module, name):
rkeys = getattr(module, 'runtime_keys', {})
for (attr, cname) in iteritems(rkeys):
v = args.get(attr, None)
if v is not None:
config[cname] = v
if not isinstance(args, collections.Mapping):
args = vars(args)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_config_discovery(config, modules):
'''Let modules detect additional configuration values.
`config` is the initial dictionary with command-line and
file-derived values, but nothing else, filled in. This calls
:meth:`yakonfig.configurable.Configurable.discover_config` on
every configuration 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 main(arguments=None, config=None):
""" Parse arguments for ``idid`` command. Pass optional parameter ``arguments`` as either command line string or list of o... |
# Parse options, initialize gathered stats
options = LoggOptions(arguments=arguments).parse()
# FIXME: pass in only config; set config.journal = options.journal
if not config:
config = options.config_file
logg = Logg(config, options.journal)
return logg.logg_record(options.logg, opti... |
<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(self, opts, args):
""" Perform additional check for ``idid`` command arguments """ |
k_args = len(args)
_dt = opts.date = None
logg = opts.logg = None
journal = opts.journal = None
default_journal = self.config.get('default_journal')
_journals = self.config.get('journals') or {}
log.debug(' ... got {0} args [{1}]'.format(k_args, args))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_root_tex_document(base_dir="."):
"""Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``... |
log = logging.getLogger(__name__)
for tex_path in iter_tex_documents(base_dir=base_dir):
with codecs.open(tex_path, 'r', encoding='utf-8') as f:
text = f.read()
if len(docclass_pattern.findall(text)) > 0:
log.debug("Found root tex {0}".format(tex_path))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_tex_documents(base_dir="."):
"""Iterate through all .tex documents in the current directory.""" |
for path, dirlist, filelist in os.walk(base_dir):
for name in fnmatch.filter(filelist, "*.tex"):
yield os.path.join(path, 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 inline(root_text, base_dir="", replacer=None, ifexists_replacer=None):
"""Inline all input latex files. The inlining is accomplished recursively. All files a... |
def _sub_line(match):
"""Function to be used with re.sub to inline files for each match."""
fname = match.group(1)
if not fname.endswith('.tex'):
full_fname = ".".join((fname, 'tex'))
else:
full_fname = fname
full_path = os.path.abspath(os.path.join(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 inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""):
"""Inline all input latex files that exist as git blobs in a tree object. The inlining is acco... |
def _sub_blob(match):
"""Function to be used with re.sub to inline files for each match."""
fname = match.group(1)
if not fname.endswith('.tex'):
full_fname = ".".join((fname, 'tex'))
else:
full_fname = fname
git_rel_path = os.path.relpath(full_fname,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get(self, uri, options):
""" Quick and dirty wrapper around the requests object to do some simple data catching :params uri: a string, the uri you want to r... |
url = "http://%s/%s" % (self.host, uri)
r = requests.get(url, params=options)
if r.status_code == 200:
data = r.json()
return data['results']
else:
# Throws anything not 200 error
r.raise_for_status() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setWindowTitle(self, newTitle=''):
"""Prepend Rampage to all window titles.""" |
title = 'Rampage - ' + newTitle
super(MainWindow, self).setWindowTitle(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 load(jwks):
"""Parse a JWKSet and return a dictionary that maps key IDs on keys.""" |
sign_keys = {}
verify_keys = {}
try:
keyset = json.loads(jwks)
for key in keyset['keys']:
for op in key['key_ops']:
if op == 'sign':
k = sign_keys
elif op == 'verify':
k = verify_keys
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 version():
""" Get the local package version. """ |
path = join("lib", _CONFIG["name"], "__version__.py")
with open(path) as stream:
exec(stream.read())
return __version__ |
<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_config_path(self):
""" Reads config path from environment variable CLOEEPY_CONFIG_PATH and sets as instance attr """ |
self._path = os.getenv("CLOEEPY_CONFIG_PATH")
if self._path is None:
msg = "CLOEEPY_CONFIG_PATH is not set. Exiting..."
sys.exit(msg) |
<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_config(self):
""" Loads the YAML configuration file and sets python dictionary and raw contents as instance attrs. """ |
if not os.path.exists(self._path):
sys.exit("Config path %s does not exist" % self._path)
# create empty config object
self._config_dict = {}
# read file and marshal yaml
with open(self._path, 'r') as f:
self._raw = f.read()
self._config_dict ... |
<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_attributes(self):
""" Recursively transforms config dictionaries into instance attrs to make for easy dot attribute access instead of dictionary access.... |
# turn config dict into nested objects
config = obj(self._config_dict)
# set the attributes onto instance
for k, v in self._config_dict.items():
setattr(self, k, getattr(config, k)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def highlight(__text: str, *, lexer: str = 'diff', formatter: str = 'terminal') -> str: """Highlight text highlighted using ``pygments``. Returns text untouched i... |
if sys.stdout.isatty():
lexer = get_lexer_by_name(lexer)
formatter = get_formatter_by_name(formatter)
__text = pyg_highlight(__text, lexer, formatter)
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 html2text(__html: str, *, width: int = 80, ascii_replacements: bool = False) -> str: """HTML to plain text renderer. See also: :pypi:`html2text` Args: __html:... |
html2.BODY_WIDTH = width
html2.UNICODE_SNOB = ascii_replacements
return html2.html2text(__html).strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *, count: int = 0, flags: int = 0) -> str: """Jinja filter for regexp replacements. See :f... |
return re.sub(__pattern, __repl, __string, count, flags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(__pkg: str) -> jinja2.Environment: """Configure a new Jinja environment with our filters. Args: __pkg: Package name to use as base for templates searche... |
dirs = [path.join(d, 'templates')
for d in xdg_basedir.get_data_dirs(__pkg)]
env = jinja2.Environment(
autoescape=jinja2.select_autoescape(['html', 'xml']),
loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(s) for s in dirs]))
env.loader.loaders.append(jinja2.PackageLoader(__... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_intercom_user(obj_id):
"""Creates or updates single user account on intercom""" |
UserModel = get_user_model()
intercom_user = False
instance = UserModel.objects.get(pk=obj_id)
data = instance.get_intercom_data()
if not getattr(settings, "SKIP_INTERCOM", False):
try:
intercom_user = intercom.users.create(**data)
except errors.ServiceUnavailableError:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def LoadExclusions(self, snps):
""" Load locus exclusions. :param snps: Can either be a list of rsids or a file containing rsids. :return: None If snps is a file... |
snp_names = []
if len(snps) == 1 and os.path.isfile(snps[0]):
snp_names = open(snps).read().strip().split()
else:
snp_names = snps
for snp in snp_names:
if len(snp.strip()) > 0:
self.ignored_rs.append(snp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getserialnum(flist):
""" This function assumes the serial number of the camera is in a particular place in the filename. Yes, this is a little lame, but it's... |
sn = []
for f in flist:
tmp = search(r'(?<=CamSer)\d{3,6}', f)
if tmp:
ser = int(tmp.group())
else:
ser = None
sn.append(ser)
return sn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDMCparam(fn: Path, xyPix, xyBin, FrameIndReq=None, ut1req=None, kineticsec=None, startUTC=None, nHeadBytes=4, verbose=0):
""" nHeadBytes=4 for 2013-2016 d... |
Nmetadata = nHeadBytes // 2 # FIXME for DMCdata version 1 only
if not fn.is_file(): # leave this here, getsize() doesn't fail on directory
raise ValueError(f'{fn} is not a file!')
print(f'reading {fn}')
# int() in case we are fed a float or int
SuperX = int(xyPix[0] // xyBin[0])
Su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def whichframes(fn, FrameIndReq, kineticsec, ut1req, startUTC, firstRawInd, lastRawInd, BytesPerImage, BytesPerFrame, verbose):
ext = Path(fn).suffix # %% get fi... |
FrameIndRel = ut12frame(ut1req,
arange(0, nFrame, 1, dtype=int64),
ut1_unix_all)
# NOTE: no ut1req or problems with ut1req, canNOT use else, need to test len() in case index is [0] validly
if FrameIndRel is None or len(FrameIndRel) == 0:
Fram... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDMCframe(f, iFrm: int, finf: dict, verbose: bool=False):
""" f is open file handle """ |
# on windows, "int" is int32 and overflows at 2.1GB! We need np.int64
currByte = iFrm * finf['bytesperframe']
# %% advance to start of frame in bytes
if verbose:
print(f'seeking to byte {currByte}')
assert isinstance(iFrm, (int, int64)), 'int32 will fail on files > 2GB'
try:
f.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 _fixSize(self):
"""Fix the menu size. Commonly called when the font is changed""" |
self.height = 0
for o in self.options:
text = o['label']
font = o['font']
ren = font.render(text, 1, (0, 0, 0))
if ren.get_width() > self.width:
self.width = ren.get_width()
self.height += font.get_height() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, surface):
"""Blit the menu to a surface.""" |
offset = 0
i = 0
ol, ot = self.screen_topleft_offset
first = self.options and self.options[0]
last = self.options and self.options[-1]
for o in self.options:
indent = o.get('padding_col', 0)
# padding above the line
if o != first and ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, events, time_passed=None):
"""Update the menu and get input for the menu. @events: the pygame catched events @time_passed: delta time since the ... |
for e in events:
if e.type == pygame.QUIT:
raise SystemExit
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
raise SystemExit
if e.key == pygame.K_DOWN:
self.option += 1
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _checkMousePositionForFocus(self):
"""Check the mouse position to know if move focus on a option""" |
i = 0
cur_pos = pygame.mouse.get_pos()
ml, mt = self.position
for o in self.options:
rect = o.get('label_rect')
if rect:
if rect.collidepoint(cur_pos) and self.mouse_pos != cur_pos:
self.option = i
self.mous... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_at(self, x, y):
"""Center the menu at x, y""" |
self.x = x - (self.width / 2)
self.y = y - (self.height / 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 run_bots(bots):
""" Run many bots in parallel. :param bots: IRC bots to run. :type bots: list """ |
greenlets = [spawn(bot.run) for bot in bots]
try:
joinall(greenlets)
except KeyboardInterrupt:
for bot in bots:
bot.disconnect()
finally:
killall(greenlets) |
<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(cls, data):
""" Extracts message informations from `data`. :param data: received line. :type data: unicode :return: extracted informations (source, des... |
src = u''
dst = None
if data[0] == u':':
src, data = data[1:].split(u' ', 1)
if u' :' in data:
data, trailing = data.split(u' :', 1)
args = data.split()
args.extend(trailing.split())
else:
args = data.split()
co... |
<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(cls, prefix):
""" Extracts informations from `prefix`. :param prefix: prefix with format ``<servername>|<nick>['!'<user>]['@'<host>]``. :type prefix: u... |
try:
nick, rest = prefix.split(u'!')
except ValueError:
return prefix, None, None, None
try:
mode, rest = rest.split(u'=')
except ValueError:
mode, rest = None, rest
try:
user, host = rest.split(u'@')
except Val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_connection(self):
""" Creates a transport channel. :return: transport channel instance :rtype: :class:`fatbotslim.irc.tcp.TCP` or :class:`fatbotslim.... |
transport = SSL if self.ssl else TCP
return transport(self.server, self.port) |
<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 the bot to the server and identifies itself. """ |
self.conn = self._create_connection()
spawn(self.conn.connect)
self.set_nick(self.nick)
self.cmd(u'USER', u'{0} 3 * {1}'.format(self.nick, self.realname)) |
<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, command):
""" Sends a raw line to the server. :param command: line to send. :type command: unicode """ |
command = command.encode('utf-8')
log.debug('>> ' + command)
self.conn.oqueue.put(command) |
<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(self, msg):
""" Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` """ |
def handler_yielder():
for handler in self.handlers:
yield handler
def handler_callback(_):
if msg.propagate:
try:
h = hyielder.next()
g = self._pool.spawn(handler_runner, h)
g.link(han... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomize_nick(cls, base, suffix_length=3):
""" Generates a pseudo-random nickname. :param base: prefix to use for the generated nickname. :type base: unicod... |
suffix = u''.join(choice(u'0123456789') for _ in range(suffix_length))
return u'{0}{1}'.format(base, suffix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_handler(self, handler, args=None, kwargs=None):
""" Registers a new handler. :param handler: handler to register. :type handler: :class:`fatbotslim.handl... |
args = [] if args is None else args
kwargs = {} if kwargs is None else kwargs
handler_instance = handler(self, *args, **kwargs)
if isinstance(handler_instance, RightsHandler):
self.rights = handler_instance
if handler_instance not in self.handlers:
self.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 cmd(self, command, args, prefix=None):
""" Sends a command to the server. :param command: IRC code to send. :type command: unicode :param args: arguments to ... |
if prefix is None:
prefix = u''
raw_cmd = u'{0} {1} {2}'.format(prefix, command, args).strip()
self._send(raw_cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ctcp_reply(self, command, dst, message=None):
""" Sends a reply to a CTCP request. :param command: CTCP command to use. :type command: str :param dst: sender... |
if message is None:
raw_cmd = u'\x01{0}\x01'.format(command)
else:
raw_cmd = u'\x01{0} {1}\x01'.format(command, message)
self.notice(dst, raw_cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def msg(self, target, msg):
""" Sends a message to an user or channel. :param target: user or channel to send to. :type target: str :param msg: message to send. ... |
self.cmd(u'PRIVMSG', u'{0} :{1}'.format(target, msg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notice(self, target, msg):
""" Sends a NOTICE to an user or channel. :param target: user or channel to send to. :type target: str :param msg: message to send... |
self.cmd(u'NOTICE', u'{0} :{1}'.format(target, msg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def siget(fullname=""):
"""Returns a softimage object given its fullname.""" |
fullname = str(fullname)
if not len(fullname):
return None
return sidict.GetObject(fullname, 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 cmd_wrapper(cmd_name, **kwds):
"""Wrap and execute a softimage command accepting named arguments""" |
cmd = si.Commands(cmd_name)
if not cmd:
raise Exception(cmd_name + " doesnt found!")
for arg in cmd.Arguments:
value = kwds.get(arg.Name)
if value:
arg.Value = value
return cmd.Execute() |
<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_logger(middleware_settings):
""" Creates a logger using the given settings. """ |
if django_settings.DEBUG:
level = logging.DEBUG
formatter = logging.Formatter(
middleware_settings['LOGGER_FORMAT_DEBUG'])
else:
level = middleware_settings['LOGGER_LEVEL']
formatter = logging.Formatter(middleware_settings['LOGGER_FORMAT'])
handler = logging.Str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def press(*keys):
""" Simulates a key-press for all the keys passed to the function :param keys: list of keys to be pressed :return: None """ |
for key in keys:
win32api.keybd_event(codes[key], 0, 0, 0)
release(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 hold(*keys, hold_time = 0, hold_while = None):
""" Simulates the holding of all the keys passed to the function These keys are held down for a default period... |
for key in keys:
win32api.keybd_event(codes[key], 0, 0, 0)
if callable(hold_while):
while hold_while():
pass
else:
time.sleep(hold_time)
release(*keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(*keys):
""" Simulates the release of all the keys passed to this function :param keys: list of keys to be released :return: None """ |
for key in keys:
win32api.keybd_event(codes[key], 0, win32con.KEYEVENTF_KEYUP, 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_input_value(value):
""" Returns an input value normalized for RightScale API 2.0. This typically means adjusting the *input type* prefix to be one ... |
if value in ('blank', 'ignore', 'inherit'):
return value
# assume any unspecified or unknown types are text
tokens = value.split(':')
if (len(tokens) < 2
or tokens[0] not in ('text', 'env', 'cred', 'key', 'array')):
return 'text:%s' % 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 create_stack(self, name):
""" Creates stack if necessary. """ |
deployment = find_exact(self.api.deployments, name=name)
if not deployment:
try:
# TODO: replace when python-rightscale handles non-json
self.api.client.post(
'/api/deployments',
data={'deployment[name]': 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 set_features_types_from_dataframe(self, data_frame):
""" Sets the features types from the given data_frame. All the calls except the first one are ignored. "... |
if self.__feature_types_set:
return
self.__feature_types_set = True
dtypes = data_frame.dtypes
for feature in self.__iter__():
name = feature.get_name()
type_name = data_type_to_type_name(dtypes[name])
feature.set_type_name(type_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 handle_api_error(resp):
"""Stolen straight from the Stripe Python source.""" |
content = yield resp.json()
headers = HeaderWrapper(resp.headers)
try:
err = content['error']
except (KeyError, TypeError):
raise error.APIError(
"Invalid response object from API: %r (HTTP response code "
"was %d)" % (content, resp.code),
resp, res... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5):
'''Return the point between two points on N dimensions.
'''
assert isinstance(a, tuple)
assert isinstance(b, tuple)
l_pt = len(a)
assert l_pt > 1
assert l_pt == len(b)
for i in a:
assert isinstance(i, float)
for i in 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 pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)):
'''Return given point rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(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 pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)):
'''Return given points rotated around a center point in N dimensions.
Angle is list of rotation in radians for each pair of axis.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert 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 pt_scale(pt=(0.0, 0.0), f=1.0):
'''Return given point scaled by factor f from origin.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(f, float)
return tuple([pt[i]*f for i in range(l_pt)]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.