output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _flush_bits_to_stream(self): """Flush the bits to the stream. This is used when a few bits have been read and ``self._bits`` contains unconsumed/ flushed bits when data is to be written to the stream """ if len(self._bits) == 0: return 0 bits = list(self....
Implement a Python 3 function for flushing the bits to the stream. This is used when the bits are not written to the stream.
You are a Python code generator, capable of creating scripts from specifications.
ensure that all fields in the given file are present in the given file
Explain what the following Python 3 code does def _validate_markdown(self, expfile): '''ensure that fields are present in markdown file''' try: import yaml except: bot.error('Python yaml is required for testing yml/markdown files.') sys.exit(1) self....
You are a Python code architect, reviewing and designing scalable and efficient code
def perform_checks(template, do_redirect=False, context=None, next=None, quiet=False): '''return all checks for required variables before returning to desired view Parameters ========== template: the html temp...
Write a Python 3 function that can perform all checks for required variables before returning to
As a Python code composer, you craft elegant and concise scripts.
Returns 0 if successful or - 1 if unsuccessful.
Make a summary of the following Python 3 code def FSeek(params, ctxt, scope, stream, coord): if len(params) != 1: raise errors.InvalidArguments(coord, "{} args".format(len(params)), "FSeek accepts only one argument") pos = PYVAL(params[0]) curr_pos = stream.tell() fsize = stream.size() ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns 0 if successful or - 1 if unsuccessful.
Here you have a function in Python 3, explain what it does def FSkip(params, ctxt, scope, stream, coord): if len(params) != 1: raise errors.InvalidArguments(coord, "{} args".format(len(params)), "FSkip accepts only one argument") skip_amt = PYVAL(params[0]) pos = skip_amt + stream.tell() return...
You are a Python code analyst, evaluating scripts for potential improvements.
Packs and unpacks the data of the current node into a new node.
Can you tell what is the following Python 3 function doing def packer_gzip(params, ctxt, scope, stream, coord): if len(params) <= 1: raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least two arguments") # to gzip it (pack it) if params[0]: return pack_gzip(params[1:]...
As a Python code composer, you craft elegant and concise scripts.
Packs the params and returns a gzipped version of the resulting data.
Explain what the following Python 3 code does def pack_gzip(params, ctxt, scope, stream, coord): if len(params) == 0: raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least one argument") built = utils.binary("") for param in params: if isinstance(param, pfp.field...
You are a Python code architect, reviewing and designing scalable and efficient code
def watch_length(params, ctxt, scope, stream, coord): """WatchLength - Watch the total length of each of the params. Example: The code below uses the ``WatchLength`` update function to update the ``length`` field to the length of the ``data`` field :: int length<watch=data, upd...
Implement a function in Python 3 to watch the total length of each parameter.
As a Python code analyst, you investigate and solve complex coding mysteries
def watch_crc(params, ctxt, scope, stream, coord): """WatchCrc32 - Watch the total crc32 of the params. Example: The code below uses the ``WatchCrc32`` update function to update the ``crc`` field to the crc of the ``length`` and ``data`` fields :: char length; char ...
Implement a function in Python 3 to watch the total CRC32 of the params.
You are a Python code analyst, evaluating scripts for potential improvements.
def _validate_folder(self, folder=None): ''' validate folder takes a cloned github repo, ensures the existence of the config.json, and validates it. ''' from expfactory.experiment import load_experiment if folder is None: folder=os.path.abspath(os.getcwd()) ...
Can you write a function in Python 3 where it validates folder takes a cloned github repo ensures the existence of the config. json and validates it.
As a python code expert, you are capable of creating scripts from specifications.
Validate a folder and optionally a config. json or url.
Here you have a function in Python 3, explain what it does def validate(self, folder, cleanup=False, validate_folder=True): ''' validate is the entrypoint to all validation, for a folder, config, or url. If a URL is found, it is cloned and cleaned up. :param validate_folder: e...
You are a Python code architect, reviewing and designing scalable and efficient code
def _validate_config(self, folder, validate_folder=True): ''' validate config is the primary validation function that checks for presence and format of required fields. Parameters ========== :folder: full path to folder with config.json :name: if provided, the folder...
Can you write a function in Python 3 where it validates config is the primary validation function that checks for presence and format of required fields. Parameters ========== :folder: full path to folder with config.json :name: if provided, the folder name to check against exp_id
As a Python code analyst, you investigate and solve complex coding mysteries
get_validation_fields returns a list of tuples that are required to be passed to the validation function.
Can you generate a brief explanation for the following Python 3 code def get_validation_fields(self): '''get_validation_fields returns a list of tuples (each a field) we only require the exp_id to coincide with the folder name, for the sake of reproducibility (given that all are served fro...
As a Python code analyst, you investigate and solve complex coding mysteries
generate a lookup data structure from a delimited file.
Here you have a function in Python 3, explain what it does def generate_runtime_vars(variable_file=None, sep=','): '''generate a lookup data structure from a delimited file. We typically obtain the file name and delimiter from the environment by way of EXPFACTORY_RUNTIME_VARS, and EXPFACTORY_R...
You are a Python code generator, capable of creating scripts from specifications.
def _read_runtime_vars(variable_file, sep=','): '''read the entire runtime variable file, and return a list of lists, each corresponding to a row. We also check the header, and exit if anything is missing or malformed. Parameters ========== variable_file: full path to the tabula...
Write a Python 3 script to read the entire runtime variable file and return a list of lists each corresponding to a row.
As a Python code composer, you craft elegant and concise scripts.
def _parse_row(row, sep=','): '''parse row is a helper function to simply clean up a string, and parse into a row based on a delimiter. If a required length is provided, we check for this too. ''' parsed = row.split(sep) parsed = [x for x in parsed if x.strip()] return parsed
Implement a Python 3 function for parsing a row into a list of strings
You are a Python code generator, capable of creating scripts from specifications.
validate_header verifies that the header row contains the exp_id var_name var_value and token.
Can you generate the documentation for the following Python 3 function def validate_header(header, required_fields=None): '''validate_header ensures that the first row contains the exp_id, var_name, var_value, and token. Capitalization isn't important, but ordering is. This criteria is very strict, bu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_lines(cls, pattern_factory, lines): """ Compiles the pattern lines. *pattern_factory* can be either the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. It must accept an uncompiled pattern (:class:`str`) and return the compiled...
How would you code a function in Python 3 to compile the pattern lines.
As a Python code composer, you craft elegant and concise scripts.
Matches the file to this path - spec.
Explain what the following Python 3 code does def match_file(self, file, separators=None): norm_file = util.normalize_file(file, separators=separators) return util.match_file(self.patterns, norm_file)
As a Python code composer, you craft elegant and concise scripts.
Matches the files to this path - spec.
Explain what the following Python 3 code does def match_files(self, files, separators=None): if isinstance(files, (bytes, unicode)): raise TypeError("files:{!r} is not an iterable.".format(files)) file_map = util.normalize_files(files, separators=separators) matched_files = util.match_files(self.patterns, ite...
As a Python code composer, you craft elegant and concise scripts.
def match_tree(self, root, on_error=None, follow_links=None): """ Walks the specified root path for all files and matches them to this path-spec. *root* (:class:`str`) is the root directory to search for files. *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler...
Can you implement a function in Python 3 that walks the specified root path for all files and matches them to thispath - spec.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a pattern into a regular expression.
Can you tell what is the following Python 3 function doing def pattern_to_regex(cls, pattern): if isinstance(pattern, unicode): return_type = unicode elif isinstance(pattern, bytes): return_type = bytes pattern = pattern.decode(_BYTES_ENCODING) else: raise TypeError("pattern:{!r} is not a unicode or b...
You are a Python code architect, reviewing and designing scalable and efficient code
def _translate_segment_glob(pattern): """ Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`). ""...
Create a Python 3 function to translate the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`).
As a Python code translator, you convert algorithms and pseudocode into Python.
Override to add deprecation warning to GitIgnorePattern. pattern_to_regex.
Here you have a function in Python 3, explain what it does def pattern_to_regex(cls, *args, **kw): cls._deprecated() return super(GitIgnorePattern, cls).pattern_to_regex(*args, **kw)
As a Python code translator, you convert algorithms and pseudocode into Python.
Walks the specified directory for all files and yields the absolute paths to each file in the tree.
Here you have a function in Python 3, explain what it does def iter_tree(root, on_error=None, follow_links=None): if on_error is not None and not callable(on_error): raise TypeError("on_error:{!r} is not callable.".format(on_error)) if follow_links is None: follow_links = True for file_rel in _iter_tree_next(o...
As a Python code analyst, you investigate and solve complex coding mysteries
Iterate the directory tree and return the next entry in the tree.
Can you generate a brief explanation for the following Python 3 code def _iter_tree_next(root_full, dir_rel, memo, on_error, follow_links): dir_full = os.path.join(root_full, dir_rel) dir_real = os.path.realpath(dir_full) # Remember each encountered ancestor directory and its canonical # (real) path. If a canonica...
You are a Python code generator, capable of creating scripts from specifications.
def match_file(patterns, file): """ Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; ...
Create a Python 3 function to match the file to the patterns. contains the patterns to use. contains the patterns to use. returns a boolean indicating if the file is matched.
As a Python code analyst, you investigate and solve complex coding mysteries
def match_files(patterns, files): """ Matches the files to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the normalized file paths to be matched against *patt...
How would you implement a function in Python 3 that matches the files to the patterns.
As a Python code translator, you convert algorithms and pseudocode into Python.
Normalizes the file path to use the POSIX path separator.
Can you generate a brief explanation for the following Python 3 code def normalize_file(file, separators=None): # Normalize path separators. if separators is None: separators = NORMALIZE_PATH_SEPS norm_file = file for sep in separators: norm_file = norm_file.replace(sep, posixpath.sep) # Remove current direct...
As a Python code translator, you convert algorithms and pseudocode into Python.
def normalize_files(files, separators=None): """ Normalizes the file paths to use the POSIX path separator. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the file paths to be normalized. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally conta...
Can you create a Python 3 function that normalizes the file paths to use the POSIX path separator.
As a python code expert, you are capable of creating scripts from specifications.
def register_pattern(name, pattern_factory, override=None): """ Registers the specified pattern factory. *name* (:class:`str`) is the name to register the pattern factory under. *pattern_factory* (:class:`~collections.abc.Callable`) is used to compile patterns. It must accept an uncompiled pattern (:class:`str`...
Can you create a Python 3 function that registers a pattern factory.
As a Python code analyst, you investigate and solve complex coding mysteries
def message(self): """ *message* (:class:`str`) is the error message. """ return "Real path {real!r} was encountered at {first!r} and then {second!r}.".format( real=self.real_path, first=self.first_path, second=self.second_path, )
Create a Python 3 function to return the error message.
As a Python code composer, you craft elegant and concise scripts.
def match(self, files): """ Matches this pattern against the specified files. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each file relative to the root directory (e.g., ``"relative/path/to/file"``). Returns an :class:`~collections.abc.Iterable` yielding each matched file path (:...
Can you implement a function in Python 3 that matches this pattern against the specified files.
As a Python code analyst, you investigate and solve complex coding mysteries
def match(self, files): """ Matches this pattern against the specified files. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each file relative to the root directory (e.g., "relative/path/to/file"). Returns an :class:`~collections.abc.Iterable` yielding each matched file path (:clas...
Create a Python 3 function to match this pattern against the specified files.
As a python code expert, you are capable of creating scripts from specifications.
def user_default_serializer(self, obj): """Convert a User to a cached instance representation.""" if not obj: return None self.user_default_add_related_pks(obj) return dict(( ('id', obj.id), ('username', obj.username), self.field_to_json('D...
How would you code a function in Python 3 to convert a User to a cached instance representation.
As a python code expert, you are capable of creating scripts from specifications.
Load a User from the database.
Here you have a function in Python 3, explain what it does def user_default_loader(self, pk): try: obj = User.objects.get(pk=pk) except User.DoesNotExist: return None else: self.user_default_add_related_pks(obj) return obj
You are a Python code analyst, evaluating scripts for potential improvements.
Add related primary keys to a User instance.
Here you have a function in Python 3, explain what it does def user_default_add_related_pks(self, obj): if not hasattr(obj, '_votes_pks'): obj._votes_pks = list(obj.votes.values_list('pk', flat=True))
As a python code expert, you are capable of creating scripts from specifications.
def group_default_invalidator(self, obj): """Invalidated cached items when the Group changes.""" user_pks = User.objects.values_list('pk', flat=True) return [('User', pk, False) for pk in user_pks]
Create a Python 3 function for invalidating cached items when the Group changes.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a Question to a cached instance representation.
Make a summary of the following Python 3 code def question_default_serializer(self, obj): if not obj: return None self.question_default_add_related_pks(obj) return dict(( ('id', obj.id), ('question_text', obj.question_text), self.field_to_json('Dat...
You are a Python code analyst, evaluating scripts for potential improvements.
def question_default_loader(self, pk): """Load a Question from the database.""" try: obj = Question.objects.get(pk=pk) except Question.DoesNotExist: return None else: self.question_default_add_related_pks(obj) return obj
How would you code a function in Python 3 to load a Question from the database.
As a python code expert, you are capable of creating scripts from specifications.
Add related primary keys to a Question instance.
Given the following Python 3 function, write the documentation def question_default_add_related_pks(self, obj): if not hasattr(obj, '_choice_pks'): obj._choice_pks = list(obj.choices.values_list('pk', flat=True))
As a Python code analyst, you investigate and solve complex coding mysteries
Convert a Choice to a cached instance representation.
Can you generate a brief explanation for the following Python 3 code def choice_default_serializer(self, obj): if not obj: return None self.choice_default_add_related_pks(obj) return dict(( ('id', obj.id), ('choice_text', obj.choice_text), self.fie...
You are a Python code analyst, evaluating scripts for potential improvements.
def choice_default_loader(self, pk): """Load a Choice from the database.""" try: obj = Choice.objects.get(pk=pk) except Choice.DoesNotExist: return None else: self.choice_default_add_related_pks(obj) return obj
Write a Python 3 script for loading a Choice from the database.
As a python code expert, you are capable of creating scripts from specifications.
Add related primary keys to a Choice instance.
Can you tell what is the following Python 3 function doing def choice_default_add_related_pks(self, obj): if not hasattr(obj, '_voter_pks'): obj._voter_pks = obj.voters.values_list('pk', flat=True)
You are a Python code architect, reviewing and designing scalable and efficient code
Invalidated cached items when the Choice changes.
Explain what the following Python 3 code does def choice_default_invalidator(self, obj): invalid = [('Question', obj.question_id, True)] for pk in obj.voters.values_list('pk', flat=True): invalid.append(('User', pk, False)) return invalid
You are a Python code architect, reviewing and designing scalable and efficient code
def cache(self): """Get the Django cache interface. This allows disabling the cache with settings.USE_DRF_INSTANCE_CACHE=False. It also delays import so that Django Debug Toolbar will record cache requests. """ if not self._cache: use_cache = getattr(setting...
Write a Python 3 function that can get the Django cache interface.
As a Python code composer, you craft elegant and concise scripts.
def delete_all_versions(self, model_name, obj_pk): """Delete all versions of a cached instance.""" if self.cache: for version in self.versions: key = self.key_for(version, model_name, obj_pk) self.cache.delete(key)
Implement a Python 3 function for deleting all versions of a cached instance.
As a Python code analyst, you investigate and solve complex coding mysteries
def model_function(self, model_name, version, func_name): """Return the model-specific caching function.""" assert func_name in ('serializer', 'loader', 'invalidator') name = "%s_%s_%s" % (model_name.lower(), version, func_name) return getattr(self, name)
Create a Python 3 function to return the model - specific caching function.
As a Python code analyst, you investigate and solve complex coding mysteries
def field_function(self, type_code, func_name): """Return the field function.""" assert func_name in ('to_json', 'from_json') name = "field_%s_%s" % (type_code.lower(), func_name) return getattr(self, name)
How would you code a function in Python 3 to return the field function.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a field to a JSON - serializable representation.
Can you generate the documentation for the following Python 3 function def field_to_json(self, type_code, key, *args, **kwargs): assert ':' not in key to_json = self.field_function(type_code, 'to_json') key_and_type = "%s:%s" % (key, type_code) json_value = to_json(*args, **kwargs) ...
You are a Python code generator, capable of creating scripts from specifications.
def field_from_json(self, key_and_type, json_value): """Convert a JSON-serializable representation back to a field.""" assert ':' in key_and_type key, type_code = key_and_type.split(':', 1) from_json = self.field_function(type_code, 'from_json') value = from_json(json_value) ...
Implement a Python 3 function for converting a JSON - serializable representation back to a field.
As a Python code composer, you craft elegant and concise scripts.
def get_instances(self, object_specs, version=None): """Get the cached native representation for one or more objects. Keyword arguments: object_specs - A sequence of triples (model name, pk, obj): - model name - the name of the model - pk - the primary key of the instance ...
How would you code a function in Python 3 to get the cached native representation for one or more objects.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create or update a cached instance.
Can you tell what is the following Python 3 function doing def update_instance( self, model_name, pk, instance=None, version=None, update_only=False): """Create or update a cached instance. Keyword arguments are: model_name - The name of the model pk - The primar...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert a date triple to a date triple.
Here you have a function in Python 3, explain what it does def field_date_to_json(self, day): if isinstance(day, six.string_types): day = parse_date(day) return [day.year, day.month, day.day] if day else None
As a Python code translator, you convert algorithms and pseudocode into Python.
def field_datetime_from_json(self, json_val): """Convert a UTC timestamp to a UTC datetime.""" if type(json_val) == int: seconds = int(json_val) dt = datetime.fromtimestamp(seconds, utc) elif json_val is None: dt = None else: seconds, micro...
Can you create a Python 3 function that converts a UTC timestamp to a UTC datetime.
You are a Python code generator, capable of creating scripts from specifications.
Convert a datetime to a UTC timestamp w / microsecond resolution.
Can you generate the documentation for the following Python 3 function def field_datetime_to_json(self, dt): if isinstance(dt, six.string_types): dt = parse_datetime(dt) if not dt: return None ts = timegm(dt.utctimetuple()) if dt.microsecond: return "{...
As a python code expert, you are capable of creating scripts from specifications.
def field_timedelta_from_json(self, json_val): """Convert json_val to a timedelta object. json_val contains total number of seconds in the timedelta. If json_val is a string it will be converted to a float. """ if isinstance(json_val, str): return timedelta(seconds=f...
Can you write a function in Python 3 where it converts json_val to a timedelta object.
You are a Python code generator, capable of creating scripts from specifications.
def field_timedelta_to_json(self, td): """Convert timedelta to value containing total number of seconds. If there are fractions of a second the return value will be a string, otherwise it will be an int. """ if isinstance(td, six.string_types): td = parse_duration(td...
Can you implement a function in Python 3 that converts timedelta to value containing total number of seconds.
You are a Python code architect, reviewing and designing scalable and efficient code
def field_pklist_from_json(self, data): """Load a PkOnlyQueryset from a JSON dict. This uses the same format as cached_queryset_from_json """ model = get_model(data['app'], data['model']) return PkOnlyQueryset(self, model, data['pks'])
How would you implement a function in Python 3 that loads a PkOnlyQueryset from a JSON dict.
You are a Python code analyst, evaluating scripts for potential improvements.
def field_pklist_to_json(self, model, pks): """Convert a list of primary keys to a JSON dict. This uses the same format as cached_queryset_to_json """ app_label = model._meta.app_label model_name = model._meta.model_name return { 'app': app_label, ...
Write a Python 3 function that can convert a list of primary keys to a JSON dict.
As a Python code translator, you convert algorithms and pseudocode into Python.
def field_pk_from_json(self, data): """Load a PkOnlyModel from a JSON dict.""" model = get_model(data['app'], data['model']) return PkOnlyModel(self, model, data['pk'])
Write a Python 3 function for loading a PkOnlyModel from a JSON dict.
As a Python code analyst, you investigate and solve complex coding mysteries
def field_pk_to_json(self, model, pk): """Convert a primary key to a JSON dict.""" app_label = model._meta.app_label model_name = model._meta.model_name return { 'app': app_label, 'model': model_name, 'pk': pk, }
Can you create a Python 3 function that converts a primary key to a JSON dict.
As a Python code composer, you craft elegant and concise scripts.
Update cache when choice. voters changes.
Explain what the following Python 3 code does def choice_voters_changed_update_cache( sender, instance, action, reverse, model, pk_set, **kwargs): """Update cache when choice.voters changes.""" if action not in ('post_add', 'post_remove', 'post_clear'): # post_clear is not handled, because clear...
As a python code expert, you are capable of creating scripts from specifications.
Update the cache when an instance is deleted.
Can you generate the documentation for the following Python 3 function def post_delete_update_cache(sender, instance, **kwargs): name = sender.__name__ if name in cached_model_names: from .tasks import update_cache_for_instance update_cache_for_instance(name, instance.pk, instance)
As a python code expert, you are capable of creating scripts from specifications.
def post_save_update_cache(sender, instance, created, raw, **kwargs): """Update the cache when an instance is created or modified.""" if raw: return name = sender.__name__ if name in cached_model_names: delay_cache = getattr(instance, '_delay_cache', False) if not delay_cache: ...
Implement a function in Python 3 to update the cache when an instance is created or modified.
You are a Python code generator, capable of creating scripts from specifications.
def get_queryset(self): """Get the queryset for the action. If action is read action, return a CachedQueryset Otherwise, return a Django queryset """ queryset = super(CachedViewMixin, self).get_queryset() if self.action in ('list', 'retrieve'): return CachedQ...
Create a Python 3 function for getting the queryset for the action.
As a python code expert, you are capable of creating scripts from specifications.
def get_object(self, queryset=None): """ Return the object the view is displaying. Same as rest_framework.generics.GenericAPIView, but: - Failed assertions instead of deprecations """ # Determine the base queryset to use. assert queryset is None, "Passing a query...
How would you code a function in Python 3 to return the object that is displaying.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_object_or_404(self, queryset, *filter_args, **filter_kwargs): """Return an object or raise a 404. Same as Django's standard shortcut, but make sure to raise 404 if the filter_kwargs don't match the required types. """ if isinstance(queryset, CachedQueryset): ...
How would you implement a function in Python 3 that returns an object or raise a 404.
As a Python code composer, you craft elegant and concise scripts.
def r(self, **kwargs): """ Resolve the object. This returns default (if present) or fails on an Empty. """ # by using kwargs we ensure that usage of positional arguments, as if # this object were another kind of function, will fail-fast and raise # a TypeError ...
How would you implement a function in Python 3 that resolves the object. This returns default if present otherwise raises a TypeError.
You are a Python code architect, reviewing and designing scalable and efficient code
def r(self, **kwargs): """ Resolve the object. This will always succeed, since, if a lookup fails, an Empty instance will be returned farther upstream. """ # by using kwargs we ensure that usage of positional arguments, as if # this object were another kind of fu...
How would you code a function in Python 3 to resolve the object. This will always succeed, since, if a lookup fails, an Empty instance will be returned farther upstream.
As a Python code analyst, you investigate and solve complex coding mysteries
def update_cache_for_instance( model_name, instance_pk, instance=None, version=None): """Update the cache for an instance, with cascading updates.""" cache = SampleCache() invalid = cache.update_instance(model_name, instance_pk, instance, version) for invalid_name, invalid_pk, invalid_version in...
Write a Python 3 function for updating the cache for an instance with cascading updates.
You are a Python code architect, reviewing and designing scalable and efficient code
def values_list(self, *args, **kwargs): """Return the primary keys as a list. The only valid call is values_list('pk', flat=True) """ flat = kwargs.pop('flat', False) assert flat is True assert len(args) == 1 assert args[0] == self.model._meta.pk.name ret...
Implement a function in Python 3 to return the primary keys as a list.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a count of instances.
Here you have a function in Python 3, explain what it does def count(self): if self._primary_keys is None: return self.queryset.count() else: return len(self.pks)
You are a Python code analyst, evaluating scripts for potential improvements.
def filter(self, **kwargs): """Filter the base queryset.""" assert not self._primary_keys self.queryset = self.queryset.filter(**kwargs) return self
Can you create a Python 3 function that filters the base queryset.
As a Python code analyst, you investigate and solve complex coding mysteries
Return the single item from the filtered queryset.
Explain what the following Python 3 code does def get(self, *args, **kwargs): assert not args assert list(kwargs.keys()) == ['pk'] pk = kwargs['pk'] model_name = self.model.__name__ object_spec = (model_name, pk, None) instances = self.cache.get_instances((object_spec,)) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def collect(cls): """ Load all constant generators from settings.WEBPACK_CONSTANT_PROCESSORS and concat their values. """ constants = {} for method_path in WebpackConstants.get_constant_processors(): method = import_string(method_path) if not callabl...
How would you code a function in Python 3 to load all constant generators from settings. WEBPACK_CONSTANT_PROCESSORS and concat their values.
As a python code expert, you are capable of creating scripts from specifications.
def phonenumber_validation(data): """ Validates phonenumber Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the country prefix is absent. """ from phonenumber_field.phonenumber import to_python phone_number = to_python(data) if no...
Can you implement a function in Python 3 that validates the phone number.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_catalog(self, locale): """Create Django translation catalogue for `locale`.""" with translation.override(locale): translation_engine = DjangoTranslation(locale, domain=self.domain, localedirs=self.paths) trans_cat = translation_engine._catalog trans_fallback_...
Write a Python 3 script for creating Django translation catalogue for locale.
As a Python code analyst, you investigate and solve complex coding mysteries
Create list of matching packages for translation engine.
Here you have a function in Python 3, explain what it does def get_paths(cls, packages): allowable_packages = dict((app_config.name, app_config) for app_config in apps.get_app_configs()) app_configs = [allowable_packages[p] for p in packages if p in allowable_packages] # paths of requested packa...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get. po header value.
Explain what the following Python 3 code does def get_catalogue_header_value(cls, catalog, key): header_value = None if '' in catalog: for line in catalog[''].split('\n'): if line.startswith('%s:' % key): header_value = line.split(':', 1)[1].strip() ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _num_plurals(self, catalogue): """ Return the number of plurals for this catalog language, or 2 if no plural string is available. """ match = re.search(r'nplurals=\s*(\d+)', self.get_plural(catalogue) or '') if match: return int(match.groups()[0]) ...
Write a Python 3 function for returning the number of plurals for this catalog language.
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_header(self, locale, catalog): """Populate header with correct data from top-most locale file.""" return { "po-revision-date": self.get_catalogue_header_value(catalog, 'PO-Revision-Date'), "mime-version": self.get_catalogue_header_value(catalog, 'MIME-Version'), ...
How would you implement a function in Python 3 that populates header with correct data from top - most locale file.
As a Python code composer, you craft elegant and concise scripts.
Collect all domain translations and return a tuple of languages and locale_data
Here you have a function in Python 3, explain what it does def collect_translations(self): languages = {} locale_data = {} for language_code, label in settings.LANGUAGES: languages[language_code] = '%s' % label # Create django translation engine for `language_code` ...
You are a Python code analyst, evaluating scripts for potential improvements.
Tiny helper function that gets used all over the place to join the object ID to the endpoint and run a GET request
Explain what the following Python 3 code does def get_endpoint_obj(client, endpoint, object_id): ''' Tiny helper function that gets used all over the place to join the object ID to the endpoint and run a GET request, returning the result ''' endpoint = '/'.join([endpoint, str(object_id)]) return client.auth...
You are a Python code generator, capable of creating scripts from specifications.
Update an object in an endpoint
Make a summary of the following Python 3 code def update_endpoint_obj(client, endpoint, object_id, revision, data): ''' Helper method to ease the repetitiveness of updating an... SO VERY DRY (That's a doubly-effective pun becuase my predecessor - https://github.com/bsmt/wunderpy - found maintaing a P...
You are a Python code analyst, evaluating scripts for potential improvements.
Helper method to validate the response to a Wunderlist API request is as expected
Here you have a function in Python 3, explain what it does def _validate_response(self, method, response): ''' Helper method to validate the given to a Wunderlist API request is as expected ''' # TODO Fill this out using the error codes here: https://developer.wunderlist.com/documentation/concepts/forma...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a request to the given Wunderlist API endpoint.
Make a summary of the following Python 3 code def request(self, endpoint, method='GET', headers=None, params=None, data=None): ''' Send a request to the given Wunderlist API endpoint Params: endpoint -- API endpoint to send request to Keyword Args: headers -- headers to...
As a python code expert, you are capable of creating scripts from specifications.
Get an access token for a user
Given the following Python 3 function, write the documentation def get_access_token(self, code, client_id, client_secret): ''' Exchange a temporary code for an access token allowing access to a user's account See https://developer.wunderlist.com/documentation/concepts/authorization for more in...
As a Python code analyst, you investigate and solve complex coding mysteries
def authenticated_request(self, endpoint, method='GET', params=None, data=None): ''' Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type Params: endpoint -- API endpoint to send req...
Implement a Python 3 function for sending a request to the given Wunderlist API endpoint with X - Access - Token and X - Client - ID headers and ensure the response code is as expected
As a Python code analyst, you investigate and solve complex coding mysteries
Updates the list with the given ID to have the given title and public flag.
Can you generate a brief explanation for the following Python 3 code def update_list(self, list_id, revision, title=None, public=None): ''' Updates the list with the given ID to have the given title and public flag ''' return lists_endpoint.update_list(self, list_id, revision, title=title, public=public...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_tasks(self, list_id, completed=False): ''' Gets tasks for the list with the given ID, filtered by the given completion flag ''' return tasks_endpoint.get_tasks(self, list_id, completed=completed)
Write a Python 3 script to get the list of tasks for the given ID filtered by the given completion flag
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a new task with the given information in the given ID
Can you generate a brief explanation for the following Python 3 code def create_task(self, list_id, title, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None): ''' Creates a new task with the given information in the list with the given ID ''' retu...
As a Python code translator, you convert algorithms and pseudocode into Python.
Updates the task with the given ID to have the given information
Can you generate the documentation for the following Python 3 function def update_task(self, task_id, revision, title=None, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None, remove=None): ''' Updates the task with the given ID to have the given ...
As a Python code composer, you craft elegant and concise scripts.
Updates the note with the given ID to have the given content.
Given the following Python 3 function, write the documentation def update_note(self, note_id, revision, content): ''' Updates the note with the given ID to have the given content ''' return notes_endpoint.update_note(self, note_id, revision, content)
As a python code expert, you are capable of creating scripts from specifications.
Gets the subtasks for the given task with given ID
Here you have a function in Python 3, explain what it does def get_task_subtasks(self, task_id, completed=False): ''' Gets subtasks for task with given ID ''' return subtasks_endpoint.get_task_subtasks(self, task_id, completed=completed)
You are a Python code generator, capable of creating scripts from specifications.
Gets the list s subtasks for the given ID
Can you tell what is the following Python 3 function doing def get_list_subtasks(self, list_id, completed=False): ''' Gets subtasks for the list with given ID ''' return subtasks_endpoint.get_list_subtasks(self, list_id, completed=completed)
You are a Python code architect, reviewing and designing scalable and efficient code
def create_subtask(self, task_id, title, completed=False): ''' Creates a subtask with the given title under the task with the given ID Return: Newly-created subtask ''' return subtasks_endpoint.create_subtask(self, task_id, title, completed=completed)
How would you implement a function in Python 3 that creates a new subtask with the given title under the task with the given ID
As a Python code translator, you convert algorithms and pseudocode into Python.
Updates the subtask with the given ID with properties and revision
Explain what the following Python 3 code does def update_subtask(self, subtask_id, revision, title=None, completed=None): ''' Updates the subtask with the given ID See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information Returns: S...
You are a Python code generator, capable of creating scripts from specifications.
Updates the ordering of lists to have the given value.
How would you explain what the following Python 3 function does def update_list_positions_obj(self, positions_obj_id, revision, values): ''' Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out. See ht...
You are a Python code generator, capable of creating scripts from specifications.
Updates the ordering of tasks in the given positions object with the given ID to the given values.
Can you tell what is the following Python 3 function doing def update_task_positions_obj(self, positions_obj_id, revision, values): ''' Updates the ordering of tasks in the positions object with the given ID to the ordering in the given values. See https://developer.wunderlist.com/documentation...
As a python code expert, you are capable of creating scripts from specifications.