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. """ for version, nr in version_map.items(): if nr >= top_nr: if self.min <= nr <= self.max: top_version, top_nr = version, nr if top_version: return top_version """ We need to look outside the range, so maybe give a warning. """ version_problem_notify('No matching version found for range "{0:s}" from options "{1:s}"; other options might be considered.'.format( str(self), '/'.join(str(v) for v in versions)), conflict=conflict) """ Failing the above, try to find the lowest value above the range. """ top_nr = self.highest for version, nr in version_map.items(): if nr < top_nr: if nr >= self.max: top_version, top_nr = version, nr if top_version: return top_version """ Failing the above two, try to highest value below the range (so just the highest). """ top_nr = 0 for version, nr in version_map.items(): if nr > top_nr: top_version, top_nr = version, nr if top_version: return top_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 == 0 and non_str_len_no_throw(key) > 0 and all(is_slice_or_dim_range_request(subkey, depth+1) for subkey in key)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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_non_negative_index(index, length)
<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 len(self.ordered_ranges) + len(addSlices) == 0: return slice(None,None,None) ranges = self.ordered_ranges if len(addSlices) > 0: ranges = ranges + DimensionRange(*addSlices).ordered_ranges return self._combine_lists_of_ranges_on_length(data_len, *ranges)
<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) final_start, final_step, final_stop = (None, None, None) # Get our start if first.start == None and second.start == None: final_start = None else: final_start = (first.start if first.start else 0)+(second.start if second.start else 0) # Get our stop if second.stop == None: final_stop = first.stop elif first.stop == None: final_stop = (first.start if first.start else 0) + second.stop else: final_stop = min(first.stop, (first.start if first.start else 0) + second.stop) # Get our step if first.step == None and second.step == None: final_step = None else: final_step = (first.step if first.step else 1)*(second.step if second.step else 1) # If we have a start above our stop, set them to be equal if final_start > final_stop: final_start = final_stop return slice(final_start, final_stop, final_step)
<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_range, next_range) return current_range
<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 single_depth += 1 return single_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 _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: newListLen = ((get_non_negative_index(slice_ind.stop, self._length) - get_non_negative_index(slice_ind.start, self._length)) // step_size) else: newListLen = ((self._length - get_non_negative_index(slice_ind.start, self._length)) // step_size) else: if slice_ind.stop != None: newListLen = ((get_non_negative_index(slice_ind.stop, self._length)) // step_size) else: newListLen = (self._length // step_size) return ZeroList(newListLen)
<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 explicitly set to ``True``. """
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 field.name != "description"): description = getattr(self, field.name) if description: from yacms.core.templatetags.yacms_tags \ import richtext_filters description = richtext_filters(description) break # Fall back to the title if description couldn't be determined. if not description: description = str(self) # Strip everything after the first block or sentence. ends = ("</p>", "<br />", "<br/>", "<br>", "</ul>", "\n", ". ", "! ", "? ") for end in ends: pos = description.lower().find(end) if pos > -1: description = TagCloser(description[:pos]).html break else: description = truncatewords_html(description, 100) try: description = unicode(description) except NameError: pass # Python 3. return description
<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 from the quick blog form in the admin dashboard. """
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 ``TweetableAdmin``. If no sharing service is defined (bitly is the one implemented, but others could be by overriding ``generate_short_url``), the ``SHORT_URL_UNSET`` marker gets stored in the DB. In this case, ``short_url`` is temporarily (eg not persisted) set to host + ``get_absolute_url`` - this is so that we don't permanently store ``get_absolute_url``, since it may change over time. """
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(urlopen(url).read().decode("utf-8")) if response["status_code"] == 200: return response["data"]["url"] return SHORT_URL_UNSET
<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 of Django's so we can hook into the published manager and concrete subclasses. """
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 except AttributeError: queryset = concrete_model.objects.all try: return queryset(**kwargs).filter(**lookup).order_by(order)[0] except IndexError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's ``ct_field`` and ``fk_field`` attributes. """
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 isinstance(field, GenericForeignKey): names = (field.ct_field, field.fk_field) return dict([(n, getattr(self, n)) for n in names]) return {name: 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 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 we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """
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 try: return queryset(**kwargs).get(**lookup) except concrete_model.DoesNotExist: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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.structures.yaml_str_join`, :func:`util.structures.yaml_loc_join` ''' y = read_file(filename) if add_constructor: if not isinstance(add_constructor, list): add_constructor = [add_constructor] for a in add_constructor: _yaml.add_constructor(*a) if y: return _yaml.load(y)
<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_file(filename, y)
<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 blocks for k-fold cross-validation Parameters: numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- import pandas as pd import numpy as np import oxyba as ox X = np.random.normal(size=(7,5), scale=50).round(1) N,_ = X.shape K = 3; #number of blocks idxmat, dropped = ox.block_idxmat_shuffle(N,K) for b in range(K): print('\nBlock:',b) print(pd.DataFrame(X[idxmat[:,b],:], index=idxmat[:,b])) print('\nDropped observations\n', X[dropped,:] ) print('\nrow indicies of dropped observations:', dropped, '\') Why is this useful? - Avoid creating copies of dataset X during run time - Shuffle the indicies of a data point rather than the data points themselve Links: ------ - How numpy's permutation works, https://stackoverflow.com/a/15474335 """
# 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*K" numdrop = numdraws % numblocks dropped = obsidx[:numdrop] obsidx = obsidx[numdrop:] # reshape the remaing vector indicies into a matrix idxmat = obsidx.reshape((blocksize, numblocks)) # output the indicies for the blocks, and indicies of dropped obserations return idxmat, dropped
<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.merged_cell_ranges(): anchor_cell = new_rows[cell_low[1]][cell_low[0]] for row_index in range(cell_low[1], cell_high[1]): for col_index in range(cell_low[0], cell_high[0]): # NOTE: xlrd occassionally returns ranges that don't have cells. try: new_rows[row_index][col_index] = anchor_cell.copy() except IndexError: pass return new_rows
<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 time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is returned. """
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`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``. """
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: value = getattr(profile, field.name) fields[field.verbose_name.title()] = value except ProfileNotConfigured: pass return list(fields.items())
<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 extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d.png', 'name': 'd15-120f3d', 'label': 'fig:mass' :param: tarball (string): the absolute location of the tarball we wish to process :param: output_directory (string): path of file processing and extraction (optional) :param: context: if True, also try to extract context where images are referenced in the text. (optional) :return: images(list): list of dictionaries for each image with captions. """
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_files == [] or tex_files is None: raise NoTexFilesFound("No TeX files found in {0}".format(tarball)) converted_image_mapping = convert_images(image_list) return map_images_in_tex( tex_files, converted_image_mapping, output_directory, context )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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_image_data: # Convert to dict, add proper filepaths and do various cleaning cleaned_image_data = prepare_image_data( partly_extracted_image_data, output_directory, image_mapping, ) if context: # Using prev. extracted info, get contexts for each image found extract_context(tex_file, cleaned_image_data) extracted_image_data.extend(cleaned_image_data) return extracted_image_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 create request filename : string Path to tar-archive on local disk Returns ------- string Url of created functional data resource """
# 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: ' + filename) return references_to_dict(response.json()['links'])[REF_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 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 deserialize or serialize :param environment: an optional environment """
# 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 callback # the default is to raise a MissingValue() exception value = missing(value) elif hasattr(self._missing, "__call__"): value = self._missing() else: # we just assign any value value = self._missing 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 serialize(self, value, environment=None): """Serialze a value into a transportable and interchangeable format. The default assumption is that the value is JSON e.g. string or number. Some encoders also support datetime by default. Serialization should not be validated, since the developer app would be bounced, since the mistake comes from there - use unittests for this! """
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 something else. :param value: the value to be deserialized :param environment: additional environment """
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: # just reraise raise except (exc.Invalid, ValueError, TypeError) as ex: # we convert a bare Invalid into InvalidValue raise exc.InvalidValue(self, value=value, origin=ex) 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 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 buffcompress: 3rd option for builtin.open or gzip.open :return: tuple(filehandle, fileextension) ''' root, ext = splitext(filepath.replace('.gz', '')) # get rid of period ext = ext[1:] if filepath.endswith('.gz'): compress = buffcompress if compress is None: compress = 9 handle = gzip.open(filepath, mode, compress) else: buffer = buffcompress if buffer is None: buffer = -1 handle = builtins.open(filepath, mode, buffer) return (handle, ext)
<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.transport.Message` uuid :rtype: :class:`kser.result.Result` """
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/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the result is multivalued :return: the value found or None """
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 of long in short, and remove the # middle name from short if found for wl in long: if not short: break ws = short.pop(0) if not compatible_name_part(ws, wl): short.insert(0, ws) # true iff short is a compatible substring of long return short == []
<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, "delivery_info": task.request.delivery_info, "errbacks": task.request.errbacks, "eta": task.request.eta, "expires": task.request.expires, "headers": task.request.headers, "hostname": task.request.hostname, "id": task.request.id, "is_eager": task.request.is_eager, "kwargs": task.request.kwargs, "origin": task.request.origin, "parent_id": task.request.parent_id, "reply_to": task.request.reply_to, "retries": task.request.retries, "root_id": task.request.root_id, "task": task.request.task, "taskset": task.request.taskset, "timelimit": task.request.timelimit, "utc": task.request.utc, }, } if message: data["message"] = message SENTRY.extra_context (data) einfo = sys.exc_info () rc = SENTRY.captureException (einfo) del einfo LOG.error ("Sentry filed: %s", rc) except Exception as ee: logtool.log_fault (ee, message = "FAULT: Problem logging exception.", level = logging.INFO)
<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 database API. """
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 migrations from version 1 to 2, then 2 to 3, then 3 to 4. You cannot register 1 to 2 followed by 3 to 4. """
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 = migration.to_ver
<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 uninitialized database (version 0). This method is idempotent. """
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 {migration.to_ver}') self._migrate_single(conn, migration) set_user_version(conn, migration.to_ver) logger.info(f'Migrated database to {migration.to_ver}')
<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_items[0] return 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 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 retrieve the versions of. Returns: list: Of string versions. """
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 the key in the dictionary. versions (list): List of ``str`` representing the available versions of a project. """
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(), }) return super(PageAdmin, self).change_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 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 descendant pages. """
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 slugs. parent = request.GET.get("parent") if parent is not None and not change: obj.parent_id = parent obj.save() super(PageAdmin, self).save_model(request, obj, 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 _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.index(name.lower()), "") except ValueError: return (unordered, page.meta_verbose_name) return sorted(models, key=sort_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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]\nisinstance(L, (list, tuple))') # 0.41077208518981934 # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (list, tuple))') # 0.49509215354919434 # Whereas if it were the other way around, using a tuple would be # faster: # >>> timeit.timeit('L = (1,2,3)\nisinstance(L, (tuple, list))') # 0.3031749725341797 # >>> timeit.timeit('L = [1,2,3]\nisinstance(L, (tuple, list))') # 0.6147568225860596 return self.codec.encode([task, args, kw])
<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 result. """
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 moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``. """
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, "_current_page": page} page.set_helpers(context) return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_from_url(u, **kwargs): """ Returns dict containing zmq configuration arguments parsed from xbahn url Arguments: - u (urlparse.urlparse result) Returns: dict: - id (str): connection index key - typ_str (str): string representation of zmq socket type - typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL) - topic (str): subscription topic - url (str): url to use with zmq's bind function """
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)) #FIXME: should come from schema, maybe zmq+tcp:// ? transport = param.get("transport", "tcp") _id = "%s-%s-%s-%s" % (typ, topic, transport, u.netloc) if kwargs.get("prefix") is not None: _id = "%s-%s" % (kwargs.get("prefix"), _id) return { "id" : _id, "typ_str" : typ, "typ" : getattr(zmq, typ), "topic" : topic, "transport" : transport, "url" : "%s://%s" % (transport, u.netloc) }
<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 current dictionay counts dict_obj: the original dictionary object """
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 path kwargs: ------- current: a dictionary of counts for current call sub_val: the value to use for subtotal aggregation """
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), **kwargs) else: if self.make_path(key, path) == self.sub_total: # pdb.set_trace() sub_val = value kwargs['current'] = self._increment_prop(key, path, **kwargs) elif isinstance(obj, list): for item in obj: if isinstance(item, (list, dict)): kwargs = self._count_objs(item, path, **kwargs) else: if path == self.sub_total: pdb.set_trace() sub_val = item kwargs['current'] = self._increment_prop(path, **kwargs) else: kwargs['current'] = self._increment_prop(path, **kwargs) if path == self.sub_total: pdb.set_trace() sub_val = item if kwargs.get('sub_val') is None: kwargs['sub_val'] = sub_val return kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 kwargs: ------- current: dictionary count for the current dictionay """
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: current dictionary counts sub_key: the key/value to use for the subtotals """
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)) if self.list_blank: print("\nMISSING nodes for '%s':" % self.list_blank, len(self.blank))
<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 fit. """
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 in self.register)): raise ArgumentError("[line {}]: Command '{}' wants argument of type const, but {} is a register.".format(lineno, command.mnemonic(), 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[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 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 by the ``UPLOAD_TO_HANDLERS`` setting. """
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_class=None, handlers=[], global_logger=True): """ Constructs and initializes a `logging.Logger` object. Returns :class:`logging.Logger` object. :param logger_name: name of the new logger. :param log_filename: The log file location :class:`str` or None. :param app_logging_level: The logging level to use for the application. :param dep_logging_level: The logging level to use for dependencies. :param format: The format string to use :class: `str` or None. :param logger_class: The logger class to use :param handlers: List of handler instances to add. :param global_logger: If true set threepio's global logger variable to this logger. """
# 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.basicConfig( level=dep_logging_level, format=format, filename=log_filename, filemode='a+') else: logging.basicConfig( level=dep_logging_level, format=format) # Setup and add separate application logging. if logger_class: original_class = logging.getLoggerClass() logging.setLoggerClass(logger_class) new_logger = logging.getLogger(logger_name) logging.setLoggerClass(original_class) else: new_logger = logging.getLogger(logger_name) # Set the app logging level. new_logger.setLevel(app_logging_level) # required to get level to apply. # Set the global_logger by default. if global_logger: global logger logger = new_logger for handler in handlers: handler.setFormatter(formatter) handler.setLevel(app_logging_level) new_logger.addHandler(handler) return new_logger
<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: page = node.page view = page.view regex = r'^{0}$'.format(node.get_pattern()) regex_path = '{0}'.format(node.get_pattern()) view = u'{0}.{1}.{2}'.format(view.app_name, view.module_name, view.func_name) """ check_static_vars add UPY_CONTEXT to page """ page.check_static_vars(node) app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) if node.is_index: regex = r'^$' regex_path = '' app_url = url(regex, view, page.static_vars, page.scheme_name) set_to_return.append(app_url) set_url.append(regex_path) return set_to_return, set_url
<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) # Filter by sites if sites and len(sites) > 0: onsite = [] for plugin in plugins: try: if plugin.page.site in sites: onsite.append(plugin) except AttributeError: continue return onsite return plugins
<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-process. """
@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): pid = os.getpid() if connection_record.info['pid'] != pid: self.logger.debug( "Parent process %(orig)s forked (%(newproc)s) with an open database connection, " "which is being discarded and recreated." % {"newproc": pid, "orig": connection_record.info['pid']}) connection_record.connection = connection_proxy.connection = None raise exc.DisconnectionError( "Connection record belongs to pid %s, attempting to check out in pid %s" % ( connection_record.info['pid'], pid) )
<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 [] with EnvironmentContext(config, script, fn=display_version): script.run_env() return revision
<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)