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 Msg(validator, message):
""" Wraps the given validator callable, replacing any error messages raised. """ |
@wraps(Msg)
def built(value):
try:
return validator(value)
except Error as e:
e.message = message
raise e
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Default(default):
""" Creates a validator callable that replaces ``None`` with the specified default value. """ |
@wraps(Default)
def built(value):
if value == None:
return default
return value
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Eq(value, message="Not equal to {!s}"):
""" Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified... |
@wraps(Eq)
def built(_value):
if _value != value:
raise Error(message.format(value))
return _value
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Instance(expected, message="Not an instance of {}"):
""" Creates a validator that checks if the given value is an instance of ``expected``. A custom message ... |
@wraps(Instance)
def built(value):
if not isinstance(value, expected):
raise Error(message.format(expected.__name__))
return value
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Coerce(type, message="Not a valid {} value"):
""" Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error ... |
@wraps(Coerce)
def built(value):
try:
return type(value)
except (TypeError, ValueError) as e:
raise Error(message.format(type.__name__))
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def List(validator):
""" Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any ... |
@wraps(List)
def built(value):
if not hasattr(value, '__iter__'):
raise Error("Must be a list")
invalid = Invalid()
for i, item in enumerate(value):
try:
value[i] = validator(item)
except Invalid as e:
for error in e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"):
""" Creates a validator that checks if the given numeri... |
@wraps(Range)
def built(value):
if not isinstance(value, numbers.Number) or isinstance(value, bool):
raise Error("Not a number")
if min is not None and min > value:
raise Error(min_message.format(min=min, max=max))
if max is not None and value > max:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def NotEmpty():
""" Creates a validator that validates the given string is not empty. Will raise an error for non-string types. """ |
@wraps(NotEmpty)
def built(value):
if not isinstance(value, six.string_types) or not value:
raise Error("Must not be empty")
return value
return built |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Uuid(to_uuid=True):
""" Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an insta... |
@wraps(Uuid)
def built(value):
invalid = Error("Not a valid UUID")
if isinstance(value, uuid.UUID):
return value
elif not isinstance(value, six.string_types):
raise invalid
try:
as_uuid = uuid.UUID(value)
except (ValueError, Attribut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def counterpart_found(string, counterpart, options, rc_so_far):
"""The sunny-day action is to echo the counterpart to stdout. :param string: The lookup string (U... |
format = "%s" if options.no_newline else "%s\n"
sys.stdout.write(format % (counterpart))
return rc_so_far or 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 no_counterpart_found(string, options, rc_so_far):
"""Takes action determined by options.else_action. Unless told to raise an exception, this function returns... |
logger.debug("options.else_action: %s", options.else_action)
if options.else_action == "passthrough":
format_list = [string]
output_fd = sys.stdout
elif options.else_action == "exception":
raise KeyError("No counterpart found for: %s" % (string))
elif options.else_action == "err... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_input(options):
"""First send strings from any given file, one string per line, sends any strings provided on the command line. :param options: Arg... |
if options.input:
fp = open(options.input) if options.input != "-" else sys.stdin
for string in fp.readlines():
yield string
if options.strings:
for string in options.strings:
yield string |
<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_options(this_class, argparser):
"""This class method is called so that ConfigFromFile can tell the command-line parser to register the options speci... |
default_path = this_class.rc_file_basename
default_basename = os.path.basename(default_path)
argparser.add_argument('-c', "--config-file",
default=default_path,
help=("Configuration file to use for lookups " +
... |
<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_and_handle_includes(self, from_file):
"""Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that... |
logger.debug("Check/handle includes from %s", from_file)
try:
paths = self._parser.get("INCLUDE", "paths")
except (config_parser.NoSectionError,
config_parser.NoOptionError) as exc:
logger.debug("_check_and_handle_includes: EXCEPTION: %s", exc)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_imports(script):
"""Extract all imports from a python script""" |
if not os.path.isfile(script):
raise ValueError('Not a file: %s' % script)
parse_tree = parse_python(script)
result = find_imports(parse_tree)
result.path = script
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_counts( fns, define_sample_name=None, ):
""" Combine featureCounts output files for multiple samples. Parameters fns : list of strings Filenames of f... |
counts = []
for fn in fns:
df = pd.read_table(fn, skiprows=1, index_col=0)
counts.append(df[df.columns[-1]])
combined_counts = pd.DataFrame(counts).T
if define_sample_name:
names = [define_sample_name(x) for x in fns]
combined_counts.columns = names
combined_counts.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 add_to_inventory(self):
"""Adds this server and its hostvars to the ansible inventory.""" |
self.stack.add_host(self.hostname, self.groups, self.hostvars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_all(a, b):
"""\ Asserts that two iterables contain the same values. """ |
assert all(_a == _b for _a, _b in zip_longest(a, 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 coroutine(func):
""" A decorator to wrap a generator function into a callable interface. 2 5 Traceback (most recent call last):
StopIteration As you can see... |
def decorator(*args, **kwargs):
generator = func(*args, **kwargs)
next(generator)
return lambda *args: generator.send(args)
return decorator |
<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_entity(self, entity, second=False):
''' Add entity to world.
entity is of type Entity
'''
if not entity in self._entities:
if second:
self._entities.append(entity)
else:
entity.set_world(self)
else:
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 register_entity_to_group(self, entity, group):
'''
Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group
'''
if entity in self._entities:
if gro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deregister_entity_from_group(self, entity, group):
'''
Removes entity from group
'''
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_entity(self, entity, second=False):
'''
Removes entity from world and kills entity
'''
if entity in self._entities:
if second:
for group in self._groups.keys():
if entity in self._groups[group]:
self.dereg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
else:
raise UnmanagedSystemError(system) |
<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_by_tag(self, tag):
'''
Get entity by tag
tag is a string that is the tag of the Entity.
'''
matching_entities = list(filter(lambda entity: entity.get_tag() == tag,
self._entities))
if matching_entities:
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_entities_by_components(self, *components):
'''
Get entity by list of components
All members of components must be of type Component
'''
return list(filter(lambda entity:
set(components) <=
set(map(type, entity.get_comp... |
<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_world(self, world):
'''
Sets the world an entity belongs to.
Checks for tag conflicts before adding.
'''
if world.get_entity_by_tag(self._tag) and self._tag != '':
raise NonUniqueTagError(self._tag)
else:
self._world = world
wor... |
<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_tag(self, tag):
'''
Sets the tag.
If the Entity belongs to the world it will check for tag conflicts.
'''
if self._world:
if self._world.get_entity_by_tag(tag):
raise NonUniqueTagError(tag)
self._tag = tag |
<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_component(self, component):
'''
Adds a Component to an Entity
'''
if component not in self._components:
self._components.append(component)
else: # Replace Component
self._components[self._components.index(component)] = component |
<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_component(self, component_type):
'''
Gets component of component_type or returns None
'''
matching_components = list(filter(lambda component:
isinstance(component,
component_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 write_quota(outbytes: int, outfn: Path) -> Union[None, int]: """ aborts writing if not enough space on drive to write """ |
if not outfn:
return None
anch = Path(outfn).resolve().anchor
freeout = shutil.disk_usage(anch).free
if freeout < 10 * outbytes:
raise IOError(f'out of disk space on {anch}.'
'{freeout/1e9} GB free, wanting to write {outbytes/1e9} GB.')
return freeout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray: """ scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: len... |
Q = normframe(I, Clim)
Q *= 255 # stretch to [0,255] as a float
return Q.round().astype(np.uint8) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def req2frame(req, N: int=0):
""" output has to be numpy.arange for > comparison """ |
if req is None:
frame = np.arange(N, dtype=np.int64)
elif isinstance(req, int): # the user is specifying a step size
frame = np.arange(0, N, req, dtype=np.int64)
elif len(req) == 1:
frame = np.arange(0, N, req[0], dtype=np.int64)
elif len(req) == 2:
frame = np.arange(re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def imgwriteincr(fn: Path, imgs, imgslice):
""" writes HDF5 huge image files in increments """ |
if isinstance(imgslice, int):
if imgslice and not (imgslice % 2000):
print(f'appending images {imgslice} to {fn}')
if isinstance(fn, Path):
# avoid accidental overwriting of source file due to misspecified command line
assert fn.suffix == '.h5', 'Expecting to write .h5 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 safe_dump_js(js, abspath, fastmode=False, compress=False, enable_verbose=True):
"""A stable version of dump_js, silently overwrite existing file. When your p... |
abspath = str(abspath) # try stringlize
temp_abspath = "%s.tmp" % abspath
dump_js(js, temp_abspath, fastmode=fastmode,
replace=True, compress=compress, enable_verbose=enable_verbose)
shutil.move(temp_abspath, abspath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate_constituencies(apps, schema_editor):
""" Re-save constituencies to recompute fingerprints """ |
Constituency = apps.get_model("representatives", "Constituency")
for c in Constituency.objects.all():
c.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def treeprint(data, render_only=False, file=None, **options):
""" Render a tree structure based on generic python containers. The keys should be titles and the v... |
def getiter(obj):
if isinstance(obj, collections.abc.Mapping):
return obj.items()
elif (isinstance(obj, collections.abc.Iterable) and
not isinstance(obj, str)):
return enumerate(obj)
def cycle_check(item, seen=set()):
item_id = id(item)
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 terminal_size(self):
"""Gets the terminal columns size.""" |
try:
_, columns = os.popen('stty size', 'r').read().split()
return min(int(columns) - 10, 100)
except ValueError:
return self.default_terminal_size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bar(self, progress):
"""Shows on the stdout the progress bar for the given progress.""" |
if not hasattr(self, "_limit") or not self._limit:
self._limit = self.terminal_size()
graph_progress = int(progress * self._limit)
self.stdout.write('\r', ending='')
progress_format = "[%-{}s] %d%%".format(self._limit)
self.stdout.write(
self.style.SUCCES... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _Execute(self, options):
"""Handles security groups operations.""" |
whitelist = dict(
name=options["name"],
description=options.get("description", "<empty>"))
return self._agent.client.compute.security_groups.create(**whitelist) |
<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_args(args):
""" Load a config file. Merges CLI args and validates. """ |
config = kaptan.Kaptan(handler='yaml')
conf_parent = os.path.expanduser('~')
conf_app = '.clancy'
conf_filename = 'config.yaml'
conf_dir = os.path.join(conf_parent, conf_app)
for loc in [os.curdir, conf_dir]:
configpath = os.path.join(loc, conf_filename)
try:
if 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 get_default_language(language_code=None):
""" Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Ret... |
if not language_code:
language_code = settings.LANGUAGE_CODE
languages = dict(settings.LANGUAGES).keys()
# first try if there is an exact language
if language_code in languages:
return language_code
# otherwise split the language code if possible, so iso3
language_code = lan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_method(self, docstring=""):
""" Converts this action to a function or method. An optional docstring may be passed. """ |
method = lambda obj, *args, **kwargs: self(obj, *args, **kwargs)
if docstring:
method.__doc__ = docstring
return method |
<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(self, rawtitle):
"""Create a page with this title, if it doesn't exist. This method first checks whether a page with the same slug (sanitized name) e... |
slug = util.make_slug(rawtitle)
if self.site.page_exists_on_disk(slug):
raise ValueError
#print "Attempted to create a page which already exists."
#return False
self._title = unicode(rawtitle,"UTF-8")
self._slug = slug
self._dirs['source_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 write(self):
"""Write the s2 page to the corresponding source file. It always writes the (serialized) config first, and then the content (normally markdown).... |
if not os.path.isdir(self._dirs['source_dir']):
os.mkdir(self._dirs['source_dir'])
fout = codecs.open(self._dirs['source_filename'], 'w', encoding="utf-8", errors="xmlcharrefreplace")
fout.write(self._config_to_text())
if self._content:
fout.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 rename(self, new_title):
"""Rename an existing s2 page. For an existing s2 page, updates the directory and file name, as well as the internal configuration i... |
if not isinstance(new_title, str) and \
not isinstance(new_title, unicode):
raise TypeError
# print "Cannot rename page. New title must be string or unicode."
new_slug = util.make_slug(new_title)
if self.site.page_exists_on_disk(new_slug):
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self):
"""Render this page and return the rendition. Converts the markdown content to html, and then renders the (mako) template specified in the conf... |
(pthemedir, ptemplatefname) = self._theme_and_template_fp()
mylookup = TemplateLookup(directories=[self.site.dirs['s2'], pthemedir], input_encoding='utf-8', output_encoding='utf-8')
makotemplate = Template(filename=ptemplatefname, lookup=mylookup,
module_direc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self):
"""Generate the page html file. Just open the destination file for writing and write the result of rendering this page. """ |
generated_content = ''
if 'published' in (self._config['status'][0]).lower():
if os.path.isdir(self.dirs['www_dir']):
shutil.rmtree(self.dirs['www_dir'])
os.mkdir(self.dirs['www_dir'])
# copy the whole source directory of the page,
# exclu... |
<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(self):
"""Create the default configuration dictionary for this page.""" |
configinfo = {'creation_date': [ datetime.datetime.now().date().isoformat()],
'author': [self.site.site_config['default_author']],
'status': [u'draft'],
'lang': [u''],
'tags': [u''],
'title': [self._ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load(self, slug):
"""Load the page. The _file_name param is known, because this method is only called after having checked that the page exists. """ |
#here we know that the slug exists
self._slug = slug
page_dir = os.path.join(self.site.dirs['source'], self._slug)
page_file_name = os.path.join(page_dir, self._slug + '.md')
self._dirs['source_dir'] = page_dir
self._dirs['source_filename'] = page_file_name
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 _check_config(self):
"""Verify that the configuration is correct.""" |
required_data = ['creation_date',
'author',
'status',
'lang',
'tags',
'title',
'slug',
'theme',
'template',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _theme_and_template_fp(self):
"""Return the full paths for theme and template in this page""" |
ptheme = self._config['theme'][0]
if ptheme == "":
ptheme = self.site.site_config['default_theme']
pthemedir = os.path.join(self.site.dirs['themes'], ptheme)
ptemplate = self._config['template'][0]
if ptemplate == "":
ptemplate = self.site.site_config['de... |
<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_text(self, page_text):
"""Extract the s2config and the content from the raw page text.""" |
# 1 sanitize: remove leading blank lines
# 2 separate "config text" from content, store content
# 3 convert config text + \n to obtain Meta, this is the config.
lines = page_text.split('\n')
i = 0
while lines[i].strip() == '':
i += 1
if i > 0: # i 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 _config_to_text(self):
"""Render the configuration as text.""" |
r = u'' # unicode('',"UTF-8")
for k in self._config:
# if k == 'creation_date':
# r += k + ": " + self._config[k][0] + '\n'
# else:
#uk = unicode(k,"UTF-8")
cosa = '\n '.join(self._config[k]) + '\n'
r += k + ": " + cosa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def author(self):
"""Return the full path of the theme used by this page.""" |
r = self.site.site_config['default_author']
if 'author' in self._config:
r = self._config['author']
return 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 memoize(method):
"""A new method which acts like the given method but memoizes arguments See https://en.wikipedia.org/wiki/Memoization for the general idea c... |
method.cache = {}
def invalidate(*arguments, **keyword_arguments):
key = _represent_arguments(*arguments, **keyword_arguments)
if not key:
method.cache = {}
elif key in method.cache:
del method.cache[key]
else:
raise KeyError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(method):
"""Decorator to debug the given method""" |
def new_method(*args, **kwargs):
import pdb
try:
import pudb
except ImportError:
pudb = pdb
try:
pudb.runcall(method, *args, **kwargs)
except pdb.bdb.BdbQuit:
sys.exit('Normal quit from debugger')
new_method.__doc__ = metho... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def globber(main_method, globs):
"""Recognise globs in args""" |
import os
from glob import glob
def main(arguments):
lists_of_paths = [_ for _ in arguments if glob(pathname, recursive=True)]
return main_method(arguments, lists_of_paths)
return main |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dispatch_trigger(self, msg):
""" Dispatches the message to the corresponding method. """ |
if not msg.args[0].startswith(self.trigger_char):
return
split_args = msg.args[0].split()
trigger = split_args[0].lstrip(self.trigger_char)
if trigger in self.triggers:
method = getattr(self, trigger)
if msg.command == PRIVMSG:
if 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 set_restriction(self, command, user, event_types):
""" Adds restriction for given `command`. :param command: command on which the restriction should be set. ... |
self.commands_rights[command][user.lower()] = event_types
if command not in self.triggers:
self.triggers[command] = [EVT_PUBLIC, EVT_PRIVATE, EVT_NOTICE]
if not hasattr(self, command):
setattr(self, command, lambda msg: self.handle_rights(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 del_restriction(self, command, user, event_types):
""" Removes restriction for given `command`. :param command: command on which the restriction should be re... |
if user.lower() in self.commands_rights[command]:
for event_type in event_types:
try:
self.commands_rights[command][user.lower()].remove(event_type)
except ValueError:
pass
if not self.commands_rights[command][user.... |
<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_rights(self, msg):
""" Catch-all command that is called whenever a restricted command is triggered. :param msg: message that triggered the command. :t... |
command = msg.args[0][1:]
if command in self.commands_rights:
if msg.src.name.lower() in self.commands_rights[command]:
if msg.event not in self.commands_rights[command][msg.src.name.lower()]:
msg.propagate = False
elif '*' in self.commands_ri... |
<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_inclusions(item, included=[], excluded=[]):
"""Everything passes if both are empty, otherwise, we have to check if \ empty or is present.""" |
if (len(included) == 0):
if len(excluded) == 0 or item not in excluded:
return True
else:
return False
else:
if item in included:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toto(arch_name, comment='', clear=False, read_comment=False, list_members=False, time_show=False):
""" Small utility for changing comment in a zip file witho... |
if comment and clear:
clingon.RunnerError("You cannot specify --comment and --clear together")
z = None
# if archive does not exist, create it with up to 3 files from current directory
if not os.path.isfile(arch_name):
print "Creating archive", arch_name
z = zipfile.ZipFile(arch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, data, verbose, color, format, editor):
"""Query a meetup database. """ |
ctx.obj['verbose'] = verbose
if verbose:
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
ctx.obj['datadir'] = os.path.abspath(data)
if 'db' not in ctx.obj:
ctx.obj['db'] = get_db(data)
if color is None:
ctx.obj['t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_file_iterator(self, file_obj):
""" For given `file_obj` return iterator, which will read the file in `self.read_bs` chunks. Args: file_obj (file):
File... |
file_obj.seek(0)
return iter(lambda: file_obj.read(self.read_bs), '') |
<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_hash(self, file_obj):
""" Compute hash for the `file_obj`. Attr: file_obj (obj):
File-like object with ``.write()`` and ``.seek()``. Returns: str: Hexd... |
size = 0
hash_buider = self.hash_builder()
for piece in self._get_file_iterator(file_obj):
hash_buider.update(piece)
size += len(piece)
file_obj.seek(0)
return "%s_%x" % (hash_buider.hexdigest(), size) |
<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_dir_path(self, file_hash, path=None, hash_list=None):
""" Create proper filesystem paths for given `file_hash`. Args: file_hash (str):
Hash of the f... |
# first, non-recursive call - parse `file_hash`
if hash_list is None:
hash_list = list(file_hash)
if not hash_list:
raise IOError("Directory structure is too full!")
# first, non-recursive call - look for subpath of `self.path`
if not 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 file_path_from_hash(self, file_hash, path=None, hash_list=None):
""" For given `file_hash`, return path on filesystem. Args: file_hash (str):
Hash of the fi... |
# first, non-recursive call - parse `file_hash`
if hash_list is None:
hash_list = list(file_hash)
if not hash_list:
raise IOError("Directory structure is too full!")
# first, non-recursive call - look for subpath of `self.path`
if not 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 add_file(self, file_obj):
""" Add new file into the storage. Args: file_obj (file):
Opened file-like object. Returns: obj: Path where the file-like object i... |
BalancedDiscStorage._check_interface(file_obj)
file_hash = self._get_hash(file_obj)
dir_path = self._create_dir_path(file_hash)
final_path = os.path.join(dir_path, file_hash)
def copy_to_file(from_file, to_path):
with open(to_path, "wb") as out_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 _recursive_remove_blank_dirs(self, path):
""" Make sure, that blank directories are removed from the storage. Args: path (str):
Path which you suspect that ... |
path = os.path.abspath(path)
# never delete root of the storage or smaller paths
if path == self.path or len(path) <= len(self.path):
return
# if the path doesn't exists, go one level upper
if not os.path.exists(path):
return self._recursive_remove_blan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pseudolocalize(self, s):
""" Performs pseudo-localization on a string. The specific transforms to be applied to the string is defined in the transforms field... |
if not s: # If the string is empty or None
return u""
if not isinstance(s, six.text_type):
raise TypeError("String to pseudo-localize must be of type '{0}'.".format(six.text_type.__name__))
# If no transforms are defined, return the string as-is.
if not self.tra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pseudolocalizefile(self, input_filename, output_filename, input_encoding='UTF-8', output_encoding='UTF-8', overwrite_existing=True):
""" Method for pseudo-lo... |
leading_trailing_double_quotes = re.compile(r'^"|"$')
if not os.path.isfile(input_filename):
raise IOError("Input message catalog not found: {0}".format(os.path.abspath(input_filename)))
if os.path.isfile(output_filename) and not overwrite_existing:
raise IOError("Error,... |
<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_quantities(d, coords=None, massE=0.511e6):
'''
Add physically interesting quantities to
pext data.
Parameters:
-----------
d : pext array
Keywords:
---------
coords : sequence of positions for angle calculation. None
or by default, calculate no angle... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calc_quantities(d, coords=None, massE=0.511e6):
'''
Calculate physically interesting quantities from pext
Parameters:
-----------
d : pext array
Keywords:
---------
coords : sequence of positions for angle calculation. None
or by default, calculate no angles... |
<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_server(initialize=True):
"""Create a server""" |
with provider() as p:
host_string = p.create_server()
if initialize:
env.host_string = host_string
initialize_server() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, list_id):
""" Retrieve the list given for the user. """ |
r = requests.get(
"https://kippt.com/api/users/%s/lists/%s" % (self.id, list_id),
headers=self.kippt.header
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relationship(self):
""" Retrieve what the relationship between the user and then authenticated user is. """ |
r = requests.get(
"https://kippt.com/api/users/%s/relationship" % (self.id),
headers=self.kippt.header
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_titles(self, row_index, column_index):
'''
Helper method to find all titles for a particular cell.
'''
titles = []
for column_search in range(self.start[1], column_index):
cell = self.table[row_index][column_search]
if cell == None or (isinstanc... |
<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_raw_block(self):
'''
Copies the block as it was originally specified by start and end into a new table.
Returns:
A copy of the block with no block transformations.
'''
ctable = []
r, c = 0, 0
try:
for row_index in range(self.start... |
<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_numbered_block(self):
'''
Copies the block as it was originally specified by start and end into a new table.
Additionally inserts the original table indices in the first row of the block.
Returns:
A copy of the block with no block transformations.
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def convert_to_row_table(self, add_units=True):
'''
Converts the block into row titled elements. These elements are copied into the return
table, which can be much longer than the original block.
Args:
add_units: Indicates if units should be appened to each row item.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flag_is_related(self, flag):
'''
Checks for relationship between a flag and this block.
Returns:
True if the flag is related to this block.
'''
same_worksheet = flag.worksheet == self.worksheet
if isinstance(flag.location, (tuple, list)):
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unit_is_related(self, location, worksheet):
'''
Checks for relationship between a unit location and this block.
Returns:
True if the location is related to this block.
'''
same_worksheet = worksheet == self.worksheet
if isinstance(location, (tuple, list))... |
<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_relavent_flags(self):
'''
Retrieves the relevant flags for this data block.
Returns:
All flags related to this block.
'''
relavent_flags = {}
for code, flags_list in self.flags.items():
relavent_flags[code] = []
for flag in 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 get_relavent_units(self):
'''
Retrieves the relevant units for this data block.
Returns:
All flags related to this block.
'''
relavent_units = {}
for location,unit in self.units.items():
if self.unit_is_related(location, self.worksheet):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_block(self):
'''
This method is a multi-stage process which repairs row titles, then repairs column titles,
then checks for invalid rows, and finally for invalid columns.
This maybe should have been written via state machines... Also suggested as being possibly
writ... |
<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_zero_size(self):
'''
Checks for zero height or zero width blocks and flags the occurrence.
Returns:
True if the block is size 0.
'''
block_zero = self.end[0] <= self.start[0] or self.end[1] <= self.start[1]
if block_zero:
self.flag_chan... |
<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_one_size(self):
'''
Checks for single height or single width blocks and flags the occurrence.
Returns:
True if the block is size 1.
'''
block_one = self.end[0] == self.start[0]+1 or self.end[1] == self.start[1]+1
if block_one:
self.flag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _repair_row(self):
'''
Searches for missing titles that can be inferred from the surrounding data and automatically
repairs those titles.
'''
# Repair any title rows
check_for_title = True
for row_index in range(self.start[0], self.end[0]):
table_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 _repair_column(self):
'''
Same as _repair_row but for columns.
'''
# Repair any title columns
check_for_title = True
for column_index in range(self.start[1], self.end[1]):
table_column = TableTranspose(self.table)[column_index]
column_start = t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _fill_row_holes(self):
'''
Fill any remaining row title cells that are empty. This must be done after the other passes
to avoid preemptively filling in empty cells reserved for other operations.
'''
for row_index in range(self.start[0], self.max_title_row):
table_... |
<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_column_holes(self):
'''
Same as _fill_row_holes but for columns.
'''
for column_index in range(self.start[1], self.end[1]):
table_column = TableTranspose(self.table)[column_index]
column_start = table_column[self.start[0]]
if is_text_cell(col... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _validate_rows(self):
'''
Checks for any missing data row by row. It also checks for changes in cell type and flags
multiple switches as an error.
'''
for row_index in range(self.start[0], self.end[0]):
table_row = self.table[row_index]
used_row = 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 _validate_columns(self):
'''
Same as _validate_rows but for columns. Also ignore used_cells as _validate_rows should
update used_cells.
'''
for column_index in range(self.start[1], self.end[1]):
table_column = TableTranspose(self.table)[column_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 _stringify_row(self, row_index):
'''
Stringifies an entire row, filling in blanks with prior titles as they are found.
'''
table_row = self.table[row_index]
prior_cell = None
for column_index in range(self.start[1], self.end[1]):
cell, changed = self._chec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _stringify_column(self, column_index):
'''
Same as _stringify_row but for columns.
'''
table_column = TableTranspose(self.table)[column_index]
prior_cell = None
for row_index in range(self.start[0], self.end[0]):
cell, changed = self._check_interpret_cell(... |
<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_interpret_cell(self, cell, prior_cell, row_index, column_index):
'''
Helper function which checks cell type and performs cell translation to strings where
necessary.
Returns:
A tuple of the form '(cell, changed)' where 'changed' indicates if 'cell' differs from
... |
<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_fill_title_row(self, row_index):
'''
Checks the given row to see if it is all titles and fills any blanks cells if that is the
case.
'''
table_row = self.table[row_index]
# Determine if the whole row is titles
prior_row = self.table[row_index-1] if row_... |
<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_fill_title_column(self, column_index):
'''
Same as _check_fill_title_row but for columns.
'''
# Determine if the whole column is titles
table_column = TableTranspose(self.table)[column_index]
prior_column = TableTranspose(self.table)[column_index-1] if column_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.