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 choose(self, versions, conflict='silent'): """ Choose the highest version in the range. :param versions: Iterable of available versions. """
assert conflict in ('silent', 'warning', 'error') if not versions: raise VersionRangeMismatch('No versions to choose from') version_map = {} for version in versions: version_map[version] = str2nr(version, mx=self.limit) top_version, top_nr = None, 0 """ Try to find the highest value in range. """ 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 is_slice_or_dim_range_request(key, depth=0): ''' Checks if a particular key is a slice, DimensionRange or list of those types ''' # Slice, DimensionRange, or list of those elements return (is_slice_or_dim_range(key) or # Don't check more than the first depth (depth ==...
<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_restricted_index(index, length, length_index_allowed=True): ''' Converts negative indices to positive ones and indices above length to length or length-1 depending on lengthAllowed. ''' if index and index >= length: index = length if length_index_allowed else length-1 return get_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def slice_on_length(self, data_len, *addSlices): ''' Returns a slice representing the dimension range restrictions applied to a list of length data_len. If addSlices contains additional slice requirements, they are processed in the order they are given. ''' if le...
<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_ranges_on_length(self, data_len, first, second): ''' Combines a first range with a second range, where the second range is considered within the scope of the first. ''' first = get_true_slice(first, data_len) second = get_true_slice(second, data_len) ...
<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_lists_of_ranges_on_length(self, data_len, first, *range_list): ''' Combines an arbitrary length list of ranges into a single slice. ''' current_range = first for next_range in range_list: current_range = self._combine_ranges_on_length(data_len, current_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 _get_single_depth(self, multi_index): ''' Helper method for determining how many single index entries there are in a particular multi-index ''' single_depth = 0 for subind in multi_index: if is_slice_or_dim_range(subind): break ...
<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_splice(self, slice_ind): ''' Creates a splice size version of the ZeroList ''' step_size = slice_ind.step if slice_ind.step else 1 # Check for each of the four possible scenarios if slice_ind.start != None: if slice_ind.stop != None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, update_site=False, *args, **kwargs): """ Set the site to the current site when the record is first created, or the ``update_site`` argument is exp...
if update_site or (self.id is None and self.site_id is None): self.site_id = current_site_id() super(SiteRelated, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """ Set the description field on save. """
if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """
description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not description: for field in self._meta.fields: if (isinstance(field, field_type) 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 save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created...
if self.publish_date is None: self.publish_date = now() super(Displayable, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_short_url(self): """ Generates the ``short_url`` attribute if the model does not already have one. Used by the ``set_short_url_for`` template tag and ``T...
if self.short_url == SHORT_URL_UNSET: self.short_url = self.get_absolute_url_with_host() elif not self.short_url: self.short_url = self.generate_short_url() self.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 generate_short_url(self): """ Returns a new short URL generated using bit.ly if credentials for the service have been specified. """
from yacms.conf import settings if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ "access_token": settings.BITLY_ACCESS_TOKEN, "uri": self.get_absolute_url_with_host(), }) response = loads(urlop...
<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_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead o...
arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next else "-publish_date" lookup = {arg: self.publish_date} concrete_model = base_concrete_model(Displayable, self) try: queryset = concrete_model.objects.published excep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_respect_to(self): """ Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided...
try: name = self.order_with_respect_to value = getattr(self, name) except AttributeError: # No ``order_with_respect_to`` specified on the model. return {} # Support for generic relations. field = getattr(self.__class__, name) if is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """ Set the initial ordering value. """
if self._order is None: lookup = self.with_respect_to() lookup["_order__isnull"] = False concrete_model = base_concrete_model(Orderable, self) self._order = concrete_model.objects.filter(**lookup).count() super(Orderable, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, *args, **kwargs): """ Update the ordering values for siblings. """
lookup = self.with_respect_to() lookup["_order__gte"] = self._order concrete_model = base_concrete_model(Orderable, self) after = concrete_model.objects.filter(**lookup) after.update(_order=models.F("_order") - 1) super(Orderable, self).delete(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so ...
lookup = self.with_respect_to() lookup["_order"] = self._order + (1 if is_next else -1) concrete_model = base_concrete_model(Orderable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.filter ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_editable(self, request): """ Restrict in-line editing to the objects's owner and superusers. """
return request.user.is_superuser or request.user.id == self.user_id
<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_content_models(cls): """ Return all subclasses of the concrete model. """
concrete_model = base_concrete_model(ContentTyped, cls) return [m for m in apps.get_models() if m is not concrete_model and issubclass(m, concrete_model)]
<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_content_model(self): """ Set content_model to the child class's related name, or None if this is the base class. """
if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.content_model = ( None if is_base_class else self.get_content_model_name())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """
new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.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 read_yaml(filename, add_constructor=None): ''' Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util...
<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_yaml(filename, content): ''' Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written ''' y = _yaml.dump(content, indent=4, default_flow_style=False) if y: return write_fil...
<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_json(filename, content): ''' Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written ''' j = _dumps(content, indent=4, sort_keys=True) if j: return write_file(filename, j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K bloc...
# load modules import numpy as np # minimum block size: bz=int(N/K) blocksize = int(numdraws / numblocks) # shuffle vector indicies: from 0 to N-1 if random_state: np.random.seed(random_state) obsidx = np.random.permutation(numdraws) # how many to drop? i.e. "numdrop = N - bz...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_cell_table(self, merged=True): """Returns a list of lists of Cells with the cooked value and note for each cell."""
new_rows = [] for row_index, row in enumerate(self.rows(CellMode.cooked)): new_row = [] for col_index, cell_value in enumerate(row): new_row.append(Cell(cell_value, self.get_note((col_index, row_index)))) new_rows.append(new_row) if merged: for cell_low, cell_high in self.me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rows(self, cell_mode=CellMode.cooked): """Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument. "...
for row_index in range(self.nrows): yield self.parse_row(self.get_row(row_index), row_index, cell_mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode."""
return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(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 tuple_to_datetime(self, date_tuple): """Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a ...
year, month, day, hour, minute, second = date_tuple if year == month == day == 0: return time(hour, minute, second) elif hour == minute == second == 0: return date(year, month, day) else: return datetime(year, month, day, hour, minute, second)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sheets(self, index=None): """Return either a list of all sheets if index is None, or the sheet at the given index."""
if self._sheets is None: self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())] if index is None: return self._sheets else: return self._sheets[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 get_fortunes_path(): """Return the path to the fortunes data packs. """
app_config = apps.get_app_config("fortune") return Path(os.sep.join([app_config.path, "fortunes"]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` ...
fields = OrderedDict() try: profile = get_profile_for_user(user) user_fieldname = get_profile_user_fieldname() exclude = tuple(settings.ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS) for field in profile._meta.fields: if field.name not in ("id", user_fieldname) + exclude: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def username_or(user, attr): """ Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``. """
if not settings.ACCOUNTS_NO_USERNAME: attr = "username" value = getattr(user, attr) if callable(value): value = 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 process_tarball(tarball, output_directory=None, context=False): """Process one tarball end-to-end. If output directory is given, the tarball will be extracte...
if not output_directory: # No directory given, so we use the same path as the tarball output_directory = os.path.abspath("{0}_files".format(tarball)) extracted_files_list = untar(tarball, output_directory) image_list, tex_files = detect_images_and_tex(extracted_files_list) if tex_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 map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources."""
extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images partly_extracted_image_data = extract_captions( tex_file, output_directory, image_mapping.keys() ) if partly_extracted_imag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addconfig(config, *paths): """Add path to CONF_DIRS if exists."""
for path in paths: if path is not None and exists(path): config.append(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 create(url, filename): """Create new fMRI for given experiment by uploading local file. Expects an tar-archive. Parameters url : string Url to POST fMRI crea...
# Upload file to create fMRI resource. If response is not 201 the # uploaded file is not a valid functional data archive files = {'file': open(filename, 'rb')} response = requests.post(url, files=files) if response.status_code != 201: raise ValueError('invalid 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 get(self, user_name: str) -> User: """ Gets the User Resource. """
user = current_user() if user.is_admin or user.name == user_name: return self._get_or_abort(user_name) else: abort(403)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, user_name: str) -> User: """ Updates the User Resource with the name. """
current = current_user() if current.name == user_name or current.is_admin: user = self._get_or_abort(user_name) self.update(user) session.commit() session.add(user) return user else: abort(403)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_value(self, value, environment=None): """Resolve the value. Either apply missing or leave the value as is. :param value: the value either from deser...
# here we care about Undefined values if value == values.Undefined: if isinstance(self._missing, type) and issubclass(self._missing, Missing): # instantiate the missing thing missing = self._missing(self, environment) # invoke missing callba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, value, environment=None): """Serialze a value into a transportable and interchangeable format. The default assumption is that the value is JS...
value = self._resolve_value(value, environment) value = self._serialize(value, environment) 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 deserialize(self, value, environment=None): """Deserialize a value into a special application specific format or type. `value` can be `Missing`, `None` or so...
value = self._resolve_value(value, environment) try: value = self._deserialize(value, environment) if self._validator is not None: value = self._validator(self, value, environment) # pylint: disable=E1102 except exc.InvalidValue as ex: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def open(filepath, mode='rb', buffcompress=None): ''' Open a file based on the extension of the file if the filepath ends in .gz then use gzip module's open otherwise use the normal builtin open :param str filepath: Path to .gz or any other file :param str mode: mode to open file :param int...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_exception(exc, uuid=None): """ Serialize an exception into a result :param Exception exc: Exception raised :param str uuid: Current Kafka :class:`kser.t...
if not isinstance(exc, Error): exc = Error(code=500, message=str(exc)) return Result( uuid=exc.extra.get("uuid", uuid or random_uuid()), retcode=exc.code, stderr=exc.message, retval=dict(error=ErrorSchema().dump(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 search_value(self, xpath, default=None, single_value=True): """ Try to find a value in the result :param str xpath: a xpath filter see https://github.com/ken...
matches = [match.value for match in parse(xpath).find(self.retval)] if len(matches) == 0: return default return matches[0] if single_value is True else matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compatible_names(e1, e2): """This function takes either PartitionParts or Mentions as arguments """
if e1.ln() != e2.ln(): return False short, long = list(e1.mns()), e2.mns() if len(short) > len(long): return compatible_names(e2, e1) # the front first names must be compatible if not compatible_name_part(e1.fn(), e2.fn()): return False # try finding each middle 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 sentry_exception (e, request, message = None): """Yes, this eats exceptions"""
try: logtool.log_fault (e, message = message, level = logging.INFO) data = { "task": task, "request": { "args": task.request.args, "callbacks": task.request.callbacks, "called_directly": task.request.called_directly, "correlation_id": task.request.correlation_id, ...
<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_first(self, keys, default=None): """ For given keys, return value for first key that isn't ``None``. If such a key is not found, ``default`` is returned...
d = self.device for k in keys: v = d.get(k) if not v is None: return v return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CheckForeignKeysWrapper(conn): """Migration wrapper that checks foreign keys. Note that this may raise different exceptions depending on the underlying datab...
yield cur = conn.cursor() cur.execute('PRAGMA foreign_key_check') errors = cur.fetchall() if errors: raise ForeignKeyError(errors)
<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_migration(self, migration: 'Migration'): """Register a migration. You can only register migrations in order. For example, you can register migration...
if migration.from_ver >= migration.to_ver: raise ValueError('Migration cannot downgrade verson') if migration.from_ver != self._final_ver: raise ValueError('Cannot register disjoint migration') self._migrations[migration.from_ver] = migration self._final_ver = mi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migration(self, from_ver: int, to_ver: int): """Decorator to create and register a migration. """
def decorator(func): migration = Migration(from_ver, to_ver, func) self.register_migration(migration) return func 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 migrate(self, conn): """Migrate a database as needed. This method is safe to call on an up-to-date database, on an old database, on a newer database, or an u...
while self.should_migrate(conn): current_version = get_user_version(conn) migration = self._get_migration(current_version) assert migration.from_ver == current_version logger.info(f'Migrating database from {migration.from_ver}' f' to {migr...
<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_single(self, conn, migration): """Perform a single migration starting from the given version."""
with contextlib.ExitStack() as stack: for wrapper in self._wrappers: stack.enter_context(wrapper(conn)) migration.func(conn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeService(self, options): """ Construct a Broker Server """
return BrokerService( port=options['port'], debug=options['debug'], activate_ssh_server=options['activate-ssh-server'], ssh_user=options['ssh-user'], ssh_password=options['ssh-password'], ssh_port=options['ssh-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 get_work_item_by_id(self, wi_id): ''' Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None ''' work_items = self.get_work_items(id=wi_id) if work_items is not None: return work_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 package_releases(self, project_name): """ Retrieve the versions from PyPI by ``project_name``. Args: project_name (str): The name of the project we wish to ...
try: return self._connection.package_releases(project_name) except Exception as err: raise PyPIClientError(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 set_package_releases(self, project_name, versions): """ Storage package information in ``self.packages`` Args: project_name (str): This will be used as a th...
self.packages[project_name] = sorted(versions, reverse=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_object(s): """ Load backend by dotted path. """
try: m_path, o_name = s.rsplit('.', 1) except ValueError: raise ImportError('Cant import backend from path: {}'.format(s)) module = import_module(m_path) return getattr(module, o_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 get_available_themes(): """ Iterator on available themes """
for d in settings.TEMPLATE_DIRS: for _d in os.listdir(d): if os.path.isdir(os.path.join(d, _d)) and is_theme_dir(_d): yield _d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_permission(self, request, page, permission): """ Runs the custom permission check and raises an exception if False. """
if not getattr(page, "can_" + permission)(request): raise PermissionDenied
<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_view(self, request, **kwargs): """ For the ``Page`` model, redirect to the add view for the first page model, based on the ``ADD_PAGE_ORDER`` setting. ""...
if self.model is Page: return HttpResponseRedirect(self.get_content_models()[0].add_url) return super(PageAdmin, self).add_view(request, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_view(self, request, object_id, **kwargs): """ Enforce custom permissions for the page instance. """
page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() kwargs.setdefault("extra_context", {}) kwargs["extra_context"].update({ "hide_delete_link": not content_model.can_delete(request), "hide_slug_field": content_model.overridden()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_view(self, request, object_id, **kwargs): """ Enforce custom delete permissions for the page instance. """
page = get_object_or_404(Page, pk=object_id) content_model = page.get_content_model() self.check_permission(request, content_model, "delete") return super(PageAdmin, self).delete_view(request, object_id, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_model(self, request, obj, form, change): """ Set the ID of the parent page if passed in via querystring, and make sure the new slug propagates to all de...
if change and obj._old_slug != obj.slug: # _old_slug was set in PageAdminForm.clean_slug(). new_slug = obj.slug or obj.generate_unique_slug() obj.slug = obj._old_slug obj.set_slug(new_slug) # Force parent to be saved to trigger handling of ordering and 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 _maintain_parent(self, request, response): """ Maintain the parent ID in the querystring for response_add and response_change. """
location = response._headers.get("location") parent = request.GET.get("parent") if parent and location and "?" not in location[1]: url = "%s?parent=%s" % (location[1], parent) return HttpResponseRedirect(url) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_content_models(self): """ Return all Page subclasses that are admin registered, ordered based on the ``ADD_PAGE_ORDER`` setting. """
models = super(PageAdmin, self).get_content_models() order = [name.lower() for name in settings.ADD_PAGE_ORDER] def sort_key(page): name = "%s.%s" % (page._meta.app_label, page._meta.object_name) unordered = len(order) try: return (order.ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield_for_dbfield(self, db_field, **kwargs): """ Make slug mandatory. """
if db_field.name == "slug": kwargs["required"] = True kwargs["help_text"] = None return super(LinkAdmin, self).formfield_for_dbfield(db_field, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_form(self, request, form, change): """ Don't show links in the sitemap. """
obj = form.save(commit=False) if not obj.id and "in_sitemap" not in form.fields: obj.in_sitemap = False return super(LinkAdmin, self).save_form(request, form, change)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request_titles_xml() -> ET.ElementTree: """Request AniDB titles file."""
response = api.titles_request() return api.unpack_xml(response.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 _unpack_titles(etree: ET.ElementTree) -> 'Generator': """Unpack Titles from titles XML."""
for anime in etree.getroot(): yield Titles( aid=int(anime.get('aid')), titles=tuple(unpack_anime_title(title) for title in anime), )
<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, force=False) -> 'List[Titles]': """Get list of Titles. Pass force=True to bypass the cache. """
try: if force: raise CacheMissingError return self._cache.load() except CacheMissingError: titles = self._requester() self._cache.save(titles) return titles
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sending_task(self, backend): """ Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`. """
with self.backend_mutex: self.backends[backend] += 1 self.task_counter[backend] += 1 this_task = self.task_counter[backend] return this_task
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _canceling_task(self, backend): """ Used internally to decrement `backend`s current and total task counts when `backend` could not be reached. """
with self.backend_mutex: self.backends[backend] -= 1 self.task_counter[backend] -= 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_host(self, host): """ Used internally to add the default port to hosts not including portnames. """
if isinstance(host, basestring): return (host, self.default_port) return tuple(host)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _package(self, task, *args, **kw): """ Used internally. Simply wraps the arguments up in a list and encodes the list. """
# Implementation note: it is faster to use a tuple than a list here, # because json does the list-like check like so (json/encoder.py:424): # isinstance(o, (list, tuple)) # Because of this order, it is actually faster to create a list: # >>> timeit.timeit('L = [1,2,3]\nisin...
<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_signal(self, backend, signal): """ Sends the `signal` signal to `backend`. Raises ValueError if `backend` is not registered with the client. Returns the...
backend = self._expand_host(backend) if backend in self.backends: try: return self._work(backend, self._package(signal), log=False) except socket.error: raise BackendNotAvailableError else: raise ValueError('No such backend!')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def page(request): """ Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but move...
context = {} page = getattr(request, "page", None) if isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it. context = {"request": request, "page": page,...
<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_from_url(u, **kwargs): """ Returns dict containing zmq configuration arguments parsed from xbahn url Arguments: - u (urlparse.urlparse result) Returns...
path = u.path.lstrip("/").split("/") if len(path) > 2 or not path: raise AssertionError("zmq url format: zmq://<host>:<port>/<pub|sub>/<topic>") typ = path[0].upper() try: topic = path[1] except IndexError as _: topic = '' param = dict(urllib.parse.parse_qsl(u.query)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _record_blank(self, current, dict_obj): """ records the dictionay in the the 'blank' attribute based on the 'list_blank' path args: ----- current: the curren...
if not self.list_blank: return if self.list_blank not in current: self.blank.append(dict_obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_objs(self, obj, path=None, **kwargs): """ cycles through the object and adds in count values Args: ----- obj: the object to parse path: the current pa...
sub_val = None # pdb.set_trace() if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, (list, dict)): kwargs = self._count_objs(value, self.make_path(key, 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 _increment_prop(self, prop, path=None, **kwargs): """ increments the property path count args: ----- prop: the key for the prop path: the path to the prop kw...
new_path = self.make_path(prop, path) if self.method == 'simple': counter = kwargs['current'] else: counter = self.counts try: counter[new_path] += 1 except KeyError: counter[new_path] = 1 return counter
<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_counts(self, current): """ updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts...
for item in current: try: self.counts[item] += 1 except KeyError: self.counts[item] = 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_subtotals(self, current, sub_key): """ updates sub_total counts for the class instance based on the current dictionary counts args: ----- current: cur...
if not self.sub_counts.get(sub_key): self.sub_counts[sub_key] = {} for item in current: try: self.sub_counts[sub_key][item] += 1 except KeyError: self.sub_counts[sub_key][item] = 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print(self): """ prints to terminal the summray statistics """
print("TOTALS -------------------------------------------") print(json.dumps(self.counts, indent=4, sort_keys=True)) if self.sub_total: print("\nSUB TOTALS --- based on '%s' ---------" % self.sub_total) print(json.dumps(self.sub_counts, indent=4, sort_keys=True)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_ref(self, wordlist): """ Adds a reference. """
refname = wordlist[0][:-1] if(refname in self.refs): raise ReferenceError("[line {}]:{} already defined here (word) {} (line) {}".format(self.line_count, refname, self.refs[refname][0], self.refs[refname][1])) self.refs[refname] = (self.word_count, self.line_count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkargs(self, lineno, command, args): """ Check if the arguments fit the requirements of the command. Raises ArgumentError_, if an argument does not ...
for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "register" and (not arg in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type register, but {} is not a register".format(lineno, command.mnemonic(), arg)) if(wanted == "const" and (arg ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_args(self, command, args): """ Converts ``str -> int`` or ``register -> int``. """
for wanted, arg in zip(command.argtypes(), args): wanted = wanted.type_ if(wanted == "const"): try: yield to_int(arg) except: if(arg in self.processor.constants): yield self.processor.constants[arg] else: yield arg if(wanted == "register"): yield self.register_indices...
<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_to(field_path, default): """ Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined...
from yacms.conf import settings for k, v in settings.UPLOAD_TO_HANDLERS.items(): if k.lower() == field_path.lower(): return import_dotted_path(v) return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """ Read a ``str`` from ``open_stream_in`` and convert it to an integer using ``ord``. The result will be truncated according to Integer_. ...
self.repr_.setvalue(ord(self.open_stream_in.read(1))) return self.value.getvalue()
<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, word): """ Converts the ``int`` ``word`` to a ``bytes`` object and writes them to ``open_stream_out``. See ``int_to_bytes``. """
bytes_ = int_to_bytes(word, self.width) self.open_stream_out.write(bytes_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(logger_name=LOGGER_NAME, log_filename=LOG_FILENAME, app_logging_level=APP_LOGGING_LEVEL, dep_logging_level=DEP_LOGGING_LEVEL, format=None, logger_c...
# If there is no format, use a default format. if not format: format = "%(asctime)s %(name)s-%(levelname)s "\ + "[%(pathname)s %(lineno)d] %(message)s" formatter = logging.Formatter(format) # Setup the root logging for dependencies, etc. if log_filename: logging.ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUrlList(): """ This function get the Page List from the DB and return the tuple to use in the urls.py, urlpatterns """
""" IF YOU WANT REBUILD YOUR STRUCTURE UNCOMMENT THE FOLLOWING LINE """ #Node.rebuild() set_to_return = [] set_url = [] roots = Node.objects.filter(parent__isnull=True) for root in roots: nodes = root.get_descendants() for node in nodes: if node.page: ...
<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_plugins(sites=None): """ Returns all GoScale plugins It ignored all other django-cms plugins """
plugins = [] # collect GoScale plugins for plugin in CMSPlugin.objects.all(): if plugin: cl = plugin.get_plugin_class().model if 'posts' in cl._meta.get_all_field_names(): instance = plugin.get_plugin_instance()[0] plugins.append(instance) ...
<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_plugin(plugin_id): """ Updates a single plugin by ID Returns a plugin instance and posts count """
try: instance = CMSPlugin.objects.get(id=plugin_id).get_plugin_instance()[0] instance.update() except: return None, 0 return instance, instance.posts.count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict2obj(d): """A helper function which convert a dict to an object. """
if isinstance(d, (list, tuple)): d = [dict2obj(x) for x in d] if not isinstance(d, dict): return d class ObjectFromDict(object): pass o = ObjectFromDict() #an object created from a dict for k in d: o.__dict__[k] = dict2obj(d[k]) return 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 _add_process_guards(self, engine): """Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-proc...
@sqlalchemy.event.listens_for(engine, "connect") def connect(dbapi_connection, connection_record): connection_record.info['pid'] = os.getpid() @sqlalchemy.event.listens_for(engine, "checkout") def checkout(dbapi_connection, connection_record, connection_proxy): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current(self): """ Display the current database revision """
config = self.alembic_config() script = ScriptDirectory.from_config(config) revision = 'base' def display_version(rev, context): for rev in script.get_all_current(rev): nonlocal revision revision = rev.cmd_format(False) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revision(self, message): """ Create a new revision file :param message: """
alembic.command.revision(self.alembic_config(), message=message)