code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
load_metafile.cache_clear()
meta = load_metafile(fullpath)
if not meta:
return True
# update the category meta file mapping
category = meta.get('Category', utils.get_category(relpath))
values = {
'category': category,
'file_path': fullpath,
'sort_name': me... | def scan_file(fullpath, relpath) | scan a file and put it into the index | 5.438581 | 5.34481 | 1.017544 |
if self._meta and self._meta.get('name'):
# get it from the meta file
return self._meta.get('name')
# infer it from the basename
return self.basename.replace('_', ' ').title() | def name(self) | Get the display name of the category | 5.247737 | 4.882192 | 1.074873 |
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._description)
return utils.CallableProxy(None) | def description(self) | Get the textual description of the category | 19.434856 | 21.027372 | 0.924265 |
ret = []
here = self
while here:
ret.append(here)
here = here.parent
return list(reversed(ret)) | def breadcrumb(self) | Get the category hierarchy leading up to this category, including
root and self.
For example, path/to/long/category will return a list containing
Category('path'), Category('path/to'), and Category('path/to/long'). | 4.254313 | 4.041191 | 1.052737 |
if self._record and self._record.sort_name:
return self._record.sort_name
return self.name | def sort_name(self) | Get the sorting name of this category | 4.965058 | 4.588916 | 1.081967 |
if self.path:
return Category(os.path.dirname(self.path))
return None | def parent(self) | Get the parent category | 7.432991 | 4.557339 | 1.630993 |
if recurse:
# No need to filter
return sorted([Category(e) for e in self._subcats_recursive],
key=lambda c: c.sort_breadcrumb)
# get all the subcategories, with only the first subdir added
# number of path components to ingest
... | def _get_subcats(self, recurse=False) | Get the subcategories of this category
recurse -- whether to include their subcategories as well | 6.362339 | 6.266622 | 1.015274 |
for record in self._entries(spec).order_by(model.Entry.local_date,
model.Entry.id)[:1]:
return entry.Entry(record)
return None | def _first(self, **spec) | Get the earliest entry in this category, optionally including subcategories | 9.539699 | 8.647634 | 1.103157 |
for record in self._entries(spec).order_by(orm.desc(model.Entry.local_date),
orm.desc(model.Entry.id))[:1]:
return entry.Entry(record)
return None | def _last(self, **spec) | Get the latest entry in this category, optionally including subcategories | 8.913107 | 7.485998 | 1.190637 |
match = re.match(
r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', datestr)
if not match:
return (arrow.get(datestr,
tzinfo=config.timezone).replace(tzinfo=config.timezone),
'day', 'YYYY-MM-DD')
year, month, day, week = match.group(1, 3,... | def parse_date(datestr) | Parse a date expression into a tuple of:
(start_date, span_type, span_format)
Arguments:
datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional) | 2.655708 | 2.573483 | 1.031951 |
if isinstance(search_path, str):
search_path = [search_path]
for relative in search_path:
candidate = os.path.normpath(os.path.join(relative, path))
if os.path.isfile(candidate):
return candidate
return None | def find_file(path, search_path) | Find a file by relative path. Arguments:
path -- the image's filename
search_path -- a list of directories to check in
Returns: the resolved file path | 2.205405 | 2.439989 | 0.903858 |
from . import entry # pylint:disable=cyclic-import
try:
entry_id = int(rel_path)
record = model.Entry.get(id=entry_id)
if record:
return entry.Entry(record)
except ValueError:
pass
if rel_path.startswith('/'):
search_path = [config.content_fol... | def find_entry(rel_path, search_path) | Find an entry by relative path. Arguments:
path -- the entry's filename (or entry ID)
search_path -- a list of directories to check in
Returns: the resolved Entry object | 3.021336 | 3.116727 | 0.969394 |
if os.sep != '/':
path = '/'.join(path.split(os.sep))
return flask.url_for('static', filename=path, _external=absolute) | def static_url(path, absolute=False) | Shorthand for returning a URL for the requested static file.
Arguments:
path -- the path to the file (relative to the static files directory)
absolute -- whether the link should be absolute or relative | 3.490587 | 3.991074 | 0.874598 |
text = '<' + name
if isinstance(attrs, dict):
attr_list = attrs.items()
elif isinstance(attrs, list):
attr_list = attrs
elif attrs is not None:
raise TypeError("Unhandled attrs type " + str(type(attrs)))
for key, val in attr_list:
if val is not None:
... | def make_tag(name, attrs, start_end=False) | Build an HTML tag from the given name and attributes.
Arguments:
name -- the name of the tag (p, div, etc.)
attrs -- a dict of attributes to apply to the tag
start_end -- whether this tag should be self-closing | 2.522475 | 2.85035 | 0.88497 |
stat = os.stat(fullpath)
return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value]) | def file_fingerprint(fullpath) | Get a metadata fingerprint for a file | 2.844978 | 2.92775 | 0.971728 |
out_args = input_args
for dest_key, src_keys in remap.items():
remap_value = None
if isinstance(src_keys, str):
src_keys = [src_keys]
for key in src_keys:
if key in input_args:
remap_value = input_args[key]
break
if r... | def remap_args(input_args, remap) | Generate a new argument list by remapping keys. The 'remap'
dict maps from destination key -> priority list of source keys | 2.037552 | 2.071954 | 0.983396 |
if path.startswith('@'):
# static resource
return static_url(path[1:], absolute=absolute)
if absolute:
# absolute-ify whatever the URL is
return urllib.parse.urljoin(flask.request.url, path)
return path | def remap_link_target(path, absolute=False) | remap a link target to a static URL if it's prefixed with @ | 6.277899 | 4.895337 | 1.282424 |
return '/'.join(os.path.dirname(filename).split(os.sep)) | def get_category(filename) | Get a default category name from a filename in a cross-platform manner | 4.831346 | 4.088248 | 1.181764 |
if self._default_args:
return self._func(
*self._default_args,
**self._default_kwargs)
return self._func(**self._default_kwargs) | def _default(self) | Get the default function return | 4.313456 | 3.684484 | 1.170708 |
try:
db.bind(**config.database_config)
except OSError:
# Attempted to connect to a file-based database where the file didn't
# exist
db.bind(**config.database_config, create_db=True)
rebuild = True
try:
db.generate_mapping(create_tables=True)
with o... | def setup() | Set up the database | 3.432004 | 3.349288 | 1.024697 |
return self.status not in (PublishStatus.DRAFT.value,
PublishStatus.GONE.value) | def visible(self) | Returns true if the entry should be viewable | 11.777036 | 11.563465 | 1.018469 |
card = CardData()
parser = CardParser(card, config, image_search_path)
misaka.Markdown(parser, extensions=markdown.ENABLED_EXTENSIONS)(text)
return card | def extract_card(text, config, image_search_path) | Extract card data based on the provided texts. | 8.441181 | 8.160661 | 1.034375 |
if not self._out.description:
self._out.description = content
return ' ' | def paragraph(self, content) | Turn the first paragraph of text into the summary text | 12.739316 | 10.483274 | 1.215204 |
''' extract the images '''
max_images = self._config.get('count')
if max_images is not None and len(self._out.images) >= max_images:
# We already have enough images, so bail out
return ' '
image_specs = raw_url
if title:
image_specs += ' "{}"'... | def image(self, raw_url, title='', alt='') | extract the images | 4.189163 | 4.112405 | 1.018665 |
# pylint: disable=unused-argument
try:
path, image_args, _ = image.parse_image_spec(spec)
except Exception as err: # pylint: disable=broad-except
# we tried™
logger.exception("Got error on spec %s: %s", spec, err)
return None
im... | def _render_image(self, spec, alt='') | Given an image spec, try to turn it into a card image per the configuration | 5.690741 | 5.381779 | 1.057409 |
config.setup(cfg)
app = _PublApp(name,
template_folder=config.template_folder,
static_folder=config.static_folder,
static_url_path=config.static_url_path)
for route in [
'/',
'/<path:category>/',
'/<template... | def publ(name, cfg) | Create a Flask app and configure it for use with Publ | 3.230716 | 3.184153 | 1.014623 |
model.setup()
index.scan_index(config.content_folder)
index.background_scan(config.content_folder) | def startup() | Startup routine for initiating the content indexer | 13.774597 | 9.787046 | 1.407431 |
if response.cache_control.max_age is None and 'CACHE_DEFAULT_TIMEOUT' in config.cache:
response.cache_control.max_age = config.cache['CACHE_DEFAULT_TIMEOUT']
return response | def set_cache_expiry(response) | Set the cache control headers | 3.247879 | 3.432724 | 0.946152 |
def decorator(func):
self.add_path_regex(regex, func)
return decorator | def path_alias_regex(self, regex) | A decorator that adds a path-alias regular expression; calls
add_path_regex | 8.827519 | 6.771262 | 1.303674 |
for regex, func in self._regex_map:
match = re.match(regex, path)
if match:
return func(match)
return None, None | def get_path_regex(self, path) | Evaluate the registered path-alias regular expressions | 3.74201 | 3.779603 | 0.990054 |
base, _ = os.path.splitext(basename)
return re.sub(r'[ _-]+', r' ', base).title() | def guess_title(basename) | Attempt to guess the title from the filename | 5.125504 | 4.200027 | 1.22035 |
warn_duplicate = False
if 'Entry-ID' in entry:
entry_id = int(entry['Entry-ID'])
else:
entry_id = None
# See if we've inadvertently duplicated an entry ID
if entry_id:
try:
other_entry = model.Entry.get(id=entry_id)
if (other_entry
... | def get_entry_id(entry, fullpath, assign_id) | Get or generate an entry ID for an entry | 3.958309 | 3.942154 | 1.004098 |
with tempfile.NamedTemporaryFile('w', delete=False) as file:
tmpfile = file.name
# we can't just use file.write(str(entry)) because otherwise the
# headers "helpfully" do MIME encoding normalization.
# str(val) is necessary to get around email.header's encoding
# shenani... | def save_file(fullpath, entry) | Save a message file out, without mangling the headers | 5.732183 | 5.551924 | 1.032468 |
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
# Since a file has changed, the lrucache is invalid.
load_message.cache_clear()
try:
entry = load_message(fullpath)
except FileNotFoundError:
# The file doesn't exist, so remove it from the index
r... | def scan_file(fullpath, relpath, assign_id) | scan a file and put it into the index | 2.923084 | 2.905848 | 1.005931 |
load_message.cache_clear()
orm.delete(pa for pa in model.PathAlias if pa.entry.file_path == filepath)
orm.delete(item for item in model.Entry if item.file_path == filepath)
orm.commit() | def expire_file(filepath) | Expire a record for a missing file | 7.902005 | 7.446463 | 1.061176 |
load_message.cache_clear()
# This entry no longer exists so delete it, and anything that references it
# SQLite doesn't support cascading deletes so let's just clean up
# manually
orm.delete(pa for pa in model.PathAlias if pa.entry == record)
record.delete()
orm.commit() | def expire_record(record) | Expire a record for a missing entry | 15.259574 | 14.974792 | 1.019017 |
if self._record.redirect_url:
return links.resolve(self._record.redirect_url,
self.search_path, kwargs.get('absolute'))
return self._permalink(*args, **kwargs) | def _link(self, *args, **kwargs) | Returns a link, potentially pre-redirected | 12.146531 | 9.36412 | 1.297135 |
return flask.url_for('entry',
entry_id=self._record.id,
category=self._record.category if expand else None,
slug_text=self._record.slug_text if expand else None,
_external=absolute,
... | def _permalink(self, absolute=False, expand=True, **kwargs) | Returns a canonical URL for the item | 4.469878 | 4.444495 | 1.005711 |
return [os.path.dirname(self._record.file_path)] + self.category.search_path | def search_path(self) | The relative image search path for this entry | 10.801685 | 9.411337 | 1.147731 |
filepath = self._record.file_path
try:
return load_message(filepath)
except FileNotFoundError:
expire_file(filepath)
empty = email.message.Message()
empty.set_payload('')
return empty | def _message(self) | get the message payload | 8.860682 | 7.82729 | 1.132024 |
body, _, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_markup,
body,
is_markdown) if body else CallableProxy(None) | def body(self) | Get the above-the-fold entry body text | 24.526352 | 18.885723 | 1.298672 |
_, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_markup,
more,
is_markdown) if more else CallableProxy(None) | def more(self) | Get the below-the-fold entry body text | 28.002586 | 21.4079 | 1.308049 |
body, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_card,
body or more) if is_markdown else CallableProxy(None) | def card(self) | Get the entry's OpenGraph card | 35.734249 | 25.834452 | 1.383201 |
if self.get('Summary'):
return self.get('Summary')
body, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_summary,
body or more) if is_markdown else CallableProxy(None) | def summary(self) | Get the entry's summary text | 18.921902 | 15.839801 | 1.19458 |
if self.get('Last-Modified'):
return arrow.get(self.get('Last-Modified'))
return self.date | def last_modified(self) | Get the date of last file modification | 5.026493 | 4.953694 | 1.014696 |
if is_markdown:
return markdown.to_html(
text,
config=kwargs,
search_path=self.search_path)
return html_entry.process(
text,
config=kwargs,
search_path=self.search_path) | def _get_markup(self, text, is_markdown, **kwargs) | get the rendered markup for an entry
is_markdown -- whether the entry is formatted as Markdown
kwargs -- parameters to pass to the Markdown processor | 5.435977 | 5.334385 | 1.019045 |
def og_tag(key, val):
return utils.make_tag('meta', {'property': key, 'content': val}, start_end=True)
tags = og_tag('og:title', self.title(markup=False))
tags += og_tag('og:url', self.link(absolute=True))
card = cards.extract_card(text, kwargs, self.... | def _get_card(self, text, **kwargs) | Render out the tags for a Twitter/OpenGraph card for this entry. | 5.312647 | 4.978813 | 1.067051 |
card = cards.extract_card(text, kwargs, self.search_path)
return flask.Markup((card.description or '').strip()) | def _get_summary(self, text, **kwargs) | Render out just the summary | 22.024195 | 19.004595 | 1.158888 |
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_before_entry(query, self._record)
for record in query.order_by(orm.desc(model.Entry.local_date),
orm.desc(model... | def _previous(self, **kwargs) | Get the previous item in any particular category | 7.364116 | 6.693603 | 1.100172 |
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_after_entry(query, self._record)
for record in query.order_by(model.Entry.local_date,
model.Entry.id)[:1]:
... | def _next(self, **kwargs) | Get the next item in any particular category | 8.34673 | 7.608843 | 1.096978 |
# copy the necessary configuration values over
this_module = sys.modules[__name__]
for name, value in cfg.items():
if hasattr(this_module, name):
setattr(this_module, name, value) | def setup(cfg) | set up the global configuration from an object | 3.659656 | 3.595054 | 1.017969 |
_, ext = os.path.splitext(template.filename)
return EXTENSION_MAP.get(ext, 'text/html; charset=utf-8') | def mime_type(template) | infer the content-type from the extension | 3.882891 | 3.741551 | 1.037776 |
if isinstance(template_list, str):
template_list = [template_list]
for template in template_list:
path = os.path.normpath(category)
while path is not None:
for extension in ['', '.html', '.htm', '.xml', '.json']:
candidate = os.path.join(path, template ... | def map_template(category, template_list) | Given a file path and an acceptable list of templates, return the
best-matching template's path relative to the configured template
directory.
Arguments:
category -- The path to map
template_list -- A template to look up (as a string), or a list of templates. | 2.631252 | 2.526916 | 1.04129 |
if isinstance(relation, Entry):
path = relation.category.path
elif isinstance(relation, Category):
path = relation.path
else:
path = relation
tmpl = map_template(path, template)
return tmpl.filename if tmpl else None | def get_template(template, relation) | Given an entry or a category, return the path to a related template | 4.900012 | 3.677231 | 1.332528 |
path = []
if entry is not None:
path += entry.search_path
if category is not None:
# Since the category might be different than the entry's category we add
# this too
path += category.search_path
if template is not None:
path.append(os.path.join(
... | def image_function(template=None, entry=None, category=None) | Get a function that gets an image | 4.86854 | 4.66468 | 1.043703 |
text = render_template(
template.filename,
template=template,
image=image_function(
template=template,
category=kwargs.get('category'),
entry=kwargs.get('entry')),
**kwargs
)
return text, caching.get_etag(text) | def render_publ_template(template, **kwargs) | Render out a template, providing the image function based on the args.
Returns tuple of (rendered text, etag) | 6.476563 | 5.652702 | 1.145746 |
if isinstance(error_codes, int):
error_codes = [error_codes]
error_code = error_codes[0]
template_list = [str(code) for code in error_codes]
template_list.append(str(int(error_code / 100) * 100))
template_list.append('error')
template = map_template(category, template_list)
i... | def render_error(category, error_message, error_codes, exception=None) | Render an error page.
Arguments:
category -- The category of the request
error_message -- The message to provide to the error template
error_codes -- The applicable HTTP error code(s). Will usually be an
integer or a list of integers; the HTTP error response will always
be the first er... | 3.804646 | 3.770544 | 1.009044 |
_, _, category = str.partition(request.path, '/')
qsize = index.queue_length()
if isinstance(error, http_error.NotFound) and qsize:
response = flask.make_response(render_error(
category, "Site reindex in progress (qs={})".format(qsize), 503))
response.headers['Retry-After']... | def render_exception(error) | Catch-all renderer for the top-level exception handler | 3.931853 | 3.906155 | 1.006579 |
redir = path_alias.get_redirect('/' + path)
if not redir:
raise http_error.NotFound("Path redirection not found")
return redir | def render_path_alias(path) | Render a known path-alias (used primarily for forced .php redirects) | 8.898857 | 7.765512 | 1.145946 |
# pylint:disable=too-many-return-statements
# See if this is an aliased path
redir = get_redirect()
if redir:
return redir
# Forbidden template types
if template and template.startswith('_'):
raise http_error.Forbidden("Template is private")
if template in ['entry', 'e... | def render_category(category='', template=None) | Render a category page.
Arguments:
category -- The category to render
template -- The template to render it with | 4.891937 | 5.029342 | 0.972679 |
# pylint: disable=too-many-return-statements
# check if it's a valid entry
record = model.Entry.get(id=entry_id)
if not record:
# It's not a valid entry, so see if it's a redirection
path_redirect = get_redirect()
if path_redirect:
return path_redirect
... | def render_entry(entry_id, slug_text='', category='') | Render an entry page.
Arguments:
entry_id -- The numeric ID of the entry to render
slug_text -- The expected URL slug text
category -- The expected category | 3.706204 | 3.693904 | 1.00333 |
if request.if_none_match.contains('chit') or request.if_modified_since:
return 'Not modified', 304
out_bytes = base64.b64decode(
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
return out_bytes, {'Content-Type': 'image/gif', 'ETag': 'chit',
'Last-Mod... | def render_transparent_chit() | Render a transparent chit for external, sized images | 3.271289 | 3.139154 | 1.042092 |
record = model.Image.get(asset_name=filename)
if not record:
raise http_error.NotFound("File not found")
if not record.is_asset:
raise http_error.Forbidden()
return flask.send_file(record.file_path, conditional=True) | def retrieve_asset(filename) | Retrieves a non-image asset associated with an entry | 4.728022 | 4.851857 | 0.974477 |
now = time.time()
for func, spec in self.tasks.items():
if force or now >= spec.get('next_run', 0):
func()
spec['next_run'] = now + spec['interval'] | def run(self, force=False) | Run all pending tasks; 'force' will run all tasks whether they're
pending or not. | 3.635842 | 3.499752 | 1.038886 |
record = model.Image.get(file_path=file_path)
fingerprint = ','.join((utils.file_fingerprint(file_path),
str(RENDITION_VERSION)))
if not record or record.fingerprint != fingerprint:
# Reindex the file
logger.info("Updating image %s -> %s", file_path, fingerpr... | def _get_asset(file_path) | Get the database record for an asset file | 3.069978 | 2.981515 | 1.029671 |
if path.startswith('@'):
return StaticImage(path[1:], search_path)
if path.startswith('//') or '://' in path:
return RemoteImage(path, search_path)
if os.path.isabs(path):
file_path = utils.find_file(os.path.relpath(
path, '/'), config.content_folder)
else:
... | def get_image(path, search_path) | Get an Image object. If the path is given as absolute, it will be
relative to the content directory; otherwise it will be relative to the
search path.
path -- the image's filename
search_path -- a search path for the image (string or list of strings) | 3.151083 | 3.113281 | 1.012142 |
# per https://stackoverflow.com/a/49723227/318857
args = 'f({})'.format(args)
tree = ast.parse(args)
funccall = tree.body[0].value
args = [ast.literal_eval(arg) for arg in funccall.args]
kwargs = {arg.arg: ast.literal_eval(arg.value)
for arg in funccall.keywords}
if len... | def parse_arglist(args) | Parses an arglist into arguments for Image, as a kwargs dict | 2.993383 | 2.773637 | 1.079227 |
match = re.match(r'([^\{]*)(\{(.*)\})$', alt)
if match:
alt = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return alt, args | def parse_alt_text(alt) | Parses the arguments out from a Publ-Markdown alt text into a tuple of text, args | 3.511517 | 3.357727 | 1.045802 |
# I was having trouble coming up with a single RE that did it right,
# so let's just break it down into sub-problems. First, parse out the
# alt text...
match = re.match(r'(.+)\s+\"(.*)\"\s*$', spec)
if match:
spec, title = match.group(1, 2)
else:
title = None
# and no... | def parse_image_spec(spec) | Parses out a Publ-Markdown image spec into a tuple of path, args, title | 4.899119 | 4.49414 | 1.090113 |
spec_list = [spec.strip() for spec in image_specs.split('|')]
original_count = len(spec_list)
if 'count' in container_args:
if 'count_offset' in container_args:
spec_list = spec_list[container_args['count_offset']:]
spec_list = spec_list[:container_args['count']]
retu... | def get_spec_list(image_specs, container_args) | Given a list of specs and a set of container args, return a tuple of
the final container argument list and the original list size | 2.695432 | 2.590846 | 1.040368 |
if os.path.isfile(os.path.join(config.static_folder, filename)):
return flask.redirect(flask.url_for('static', filename=filename))
retry_count = int(flask.request.args.get('retry_count', 0))
if retry_count < 10:
time.sleep(0.25) # ghastly hack to get the client to backoff a bit
... | def get_async(filename) | Asynchronously fetch an image | 3.328413 | 3.230788 | 1.030217 |
add = {}
if 'prefix' in kwargs:
attr_prefixes = kwargs.get('prefix')
if isinstance(kwargs['prefix'], str):
attr_prefixes = [attr_prefixes]
for prefix in attr_prefixes:
for k, val in kwargs.items():
if k.st... | def get_img_attrs(self, style=None, **kwargs) | Get an attribute list (src, srcset, style, et al) for the image.
style -- an optional list of CSS style fragments
Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x'] | 3.174178 | 3.431723 | 0.924952 |
try:
style = []
for key in ('img_style', 'style'):
if key in kwargs:
if isinstance(kwargs[key], (list, tuple, set)):
style += list(kwargs[key])
else:
style.append(kwargs[key... | def get_img_tag(self, title='', alt_text='', **kwargs) | Build a <img> tag for the image with the specified options.
Returns: an HTML fragment. | 4.09026 | 4.172644 | 0.980256 |
text = self._css_background(**kwargs)
if uncomment:
text = ' */ {} /* '.format(text)
return text | def get_css_background(self, uncomment=False, **kwargs) | Get the CSS background attributes for an element.
Additional arguments:
uncomment -- surround the attributes with `*/` and `/*` so that the
template tag can be kept inside a comment block, to keep syntax
highlighters happy | 8.364498 | 8.789392 | 0.951658 |
fullsize_args = {}
if 'absolute' in kwargs:
fullsize_args['absolute'] = kwargs['absolute']
for key in ('width', 'height', 'quality', 'format', 'background', 'crop'):
fsk = 'fullsize_' + key
if fsk in kwargs:
fullsize_args[key] = kwar... | def get_fullsize(self, kwargs) | Get the fullsize rendition URL | 3.240235 | 3.024881 | 1.071194 |
return utils.make_tag('a', {
'href': self.get_fullsize(kwargs),
'data-lightbox': kwargs['gallery_id'],
'title': title
}) | def _fullsize_link_tag(self, kwargs, title) | Render a <a href> that points to the fullsize rendition specified | 5.172065 | 5.555357 | 0.931005 |
spec = alias.split()
path = spec[0]
values = {**kwargs, 'path': path}
if len(spec) > 1:
values['template'] = spec[1]
record = model.PathAlias.get(path=path)
if record:
record.set(**values)
else:
record = model.PathAlias(**values)
orm.commit()
return ... | def set_alias(alias, **kwargs) | Set a path alias.
Arguments:
alias -- The alias specification
entry -- The entry to alias it to
category -- The category to alias it to
url -- The external URL to alias it to | 4.355869 | 4.356818 | 0.999782 |
orm.delete(p for p in model.PathAlias if p.path == path)
orm.commit() | def remove_alias(path) | Remove a path alias.
Arguments:
path -- the path to remove the alias of | 10.083405 | 13.047295 | 0.772835 |
if isinstance(target, model.Entry):
orm.delete(p for p in model.PathAlias if p.entry == target)
elif isinstance(target, model.Category):
orm.delete(p for p in model.PathAlias if p.category == target)
else:
raise TypeError("Unknown type {}".format(type(target)))
orm.commit() | def remove_aliases(target) | Remove all aliases to a destination | 3.596749 | 3.5352 | 1.01741 |
# pylint:disable=too-many-return-statements
record = model.PathAlias.get(path=path)
if not record:
return None, None
template = record.template if record.template != 'index' else None
if record.entry and record.entry.visible:
if record.template:
# a template was ... | def get_alias(path) | Get a path alias for a single path
Returns a tuple of (url,is_permanent) | 4.702373 | 4.630721 | 1.015473 |
if isinstance(paths, str):
paths = [paths]
for path in paths:
url, permanent = get_alias(path)
if url:
return redirect(url, 301 if permanent else 302)
url, permanent = current_app.get_path_regex(path)
if url:
return redirect(url, 301 if per... | def get_redirect(paths) | Get a redirect from a path or list of paths
Arguments:
paths -- either a single path string, or a list of paths to check
Returns: a flask.redirect() result | 2.995183 | 2.781077 | 1.076987 |
exif_orientation_tag = 0x0112
exif_transpose_sequences = [
[],
[],
[PIL.Image.FLIP_LEFT_RIGHT],
[PIL.Image.ROTATE_180],
[PIL.Image.FLIP_TOP_BOTTOM],
[PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.ROTATE_90],
[PIL.Image.ROTATE_270],
[PIL.Image.FLIP_TOP... | def fix_orientation(image) | adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
As per CIPA DC-008-2012, the orie... | 1.946969 | 1.957872 | 0.994431 |
if not LocalImage._thread_pool:
logger.info("Starting LocalImage threadpool")
LocalImage._thread_pool = concurrent.futures.ThreadPoolExecutor(
thread_name_prefix="Renderer")
return LocalImage._thread_pool | def thread_pool() | Get the rendition threadpool | 5.591059 | 4.567025 | 1.224224 |
# pylint:disable=too-many-locals
basename, ext = os.path.splitext(
os.path.basename(self._record.file_path))
basename = utils.make_slug(basename)
if kwargs.get('format'):
ext = '.' + kwargs['format']
# The spec for building the output filename
... | def get_rendition(self, output_scale=1, **kwargs) | Get the rendition for this image, generating it if necessary.
Returns a tuple of `(relative_path, width, height)`, where relative_path
is relative to the static file directory (i.e. what one would pass into
`get_static()`)
output_scale -- the upsample factor for the requested rendition
... | 3.186717 | 3.185968 | 1.000235 |
if crop and box:
# Both boxes are the same size; just line them up.
return (box[0] + crop[0], box[1] + crop[1],
box[2] + crop[0], box[3] + crop[1])
if crop:
# We don't have a fit box, so just convert the crop box
return (crop... | def _adjust_crop_box(box, crop) | Given a fit box and a crop box, adjust one to the other | 3.621979 | 3.004794 | 1.2054 |
if isinstance(argument, str):
return tuple(int(p.strip()) for p in argument.split(','))
return argument | def _parse_tuple_string(argument) | Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) | 3.96669 | 3.223782 | 1.230446 |
if crop:
# Use the cropping rectangle size
_, _, width, height = crop
else:
# Use the original image size
width = self._record.width
height = self._record.height
mode = spec.get('resize', 'fit')
if mode == 'fit':
... | def get_rendition_size(self, spec, output_scale, crop) | Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box) | 2.494316 | 2.54691 | 0.97935 |
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
min_width = spec.get('scale_min_width')
if min_width and width < min_width:
height = height * min_width / wid... | def get_rendition_fit_size(spec, input_w, input_h, output_scale) | Determine the scaled size based on the provided spec | 1.676542 | 1.668312 | 1.004933 |
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
if spec.get('scale_min_width'):
width = max(width, spec['spec_min_width'])
if spec.get('scale_min_height'):
... | def get_rendition_fill_size(spec, input_w, input_h, output_scale) | Determine the scale-crop size given the provided spec | 1.988589 | 1.970222 | 1.009322 |
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
min_width = spec.get('scale_min_width')
if min_width and width < min_width:
width = min_width
min_he... | def get_rendition_stretch_size(spec, input_w, input_h, output_scale) | Determine the scale-crop size given the provided spec | 1.723435 | 1.680101 | 1.025793 |
if bgcolor:
background = PIL.Image.new('RGB', image.size, bgcolor)
background.paste(image, mask=image.split()[3])
return background
return image.convert('RGB') | def flatten(image, bgcolor=None) | Flatten an image, with an optional background color | 2.461809 | 2.484261 | 0.990962 |
img_1x, size = self.get_rendition(
1, **utils.remap_args(kwargs, {"quality": "quality_ldpi"}))
img_2x, _ = self.get_rendition(
2, **utils.remap_args(kwargs, {"quality": "quality_hdpi"}))
return (img_1x, img_2x, size) | def _get_renditions(self, kwargs) | Get a bunch of renditions; returns a tuple of 1x, 2x, size | 4.126805 | 3.493809 | 1.181177 |
# Get the 1x and 2x renditions
img_1x, img_2x, size = self._get_renditions(kwargs)
return {
'src': img_1x,
'width': size[0],
'height': size[1],
'srcset': "{} 1x, {} 2x".format(img_1x, img_2x) if img_1x != img_2x else None,
's... | def _get_img_attrs(self, style, kwargs) | Get the attributes of an an <img> tag for this image, hidpi-aware | 2.97117 | 2.842361 | 1.045318 |
# Get the 1x and 2x renditions
img_1x, img_2x, _ = self._get_renditions(kwargs)
tmpl = 'background-image: url("{s1x}");'
if img_1x != img_2x:
image_set = 'image-set(url("{s1x}") 1x, url("{s2x}") 2x)'
tmpl += 'background-image: {ss};background-image: -we... | def _css_background(self, **kwargs) | Get the CSS specifiers for this as a hidpi-capable background image | 3.629845 | 3.298181 | 1.10056 |
processor = HTMLEntry(config, search_path)
processor.feed(text)
text = processor.get_data()
if not config.get('no_smartquotes'):
text = misaka.smartypants(text)
return flask.Markup(text) | def process(text, config, search_path) | Process an HTML entry's HTML | 5.992612 | 5.296183 | 1.131496 |
if tag.lower() == 'img':
attrs = self._image_attrs(attrs)
# Remap the attributes
out_attrs = []
for key, val in attrs:
if (key.lower() == 'href'
or (key.lower() == 'src' and not tag.lower() == 'img')):
out_attrs.appen... | def _handle_tag(self, tag, attrs, self_closing) | Handle a tag.
attrs -- the attributes of the tag
self_closing -- whether this is self-closing | 3.781597 | 3.692881 | 1.024024 |
path = None
config = {**self._config}
for key, val in attrs:
if key.lower() == 'width' or key.lower() == 'height':
try:
config[key.lower()] = int(val)
except ValueError:
pass
elif key.lower... | def _image_attrs(self, attrs) | Rewrite the SRC attribute on an <img> tag, possibly adding a SRCSET. | 3.81367 | 3.604005 | 1.058175 |
files = model.FileFingerprint.select().order_by(
orm.desc(model.FileFingerprint.file_mtime))
for file in files:
return file.file_mtime, file.file_path
return None, None | def last_modified() | information about the most recently modified file | 5.053577 | 4.89566 | 1.032257 |
logger.debug("Scanning file: %s (%s) %s", fullpath, relpath, assign_id)
def do_scan():
_, ext = os.path.splitext(fullpath)
try:
if ext in ENTRY_TYPES:
logger.info("Scanning entry: %s", fullpath)
return entry.scan_file(fullpath, relpath... | def scan_file(fullpath, relpath, assign_id) | Scan a file for the index
fullpath -- The full path to the file
relpath -- The path to the file, relative to its base directory
assign_id -- Whether to assign an ID to the file if not yet assigned
This calls into various modules' scanner functions; the expectation is that
the scan_file function wi... | 3.127666 | 3.166724 | 0.987666 |
record = model.FileFingerprint.get(file_path=fullpath)
if record:
return record.fingerprint
return None | def get_last_fingerprint(fullpath) | Get the last known modification time for a file | 5.745906 | 5.780246 | 0.994059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.