output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Collect entities for theses tags.
Make a summary of the following Python 3 code def get_entities_for_reindex(tags): if isinstance(tags, Tag): tags = (tags,) session = db.session() indexing = get_service("indexing") tbl = Entity.__table__ tag_ids = [t.id for t in tags] query = ( sa.sql.select([tbl.c.entity_type, ...
As a Python code composer, you craft elegant and concise scripts.
Schedule entities to be reindexed.
How would you explain what the following Python 3 function does def schedule_entities_reindex(entities): entities = [(e[0], e[1], e[2], dict(e[3])) for e in entities] return index_update.apply_async(kwargs={"index": "default", "items": entities})
As a python code expert, you are capable of creating scripts from specifications.
Scan the file for an anti - virus and store the result in the object s meta attribute.
Given the following Python 3 function, write the documentation def scan(self, file_or_stream): if not clamd: return None res = self._scan(file_or_stream) if isinstance(file_or_stream, Blob): file_or_stream.meta["antivirus"] = res return res
As a python code expert, you are capable of creating scripts from specifications.
Compatibility wrapper for Python 2. 6 missin g subprocess. check_output
How would you explain what the following Python 3 function does def check_output(*args, **kwargs): '''Compatibility wrapper for Python 2.6 missin g subprocess.check_output''' if hasattr(subprocess, 'check_output'): return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True, ...
You are a Python code architect, reviewing and designing scalable and efficient code
This method is called by the view class to prepare the arguments for the view.
Can you generate the documentation for the following Python 3 function def prepare_args(self, args, kwargs): args, kwargs = super().prepare_args(args, kwargs) form_kwargs = self.get_form_kwargs() self.form = self.Form(**form_kwargs) return args, kwargs
As a python code expert, you are capable of creating scripts from specifications.
def form_valid(self, redirect_to=None): """Save object. Called when form is validated. :param redirect_to: real url (created with url_for) to redirect to, instead of the view by default. """ session = db.session() with session.no_autoflush: self.b...
Write a Python 3 script to call when form is validated.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_item(self, obj): """Return a result item. :param obj: Instance object :returns: a dictionnary with at least `id` and `text` values """ return {"id": obj.id, "text": self.get_label(obj), "name": obj.name}
Write a Python 3 script for returning a result item with at least id and text values.
As a Python code composer, you craft elegant and concise scripts.
def pip(name): '''Parse requirements file''' with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f: return f.readlines()
Write a Python 3 script to parse pip requirements file
You are a Python code analyst, evaluating scripts for potential improvements.
def convert(self, blob, size=500): """Size is the maximum horizontal size.""" file_list = [] with make_temp_file(blob) as in_fn, make_temp_file() as out_fn: try: subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn]) file_list = sorted(glob.glob(f...
Write a Python 3 script for converting the image from one file to another.
You are a Python code architect, reviewing and designing scalable and efficient code
Convert a PDF file using Unoconv.
Can you generate a brief explanation for the following Python 3 code def convert(self, blob, **kw): timeout = self.run_timeout with make_temp_file(blob) as in_fn, make_temp_file( prefix="tmp-unoconv-", suffix=".pdf" ) as out_fn: args = ["-f", "pdf", "-o", out_fn, in_fn] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a file using soffice converter.
Explain what the following Python 3 code does def convert(self, blob, **kw): timeout = self.run_timeout with make_temp_file(blob) as in_fn: cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn] # # TODO: fix this if needed, or remove if not needed # if os...
You are a Python code generator, capable of creating scripts from specifications.
Blank lines delimitates paragraphs.
Can you generate a brief explanation for the following Python 3 code def paragraphs(value): result = "\n\n".join( "<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n"))) for p in _PARAGRAPH_RE.split(escape(value)) ) return result
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a rough size string.
Make a summary of the following Python 3 code def roughsize(size, above=20, mod=10): if size < above: return str(size) return "{:d}+".format(size - size % mod)
As a python code expert, you are capable of creating scripts from specifications.
Parse a string date time to a datetime object.
Here you have a function in Python 3, explain what it does def datetimeparse(s): try: dt = dateutil.parser.parse(s) except ValueError: return None return utc_dt(dt)
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a string representation of the current date or time.
Can you generate the documentation for the following Python 3 function def age(dt, now=None, add_direction=True, date_threshold=None): # Fail silently for now XXX if not dt: return "" if not now: now = datetime.datetime.utcnow() locale = babel.get_locale() dt = utc_dt(dt) now =...
You are a Python code architect, reviewing and designing scalable and efficient code
def babel2datepicker(pattern): """Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by bootstrap-datepicker.""" if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "dd", ...
Can you create a Python 3 function that converts date format from babel to bootstrap - datepicker.
You are a Python code generator, capable of creating scripts from specifications.
def app_state(self): """Current service state in current application. :raise:RuntimeError if working outside application context. """ try: return current_app.extensions[self.name] except KeyError: raise ServiceNotRegistered(self.name)
Can you implement a function in Python 3 that returns the current state of the service in current application.
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator for service methods that must be ran only if service is in running state.
Explain what the following Python 3 code does def if_running(meth): @wraps(meth) def check_running(self, *args, **kwargs): if not self.running: return return meth(self, *args, **kwargs) return check_running
You are a Python code analyst, evaluating scripts for potential improvements.
def publish(self): '''Publish the current release to PyPI''' if self.config.publish: logger.info('Publish') self.execute(self.config.publish)
Can you implement a function in Python 3 that publishes the current release to PyPI
You are a Python code architect, reviewing and designing scalable and efficient code
Display a success message
Can you generate a brief explanation for the following Python 3 code def success(text): '''Display a success message''' print(' '.join((green('✔'), white(text)))) sys.stdout.flush()
As a Python code composer, you craft elegant and concise scripts.
def error(text): '''Display an error message''' print(red('✘ {0}'.format(text))) sys.stdout.flush()
Write a Python 3 function for displaying an error message
As a Python code translator, you convert algorithms and pseudocode into Python.
def deps(ctx): '''Install or update development dependencies''' header(deps.__doc__) with ctx.cd(ROOT): ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True)
Write a Python 3 function that can install or update development dependencies
As a Python code analyst, you investigate and solve complex coding mysteries
Run a quality report
How would you explain what the following Python 3 function does def qa(ctx): '''Run a quality report''' header(qa.__doc__) with ctx.cd(ROOT): info('Python Static Analysis') flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True) if flake8_results.failed: error('Ther...
As a Python code composer, you craft elegant and concise scripts.
Generate bash completion script
Can you generate the documentation for the following Python 3 function def completion(ctx): '''Generate bash completion script''' header(completion.__doc__) with ctx.cd(ROOT): ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True) success('Completion generated in bumpr-complete.sh...
As a python code expert, you are capable of creating scripts from specifications.
def _check_view_permission(self, view): """ :param view: a :class:`ObjectView` class or instance """ security = get_service("security") return security.has_permission(current_user, view.permission, self.obj)
Write a Python 3 script for checking if the current user has permission to view.
As a Python code analyst, you investigate and solve complex coding mysteries
Register an entity as a taggable class.
Explain what the following Python 3 code does def register(cls): if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") SupportTagging.register(cls) return cls
You are a Python code architect, reviewing and designing scalable and efficient code
returns True if the object supports tagging
Can you generate the documentation for the following Python 3 function def supports_tagging(obj): if isinstance(obj, type): return issubclass(obj, SupportTagging) if not isinstance(obj, SupportTagging): return False if obj.id is None: return False return True
You are a Python code analyst, evaluating scripts for potential improvements.
Register an entity as a attachmentable class.
Can you generate the documentation for the following Python 3 function def register(cls): if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") SupportAttachment.register(cls) return cls
As a python code expert, you are capable of creating scripts from specifications.
def supports_attachments(obj): """ :param obj: a class or instance :returns: True is obj supports attachments. """ if isinstance(obj, type): return issubclass(obj, SupportAttachment) if not isinstance(obj, SupportAttachment): return False if obj.id is None: return ...
Write a Python 3 function that can return True if the object supports attachments.
You are a Python code generator, capable of creating scripts from specifications.
def for_entity(obj, check_support_attachments=False): """Return attachments on an entity.""" if check_support_attachments and not supports_attachments(obj): return [] return getattr(obj, ATTRIBUTE)
Can you implement a function in Python 3 that returns a list of attachments on an entity.
You are a Python code analyst, evaluating scripts for potential improvements.
def strip_label(mapper, connection, target): """Strip labels at ORM level so the unique=True means something.""" if target.label is not None: target.label = target.label.strip()
Write a Python 3 function for stripping labels at ORM level so the unique = True means something.
You are a Python code analyst, evaluating scripts for potential improvements.
Set item to last position if position not defined.
Here you have a function in Python 3, explain what it does def _before_insert(mapper, connection, target): if target.position is None: func = sa.sql.func stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)]) target.position = connection.execute(stmt).scalar() + 1
You are a Python code analyst, evaluating scripts for potential improvements.
Like. get but by label.
Explain what the following Python 3 code does def by_label(self, label): # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(label=label).one() except sa.orm.exc.NoResultFound: return None
As a Python code translator, you convert algorithms and pseudocode into Python.
def by_position(self, position): """Like `.get()`, but by position number.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(position=position).one() except sa.orm.exc.NoResultFound: return None
Write a Python 3 script to like get but by position number.
You are a Python code architect, reviewing and designing scalable and efficient code
Used during exception handling in case we need to remove session and merge instances in the new session.
Can you tell what is the following Python 3 function doing def _remove_session_save_objects(self): if self.testing: return # Before destroying the session, get all instances to be attached to the # new session. Without this, we get DetachedInstance errors, like when # tryin t...
You are a Python code architect, reviewing and designing scalable and efficient code
Log exception only if Sentry is not used.
Can you generate the documentation for the following Python 3 function def log_exception(self, exc_info): dsn = self.config.get("SENTRY_DSN") if not dsn: super().log_exception(exc_info)
You are a Python code architect, reviewing and designing scalable and efficient code
Install Sentry handler if config defines Sentry_DSN.
Can you generate the documentation for the following Python 3 function def init_sentry(self): dsn = self.config.get("SENTRY_DSN") if not dsn: return try: import sentry_sdk except ImportError: logger.error( 'SENTRY_DSN is defined in con...
As a Python code analyst, you investigate and solve complex coding mysteries
Install a default error handler for the given HTTP error code.
Can you generate the documentation for the following Python 3 function def install_default_handler(self, http_error_code): logger.debug( "Set Default HTTP error handler for status code %d", http_error_code ) handler = partial(self.handle_http_error, http_error_code) self.erro...
You are a Python code generator, capable of creating scripts from specifications.
Associate a url_func with an entity s type.
How would you explain what the following Python 3 function does def register(self, entity, url_func): if not inspect.isclass(entity): entity = entity.__class__ assert issubclass(entity, db.Model) self._map[entity.entity_type] = url_func
As a Python code translator, you convert algorithms and pseudocode into Python.
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs): """Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_...
Write a Python 3 script to return canonical view URL for given entity instance.
You are a Python code generator, capable of creating scripts from specifications.
Return the path object used for storing the value.
Can you generate the documentation for the following Python 3 function def file(self): from abilian.services.repository import session_repository as repository return repository.get(self, self.uuid)
You are a Python code analyst, evaluating scripts for potential improvements.
Return the value of the key.
Can you generate the documentation for the following Python 3 function def value(self): # type: () -> bytes """Binary value content.""" v = self.file return v.open("rb").read() if v is not None else v
You are a Python code generator, capable of creating scripts from specifications.
def value(self, value, encoding="utf-8"): """Store binary content to applications's repository and update `self.meta['md5']`. :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode """ from abilian.ser...
How would you implement a function in Python 3 that stores binary content to applications s repository and update self. meta. mimetype.
You are a Python code architect, reviewing and designing scalable and efficient code
def value(self): """Remove value from repository.""" from abilian.services.repository import session_repository as repository repository.delete(self, self.uuid)
How would you implement a function in Python 3 that removes value from repository.
You are a Python code generator, capable of creating scripts from specifications.
Return md5 from meta or compute it if absent.
Can you generate the documentation for the following Python 3 function def md5(self): md5 = self.meta.get("md5") if md5 is None: md5 = str(hashlib.md5(self.value).hexdigest()) return md5
As a Python code translator, you convert algorithms and pseudocode into Python.
def forgotten_pw(new_user=False): """Reset password for users who have already activated their accounts.""" email = request.form.get("email", "").lower() action = request.form.get("action") if action == "cancel": return redirect(url_for("login.login_form")) if not email: flash(_("Y...
Write a Python 3 function that can forget password for users who have already activated their accounts.
As a Python code composer, you craft elegant and concise scripts.
def send_reset_password_instructions(user): # type: (User) -> None """Send the reset password instructions email for the specified user. :param user: The user to send the instructions to """ token = generate_reset_password_token(user) url = url_for("login.reset_password", token=token) reset...
Can you implement a function in Python 3 that sends the reset password instructions email for the specified user.
As a Python code analyst, you investigate and solve complex coding mysteries
def generate_reset_password_token(user): # type: (User) -> Any """Generate a unique reset password token for the specified user. :param user: The user to work with """ data = [str(user.id), md5(user.password)] return get_serializer("reset").dumps(data)
Implement a Python 3 function for generating a unique reset password token for the specified user.
You are a Python code generator, capable of creating scripts from specifications.
def send_mail(subject, recipient, template, **context): """Send an email using the Flask-Mail extension. :param subject: Email subject :param recipient: Email recipient :param template: The name of the email template :param context: The context to render the template with """ config = curr...
Create a Python 3 function to send an email using the Flask - Mail extension.
As a Python code analyst, you investigate and solve complex coding mysteries
def register_plugin(self, name): """Load and register a plugin given its package name.""" logger.info("Registering plugin: " + name) module = importlib.import_module(name) module.register_plugin(self)
Implement a function in Python 3 to load and register a plugin given its package name.
As a Python code translator, you convert algorithms and pseudocode into Python.
def register_plugins(self): """Load plugins listed in config variable 'PLUGINS'.""" registered = set() for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]): if plugin_fqdn not in registered: self.register_plugin(plugin_fqdn) registered.ad...
Write a Python 3 script for loading plugins listed in config variable PLUGINS.
As a Python code analyst, you investigate and solve complex coding mysteries
def init_breadcrumbs(self): """Insert the first element in breadcrumbs. This happens during `request_started` event, which is triggered before any url_value_preprocessor and `before_request` handlers. """ g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_r...
Can you write a function in Python 3 where it inserts the first element in breadcrumbs.
You are a Python code architect, reviewing and designing scalable and efficient code
Verify that the instance folder exists is a directory and has necessary permissions.
Given the following Python 3 function, write the documentation def check_instance_folder(self, create=False): path = Path(self.instance_path) err = None eno = 0 if not path.exists(): if create: logger.info("Create instance folder: %s", path) p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize flask extensions helpers and services.
Given the following Python 3 function, write the documentation def init_extensions(self): extensions.redis.init_app(self) extensions.mail.init_app(self) extensions.deferred_js.init_app(self) extensions.upstream_info.extension.init_app(self) actions.init_app(self) # auth_...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_url_rule(self, rule, endpoint=None, view_func=None, roles=None, **options): """See :meth:`Flask.add_url_rule`. If `roles` parameter is present, it must be a :class:`abilian.service.security.models.Role` instance, or a list of Role instances. """ super().add_url_r...
Create a Python 3 function for adding a url rule to the current flask instance.
You are a Python code analyst, evaluating scripts for potential improvements.
Add an access controller function to the application level.
Explain what the following Python 3 code does def add_access_controller(self, name: str, func: Callable, endpoint: bool = False): auth_state = self.extensions[auth_service.name] adder = auth_state.add_bp_access_controller if endpoint: adder = auth_state.add_endpoint_access_controlle...
As a python code expert, you are capable of creating scripts from specifications.
def add_static_url(self, url_path, directory, endpoint=None, roles=None): """Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flas...
Create a Python 3 function to add a new url rule for static files.
As a python code expert, you are capable of creating scripts from specifications.
Send a single message instance.
Explain what the following Python 3 code does def _message_send(self, connection): sender = current_app.config["MAIL_SENDER"] if not self.extra_headers: self.extra_headers = {} self.extra_headers["Sender"] = sender connection.send(self, sender)
You are a Python code analyst, evaluating scripts for potential improvements.
Filter the metadata for a connection.
Here you have a function in Python 3, explain what it does def _filter_metadata_for_connection(target, connection, **kw): engine = connection.engine.name default_engines = (engine,) tables = target if isinstance(target, sa.Table) else kw.get("tables", []) for table in tables: indexes = list(tabl...
You are a Python code analyst, evaluating scripts for potential improvements.
Polymorphic variant of Flask s url_for function.
Explain what the following Python 3 code does def url_for(obj, **kw): if isinstance(obj, str): return flask_url_for(obj, **kw) try: return current_app.default_view.url_for(obj, **kw) except KeyError: if hasattr(obj, "_url"): return obj._url elif hasattr(obj, "url...
As a Python code analyst, you investigate and solve complex coding mysteries
Send a file from a directory.
Make a summary of the following Python 3 code def send_file_from_directory(filename, directory, app=None): if app is None: app = current_app cache_timeout = app.get_send_file_max_age(filename) return send_from_directory(directory, filename, cache_timeout=cache_timeout)
As a Python code analyst, you investigate and solve complex coding mysteries
def get_model_changes( entity_type, year=None, month=None, day=None, hour=None, since=None ): # type: (Text, int, int, int, int, datetime) -> Query """Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware th...
Implement a Python 3 function for getting models modified at the given date with the Audit service.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: ...
Write a Python 3 function for adding the changed columns as a diff attribute.
As a Python code translator, you convert algorithms and pseudocode into Python.
Test whether a function expects an argument.
Explain what the following Python 3 code does def _has_argument(func): if hasattr(inspect, 'signature'): # New way in python 3.3 sig = inspect.signature(func) return bool(sig.parameters) else: # Old way return bool(inspect.getargspec(func).args)
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_site(cls, searchpath="templates", outpath=".", contexts=None, rules=None, encoding="utf8", followlinks=True, extensions=None, staticpaths=None, filte...
How would you code a function in Python 3 to create a new Site object.
You are a Python code generator, capable of creating scripts from specifications.
Get the context for a template.
Can you generate a brief explanation for the following Python 3 code def get_context(self, template): context = {} for regex, context_generator in self.contexts: if re.match(regex, template.name): if inspect.isfunction(context_generator): if _has_argument(...
As a python code expert, you are capable of creating scripts from specifications.
Find a matching compilation rule for a template name.
Can you tell what is the following Python 3 function doing def get_rule(self, template_name): for regex, render_func in self.rules: if re.match(regex, template_name): return render_func raise ValueError("no matching rule")
As a Python code analyst, you investigate and solve complex coding mysteries
def is_static(self, filename): """Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check ...
How would you code a function in Python 3 to check if a file is static.
As a Python code analyst, you investigate and solve complex coding mysteries
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of t...
How would you code a function in Python 3 to check if a file is a partial.
You are a Python code architect, reviewing and designing scalable and efficient code
Check if a file is a template.
How would you explain what the following Python 3 function does def is_template(self, filename): if self.is_partial(filename): return False if self.is_ignored(filename): return False if self.is_static(filename): return False return True
You are a Python code generator, capable of creating scripts from specifications.
def _ensure_dir(self, template_name): """Ensure the output directory for a template exists.""" head = os.path.dirname(template_name) if head: file_dirpath = os.path.join(self.outpath, head) if not os.path.exists(file_dirpath): os.makedirs(file_dirpath)
Create a Python 3 function to ensure the output directory for a template exists.
You are a Python code generator, capable of creating scripts from specifications.
def render_template(self, template, context=None, filepath=None): """Render a single :class:`jinja2.Template` object. If a Rule matching the template is found, the rendering task is delegated to the rule. :param template: A :class:`jinja2.Template` to render. :para...
How would you code a function in Python 3 to render a single template object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Render a collection of templates into a file or file - like object.
How would you explain what the following Python 3 function does def render_templates(self, templates, filepath=None): for template in templates: self.render_template(template, filepath)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_dependencies(self, filename): """Get a list of files that depends on the file named *filename*. :param filename: the name of the file to find dependencies of """ if self.is_partial(filename): return self.templates elif self.is_template(filename): ...
Implement a Python 3 function for returning a list of files that depend on the file named filename.
As a Python code translator, you convert algorithms and pseudocode into Python.
def render(self, use_reloader=False): """Generate the site. :param use_reloader: if given, reload templates on modification """ self.render_templates(self.templates) self.copy_static(self.static_names) if use_reloader: self.logger.info("Watching '%s' for cha...
Implement a Python 3 function for generating the site. :param use_reloader: if given, reload templates on modification
As a python code expert, you are capable of creating scripts from specifications.
def register_jinja_loaders(self, *loaders): """Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered i...
Can you create a Python 3 function that registers one or many jinja2. Loader instances for templates lookup.
You are a Python code generator, capable of creating scripts from specifications.
Search templates in custom app templates dir ( default Flask behaviour fallback on abilian templates.
Can you tell what is the following Python 3 function doing def jinja_loader(self): loaders = self._jinja_loaders del self._jinja_loaders loaders.append(Flask.jinja_loader.func(self)) loaders.reverse() return jinja2.ChoiceLoader(loaders)
You are a Python code analyst, evaluating scripts for potential improvements.
Render a single site.
Explain what the following Python 3 code does def render(args): srcpath = ( os.path.join(os.getcwd(), 'templates') if args['--srcpath'] is None else args['--srcpath'] if os.path.isabs(args['--srcpath']) else os.path.join(os.getcwd(), args['--srcpath']) ) if not os.path.isdir(srcpath...
You are a Python code generator, capable of creating scripts from specifications.
def indexable_role(principal): """Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`. """ principal = unwrap(principal) if hasattr(principal, "...
How would you implement a function in Python 3 that returns a string suitable for query against allowed_roles_and_users or allowed_users_and_users field.
As a Python code translator, you convert algorithms and pseudocode into Python.
def to_text(self, digest, blob, mime_type): """Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = "txt:" + digest text = ...
Write a Python 3 script for converting a file to plain text.
As a Python code analyst, you investigate and solve complex coding mysteries
def has_image(self, digest, mime_type, index, size=500): """Tell if there is a preview image.""" cache_key = f"img:{index}:{size}:{digest}" return mime_type.startswith("image/") or cache_key in self.cache
How would you code a function in Python 3 to tell if there is a preview image.
As a python code expert, you are capable of creating scripts from specifications.
def get_image(self, digest, blob, mime_type, index, size=500): """Return an image for the given content, only if it already exists in the image cache.""" # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{dig...
Create a Python 3 function to return an image for the given content in the image cache.
As a Python code composer, you craft elegant and concise scripts.
Convert a file to a list of images.
Can you generate the documentation for the following Python 3 function def to_image(self, digest, blob, mime_type, index, size=500): # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" converted = self.cache....
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_metadata(self, digest, content, mime_type): """Get a dictionary representing the metadata embedded in the given content.""" # XXX: ad-hoc for now, refactor later if mime_type.startswith("image/"): img = Image.open(BytesIO(content)) ret = {} if...
Can you implement a function in Python 3 that gets a dictionary representing the metadata embedded in the given content.
You are a Python code architect, reviewing and designing scalable and efficient code
Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command.
Here you have a function in Python 3, explain what it does def ToByteArray(self): lc = self.InternalEncodeLc() out = bytearray(4) # will extend out[0] = self.cla out[1] = self.ins out[2] = self.p1 out[3] = self.p2 if self.data: out.extend(lc) out.extend(self.data) out.ext...
You are a Python code generator, capable of creating scripts from specifications.
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # Ensure environment variable is present plugin_cmd = os.environ.get(SK_SIGNING_PLUGIN_ENV_VAR) if plugin_cmd is None: raise errors.PluginError('{} env var is not set' ...
Write a Python 3 script to authenticate the user with the challenge_data.
You are a Python code architect, reviewing and designing scalable and efficient code
def _BuildPluginRequest(self, app_id, challenge_data, origin): """Builds a JSON request in the form that the plugin expects.""" client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item...
Implement a Python 3 function for building a JSON request for the plugin.
As a Python code translator, you convert algorithms and pseudocode into Python.
Builds the response to return to the caller.
Can you generate the documentation for the following Python 3 function def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response): encoded_client_data = self._Base64Encode(client_data) signature_data = str(plugin_response['signatureData']) key_handle = str(plugin_response['keyHandle']) ...
As a python code expert, you are capable of creating scripts from specifications.
def _CallPlugin(self, cmd, input_json): """Calls the plugin and validates the response.""" # Calculate length of input input_length = len(input_json) length_bytes_le = struct.pack('<I', input_length) request = length_bytes_le + input_json.encode() # Call plugin sign_process = subprocess.Pop...
Can you implement a function in Python 3 that calls the plugin and validates the response.
You are a Python code generator, capable of creating scripts from specifications.
Initializes the device and obtains channel id.
Explain what the following Python 3 code does def InternalInit(self): self.cid = UsbHidTransport.U2FHID_BROADCAST_CID nonce = bytearray(os.urandom(8)) r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce) if len(r) < 17: raise errors.HidError('unexpected init reply len') if r[0:8] != n...
As a Python code composer, you craft elegant and concise scripts.
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload)...
How would you code a function in Python 3 to send and receives a message from the device.
You are a Python code architect, reviewing and designing scalable and efficient code
def InternalSend(self, cmd, payload): """Sends a message to the device, including fragmenting it.""" length_to_send = len(payload) max_payload = self.packet_size - 7 first_frame = payload[0:max_payload] first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd, ...
Write a Python 3 script to send a message to the device including fragmenting it.
You are a Python code analyst, evaluating scripts for potential improvements.
def InternalRecv(self): """Receives a message from the device, including defragmenting it.""" first_read = self.InternalReadFrame() first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size, first_read) data = first_packet.pay...
Write a Python 3 script to receive a message from the device including defragmenting it.
You are a Python code analyst, evaluating scripts for potential improvements.
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # If authenticator is not plugged in, prompt try: device = u2f.GetLocalU2FInterface(origin=self.origin) except errors.NoDeviceFoundError: print_callback('Please insert yo...
Write a Python 3 function for authenticating the user with the given application ID.
You are a Python code architect, reviewing and designing scalable and efficient code
Determine on a platform - specific basis which module to use.
Here you have a function in Python 3, explain what it does def InternalPlatformSwitch(funcname, *args, **kwargs): # pylint: disable=g-import-not-at-top clz = None if sys.platform.startswith('linux'): from pyu2f.hid import linux clz = linux.LinuxHidDevice elif sys.platform.startswith('win32'): from p...
You are a Python code architect, reviewing and designing scalable and efficient code
def GetJson(self): """Returns JSON version of ClientData compatible with FIDO spec.""" # The U2F Raw Messages specification specifies that the challenge is encoded # with URL safe Base64 without padding encoding specified in RFC 4648. # Python does not natively support a paddingless encoding, so we sim...
Implement a function in Python 3 to return JSON version of ClientData compatible with FIDO spec.
As a python code expert, you are capable of creating scripts from specifications.
def GetValueLength(rd, pos): """Get value length for a key in rd. For a key at position pos in the Report Descriptor rd, return the length of the associated value. This supports both short and long format values. Args: rd: Report Descriptor pos: The position of the key in rd. Returns: (key_s...
How would you implement a function in Python 3 that gets the length of a value in a report descriptor.
You are a Python code analyst, evaluating scripts for potential improvements.
Reads value_size bytes from rd at offset least signifcant byte first.
How would you explain what the following Python 3 function does def ReadLsbBytes(rd, offset, value_size): encoding = None if value_size == 1: encoding = '<B' elif value_size == 2: encoding = '<H' elif value_size == 4: encoding = '<L' else: raise errors.HidError('Invalid value size specified')...
You are a Python code generator, capable of creating scripts from specifications.
def ParseReportDescriptor(rd, desc): """Parse the binary report descriptor. Parse the binary report descriptor into a DeviceDescriptor object. Args: rd: The binary report descriptor desc: The DeviceDescriptor object to update with the results from parsing the descriptor. Returns: None "...
Write a Python 3 function for parsing the binary report descriptor into a DeviceDescriptor object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def Write(self, packet): """See base class.""" out = bytearray([0] + packet) # Prepend the zero-byte (report ID) os.write(self.dev, out)
Write a Python 3 function for writing packet to the device.
As a Python code composer, you craft elegant and concise scripts.