id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
11,200 | PlaidWeb/Publ | publ/rendering.py | render_entry | 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
"""
# 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
logger.info("Attempted to retrieve nonexistent entry %d", entry_id)
raise http_error.NotFound("No such entry")
# see if the file still exists
if not os.path.isfile(record.file_path):
expire_record(record)
# See if there's a redirection
path_redirect = get_redirect()
if path_redirect:
return path_redirect
raise http_error.NotFound("No such entry")
# Show an access denied error if the entry has been set to draft mode
if record.status == model.PublishStatus.DRAFT.value:
raise http_error.Forbidden("Entry not available")
# Show a gone error if the entry has been deleted
if record.status == model.PublishStatus.GONE.value:
raise http_error.Gone()
# check if the canonical URL matches
if record.category != category or record.slug_text != slug_text:
# This could still be a redirected path...
path_redirect = get_redirect()
if path_redirect:
return path_redirect
# Redirect to the canonical URL
return redirect(url_for('entry',
entry_id=entry_id,
category=record.category,
slug_text=record.slug_text))
# if the entry canonically redirects, do that now
entry_redirect = record.redirect_url
if entry_redirect:
return redirect(entry_redirect)
entry_template = (record.entry_template
or Category(category).get('Entry-Template')
or 'entry')
tmpl = map_template(category, entry_template)
if not tmpl:
raise http_error.BadRequest("Missing entry template")
# Get the viewable entry
entry_obj = Entry(record)
# does the entry-id header mismatch? If so the old one is invalid
if int(entry_obj.get('Entry-ID')) != record.id:
expire_record(record)
return redirect(url_for('entry', entry_id=int(entry_obj.get('Entry-Id'))))
rendered, etag = render_publ_template(
tmpl,
_url_root=request.url_root,
entry=entry_obj,
category=Category(category))
if request.if_none_match.contains(etag):
return 'Not modified', 304
return rendered, {'Content-Type': mime_type(tmpl),
'ETag': etag} | python | def render_entry(entry_id, slug_text='', category=''):
# 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
logger.info("Attempted to retrieve nonexistent entry %d", entry_id)
raise http_error.NotFound("No such entry")
# see if the file still exists
if not os.path.isfile(record.file_path):
expire_record(record)
# See if there's a redirection
path_redirect = get_redirect()
if path_redirect:
return path_redirect
raise http_error.NotFound("No such entry")
# Show an access denied error if the entry has been set to draft mode
if record.status == model.PublishStatus.DRAFT.value:
raise http_error.Forbidden("Entry not available")
# Show a gone error if the entry has been deleted
if record.status == model.PublishStatus.GONE.value:
raise http_error.Gone()
# check if the canonical URL matches
if record.category != category or record.slug_text != slug_text:
# This could still be a redirected path...
path_redirect = get_redirect()
if path_redirect:
return path_redirect
# Redirect to the canonical URL
return redirect(url_for('entry',
entry_id=entry_id,
category=record.category,
slug_text=record.slug_text))
# if the entry canonically redirects, do that now
entry_redirect = record.redirect_url
if entry_redirect:
return redirect(entry_redirect)
entry_template = (record.entry_template
or Category(category).get('Entry-Template')
or 'entry')
tmpl = map_template(category, entry_template)
if not tmpl:
raise http_error.BadRequest("Missing entry template")
# Get the viewable entry
entry_obj = Entry(record)
# does the entry-id header mismatch? If so the old one is invalid
if int(entry_obj.get('Entry-ID')) != record.id:
expire_record(record)
return redirect(url_for('entry', entry_id=int(entry_obj.get('Entry-Id'))))
rendered, etag = render_publ_template(
tmpl,
_url_root=request.url_root,
entry=entry_obj,
category=Category(category))
if request.if_none_match.contains(etag):
return 'Not modified', 304
return rendered, {'Content-Type': mime_type(tmpl),
'ETag': etag} | [
"def",
"render_entry",
"(",
"entry_id",
",",
"slug_text",
"=",
"''",
",",
"category",
"=",
"''",
")",
":",
"# pylint: disable=too-many-return-statements",
"# check if it's a valid entry",
"record",
"=",
"model",
".",
"Entry",
".",
"get",
"(",
"id",
"=",
"entry_id"... | 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 | [
"Render",
"an",
"entry",
"page",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/rendering.py#L269-L354 |
11,201 | PlaidWeb/Publ | publ/rendering.py | render_transparent_chit | def render_transparent_chit():
""" Render a transparent chit for external, sized images """
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-Modified': 'Tue, 31 Jul 1990 08:00:00 -0000'} | python | def render_transparent_chit():
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-Modified': 'Tue, 31 Jul 1990 08:00:00 -0000'} | [
"def",
"render_transparent_chit",
"(",
")",
":",
"if",
"request",
".",
"if_none_match",
".",
"contains",
"(",
"'chit'",
")",
"or",
"request",
".",
"if_modified_since",
":",
"return",
"'Not modified'",
",",
"304",
"out_bytes",
"=",
"base64",
".",
"b64decode",
"... | Render a transparent chit for external, sized images | [
"Render",
"a",
"transparent",
"chit",
"for",
"external",
"sized",
"images"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/rendering.py#L357-L366 |
11,202 | PlaidWeb/Publ | publ/rendering.py | retrieve_asset | def retrieve_asset(filename):
""" Retrieves a non-image asset associated with an entry """
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) | python | def retrieve_asset(filename):
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",
")",
":",
"record",
"=",
"model",
".",
"Image",
".",
"get",
"(",
"asset_name",
"=",
"filename",
")",
"if",
"not",
"record",
":",
"raise",
"http_error",
".",
"NotFound",
"(",
"\"File not found\"",
")",
"if",
"not",
... | Retrieves a non-image asset associated with an entry | [
"Retrieves",
"a",
"non",
"-",
"image",
"asset",
"associated",
"with",
"an",
"entry"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/rendering.py#L370-L379 |
11,203 | PlaidWeb/Publ | publ/maintenance.py | Maintenance.run | def run(self, force=False):
""" Run all pending tasks; 'force' will run all tasks whether they're
pending or not. """
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'] | python | def run(self, force=False):
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",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"func",
",",
"spec",
"in",
"self",
".",
"tasks",
".",
"items",
"(",
")",
":",
"if",
"force",
"or",
"now",
">=",
"spec",
".",
"g... | Run all pending tasks; 'force' will run all tasks whether they're
pending or not. | [
"Run",
"all",
"pending",
"tasks",
";",
"force",
"will",
"run",
"all",
"tasks",
"whether",
"they",
"re",
"pending",
"or",
"not",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/maintenance.py#L16-L23 |
11,204 | PlaidWeb/Publ | publ/image/__init__.py | _get_asset | def _get_asset(file_path):
""" Get the database record for an asset file """
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, fingerprint)
# compute the md5sum; from https://stackoverflow.com/a/3431838/318857
md5 = hashlib.md5()
md5.update(bytes(RENDITION_VERSION))
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(16384), b""):
md5.update(chunk)
values = {
'file_path': file_path,
'checksum': md5.hexdigest(),
'fingerprint': fingerprint,
}
try:
image = PIL.Image.open(file_path)
image = fix_orientation(image)
except IOError:
image = None
if image:
values['width'] = image.width
values['height'] = image.height
values['transparent'] = image.mode in ('RGBA', 'P')
values['is_asset'] = False
else:
# PIL could not figure out what file type this is, so treat it as
# an asset
values['is_asset'] = True
values['asset_name'] = os.path.join(values['checksum'][:5],
os.path.basename(file_path))
record = model.Image.get(file_path=file_path)
if record:
record.set(**values)
else:
record = model.Image(**values)
orm.commit()
return record | python | def _get_asset(file_path):
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, fingerprint)
# compute the md5sum; from https://stackoverflow.com/a/3431838/318857
md5 = hashlib.md5()
md5.update(bytes(RENDITION_VERSION))
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(16384), b""):
md5.update(chunk)
values = {
'file_path': file_path,
'checksum': md5.hexdigest(),
'fingerprint': fingerprint,
}
try:
image = PIL.Image.open(file_path)
image = fix_orientation(image)
except IOError:
image = None
if image:
values['width'] = image.width
values['height'] = image.height
values['transparent'] = image.mode in ('RGBA', 'P')
values['is_asset'] = False
else:
# PIL could not figure out what file type this is, so treat it as
# an asset
values['is_asset'] = True
values['asset_name'] = os.path.join(values['checksum'][:5],
os.path.basename(file_path))
record = model.Image.get(file_path=file_path)
if record:
record.set(**values)
else:
record = model.Image(**values)
orm.commit()
return record | [
"def",
"_get_asset",
"(",
"file_path",
")",
":",
"record",
"=",
"model",
".",
"Image",
".",
"get",
"(",
"file_path",
"=",
"file_path",
")",
"fingerprint",
"=",
"','",
".",
"join",
"(",
"(",
"utils",
".",
"file_fingerprint",
"(",
"file_path",
")",
",",
... | Get the database record for an asset file | [
"Get",
"the",
"database",
"record",
"for",
"an",
"asset",
"file"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L98-L144 |
11,205 | PlaidWeb/Publ | publ/image/__init__.py | get_image | 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)
"""
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:
file_path = utils.find_file(path, search_path)
if not file_path:
return ImageNotFound(path, search_path)
record = _get_asset(file_path)
if record.is_asset:
return FileAsset(record, search_path)
return LocalImage(record, search_path) | python | def get_image(path, search_path):
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:
file_path = utils.find_file(path, search_path)
if not file_path:
return ImageNotFound(path, search_path)
record = _get_asset(file_path)
if record.is_asset:
return FileAsset(record, search_path)
return LocalImage(record, search_path) | [
"def",
"get_image",
"(",
"path",
",",
"search_path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'@'",
")",
":",
"return",
"StaticImage",
"(",
"path",
"[",
"1",
":",
"]",
",",
"search_path",
")",
"if",
"path",
".",
"startswith",
"(",
"'//'",
")"... | 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) | [
"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",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L147-L173 |
11,206 | PlaidWeb/Publ | publ/image/__init__.py | parse_arglist | def parse_arglist(args):
""" Parses an arglist into arguments for Image, as a kwargs dict """
# 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(args) > 2:
raise TypeError(
"Expected at most 2 positional args but {} were given".format(len(args)))
if len(args) >= 1:
kwargs['width'] = int(args[0])
if len(args) >= 2:
kwargs['height'] = int(args[1])
return kwargs | python | def parse_arglist(args):
# 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(args) > 2:
raise TypeError(
"Expected at most 2 positional args but {} were given".format(len(args)))
if len(args) >= 1:
kwargs['width'] = int(args[0])
if len(args) >= 2:
kwargs['height'] = int(args[1])
return kwargs | [
"def",
"parse_arglist",
"(",
"args",
")",
":",
"# per https://stackoverflow.com/a/49723227/318857",
"args",
"=",
"'f({})'",
".",
"format",
"(",
"args",
")",
"tree",
"=",
"ast",
".",
"parse",
"(",
"args",
")",
"funccall",
"=",
"tree",
".",
"body",
"[",
"0",
... | Parses an arglist into arguments for Image, as a kwargs dict | [
"Parses",
"an",
"arglist",
"into",
"arguments",
"for",
"Image",
"as",
"a",
"kwargs",
"dict"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L176-L197 |
11,207 | PlaidWeb/Publ | publ/image/__init__.py | parse_alt_text | def parse_alt_text(alt):
""" Parses the arguments out from a Publ-Markdown alt text into a tuple of text, args """
match = re.match(r'([^\{]*)(\{(.*)\})$', alt)
if match:
alt = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return alt, args | python | def parse_alt_text(alt):
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",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'([^\\{]*)(\\{(.*)\\})$'",
",",
"alt",
")",
"if",
"match",
":",
"alt",
"=",
"match",
".",
"group",
"(",
"1",
")",
"args",
"=",
"parse_arglist",
"(",
"match",
".",
... | Parses the arguments out from a Publ-Markdown alt text into a tuple of text, args | [
"Parses",
"the",
"arguments",
"out",
"from",
"a",
"Publ",
"-",
"Markdown",
"alt",
"text",
"into",
"a",
"tuple",
"of",
"text",
"args"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L200-L209 |
11,208 | PlaidWeb/Publ | publ/image/__init__.py | parse_image_spec | def parse_image_spec(spec):
""" Parses out a Publ-Markdown image spec into a tuple of path, args, title """
# 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 now parse out the arglist
match = re.match(r'([^\{]*)(\{(.*)\})\s*$', spec)
if match:
spec = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return spec, args, (title and html.unescape(title)) | python | def parse_image_spec(spec):
# 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 now parse out the arglist
match = re.match(r'([^\{]*)(\{(.*)\})\s*$', spec)
if match:
spec = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return spec, args, (title and html.unescape(title)) | [
"def",
"parse_image_spec",
"(",
"spec",
")",
":",
"# 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*$'",
"... | Parses out a Publ-Markdown image spec into a tuple of path, args, title | [
"Parses",
"out",
"a",
"Publ",
"-",
"Markdown",
"image",
"spec",
"into",
"a",
"tuple",
"of",
"path",
"args",
"title"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L212-L232 |
11,209 | PlaidWeb/Publ | publ/image/__init__.py | get_spec_list | 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 """
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']]
return spec_list, original_count | python | def get_spec_list(image_specs, container_args):
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']]
return spec_list, original_count | [
"def",
"get_spec_list",
"(",
"image_specs",
",",
"container_args",
")",
":",
"spec_list",
"=",
"[",
"spec",
".",
"strip",
"(",
")",
"for",
"spec",
"in",
"image_specs",
".",
"split",
"(",
"'|'",
")",
"]",
"original_count",
"=",
"len",
"(",
"spec_list",
")... | 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 | [
"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"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L235-L247 |
11,210 | PlaidWeb/Publ | publ/image/__init__.py | get_async | def get_async(filename):
""" Asynchronously fetch an image """
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
return flask.redirect(flask.url_for('async',
filename=filename,
cb=random.randint(0, 2**48),
retry_count=retry_count + 1))
# the image isn't available yet; generate a placeholder and let the
# client attempt to re-fetch periodically, maybe
vals = [int(b) for b in hashlib.md5(
filename.encode('utf-8')).digest()[0:12]]
placeholder = PIL.Image.new('RGB', (2, 2))
placeholder.putdata(list(zip(vals[0::3], vals[1::3], vals[2::3])))
outbytes = io.BytesIO()
placeholder.save(outbytes, "PNG")
outbytes.seek(0)
response = flask.make_response(
flask.send_file(outbytes, mimetype='image/png'))
response.headers['Refresh'] = 5
return response | python | def get_async(filename):
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
return flask.redirect(flask.url_for('async',
filename=filename,
cb=random.randint(0, 2**48),
retry_count=retry_count + 1))
# the image isn't available yet; generate a placeholder and let the
# client attempt to re-fetch periodically, maybe
vals = [int(b) for b in hashlib.md5(
filename.encode('utf-8')).digest()[0:12]]
placeholder = PIL.Image.new('RGB', (2, 2))
placeholder.putdata(list(zip(vals[0::3], vals[1::3], vals[2::3])))
outbytes = io.BytesIO()
placeholder.save(outbytes, "PNG")
outbytes.seek(0)
response = flask.make_response(
flask.send_file(outbytes, mimetype='image/png'))
response.headers['Refresh'] = 5
return response | [
"def",
"get_async",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"static_folder",
",",
"filename",
")",
")",
":",
"return",
"flask",
".",
"redirect",
"(",
"flask",
".",
... | Asynchronously fetch an image | [
"Asynchronously",
"fetch",
"an",
"image"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/__init__.py#L261-L288 |
11,211 | PlaidWeb/Publ | publ/image/image.py | Image.get_css_background | 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
"""
text = self._css_background(**kwargs)
if uncomment:
text = ' */ {} /* '.format(text)
return text | python | def get_css_background(self, uncomment=False, **kwargs):
text = self._css_background(**kwargs)
if uncomment:
text = ' */ {} /* '.format(text)
return text | [
"def",
"get_css_background",
"(",
"self",
",",
"uncomment",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"text",
"=",
"self",
".",
"_css_background",
"(",
"*",
"*",
"kwargs",
")",
"if",
"uncomment",
":",
"text",
"=",
"' */ {} /* '",
".",
"format",
... | 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 | [
"Get",
"the",
"CSS",
"background",
"attributes",
"for",
"an",
"element",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/image.py#L116-L130 |
11,212 | PlaidWeb/Publ | publ/image/image.py | Image.get_fullsize | def get_fullsize(self, kwargs):
""" Get the fullsize rendition URL """
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] = kwargs[fsk]
img_fullsize, _ = self.get_rendition(1, **fullsize_args)
return img_fullsize | python | def get_fullsize(self, kwargs):
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] = kwargs[fsk]
img_fullsize, _ = self.get_rendition(1, **fullsize_args)
return img_fullsize | [
"def",
"get_fullsize",
"(",
"self",
",",
"kwargs",
")",
":",
"fullsize_args",
"=",
"{",
"}",
"if",
"'absolute'",
"in",
"kwargs",
":",
"fullsize_args",
"[",
"'absolute'",
"]",
"=",
"kwargs",
"[",
"'absolute'",
"]",
"for",
"key",
"in",
"(",
"'width'",
",",... | Get the fullsize rendition URL | [
"Get",
"the",
"fullsize",
"rendition",
"URL"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/image.py#L160-L173 |
11,213 | PlaidWeb/Publ | publ/path_alias.py | set_alias | 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
"""
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 record | python | def set_alias(alias, **kwargs):
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 record | [
"def",
"set_alias",
"(",
"alias",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"alias",
".",
"split",
"(",
")",
"path",
"=",
"spec",
"[",
"0",
"]",
"values",
"=",
"{",
"*",
"*",
"kwargs",
",",
"'path'",
":",
"path",
"}",
"if",
"len",
"(",
... | 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 | [
"Set",
"a",
"path",
"alias",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/path_alias.py#L11-L38 |
11,214 | PlaidWeb/Publ | publ/path_alias.py | remove_alias | def remove_alias(path):
""" Remove a path alias.
Arguments:
path -- the path to remove the alias of
"""
orm.delete(p for p in model.PathAlias if p.path == path)
orm.commit() | python | def remove_alias(path):
orm.delete(p for p in model.PathAlias if p.path == path)
orm.commit() | [
"def",
"remove_alias",
"(",
"path",
")",
":",
"orm",
".",
"delete",
"(",
"p",
"for",
"p",
"in",
"model",
".",
"PathAlias",
"if",
"p",
".",
"path",
"==",
"path",
")",
"orm",
".",
"commit",
"(",
")"
] | Remove a path alias.
Arguments:
path -- the path to remove the alias of | [
"Remove",
"a",
"path",
"alias",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/path_alias.py#L42-L50 |
11,215 | PlaidWeb/Publ | publ/path_alias.py | remove_aliases | def remove_aliases(target):
""" Remove all aliases to a destination """
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() | python | def remove_aliases(target):
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",
")",
":",
"if",
"isinstance",
"(",
"target",
",",
"model",
".",
"Entry",
")",
":",
"orm",
".",
"delete",
"(",
"p",
"for",
"p",
"in",
"model",
".",
"PathAlias",
"if",
"p",
".",
"entry",
"==",
"target",
")",
"e... | Remove all aliases to a destination | [
"Remove",
"all",
"aliases",
"to",
"a",
"destination"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/path_alias.py#L54-L63 |
11,216 | PlaidWeb/Publ | publ/path_alias.py | get_alias | def get_alias(path):
""" Get a path alias for a single path
Returns a tuple of (url,is_permanent)
"""
# 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 requested, so we go to the category page
category = (record.category.category
if record.category else record.entry.category)
return url_for('category',
start=record.entry.id,
template=template,
category=category), True
from . import entry # pylint:disable=cyclic-import
outbound = entry.Entry(record.entry).get('Redirect-To')
if outbound:
# The entry has a Redirect-To (soft redirect) header
return outbound, False
return url_for('entry',
entry_id=record.entry.id,
category=record.entry.category,
slug_text=record.entry.slug_text), True
if record.category:
return url_for('category',
category=record.category.category,
template=template), True
if record.url:
# This is an outbound URL that might be changed by the user, so
# we don't do a 301 Permanently moved
return record.url, False
return None, None | python | def get_alias(path):
# 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 requested, so we go to the category page
category = (record.category.category
if record.category else record.entry.category)
return url_for('category',
start=record.entry.id,
template=template,
category=category), True
from . import entry # pylint:disable=cyclic-import
outbound = entry.Entry(record.entry).get('Redirect-To')
if outbound:
# The entry has a Redirect-To (soft redirect) header
return outbound, False
return url_for('entry',
entry_id=record.entry.id,
category=record.entry.category,
slug_text=record.entry.slug_text), True
if record.category:
return url_for('category',
category=record.category.category,
template=template), True
if record.url:
# This is an outbound URL that might be changed by the user, so
# we don't do a 301 Permanently moved
return record.url, False
return None, None | [
"def",
"get_alias",
"(",
"path",
")",
":",
"# pylint:disable=too-many-return-statements",
"record",
"=",
"model",
".",
"PathAlias",
".",
"get",
"(",
"path",
"=",
"path",
")",
"if",
"not",
"record",
":",
"return",
"None",
",",
"None",
"template",
"=",
"record... | Get a path alias for a single path
Returns a tuple of (url,is_permanent) | [
"Get",
"a",
"path",
"alias",
"for",
"a",
"single",
"path"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/path_alias.py#L66-L111 |
11,217 | PlaidWeb/Publ | publ/path_alias.py | get_redirect | 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
"""
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 permanent else 302)
return None | python | def get_redirect(paths):
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 permanent else 302)
return None | [
"def",
"get_redirect",
"(",
"paths",
")",
":",
"if",
"isinstance",
"(",
"paths",
",",
"str",
")",
":",
"paths",
"=",
"[",
"paths",
"]",
"for",
"path",
"in",
"paths",
":",
"url",
",",
"permanent",
"=",
"get_alias",
"(",
"path",
")",
"if",
"url",
":"... | 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 | [
"Get",
"a",
"redirect",
"from",
"a",
"path",
"or",
"list",
"of",
"paths"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/path_alias.py#L114-L136 |
11,218 | PlaidWeb/Publ | publ/image/local.py | LocalImage.thread_pool | def thread_pool():
""" Get the rendition threadpool """
if not LocalImage._thread_pool:
logger.info("Starting LocalImage threadpool")
LocalImage._thread_pool = concurrent.futures.ThreadPoolExecutor(
thread_name_prefix="Renderer")
return LocalImage._thread_pool | python | def thread_pool():
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",
"(",
")",
":",
"if",
"not",
"LocalImage",
".",
"_thread_pool",
":",
"logger",
".",
"info",
"(",
"\"Starting LocalImage threadpool\"",
")",
"LocalImage",
".",
"_thread_pool",
"=",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
... | Get the rendition threadpool | [
"Get",
"the",
"rendition",
"threadpool"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L65-L71 |
11,219 | PlaidWeb/Publ | publ/image/local.py | LocalImage._adjust_crop_box | def _adjust_crop_box(box, crop):
""" Given a fit box and a crop box, adjust one to the other """
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[0], crop[1], crop[0] + crop[2], crop[1] + crop[3])
# We don't have a crop box, so return the fit box (even if it's None)
return box | python | def _adjust_crop_box(box, crop):
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[0], crop[1], crop[0] + crop[2], crop[1] + crop[3])
# We don't have a crop box, so return the fit box (even if it's None)
return box | [
"def",
"_adjust_crop_box",
"(",
"box",
",",
"crop",
")",
":",
"if",
"crop",
"and",
"box",
":",
"# Both boxes are the same size; just line them up.",
"return",
"(",
"box",
"[",
"0",
"]",
"+",
"crop",
"[",
"0",
"]",
",",
"box",
"[",
"1",
"]",
"+",
"crop",
... | Given a fit box and a crop box, adjust one to the other | [
"Given",
"a",
"fit",
"box",
"and",
"a",
"crop",
"box",
"adjust",
"one",
"to",
"the",
"other"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L180-L193 |
11,220 | PlaidWeb/Publ | publ/image/local.py | LocalImage.get_rendition_size | def get_rendition_size(self, spec, output_scale, crop):
"""
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
"""
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':
return self.get_rendition_fit_size(spec, width, height, output_scale)
if mode == 'fill':
return self.get_rendition_fill_size(spec, width, height, output_scale)
if mode == 'stretch':
return self.get_rendition_stretch_size(spec, width, height, output_scale)
raise ValueError("Unknown resize mode {}".format(mode)) | python | def get_rendition_size(self, spec, output_scale, crop):
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':
return self.get_rendition_fit_size(spec, width, height, output_scale)
if mode == 'fill':
return self.get_rendition_fill_size(spec, width, height, output_scale)
if mode == 'stretch':
return self.get_rendition_stretch_size(spec, width, height, output_scale)
raise ValueError("Unknown resize mode {}".format(mode)) | [
"def",
"get_rendition_size",
"(",
"self",
",",
"spec",
",",
"output_scale",
",",
"crop",
")",
":",
"if",
"crop",
":",
"# Use the cropping rectangle size",
"_",
",",
"_",
",",
"width",
",",
"height",
"=",
"crop",
"else",
":",
"# Use the original image size",
"w... | Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box) | [
"Wrapper",
"to",
"determine",
"the",
"overall",
"rendition",
"size",
"and",
"cropping",
"box"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L254-L279 |
11,221 | PlaidWeb/Publ | publ/image/local.py | LocalImage.get_rendition_fit_size | def get_rendition_fit_size(spec, input_w, input_h, output_scale):
""" Determine the scaled size based on the provided spec """
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 / width
width = min_width
min_height = spec.get('scale_min_height')
if min_height and height < min_height:
width = width * min_height / height
height = min_height
tgt_width, tgt_height = spec.get('width'), spec.get('height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
tgt_width, tgt_height = spec.get('max_width'), spec.get('max_height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
width = width * output_scale
height = height * output_scale
# Never scale to larger than the base rendition
width = min(round(width), input_w)
height = min(round(height), input_h)
return (width, height), None | python | def get_rendition_fit_size(spec, input_w, input_h, output_scale):
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 / width
width = min_width
min_height = spec.get('scale_min_height')
if min_height and height < min_height:
width = width * min_height / height
height = min_height
tgt_width, tgt_height = spec.get('width'), spec.get('height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
tgt_width, tgt_height = spec.get('max_width'), spec.get('max_height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
width = width * output_scale
height = height * output_scale
# Never scale to larger than the base rendition
width = min(round(width), input_w)
height = min(round(height), input_h)
return (width, height), None | [
"def",
"get_rendition_fit_size",
"(",
"spec",
",",
"input_w",
",",
"input_h",
",",
"output_scale",
")",
":",
"width",
"=",
"input_w",
"height",
"=",
"input_h",
"scale",
"=",
"spec",
".",
"get",
"(",
"'scale'",
")",
"if",
"scale",
":",
"width",
"=",
"widt... | Determine the scaled size based on the provided spec | [
"Determine",
"the",
"scaled",
"size",
"based",
"on",
"the",
"provided",
"spec"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L282-L330 |
11,222 | PlaidWeb/Publ | publ/image/local.py | LocalImage.flatten | def flatten(image, bgcolor=None):
""" Flatten an image, with an optional background color """
if bgcolor:
background = PIL.Image.new('RGB', image.size, bgcolor)
background.paste(image, mask=image.split()[3])
return background
return image.convert('RGB') | python | def flatten(image, bgcolor=None):
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",
")",
":",
"if",
"bgcolor",
":",
"background",
"=",
"PIL",
".",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"image",
".",
"size",
",",
"bgcolor",
")",
"background",
".",
"paste",
"(",
"image",
... | Flatten an image, with an optional background color | [
"Flatten",
"an",
"image",
"with",
"an",
"optional",
"background",
"color"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L427-L434 |
11,223 | PlaidWeb/Publ | publ/image/local.py | LocalImage._get_renditions | def _get_renditions(self, kwargs):
""" Get a bunch of renditions; returns a tuple of 1x, 2x, size """
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) | python | def _get_renditions(self, kwargs):
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",
")",
":",
"img_1x",
",",
"size",
"=",
"self",
".",
"get_rendition",
"(",
"1",
",",
"*",
"*",
"utils",
".",
"remap_args",
"(",
"kwargs",
",",
"{",
"\"quality\"",
":",
"\"quality_ldpi\"",
"}",
")",
")... | Get a bunch of renditions; returns a tuple of 1x, 2x, size | [
"Get",
"a",
"bunch",
"of",
"renditions",
";",
"returns",
"a",
"tuple",
"of",
"1x",
"2x",
"size"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L436-L443 |
11,224 | PlaidWeb/Publ | publ/image/local.py | LocalImage._css_background | def _css_background(self, **kwargs):
""" Get the CSS specifiers for this as a hidpi-capable background image """
# 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: -webkit-{ss};'.format(
ss=image_set)
return tmpl.format(s1x=img_1x, s2x=img_2x) | python | def _css_background(self, **kwargs):
# 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: -webkit-{ss};'.format(
ss=image_set)
return tmpl.format(s1x=img_1x, s2x=img_2x) | [
"def",
"_css_background",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the 1x and 2x renditions",
"img_1x",
",",
"img_2x",
",",
"_",
"=",
"self",
".",
"_get_renditions",
"(",
"kwargs",
")",
"tmpl",
"=",
"'background-image: url(\"{s1x}\");'",
"if",
"img... | Get the CSS specifiers for this as a hidpi-capable background image | [
"Get",
"the",
"CSS",
"specifiers",
"for",
"this",
"as",
"a",
"hidpi",
"-",
"capable",
"background",
"image"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L461-L472 |
11,225 | PlaidWeb/Publ | publ/html_entry.py | process | def process(text, config, search_path):
""" Process an HTML entry's HTML """
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) | python | def process(text, config, search_path):
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",
")",
":",
"processor",
"=",
"HTMLEntry",
"(",
"config",
",",
"search_path",
")",
"processor",
".",
"feed",
"(",
"text",
")",
"text",
"=",
"processor",
".",
"get_data",
"(",
")",
"if",
"n... | Process an HTML entry's HTML | [
"Process",
"an",
"HTML",
"entry",
"s",
"HTML"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/html_entry.py#L93-L102 |
11,226 | PlaidWeb/Publ | publ/html_entry.py | HTMLEntry._handle_tag | def _handle_tag(self, tag, attrs, self_closing):
""" Handle a tag.
attrs -- the attributes of the tag
self_closing -- whether this is self-closing
"""
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.append((key, links.resolve(
val, self._search_path, self._config.get('absolute'))))
else:
out_attrs.append((key, val))
self.append(
utils.make_tag(
tag,
out_attrs,
self_closing)) | python | def _handle_tag(self, tag, attrs, self_closing):
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.append((key, links.resolve(
val, self._search_path, self._config.get('absolute'))))
else:
out_attrs.append((key, val))
self.append(
utils.make_tag(
tag,
out_attrs,
self_closing)) | [
"def",
"_handle_tag",
"(",
"self",
",",
"tag",
",",
"attrs",
",",
"self_closing",
")",
":",
"if",
"tag",
".",
"lower",
"(",
")",
"==",
"'img'",
":",
"attrs",
"=",
"self",
".",
"_image_attrs",
"(",
"attrs",
")",
"# Remap the attributes",
"out_attrs",
"=",... | Handle a tag.
attrs -- the attributes of the tag
self_closing -- whether this is self-closing | [
"Handle",
"a",
"tag",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/html_entry.py#L34-L58 |
11,227 | PlaidWeb/Publ | publ/index.py | last_modified | def last_modified():
""" information about the most recently modified file """
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 | python | def last_modified():
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",
"(",
")",
":",
"files",
"=",
"model",
".",
"FileFingerprint",
".",
"select",
"(",
")",
".",
"order_by",
"(",
"orm",
".",
"desc",
"(",
"model",
".",
"FileFingerprint",
".",
"file_mtime",
")",
")",
"for",
"file",
"in",
"files",
":... | information about the most recently modified file | [
"information",
"about",
"the",
"most",
"recently",
"modified",
"file"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L58-L64 |
11,228 | PlaidWeb/Publ | publ/index.py | scan_file | 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 will return a truthy value if it was scanned
successfully, False if it failed, and None if there is nothing to scan.
"""
logger.debug("Scanning file: %s (%s) %s", fullpath, relpath, assign_id)
def do_scan():
""" helper function to do the scan and gather the result """
_, ext = os.path.splitext(fullpath)
try:
if ext in ENTRY_TYPES:
logger.info("Scanning entry: %s", fullpath)
return entry.scan_file(fullpath, relpath, assign_id)
if ext in CATEGORY_TYPES:
logger.info("Scanning meta info: %s", fullpath)
return category.scan_file(fullpath, relpath)
return None
except: # pylint: disable=bare-except
logger.exception("Got error parsing %s", fullpath)
return False
result = do_scan()
if result is False and not assign_id:
logger.info("Scheduling fixup for %s", fullpath)
THREAD_POOL.submit(scan_file, fullpath, relpath, True)
else:
logger.debug("%s complete", fullpath)
if result:
set_fingerprint(fullpath)
SCHEDULED_FILES.remove(fullpath) | python | def scan_file(fullpath, relpath, assign_id):
logger.debug("Scanning file: %s (%s) %s", fullpath, relpath, assign_id)
def do_scan():
""" helper function to do the scan and gather the result """
_, ext = os.path.splitext(fullpath)
try:
if ext in ENTRY_TYPES:
logger.info("Scanning entry: %s", fullpath)
return entry.scan_file(fullpath, relpath, assign_id)
if ext in CATEGORY_TYPES:
logger.info("Scanning meta info: %s", fullpath)
return category.scan_file(fullpath, relpath)
return None
except: # pylint: disable=bare-except
logger.exception("Got error parsing %s", fullpath)
return False
result = do_scan()
if result is False and not assign_id:
logger.info("Scheduling fixup for %s", fullpath)
THREAD_POOL.submit(scan_file, fullpath, relpath, True)
else:
logger.debug("%s complete", fullpath)
if result:
set_fingerprint(fullpath)
SCHEDULED_FILES.remove(fullpath) | [
"def",
"scan_file",
"(",
"fullpath",
",",
"relpath",
",",
"assign_id",
")",
":",
"logger",
".",
"debug",
"(",
"\"Scanning file: %s (%s) %s\"",
",",
"fullpath",
",",
"relpath",
",",
"assign_id",
")",
"def",
"do_scan",
"(",
")",
":",
"\"\"\" helper function to do ... | 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 will return a truthy value if it was scanned
successfully, False if it failed, and None if there is nothing to scan. | [
"Scan",
"a",
"file",
"for",
"the",
"index"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L77-L117 |
11,229 | PlaidWeb/Publ | publ/index.py | get_last_fingerprint | def get_last_fingerprint(fullpath):
""" Get the last known modification time for a file """
record = model.FileFingerprint.get(file_path=fullpath)
if record:
return record.fingerprint
return None | python | def get_last_fingerprint(fullpath):
record = model.FileFingerprint.get(file_path=fullpath)
if record:
return record.fingerprint
return None | [
"def",
"get_last_fingerprint",
"(",
"fullpath",
")",
":",
"record",
"=",
"model",
".",
"FileFingerprint",
".",
"get",
"(",
"file_path",
"=",
"fullpath",
")",
"if",
"record",
":",
"return",
"record",
".",
"fingerprint",
"return",
"None"
] | Get the last known modification time for a file | [
"Get",
"the",
"last",
"known",
"modification",
"time",
"for",
"a",
"file"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L121-L126 |
11,230 | PlaidWeb/Publ | publ/index.py | set_fingerprint | def set_fingerprint(fullpath, fingerprint=None):
""" Set the last known modification time for a file """
try:
fingerprint = fingerprint or utils.file_fingerprint(fullpath)
record = model.FileFingerprint.get(file_path=fullpath)
if record:
record.set(fingerprint=fingerprint,
file_mtime=os.stat(fullpath).st_mtime)
else:
record = model.FileFingerprint(
file_path=fullpath,
fingerprint=fingerprint,
file_mtime=os.stat(fullpath).st_mtime)
orm.commit()
except FileNotFoundError:
orm.delete(fp for fp in model.FileFingerprint if fp.file_path == fullpath) | python | def set_fingerprint(fullpath, fingerprint=None):
try:
fingerprint = fingerprint or utils.file_fingerprint(fullpath)
record = model.FileFingerprint.get(file_path=fullpath)
if record:
record.set(fingerprint=fingerprint,
file_mtime=os.stat(fullpath).st_mtime)
else:
record = model.FileFingerprint(
file_path=fullpath,
fingerprint=fingerprint,
file_mtime=os.stat(fullpath).st_mtime)
orm.commit()
except FileNotFoundError:
orm.delete(fp for fp in model.FileFingerprint if fp.file_path == fullpath) | [
"def",
"set_fingerprint",
"(",
"fullpath",
",",
"fingerprint",
"=",
"None",
")",
":",
"try",
":",
"fingerprint",
"=",
"fingerprint",
"or",
"utils",
".",
"file_fingerprint",
"(",
"fullpath",
")",
"record",
"=",
"model",
".",
"FileFingerprint",
".",
"get",
"("... | Set the last known modification time for a file | [
"Set",
"the",
"last",
"known",
"modification",
"time",
"for",
"a",
"file"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L130-L146 |
11,231 | PlaidWeb/Publ | publ/index.py | background_scan | def background_scan(content_dir):
""" Start background scanning a directory for changes """
observer = watchdog.observers.Observer()
observer.schedule(IndexWatchdog(content_dir),
content_dir, recursive=True)
logging.info("Watching %s for changes", content_dir)
observer.start() | python | def background_scan(content_dir):
observer = watchdog.observers.Observer()
observer.schedule(IndexWatchdog(content_dir),
content_dir, recursive=True)
logging.info("Watching %s for changes", content_dir)
observer.start() | [
"def",
"background_scan",
"(",
"content_dir",
")",
":",
"observer",
"=",
"watchdog",
".",
"observers",
".",
"Observer",
"(",
")",
"observer",
".",
"schedule",
"(",
"IndexWatchdog",
"(",
"content_dir",
")",
",",
"content_dir",
",",
"recursive",
"=",
"True",
"... | Start background scanning a directory for changes | [
"Start",
"background",
"scanning",
"a",
"directory",
"for",
"changes"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L188-L194 |
11,232 | PlaidWeb/Publ | publ/index.py | prune_missing | def prune_missing(table):
""" Prune any files which are missing from the specified table """
try:
for item in table.select():
if not os.path.isfile(item.file_path):
logger.info("File disappeared: %s", item.file_path)
item.delete()
except: # pylint:disable=bare-except
logger.exception("Error pruning %s", table) | python | def prune_missing(table):
try:
for item in table.select():
if not os.path.isfile(item.file_path):
logger.info("File disappeared: %s", item.file_path)
item.delete()
except: # pylint:disable=bare-except
logger.exception("Error pruning %s", table) | [
"def",
"prune_missing",
"(",
"table",
")",
":",
"try",
":",
"for",
"item",
"in",
"table",
".",
"select",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"item",
".",
"file_path",
")",
":",
"logger",
".",
"info",
"(",
"\"File disa... | Prune any files which are missing from the specified table | [
"Prune",
"any",
"files",
"which",
"are",
"missing",
"from",
"the",
"specified",
"table"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L198-L206 |
11,233 | PlaidWeb/Publ | publ/index.py | scan_index | def scan_index(content_dir):
""" Scan all files in a content directory """
def scan_directory(root, files):
""" Helper function to scan a single directory """
try:
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpath, content_dir)
fingerprint = utils.file_fingerprint(fullpath)
last_fingerprint = get_last_fingerprint(fullpath)
if fingerprint != last_fingerprint and SCHEDULED_FILES.add(fullpath):
scan_file(fullpath, relpath, False)
except: # pylint:disable=bare-except
logger.exception("Got error parsing directory %s", root)
for root, _, files in os.walk(content_dir, followlinks=True):
THREAD_POOL.submit(scan_directory, root, files)
for table in (model.Entry, model.Category, model.Image, model.FileFingerprint):
THREAD_POOL.submit(prune_missing, table) | python | def scan_index(content_dir):
def scan_directory(root, files):
""" Helper function to scan a single directory """
try:
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpath, content_dir)
fingerprint = utils.file_fingerprint(fullpath)
last_fingerprint = get_last_fingerprint(fullpath)
if fingerprint != last_fingerprint and SCHEDULED_FILES.add(fullpath):
scan_file(fullpath, relpath, False)
except: # pylint:disable=bare-except
logger.exception("Got error parsing directory %s", root)
for root, _, files in os.walk(content_dir, followlinks=True):
THREAD_POOL.submit(scan_directory, root, files)
for table in (model.Entry, model.Category, model.Image, model.FileFingerprint):
THREAD_POOL.submit(prune_missing, table) | [
"def",
"scan_index",
"(",
"content_dir",
")",
":",
"def",
"scan_directory",
"(",
"root",
",",
"files",
")",
":",
"\"\"\" Helper function to scan a single directory \"\"\"",
"try",
":",
"for",
"file",
"in",
"files",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
... | Scan all files in a content directory | [
"Scan",
"all",
"files",
"in",
"a",
"content",
"directory"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L209-L230 |
11,234 | PlaidWeb/Publ | publ/index.py | ConcurrentSet.add | def add(self, item):
""" Add an item to the set, and return whether it was newly added """
with self.lock:
if item in self.set:
return False
self.set.add(item)
return True | python | def add(self, item):
with self.lock:
if item in self.set:
return False
self.set.add(item)
return True | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"item",
"in",
"self",
".",
"set",
":",
"return",
"False",
"self",
".",
"set",
".",
"add",
"(",
"item",
")",
"return",
"True"
] | Add an item to the set, and return whether it was newly added | [
"Add",
"an",
"item",
"to",
"the",
"set",
"and",
"return",
"whether",
"it",
"was",
"newly",
"added"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L38-L44 |
11,235 | PlaidWeb/Publ | publ/index.py | ConcurrentSet.remove | def remove(self, item):
""" Remove an item from the set, returning if it was present """
with self.lock:
if item in self.set:
self.set.remove(item)
return True
return False | python | def remove(self, item):
with self.lock:
if item in self.set:
self.set.remove(item)
return True
return False | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"item",
"in",
"self",
".",
"set",
":",
"self",
".",
"set",
".",
"remove",
"(",
"item",
")",
"return",
"True",
"return",
"False"
] | Remove an item from the set, returning if it was present | [
"Remove",
"an",
"item",
"from",
"the",
"set",
"returning",
"if",
"it",
"was",
"present"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L46-L52 |
11,236 | PlaidWeb/Publ | publ/index.py | IndexWatchdog.update_file | def update_file(self, fullpath):
""" Update a file """
if SCHEDULED_FILES.add(fullpath):
logger.debug("Scheduling reindex of %s", fullpath)
relpath = os.path.relpath(fullpath, self.content_dir)
THREAD_POOL.submit(scan_file, fullpath, relpath, False) | python | def update_file(self, fullpath):
if SCHEDULED_FILES.add(fullpath):
logger.debug("Scheduling reindex of %s", fullpath)
relpath = os.path.relpath(fullpath, self.content_dir)
THREAD_POOL.submit(scan_file, fullpath, relpath, False) | [
"def",
"update_file",
"(",
"self",
",",
"fullpath",
")",
":",
"if",
"SCHEDULED_FILES",
".",
"add",
"(",
"fullpath",
")",
":",
"logger",
".",
"debug",
"(",
"\"Scheduling reindex of %s\"",
",",
"fullpath",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpat... | Update a file | [
"Update",
"a",
"file"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L156-L161 |
11,237 | PlaidWeb/Publ | publ/view.py | parse_view_spec | def parse_view_spec(args):
""" Parse a view specification from a request arg list """
view_spec = {}
if 'date' in args:
view_spec['date'] = args['date']
elif 'id' in args:
view_spec['start'] = args['id']
if 'tag' in args:
view_spec['tag'] = args.getlist('tag')
if len(view_spec['tag']) == 1:
view_spec['tag'] = args['tag']
return view_spec | python | def parse_view_spec(args):
view_spec = {}
if 'date' in args:
view_spec['date'] = args['date']
elif 'id' in args:
view_spec['start'] = args['id']
if 'tag' in args:
view_spec['tag'] = args.getlist('tag')
if len(view_spec['tag']) == 1:
view_spec['tag'] = args['tag']
return view_spec | [
"def",
"parse_view_spec",
"(",
"args",
")",
":",
"view_spec",
"=",
"{",
"}",
"if",
"'date'",
"in",
"args",
":",
"view_spec",
"[",
"'date'",
"]",
"=",
"args",
"[",
"'date'",
"]",
"elif",
"'id'",
"in",
"args",
":",
"view_spec",
"[",
"'start'",
"]",
"="... | Parse a view specification from a request arg list | [
"Parse",
"a",
"view",
"specification",
"from",
"a",
"request",
"arg",
"list"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L414-L429 |
11,238 | PlaidWeb/Publ | publ/view.py | View.deleted | def deleted(self):
""" Gets the deleted entries from the view """
query = queries.build_query({**self.spec,
'future': False,
'_deleted': True})
return [Entry(e) for e in query] | python | def deleted(self):
query = queries.build_query({**self.spec,
'future': False,
'_deleted': True})
return [Entry(e) for e in query] | [
"def",
"deleted",
"(",
"self",
")",
":",
"query",
"=",
"queries",
".",
"build_query",
"(",
"{",
"*",
"*",
"self",
".",
"spec",
",",
"'future'",
":",
"False",
",",
"'_deleted'",
":",
"True",
"}",
")",
"return",
"[",
"Entry",
"(",
"e",
")",
"for",
... | Gets the deleted entries from the view | [
"Gets",
"the",
"deleted",
"entries",
"from",
"the",
"view"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L155-L160 |
11,239 | PlaidWeb/Publ | publ/view.py | View.last_modified | def last_modified(self):
""" Gets the most recent modification time for all entries in the view """
if self.entries:
latest = max(self.entries, key=lambda x: x.last_modified)
return arrow.get(latest.last_modified)
return arrow.get() | python | def last_modified(self):
if self.entries:
latest = max(self.entries, key=lambda x: x.last_modified)
return arrow.get(latest.last_modified)
return arrow.get() | [
"def",
"last_modified",
"(",
"self",
")",
":",
"if",
"self",
".",
"entries",
":",
"latest",
"=",
"max",
"(",
"self",
".",
"entries",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"last_modified",
")",
"return",
"arrow",
".",
"get",
"(",
"latest",
... | Gets the most recent modification time for all entries in the view | [
"Gets",
"the",
"most",
"recent",
"modification",
"time",
"for",
"all",
"entries",
"in",
"the",
"view"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L168-L173 |
11,240 | PlaidWeb/Publ | publ/view.py | View.previous | def previous(self):
""" Gets the previous page, respecting sort order """
if self._order_by == 'oldest':
return self.older
if self._order_by == 'newest':
return self.newer
return None | python | def previous(self):
if self._order_by == 'oldest':
return self.older
if self._order_by == 'newest':
return self.newer
return None | [
"def",
"previous",
"(",
"self",
")",
":",
"if",
"self",
".",
"_order_by",
"==",
"'oldest'",
":",
"return",
"self",
".",
"older",
"if",
"self",
".",
"_order_by",
"==",
"'newest'",
":",
"return",
"self",
".",
"newer",
"return",
"None"
] | Gets the previous page, respecting sort order | [
"Gets",
"the",
"previous",
"page",
"respecting",
"sort",
"order"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L188-L194 |
11,241 | PlaidWeb/Publ | publ/view.py | View.next | def next(self):
""" Gets the next page, respecting sort order """
if self._order_by == 'oldest':
return self.newer
if self._order_by == 'newest':
return self.older
return None | python | def next(self):
if self._order_by == 'oldest':
return self.newer
if self._order_by == 'newest':
return self.older
return None | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_order_by",
"==",
"'oldest'",
":",
"return",
"self",
".",
"newer",
"if",
"self",
".",
"_order_by",
"==",
"'newest'",
":",
"return",
"self",
".",
"older",
"return",
"None"
] | Gets the next page, respecting sort order | [
"Gets",
"the",
"next",
"page",
"respecting",
"sort",
"order"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L197-L203 |
11,242 | PlaidWeb/Publ | publ/view.py | View.newest | def newest(self):
""" Gets the newest entry in the view, regardless of sort order """
if self._order_by == 'newest':
return self.first
if self._order_by == 'oldest':
return self.last
return max(self.entries, key=lambda x: (x.date, x.id)) | python | def newest(self):
if self._order_by == 'newest':
return self.first
if self._order_by == 'oldest':
return self.last
return max(self.entries, key=lambda x: (x.date, x.id)) | [
"def",
"newest",
"(",
"self",
")",
":",
"if",
"self",
".",
"_order_by",
"==",
"'newest'",
":",
"return",
"self",
".",
"first",
"if",
"self",
".",
"_order_by",
"==",
"'oldest'",
":",
"return",
"self",
".",
"last",
"return",
"max",
"(",
"self",
".",
"e... | Gets the newest entry in the view, regardless of sort order | [
"Gets",
"the",
"newest",
"entry",
"in",
"the",
"view",
"regardless",
"of",
"sort",
"order"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L206-L212 |
11,243 | PlaidWeb/Publ | publ/view.py | View.oldest | def oldest(self):
""" Gets the oldest entry in the view, regardless of sort order """
if self._order_by == 'newest':
return self.last
if self._order_by == 'oldest':
return self.first
return min(self.entries, key=lambda x: (x.date, -x.id)) | python | def oldest(self):
if self._order_by == 'newest':
return self.last
if self._order_by == 'oldest':
return self.first
return min(self.entries, key=lambda x: (x.date, -x.id)) | [
"def",
"oldest",
"(",
"self",
")",
":",
"if",
"self",
".",
"_order_by",
"==",
"'newest'",
":",
"return",
"self",
".",
"last",
"if",
"self",
".",
"_order_by",
"==",
"'oldest'",
":",
"return",
"self",
".",
"first",
"return",
"min",
"(",
"self",
".",
"e... | Gets the oldest entry in the view, regardless of sort order | [
"Gets",
"the",
"oldest",
"entry",
"in",
"the",
"view",
"regardless",
"of",
"sort",
"order"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L215-L221 |
11,244 | PlaidWeb/Publ | publ/view.py | View.pages | def pages(self):
""" Gets a list of all pages for this view """
cur = self
pages = []
while cur.previous:
cur = cur.previous
while cur:
pages.append(cur)
cur = cur.next
return pages | python | def pages(self):
cur = self
pages = []
while cur.previous:
cur = cur.previous
while cur:
pages.append(cur)
cur = cur.next
return pages | [
"def",
"pages",
"(",
"self",
")",
":",
"cur",
"=",
"self",
"pages",
"=",
"[",
"]",
"while",
"cur",
".",
"previous",
":",
"cur",
"=",
"cur",
".",
"previous",
"while",
"cur",
":",
"pages",
".",
"append",
"(",
"cur",
")",
"cur",
"=",
"cur",
".",
"... | Gets a list of all pages for this view | [
"Gets",
"a",
"list",
"of",
"all",
"pages",
"for",
"this",
"view"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L232-L241 |
11,245 | PlaidWeb/Publ | publ/view.py | View.tags | def tags(self):
""" Returns a list of all the tags applied to this view """
tag_list = self.spec.get('tag', [])
if isinstance(tag_list, (list, set, tuple)):
return list(tag_list)
return [tag_list] | python | def tags(self):
tag_list = self.spec.get('tag', [])
if isinstance(tag_list, (list, set, tuple)):
return list(tag_list)
return [tag_list] | [
"def",
"tags",
"(",
"self",
")",
":",
"tag_list",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'tag'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"tag_list",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"return",
"list",
"(",
"ta... | Returns a list of all the tags applied to this view | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"tags",
"applied",
"to",
"this",
"view"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L254-L259 |
11,246 | PlaidWeb/Publ | publ/view.py | View._pagination | def _pagination(self):
""" Compute the neighboring pages from this view.
Returns a tuple of older page, newer page.
"""
oldest = self.oldest
newest = self.newest
base = {key: val for key, val in self.spec.items()
if key not in OFFSET_PRIORITY}
oldest_neighbor = View({
**base,
'before': oldest,
'order': 'newest'
}).first if oldest else None
newest_neighbor = View({
**base,
'after': newest,
'order': 'oldest'
}).first if newest else None
if 'date' in self.spec:
return self._get_date_pagination(base, oldest_neighbor, newest_neighbor)
if 'count' in self.spec:
return self._get_count_pagination(base, oldest_neighbor, newest_neighbor)
# we're not paginating
return None, None | python | def _pagination(self):
oldest = self.oldest
newest = self.newest
base = {key: val for key, val in self.spec.items()
if key not in OFFSET_PRIORITY}
oldest_neighbor = View({
**base,
'before': oldest,
'order': 'newest'
}).first if oldest else None
newest_neighbor = View({
**base,
'after': newest,
'order': 'oldest'
}).first if newest else None
if 'date' in self.spec:
return self._get_date_pagination(base, oldest_neighbor, newest_neighbor)
if 'count' in self.spec:
return self._get_count_pagination(base, oldest_neighbor, newest_neighbor)
# we're not paginating
return None, None | [
"def",
"_pagination",
"(",
"self",
")",
":",
"oldest",
"=",
"self",
".",
"oldest",
"newest",
"=",
"self",
".",
"newest",
"base",
"=",
"{",
"key",
":",
"val",
"for",
"key",
",",
"val",
"in",
"self",
".",
"spec",
".",
"items",
"(",
")",
"if",
"key"... | Compute the neighboring pages from this view.
Returns a tuple of older page, newer page. | [
"Compute",
"the",
"neighboring",
"pages",
"from",
"this",
"view",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L262-L293 |
11,247 | PlaidWeb/Publ | publ/view.py | View._get_date_pagination | def _get_date_pagination(self, base, oldest_neighbor, newest_neighbor):
""" Compute the pagination for date-based views """
_, span, date_format = utils.parse_date(self.spec['date'])
if newest_neighbor:
newer_date = newest_neighbor.date.span(span)[0]
newer_view = View({**base,
'order': self._order_by,
'date': newer_date.format(date_format)})
else:
newer_view = None
if oldest_neighbor:
older_date = oldest_neighbor.date.span(span)[0]
older_view = View({**base,
'order': self._order_by,
'date': older_date.format(date_format)})
else:
older_view = None
return older_view, newer_view | python | def _get_date_pagination(self, base, oldest_neighbor, newest_neighbor):
_, span, date_format = utils.parse_date(self.spec['date'])
if newest_neighbor:
newer_date = newest_neighbor.date.span(span)[0]
newer_view = View({**base,
'order': self._order_by,
'date': newer_date.format(date_format)})
else:
newer_view = None
if oldest_neighbor:
older_date = oldest_neighbor.date.span(span)[0]
older_view = View({**base,
'order': self._order_by,
'date': older_date.format(date_format)})
else:
older_view = None
return older_view, newer_view | [
"def",
"_get_date_pagination",
"(",
"self",
",",
"base",
",",
"oldest_neighbor",
",",
"newest_neighbor",
")",
":",
"_",
",",
"span",
",",
"date_format",
"=",
"utils",
".",
"parse_date",
"(",
"self",
".",
"spec",
"[",
"'date'",
"]",
")",
"if",
"newest_neigh... | Compute the pagination for date-based views | [
"Compute",
"the",
"pagination",
"for",
"date",
"-",
"based",
"views"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L295-L315 |
11,248 | PlaidWeb/Publ | publ/view.py | View._get_count_pagination | def _get_count_pagination(self, base, oldest_neighbor, newest_neighbor):
""" Compute the pagination for count-based views """
count = self.spec['count']
out_spec = {**base, 'count': count, 'order': self._order_by}
if self._order_by == 'newest':
older_view = View({**out_spec,
'last': oldest_neighbor}) if oldest_neighbor else None
newer_count = View({**base,
'first': newest_neighbor,
'order': 'oldest',
'count': count}) if newest_neighbor else None
newer_view = View({**out_spec,
'last': newer_count.last}) if newer_count else None
return older_view, newer_view
if self._order_by == 'oldest':
older_count = View({**base,
'last': oldest_neighbor,
'order': 'newest',
'count': count}) if oldest_neighbor else None
older_view = View({**out_spec,
'first': older_count.last}) if older_count else None
newer_view = View({**out_spec,
'first': newest_neighbor}) if newest_neighbor else None
return older_view, newer_view
return None, None | python | def _get_count_pagination(self, base, oldest_neighbor, newest_neighbor):
count = self.spec['count']
out_spec = {**base, 'count': count, 'order': self._order_by}
if self._order_by == 'newest':
older_view = View({**out_spec,
'last': oldest_neighbor}) if oldest_neighbor else None
newer_count = View({**base,
'first': newest_neighbor,
'order': 'oldest',
'count': count}) if newest_neighbor else None
newer_view = View({**out_spec,
'last': newer_count.last}) if newer_count else None
return older_view, newer_view
if self._order_by == 'oldest':
older_count = View({**base,
'last': oldest_neighbor,
'order': 'newest',
'count': count}) if oldest_neighbor else None
older_view = View({**out_spec,
'first': older_count.last}) if older_count else None
newer_view = View({**out_spec,
'first': newest_neighbor}) if newest_neighbor else None
return older_view, newer_view
return None, None | [
"def",
"_get_count_pagination",
"(",
"self",
",",
"base",
",",
"oldest_neighbor",
",",
"newest_neighbor",
")",
":",
"count",
"=",
"self",
".",
"spec",
"[",
"'count'",
"]",
"out_spec",
"=",
"{",
"*",
"*",
"base",
",",
"'count'",
":",
"count",
",",
"'order... | Compute the pagination for count-based views | [
"Compute",
"the",
"pagination",
"for",
"count",
"-",
"based",
"views"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L317-L350 |
11,249 | PlaidWeb/Publ | publ/view.py | View.tag_add | def tag_add(self, *tags):
""" Return a view with the specified tags added """
return View({**self.spec, 'tag': list(set(self.tags) | set(tags))}) | python | def tag_add(self, *tags):
return View({**self.spec, 'tag': list(set(self.tags) | set(tags))}) | [
"def",
"tag_add",
"(",
"self",
",",
"*",
"tags",
")",
":",
"return",
"View",
"(",
"{",
"*",
"*",
"self",
".",
"spec",
",",
"'tag'",
":",
"list",
"(",
"set",
"(",
"self",
".",
"tags",
")",
"|",
"set",
"(",
"tags",
")",
")",
"}",
")"
] | Return a view with the specified tags added | [
"Return",
"a",
"view",
"with",
"the",
"specified",
"tags",
"added"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L355-L357 |
11,250 | PlaidWeb/Publ | publ/view.py | View.tag_remove | def tag_remove(self, *tags):
""" Return a view with the specified tags removed """
return View({**self.spec, 'tag': list(set(self.tags) - set(tags))}) | python | def tag_remove(self, *tags):
return View({**self.spec, 'tag': list(set(self.tags) - set(tags))}) | [
"def",
"tag_remove",
"(",
"self",
",",
"*",
"tags",
")",
":",
"return",
"View",
"(",
"{",
"*",
"*",
"self",
".",
"spec",
",",
"'tag'",
":",
"list",
"(",
"set",
"(",
"self",
".",
"tags",
")",
"-",
"set",
"(",
"tags",
")",
")",
"}",
")"
] | Return a view with the specified tags removed | [
"Return",
"a",
"view",
"with",
"the",
"specified",
"tags",
"removed"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L359-L361 |
11,251 | PlaidWeb/Publ | publ/view.py | View.tag_toggle | def tag_toggle(self, *tags):
""" Return a view with the specified tags toggled """
return View({**self.spec, 'tag': list(set(self.tags) ^ set(tags))}) | python | def tag_toggle(self, *tags):
return View({**self.spec, 'tag': list(set(self.tags) ^ set(tags))}) | [
"def",
"tag_toggle",
"(",
"self",
",",
"*",
"tags",
")",
":",
"return",
"View",
"(",
"{",
"*",
"*",
"self",
".",
"spec",
",",
"'tag'",
":",
"list",
"(",
"set",
"(",
"self",
".",
"tags",
")",
"^",
"set",
"(",
"tags",
")",
")",
"}",
")"
] | Return a view with the specified tags toggled | [
"Return",
"a",
"view",
"with",
"the",
"specified",
"tags",
"toggled"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/view.py#L363-L365 |
11,252 | PlaidWeb/Publ | publ/markdown.py | to_html | def to_html(text, config, search_path):
""" Convert Markdown text to HTML """
processor = misaka.Markdown(HtmlRenderer(config, search_path),
extensions=ENABLED_EXTENSIONS)
text = processor(text)
if not config.get('no_smartquotes'):
text = misaka.smartypants(text)
return flask.Markup(text) | python | def to_html(text, config, search_path):
processor = misaka.Markdown(HtmlRenderer(config, search_path),
extensions=ENABLED_EXTENSIONS)
text = processor(text)
if not config.get('no_smartquotes'):
text = misaka.smartypants(text)
return flask.Markup(text) | [
"def",
"to_html",
"(",
"text",
",",
"config",
",",
"search_path",
")",
":",
"processor",
"=",
"misaka",
".",
"Markdown",
"(",
"HtmlRenderer",
"(",
"config",
",",
"search_path",
")",
",",
"extensions",
"=",
"ENABLED_EXTENSIONS",
")",
"text",
"=",
"processor",... | Convert Markdown text to HTML | [
"Convert",
"Markdown",
"text",
"to",
"HTML"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L167-L176 |
11,253 | PlaidWeb/Publ | publ/markdown.py | render_title | def render_title(text, markup=True, no_smartquotes=False):
""" Convert a Markdown title to HTML """
# HACK: If the title starts with something that looks like a list, save it
# for later
pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
text = pfx + misaka.Markdown(TitleRenderer(),
extensions=TITLE_EXTENSIONS)(text)
if not markup:
strip = HTMLStripper()
strip.feed(text)
text = strip.get_data()
if not no_smartquotes:
text = misaka.smartypants(text)
return flask.Markup(text) | python | def render_title(text, markup=True, no_smartquotes=False):
# HACK: If the title starts with something that looks like a list, save it
# for later
pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
text = pfx + misaka.Markdown(TitleRenderer(),
extensions=TITLE_EXTENSIONS)(text)
if not markup:
strip = HTMLStripper()
strip.feed(text)
text = strip.get_data()
if not no_smartquotes:
text = misaka.smartypants(text)
return flask.Markup(text) | [
"def",
"render_title",
"(",
"text",
",",
"markup",
"=",
"True",
",",
"no_smartquotes",
"=",
"False",
")",
":",
"# HACK: If the title starts with something that looks like a list, save it",
"# for later",
"pfx",
",",
"text",
"=",
"re",
".",
"match",
"(",
"r'([0-9. ]*)(... | Convert a Markdown title to HTML | [
"Convert",
"a",
"Markdown",
"title",
"to",
"HTML"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L218-L235 |
11,254 | PlaidWeb/Publ | publ/markdown.py | HtmlRenderer.image | def image(self, raw_url, title='', alt=''):
""" Adapt a standard Markdown image to a generated rendition set.
Container arguments used (in addition to the rendition tags):
div_class -- The CSS class name to use on any wrapper div
div_style -- Additional CSS styles to apply to the wrapper div
count -- The maximum number of images to show at once
more_text -- If there are more than `count` images, add this text indicating
that there are more images to be seen. This string gets two template
arguments, `{count}` which is the total number of images in the set,
and `{remain}` which is the number of images omitted from the set.
more_link -- If `more_text` is shown, this will format the text as a link to this location.
more_class -- If `more_text` is shown, wraps it in a `<div>` with this class.
"""
# pylint: disable=too-many-locals
text = ''
image_specs = raw_url
if title:
image_specs += ' "{}"'.format(title)
alt, container_args = image.parse_alt_text(alt)
container_args = {**self._config, **container_args}
spec_list, original_count = image.get_spec_list(
image_specs, container_args)
for spec in spec_list:
text += self._render_image(spec,
container_args,
alt)
if original_count > len(spec_list) and 'more_text' in container_args:
more_text = container_args['more_text'].format(
count=original_count,
remain=original_count - len(spec_list))
if 'more_link' in container_args:
more_text = '{a}{text}</a>'.format(
text=more_text,
a=utils.make_tag('a', {'href': container_args['more_link']}))
if 'more_class' in container_args:
more_text = '{div}{text}</div>'.format(
text=more_text,
div=utils.make_tag('div', {'class': container_args['more_class']}))
text += flask.Markup(more_text)
if text and (container_args.get('div_class') or
container_args.get('div_style')):
text = '{tag}{text}</div>'.format(
tag=utils.make_tag('div',
{'class': container_args.get('div_class'),
'style': container_args.get('div_style')}),
text=text)
# if text is ''/falsy then misaka interprets this as a failed parse...
return text or ' ' | python | def image(self, raw_url, title='', alt=''):
# pylint: disable=too-many-locals
text = ''
image_specs = raw_url
if title:
image_specs += ' "{}"'.format(title)
alt, container_args = image.parse_alt_text(alt)
container_args = {**self._config, **container_args}
spec_list, original_count = image.get_spec_list(
image_specs, container_args)
for spec in spec_list:
text += self._render_image(spec,
container_args,
alt)
if original_count > len(spec_list) and 'more_text' in container_args:
more_text = container_args['more_text'].format(
count=original_count,
remain=original_count - len(spec_list))
if 'more_link' in container_args:
more_text = '{a}{text}</a>'.format(
text=more_text,
a=utils.make_tag('a', {'href': container_args['more_link']}))
if 'more_class' in container_args:
more_text = '{div}{text}</div>'.format(
text=more_text,
div=utils.make_tag('div', {'class': container_args['more_class']}))
text += flask.Markup(more_text)
if text and (container_args.get('div_class') or
container_args.get('div_style')):
text = '{tag}{text}</div>'.format(
tag=utils.make_tag('div',
{'class': container_args.get('div_class'),
'style': container_args.get('div_style')}),
text=text)
# if text is ''/falsy then misaka interprets this as a failed parse...
return text or ' ' | [
"def",
"image",
"(",
"self",
",",
"raw_url",
",",
"title",
"=",
"''",
",",
"alt",
"=",
"''",
")",
":",
"# pylint: disable=too-many-locals",
"text",
"=",
"''",
"image_specs",
"=",
"raw_url",
"if",
"title",
":",
"image_specs",
"+=",
"' \"{}\"'",
".",
"format... | Adapt a standard Markdown image to a generated rendition set.
Container arguments used (in addition to the rendition tags):
div_class -- The CSS class name to use on any wrapper div
div_style -- Additional CSS styles to apply to the wrapper div
count -- The maximum number of images to show at once
more_text -- If there are more than `count` images, add this text indicating
that there are more images to be seen. This string gets two template
arguments, `{count}` which is the total number of images in the set,
and `{remain}` which is the number of images omitted from the set.
more_link -- If `more_text` is shown, this will format the text as a link to this location.
more_class -- If `more_text` is shown, wraps it in a `<div>` with this class. | [
"Adapt",
"a",
"standard",
"Markdown",
"image",
"to",
"a",
"generated",
"rendition",
"set",
"."
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L43-L101 |
11,255 | PlaidWeb/Publ | publ/markdown.py | HtmlRenderer.blockcode | def blockcode(self, text, lang):
""" Pass a code fence through pygments """
if lang and self._config.get('highlight_syntax', 'True'):
try:
lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
except pygments.lexers.ClassNotFound:
lexer = None
if lexer:
formatter = pygments.formatters.HtmlFormatter() # pylint: disable=no-member
return pygments.highlight(text, lexer, formatter)
return '\n<div class="highlight"><pre>{}</pre></div>\n'.format(
flask.escape(text.strip())) | python | def blockcode(self, text, lang):
if lang and self._config.get('highlight_syntax', 'True'):
try:
lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
except pygments.lexers.ClassNotFound:
lexer = None
if lexer:
formatter = pygments.formatters.HtmlFormatter() # pylint: disable=no-member
return pygments.highlight(text, lexer, formatter)
return '\n<div class="highlight"><pre>{}</pre></div>\n'.format(
flask.escape(text.strip())) | [
"def",
"blockcode",
"(",
"self",
",",
"text",
",",
"lang",
")",
":",
"if",
"lang",
"and",
"self",
".",
"_config",
".",
"get",
"(",
"'highlight_syntax'",
",",
"'True'",
")",
":",
"try",
":",
"lexer",
"=",
"pygments",
".",
"lexers",
".",
"get_lexer_by_na... | Pass a code fence through pygments | [
"Pass",
"a",
"code",
"fence",
"through",
"pygments"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L103-L116 |
11,256 | PlaidWeb/Publ | publ/markdown.py | HtmlRenderer.link | def link(self, content, link, title=''):
""" Emit a link, potentially remapped based on our embed or static rules """
link = links.resolve(link, self._search_path,
self._config.get('absolute'))
return '{}{}</a>'.format(
utils.make_tag('a', {
'href': link,
'title': title if title else None
}),
content) | python | def link(self, content, link, title=''):
link = links.resolve(link, self._search_path,
self._config.get('absolute'))
return '{}{}</a>'.format(
utils.make_tag('a', {
'href': link,
'title': title if title else None
}),
content) | [
"def",
"link",
"(",
"self",
",",
"content",
",",
"link",
",",
"title",
"=",
"''",
")",
":",
"link",
"=",
"links",
".",
"resolve",
"(",
"link",
",",
"self",
".",
"_search_path",
",",
"self",
".",
"_config",
".",
"get",
"(",
"'absolute'",
")",
")",
... | Emit a link, potentially remapped based on our embed or static rules | [
"Emit",
"a",
"link",
"potentially",
"remapped",
"based",
"on",
"our",
"embed",
"or",
"static",
"rules"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L118-L129 |
11,257 | PlaidWeb/Publ | publ/markdown.py | HtmlRenderer.paragraph | def paragraph(content):
""" emit a paragraph, stripping out any leading or following empty paragraphs """
# if the content contains a top-level div then don't wrap it in a <p>
# tag
if content.startswith('<div') and content.endswith('</div>'):
return '\n' + content + '\n'
text = '<p>' + content + '</p>'
text = re.sub(r'<p>\s*</p>', r'', text)
return text or ' ' | python | def paragraph(content):
# if the content contains a top-level div then don't wrap it in a <p>
# tag
if content.startswith('<div') and content.endswith('</div>'):
return '\n' + content + '\n'
text = '<p>' + content + '</p>'
text = re.sub(r'<p>\s*</p>', r'', text)
return text or ' ' | [
"def",
"paragraph",
"(",
"content",
")",
":",
"# if the content contains a top-level div then don't wrap it in a <p>",
"# tag",
"if",
"content",
".",
"startswith",
"(",
"'<div'",
")",
"and",
"content",
".",
"endswith",
"(",
"'</div>'",
")",
":",
"return",
"'\\n'",
"... | emit a paragraph, stripping out any leading or following empty paragraphs | [
"emit",
"a",
"paragraph",
"stripping",
"out",
"any",
"leading",
"or",
"following",
"empty",
"paragraphs"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L132-L142 |
11,258 | PlaidWeb/Publ | publ/links.py | resolve | def resolve(path, search_path, absolute=False):
""" Remap a link or source target to an appropriate entry or image rendition """
# Resolve external URLs
if re.match(r'([a-z][a-z0-9+.\-]*:)?//', path, re.I):
return path
# Resolve static assets
if path.startswith('@'):
return utils.static_url(path[1:], absolute)
path, sep, anchor = path.partition('#')
# Resolve entries
entry = utils.find_entry(path, search_path)
if entry:
return entry.permalink(absolute=absolute) + sep + anchor
# Resolve images and assets
img_path, img_args, _ = image.parse_image_spec(path)
img = image.get_image(img_path, search_path)
if not isinstance(img, image.ImageNotFound):
path, _ = img.get_rendition(**img_args)
return path + sep + anchor | python | def resolve(path, search_path, absolute=False):
# Resolve external URLs
if re.match(r'([a-z][a-z0-9+.\-]*:)?//', path, re.I):
return path
# Resolve static assets
if path.startswith('@'):
return utils.static_url(path[1:], absolute)
path, sep, anchor = path.partition('#')
# Resolve entries
entry = utils.find_entry(path, search_path)
if entry:
return entry.permalink(absolute=absolute) + sep + anchor
# Resolve images and assets
img_path, img_args, _ = image.parse_image_spec(path)
img = image.get_image(img_path, search_path)
if not isinstance(img, image.ImageNotFound):
path, _ = img.get_rendition(**img_args)
return path + sep + anchor | [
"def",
"resolve",
"(",
"path",
",",
"search_path",
",",
"absolute",
"=",
"False",
")",
":",
"# Resolve external URLs",
"if",
"re",
".",
"match",
"(",
"r'([a-z][a-z0-9+.\\-]*:)?//'",
",",
"path",
",",
"re",
".",
"I",
")",
":",
"return",
"path",
"# Resolve sta... | Remap a link or source target to an appropriate entry or image rendition | [
"Remap",
"a",
"link",
"or",
"source",
"target",
"to",
"an",
"appropriate",
"entry",
"or",
"image",
"rendition"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/links.py#L10-L33 |
11,259 | PlaidWeb/Publ | publ/caching.py | do_not_cache | def do_not_cache():
""" Return whether we should cache a page render """
from . import index # pylint: disable=cyclic-import
if index.in_progress():
# We are reindexing the site
return True
if request.if_none_match or request.if_modified_since:
# we might be returning a 304 NOT MODIFIED based on a client request,
# and we don't want to cache that as the result for *all* client
# requests to this URI
return True
return False | python | def do_not_cache():
from . import index # pylint: disable=cyclic-import
if index.in_progress():
# We are reindexing the site
return True
if request.if_none_match or request.if_modified_since:
# we might be returning a 304 NOT MODIFIED based on a client request,
# and we don't want to cache that as the result for *all* client
# requests to this URI
return True
return False | [
"def",
"do_not_cache",
"(",
")",
":",
"from",
".",
"import",
"index",
"# pylint: disable=cyclic-import",
"if",
"index",
".",
"in_progress",
"(",
")",
":",
"# We are reindexing the site",
"return",
"True",
"if",
"request",
".",
"if_none_match",
"or",
"request",
"."... | Return whether we should cache a page render | [
"Return",
"whether",
"we",
"should",
"cache",
"a",
"page",
"render"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/caching.py#L20-L35 |
11,260 | PlaidWeb/Publ | publ/queries.py | where_entry_visible | def where_entry_visible(query, date=None):
""" Generate a where clause for currently-visible entries
Arguments:
date -- The date to generate it relative to (defaults to right now)
"""
return orm.select(
e for e in query
if e.status == model.PublishStatus.PUBLISHED.value or
(e.status == model.PublishStatus.SCHEDULED.value and
(e.utc_date <= (date or arrow.utcnow().datetime))
)
) | python | def where_entry_visible(query, date=None):
return orm.select(
e for e in query
if e.status == model.PublishStatus.PUBLISHED.value or
(e.status == model.PublishStatus.SCHEDULED.value and
(e.utc_date <= (date or arrow.utcnow().datetime))
)
) | [
"def",
"where_entry_visible",
"(",
"query",
",",
"date",
"=",
"None",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"status",
"==",
"model",
".",
"PublishStatus",
".",
"PUBLISHED",
".",
"value",
"or",
... | Generate a where clause for currently-visible entries
Arguments:
date -- The date to generate it relative to (defaults to right now) | [
"Generate",
"a",
"where",
"clause",
"for",
"currently",
"-",
"visible",
"entries"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L10-L24 |
11,261 | PlaidWeb/Publ | publ/queries.py | where_entry_visible_future | def where_entry_visible_future(query):
""" Generate a where clause for entries that are visible now or in the future """
return orm.select(
e for e in query
if e.status in (model.PublishStatus.PUBLISHED.value,
model.PublishStatus.SCHEDULED.value)) | python | def where_entry_visible_future(query):
return orm.select(
e for e in query
if e.status in (model.PublishStatus.PUBLISHED.value,
model.PublishStatus.SCHEDULED.value)) | [
"def",
"where_entry_visible_future",
"(",
"query",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"status",
"in",
"(",
"model",
".",
"PublishStatus",
".",
"PUBLISHED",
".",
"value",
",",
"model",
".",
"Pu... | Generate a where clause for entries that are visible now or in the future | [
"Generate",
"a",
"where",
"clause",
"for",
"entries",
"that",
"are",
"visible",
"now",
"or",
"in",
"the",
"future"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L27-L33 |
11,262 | PlaidWeb/Publ | publ/queries.py | where_entry_deleted | def where_entry_deleted(query):
""" Generate a where clause for entries that have been deleted """
return orm.select(
e for e in query
if e.status == model.PublishStatus.GONE.value) | python | def where_entry_deleted(query):
return orm.select(
e for e in query
if e.status == model.PublishStatus.GONE.value) | [
"def",
"where_entry_deleted",
"(",
"query",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"status",
"==",
"model",
".",
"PublishStatus",
".",
"GONE",
".",
"value",
")"
] | Generate a where clause for entries that have been deleted | [
"Generate",
"a",
"where",
"clause",
"for",
"entries",
"that",
"have",
"been",
"deleted"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L36-L40 |
11,263 | PlaidWeb/Publ | publ/queries.py | where_entry_category | def where_entry_category(query, category, recurse=False):
""" Generate a where clause for a particular category """
category = str(category)
if category and recurse:
# We're recursing and aren't in /, so add the prefix clause
return orm.select(
e for e in query
if e.category == category or e.category.startswith(category + '/')
)
if not recurse:
# We're not recursing, so we need an exact match on a possibly-empty
# category
return orm.select(e for e in query if e.category == category)
# We're recursing and have no category, which means we're doing nothing
return query | python | def where_entry_category(query, category, recurse=False):
category = str(category)
if category and recurse:
# We're recursing and aren't in /, so add the prefix clause
return orm.select(
e for e in query
if e.category == category or e.category.startswith(category + '/')
)
if not recurse:
# We're not recursing, so we need an exact match on a possibly-empty
# category
return orm.select(e for e in query if e.category == category)
# We're recursing and have no category, which means we're doing nothing
return query | [
"def",
"where_entry_category",
"(",
"query",
",",
"category",
",",
"recurse",
"=",
"False",
")",
":",
"category",
"=",
"str",
"(",
"category",
")",
"if",
"category",
"and",
"recurse",
":",
"# We're recursing and aren't in /, so add the prefix clause",
"return",
"orm... | Generate a where clause for a particular category | [
"Generate",
"a",
"where",
"clause",
"for",
"a",
"particular",
"category"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L43-L60 |
11,264 | PlaidWeb/Publ | publ/queries.py | where_before_entry | def where_before_entry(query, ref):
""" Generate a where clause for prior entries
ref -- The entry of reference
"""
return orm.select(
e for e in query
if e.local_date < ref.local_date or
(e.local_date == ref.local_date and e.id < ref.id)
) | python | def where_before_entry(query, ref):
return orm.select(
e for e in query
if e.local_date < ref.local_date or
(e.local_date == ref.local_date and e.id < ref.id)
) | [
"def",
"where_before_entry",
"(",
"query",
",",
"ref",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"local_date",
"<",
"ref",
".",
"local_date",
"or",
"(",
"e",
".",
"local_date",
"==",
"ref",
".",
... | Generate a where clause for prior entries
ref -- The entry of reference | [
"Generate",
"a",
"where",
"clause",
"for",
"prior",
"entries"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L63-L72 |
11,265 | PlaidWeb/Publ | publ/queries.py | where_after_entry | def where_after_entry(query, ref):
""" Generate a where clause for later entries
ref -- the entry of reference
"""
return orm.select(
e for e in query
if e.local_date > ref.local_date or
(e.local_date == ref.local_date and
e.id > ref.id
)
) | python | def where_after_entry(query, ref):
return orm.select(
e for e in query
if e.local_date > ref.local_date or
(e.local_date == ref.local_date and
e.id > ref.id
)
) | [
"def",
"where_after_entry",
"(",
"query",
",",
"ref",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"local_date",
">",
"ref",
".",
"local_date",
"or",
"(",
"e",
".",
"local_date",
"==",
"ref",
".",
"... | Generate a where clause for later entries
ref -- the entry of reference | [
"Generate",
"a",
"where",
"clause",
"for",
"later",
"entries"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L75-L86 |
11,266 | PlaidWeb/Publ | publ/queries.py | where_entry_last | def where_entry_last(query, ref):
""" Generate a where clause where this is the last entry
ref -- the entry of reference
"""
return orm.select(
e for e in query
if e.local_date < ref.local_date or
(e.local_date == ref.local_date and
e.id <= ref.id
)
) | python | def where_entry_last(query, ref):
return orm.select(
e for e in query
if e.local_date < ref.local_date or
(e.local_date == ref.local_date and
e.id <= ref.id
)
) | [
"def",
"where_entry_last",
"(",
"query",
",",
"ref",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"local_date",
"<",
"ref",
".",
"local_date",
"or",
"(",
"e",
".",
"local_date",
"==",
"ref",
".",
"l... | Generate a where clause where this is the last entry
ref -- the entry of reference | [
"Generate",
"a",
"where",
"clause",
"where",
"this",
"is",
"the",
"last",
"entry"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L89-L100 |
11,267 | PlaidWeb/Publ | publ/queries.py | where_entry_first | def where_entry_first(query, ref):
""" Generate a where clause where this is the first entry
ref -- the entry of reference
"""
return orm.select(
e for e in query
if e.local_date > ref.local_date or
(e.local_date == ref.local_date and
e.id >= ref.id
)
) | python | def where_entry_first(query, ref):
return orm.select(
e for e in query
if e.local_date > ref.local_date or
(e.local_date == ref.local_date and
e.id >= ref.id
)
) | [
"def",
"where_entry_first",
"(",
"query",
",",
"ref",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
".",
"local_date",
">",
"ref",
".",
"local_date",
"or",
"(",
"e",
".",
"local_date",
"==",
"ref",
".",
"... | Generate a where clause where this is the first entry
ref -- the entry of reference | [
"Generate",
"a",
"where",
"clause",
"where",
"this",
"is",
"the",
"first",
"entry"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L103-L114 |
11,268 | PlaidWeb/Publ | publ/queries.py | where_entry_type | def where_entry_type(query, entry_type):
""" Generate a where clause for entries of certain types
entry_type -- one or more entries to check against
"""
if isinstance(entry_type, (list, set, tuple)):
return orm.select(e for e in query if e.entry_type in entry_type)
return orm.select(e for e in query if e.entry_type == entry_type) | python | def where_entry_type(query, entry_type):
if isinstance(entry_type, (list, set, tuple)):
return orm.select(e for e in query if e.entry_type in entry_type)
return orm.select(e for e in query if e.entry_type == entry_type) | [
"def",
"where_entry_type",
"(",
"query",
",",
"entry_type",
")",
":",
"if",
"isinstance",
"(",
"entry_type",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"return",
"orm",
".",
"select",
"(",
"e",
"for",
"e",
"in",
"query",
"if",
"e",
... | Generate a where clause for entries of certain types
entry_type -- one or more entries to check against | [
"Generate",
"a",
"where",
"clause",
"for",
"entries",
"of",
"certain",
"types"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L117-L124 |
11,269 | PlaidWeb/Publ | publ/queries.py | where_entry_tag | def where_entry_tag(query, tag):
""" Generate a where clause for entries with the given tag """
if isinstance(tag, (list, set, tuple)):
tags = [t.lower() for t in tag]
return orm.select(e for e in query for t in e.tags if t.key in tags)
return orm.select(e for e in query for t in e.tags if t.key == tag.lower()) | python | def where_entry_tag(query, tag):
if isinstance(tag, (list, set, tuple)):
tags = [t.lower() for t in tag]
return orm.select(e for e in query for t in e.tags if t.key in tags)
return orm.select(e for e in query for t in e.tags if t.key == tag.lower()) | [
"def",
"where_entry_tag",
"(",
"query",
",",
"tag",
")",
":",
"if",
"isinstance",
"(",
"tag",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"tags",
"=",
"[",
"t",
".",
"lower",
"(",
")",
"for",
"t",
"in",
"tag",
"]",
"return",
"orm... | Generate a where clause for entries with the given tag | [
"Generate",
"a",
"where",
"clause",
"for",
"entries",
"with",
"the",
"given",
"tag"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L137-L142 |
11,270 | PlaidWeb/Publ | publ/queries.py | where_entry_date | def where_entry_date(query, datespec):
""" Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format
"""
date, interval, _ = utils.parse_date(datespec)
start_date, end_date = date.span(interval)
return orm.select(
e for e in query if
e.local_date >= start_date.naive and
e.local_date <= end_date.naive
) | python | def where_entry_date(query, datespec):
date, interval, _ = utils.parse_date(datespec)
start_date, end_date = date.span(interval)
return orm.select(
e for e in query if
e.local_date >= start_date.naive and
e.local_date <= end_date.naive
) | [
"def",
"where_entry_date",
"(",
"query",
",",
"datespec",
")",
":",
"date",
",",
"interval",
",",
"_",
"=",
"utils",
".",
"parse_date",
"(",
"datespec",
")",
"start_date",
",",
"end_date",
"=",
"date",
".",
"span",
"(",
"interval",
")",
"return",
"orm",
... | Where clause for entries which match a textual date spec
datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format | [
"Where",
"clause",
"for",
"entries",
"which",
"match",
"a",
"textual",
"date",
"spec"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L145-L157 |
11,271 | PlaidWeb/Publ | publ/queries.py | get_entry | def get_entry(entry):
""" Helper function to get an entry by ID or by object """
if hasattr(entry, 'id'):
return entry
if isinstance(entry, (int, str)):
return model.Entry.get(id=int(entry))
raise ValueError("entry is of unknown type {}".format(type(entry))) | python | def get_entry(entry):
if hasattr(entry, 'id'):
return entry
if isinstance(entry, (int, str)):
return model.Entry.get(id=int(entry))
raise ValueError("entry is of unknown type {}".format(type(entry))) | [
"def",
"get_entry",
"(",
"entry",
")",
":",
"if",
"hasattr",
"(",
"entry",
",",
"'id'",
")",
":",
"return",
"entry",
"if",
"isinstance",
"(",
"entry",
",",
"(",
"int",
",",
"str",
")",
")",
":",
"return",
"model",
".",
"Entry",
".",
"get",
"(",
"... | Helper function to get an entry by ID or by object | [
"Helper",
"function",
"to",
"get",
"an",
"entry",
"by",
"ID",
"or",
"by",
"object"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L160-L168 |
11,272 | PlaidWeb/Publ | publ/queries.py | build_query | def build_query(spec):
""" build the where clause based on a view specification
spec -- The view specification. Contains the following possible values:
future -- Boolean; whether to include entries from the future
category -- Which category to limit to
recurse -- Whether to include subcategories
entry_type -- one or more entry types to include
entry_type_not -- one or more entry types to exclude
date -- a date spec
last -- the last entry to end a view on
first -- the first entry to start a view on
before -- get entries from before this one
after -- get entries from after this one
"""
query = model.Entry.select()
# primarily restrict by publication status
if spec.get('_deleted', False):
query = where_entry_deleted(query)
elif spec.get('future', False):
query = where_entry_visible_future(query)
else:
query = where_entry_visible(query)
# restrict by category
if spec.get('category') is not None:
path = str(spec.get('category', ''))
recurse = spec.get('recurse', False)
query = where_entry_category(query, path, recurse)
if spec.get('entry_type') is not None:
query = where_entry_type(query, spec['entry_type'])
if spec.get('entry_type_not') is not None:
query = where_entry_type_not(query, spec['entry_type_not'])
if spec.get('tag') is not None:
query = where_entry_tag(query, spec['tag'])
if spec.get('date') is not None:
query = where_entry_date(query, spec['date'])
if spec.get('last') is not None:
query = where_entry_last(query, get_entry(spec['last']))
if spec.get('first') is not None:
query = where_entry_first(query, get_entry(spec['first']))
if spec.get('before') is not None:
query = where_before_entry(query, get_entry(spec['before']))
if spec.get('after') is not None:
query = where_after_entry(query, get_entry(spec['after']))
return query.distinct() | python | def build_query(spec):
query = model.Entry.select()
# primarily restrict by publication status
if spec.get('_deleted', False):
query = where_entry_deleted(query)
elif spec.get('future', False):
query = where_entry_visible_future(query)
else:
query = where_entry_visible(query)
# restrict by category
if spec.get('category') is not None:
path = str(spec.get('category', ''))
recurse = spec.get('recurse', False)
query = where_entry_category(query, path, recurse)
if spec.get('entry_type') is not None:
query = where_entry_type(query, spec['entry_type'])
if spec.get('entry_type_not') is not None:
query = where_entry_type_not(query, spec['entry_type_not'])
if spec.get('tag') is not None:
query = where_entry_tag(query, spec['tag'])
if spec.get('date') is not None:
query = where_entry_date(query, spec['date'])
if spec.get('last') is not None:
query = where_entry_last(query, get_entry(spec['last']))
if spec.get('first') is not None:
query = where_entry_first(query, get_entry(spec['first']))
if spec.get('before') is not None:
query = where_before_entry(query, get_entry(spec['before']))
if spec.get('after') is not None:
query = where_after_entry(query, get_entry(spec['after']))
return query.distinct() | [
"def",
"build_query",
"(",
"spec",
")",
":",
"query",
"=",
"model",
".",
"Entry",
".",
"select",
"(",
")",
"# primarily restrict by publication status",
"if",
"spec",
".",
"get",
"(",
"'_deleted'",
",",
"False",
")",
":",
"query",
"=",
"where_entry_deleted",
... | build the where clause based on a view specification
spec -- The view specification. Contains the following possible values:
future -- Boolean; whether to include entries from the future
category -- Which category to limit to
recurse -- Whether to include subcategories
entry_type -- one or more entry types to include
entry_type_not -- one or more entry types to exclude
date -- a date spec
last -- the last entry to end a view on
first -- the first entry to start a view on
before -- get entries from before this one
after -- get entries from after this one | [
"build",
"the",
"where",
"clause",
"based",
"on",
"a",
"view",
"specification"
] | ce7893632ddc3cb70b4978a41ffd7dd06fa13565 | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L171-L227 |
11,273 | misakar/mana | mana/mana.py | create_templates_static_files | def create_templates_static_files(app_path):
"""
create templates and static
"""
templates_path = os.path.join(app_path, 'templates')
static_path = os.path.join(app_path, 'static')
_mkdir_p(templates_path)
_mkdir_p(static_path)
# create {img, css, js}
os.chdir(static_path)
img_path = os.path.join(static_path, 'img')
css_path = os.path.join(static_path, 'css')
js_path = os.path.join(static_path, 'js')
_mkdir_p(img_path)
_mkdir_p(css_path)
_mkdir_p(js_path)
return css_path, templates_path | python | def create_templates_static_files(app_path):
templates_path = os.path.join(app_path, 'templates')
static_path = os.path.join(app_path, 'static')
_mkdir_p(templates_path)
_mkdir_p(static_path)
# create {img, css, js}
os.chdir(static_path)
img_path = os.path.join(static_path, 'img')
css_path = os.path.join(static_path, 'css')
js_path = os.path.join(static_path, 'js')
_mkdir_p(img_path)
_mkdir_p(css_path)
_mkdir_p(js_path)
return css_path, templates_path | [
"def",
"create_templates_static_files",
"(",
"app_path",
")",
":",
"templates_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"'templates'",
")",
"static_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"'static'",
")",
"... | create templates and static | [
"create",
"templates",
"and",
"static"
] | 95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69 | https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/mana.py#L90-L107 |
11,274 | misakar/mana | mana/mana.py | init | def init(project_name):
"""
build a minimal flask project
"""
# the destination path
dst_path = os.path.join(os.getcwd(), project_name)
start_init_info(dst_path)
# create dst path
_mkdir_p(dst_path)
os.chdir(dst_path)
# create files
init_code('manage.py', _manage_basic_code)
init_code('requirement.txt', _requirement_code)
# create app/
app_path = os.path.join(dst_path, 'app')
_mkdir_p(app_path)
os.chdir(app_path)
# create files
init_code('views.py', _views_basic_code)
init_code('forms.py', _forms_basic_code)
init_code('__init__.py', _init_basic_code)
create_templates_static_files(app_path)
init_done_info() | python | def init(project_name):
# the destination path
dst_path = os.path.join(os.getcwd(), project_name)
start_init_info(dst_path)
# create dst path
_mkdir_p(dst_path)
os.chdir(dst_path)
# create files
init_code('manage.py', _manage_basic_code)
init_code('requirement.txt', _requirement_code)
# create app/
app_path = os.path.join(dst_path, 'app')
_mkdir_p(app_path)
os.chdir(app_path)
# create files
init_code('views.py', _views_basic_code)
init_code('forms.py', _forms_basic_code)
init_code('__init__.py', _init_basic_code)
create_templates_static_files(app_path)
init_done_info() | [
"def",
"init",
"(",
"project_name",
")",
":",
"# the destination path",
"dst_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"project_name",
")",
"start_init_info",
"(",
"dst_path",
")",
"# create dst path",
"_mkdir_p",
"... | build a minimal flask project | [
"build",
"a",
"minimal",
"flask",
"project"
] | 95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69 | https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/mana.py#L163-L192 |
11,275 | misakar/mana | mana/mana.py | startproject | def startproject(project_name):
"""
build a full status project
"""
# the destination path
dst_path = os.path.join(os.getcwd(), project_name)
start_init_info(dst_path)
# create dst path
_mkdir_p(dst_path)
# create project tree
os.chdir(dst_path)
# create files
init_code('manage.py', _manage_admin_code)
init_code('requirement.txt', _requirement_admin_code)
init_code('config.py', _config_sql_code)
# create app/
app_path = os.path.join(dst_path, 'app')
_mkdir_p(app_path)
# create files
os.chdir(app_path)
init_code('models.py', _models_admin_code)
init_code('__init__.py', _init_admin_code)
# create templates and static
css_path, templates_path = create_templates_static_files(app_path)
# create css files
os.chdir(css_path)
init_code('sign.css', _auth_login_css_code)
# create main blueprint
create_blueprint(
app_path,
'main',
_views_blueprint_code % ('main', 'main'),
_forms_basic_code,
templates_path
)
# create auth blueprint
auth_templates_path = create_blueprint(
app_path,
'auth',
_auth_views_code,
_auth_forms_code,
templates_path
)
# create auth templates files
os.chdir(auth_templates_path)
init_code('login.html', _auth_login_html_code)
# create admin site
admin_path = os.path.join(app_path, 'admin')
_mkdir_p(admin_path)
# create admin files
os.chdir(admin_path)
init_code('__init__.py', '')
init_code('views.py', _admin_views_code)
# create admin templates
os.chdir(templates_path)
admin_templates_path = os.path.join(templates_path, 'admin')
_mkdir_p(admin_templates_path)
# create admin templates files
os.chdir(admin_templates_path)
init_code('index.html', _admin_index_html_code)
init_code('logout.html', _admin_logout_html_code)
init_done_info() | python | def startproject(project_name):
# the destination path
dst_path = os.path.join(os.getcwd(), project_name)
start_init_info(dst_path)
# create dst path
_mkdir_p(dst_path)
# create project tree
os.chdir(dst_path)
# create files
init_code('manage.py', _manage_admin_code)
init_code('requirement.txt', _requirement_admin_code)
init_code('config.py', _config_sql_code)
# create app/
app_path = os.path.join(dst_path, 'app')
_mkdir_p(app_path)
# create files
os.chdir(app_path)
init_code('models.py', _models_admin_code)
init_code('__init__.py', _init_admin_code)
# create templates and static
css_path, templates_path = create_templates_static_files(app_path)
# create css files
os.chdir(css_path)
init_code('sign.css', _auth_login_css_code)
# create main blueprint
create_blueprint(
app_path,
'main',
_views_blueprint_code % ('main', 'main'),
_forms_basic_code,
templates_path
)
# create auth blueprint
auth_templates_path = create_blueprint(
app_path,
'auth',
_auth_views_code,
_auth_forms_code,
templates_path
)
# create auth templates files
os.chdir(auth_templates_path)
init_code('login.html', _auth_login_html_code)
# create admin site
admin_path = os.path.join(app_path, 'admin')
_mkdir_p(admin_path)
# create admin files
os.chdir(admin_path)
init_code('__init__.py', '')
init_code('views.py', _admin_views_code)
# create admin templates
os.chdir(templates_path)
admin_templates_path = os.path.join(templates_path, 'admin')
_mkdir_p(admin_templates_path)
# create admin templates files
os.chdir(admin_templates_path)
init_code('index.html', _admin_index_html_code)
init_code('logout.html', _admin_logout_html_code)
init_done_info() | [
"def",
"startproject",
"(",
"project_name",
")",
":",
"# the destination path",
"dst_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"project_name",
")",
"start_init_info",
"(",
"dst_path",
")",
"# create dst path",
"_mkdir... | build a full status project | [
"build",
"a",
"full",
"status",
"project"
] | 95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69 | https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/mana.py#L254-L327 |
11,276 | bachya/pyairvisual | pyairvisual/errors.py | raise_error | def raise_error(error_type: str) -> None:
"""Raise the appropriate error based on error message."""
try:
error = next((v for k, v in ERROR_CODES.items() if k in error_type))
except StopIteration:
error = AirVisualError
raise error(error_type) | python | def raise_error(error_type: str) -> None:
try:
error = next((v for k, v in ERROR_CODES.items() if k in error_type))
except StopIteration:
error = AirVisualError
raise error(error_type) | [
"def",
"raise_error",
"(",
"error_type",
":",
"str",
")",
"->",
"None",
":",
"try",
":",
"error",
"=",
"next",
"(",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"ERROR_CODES",
".",
"items",
"(",
")",
"if",
"k",
"in",
"error_type",
")",
")",
"except",
"S... | Raise the appropriate error based on error message. | [
"Raise",
"the",
"appropriate",
"error",
"based",
"on",
"error",
"message",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/errors.py#L63-L69 |
11,277 | bachya/pyairvisual | pyairvisual/client.py | _raise_on_error | def _raise_on_error(data: Union[str, dict]) -> None:
"""Raise the appropriate exception on error."""
if isinstance(data, str):
raise_error(data)
elif 'status' in data and data['status'] != 'success':
raise_error(data['data']['message']) | python | def _raise_on_error(data: Union[str, dict]) -> None:
if isinstance(data, str):
raise_error(data)
elif 'status' in data and data['status'] != 'success':
raise_error(data['data']['message']) | [
"def",
"_raise_on_error",
"(",
"data",
":",
"Union",
"[",
"str",
",",
"dict",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"raise_error",
"(",
"data",
")",
"elif",
"'status'",
"in",
"data",
"and",
"data",
"[",
... | Raise the appropriate exception on error. | [
"Raise",
"the",
"appropriate",
"exception",
"on",
"error",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/client.py#L53-L58 |
11,278 | bachya/pyairvisual | pyairvisual/api.py | API.city | async def city(self, city: str, state: str, country: str) -> dict:
"""Return data for the specified city."""
data = await self._request(
'get',
'city',
params={
'city': city,
'state': state,
'country': country
})
return data['data'] | python | async def city(self, city: str, state: str, country: str) -> dict:
data = await self._request(
'get',
'city',
params={
'city': city,
'state': state,
'country': country
})
return data['data'] | [
"async",
"def",
"city",
"(",
"self",
",",
"city",
":",
"str",
",",
"state",
":",
"str",
",",
"country",
":",
"str",
")",
"->",
"dict",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'city'",
",",
"params",
"=",
"{",
"'cit... | Return data for the specified city. | [
"Return",
"data",
"for",
"the",
"specified",
"city",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L28-L38 |
11,279 | bachya/pyairvisual | pyairvisual/api.py | API.node | async def node(self, node_id: str) -> dict:
"""Return data from a node by its ID."""
return await self._request('get', node_id, base_url=NODE_URL_SCAFFOLD) | python | async def node(self, node_id: str) -> dict:
return await self._request('get', node_id, base_url=NODE_URL_SCAFFOLD) | [
"async",
"def",
"node",
"(",
"self",
",",
"node_id",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"node_id",
",",
"base_url",
"=",
"NODE_URL_SCAFFOLD",
")"
] | Return data from a node by its ID. | [
"Return",
"data",
"from",
"a",
"node",
"by",
"its",
"ID",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L54-L56 |
11,280 | bachya/pyairvisual | pyairvisual/supported.py | Supported.states | async def states(self, country: str) -> list:
"""Return a list of supported states in a country."""
data = await self._request(
'get', 'states', params={'country': country})
return [d['state'] for d in data['data']] | python | async def states(self, country: str) -> list:
data = await self._request(
'get', 'states', params={'country': country})
return [d['state'] for d in data['data']] | [
"async",
"def",
"states",
"(",
"self",
",",
"country",
":",
"str",
")",
"->",
"list",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'states'",
",",
"params",
"=",
"{",
"'country'",
":",
"country",
"}",
")",
"return",
"[",
... | Return a list of supported states in a country. | [
"Return",
"a",
"list",
"of",
"supported",
"states",
"in",
"a",
"country",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L26-L30 |
11,281 | bachya/pyairvisual | pyairvisual/supported.py | Supported.stations | async def stations(self, city: str, state: str, country: str) -> list:
"""Return a list of supported stations in a city."""
data = await self._request(
'get',
'stations',
params={
'city': city,
'state': state,
'country': country
})
return [station for station in data['data']] | python | async def stations(self, city: str, state: str, country: str) -> list:
data = await self._request(
'get',
'stations',
params={
'city': city,
'state': state,
'country': country
})
return [station for station in data['data']] | [
"async",
"def",
"stations",
"(",
"self",
",",
"city",
":",
"str",
",",
"state",
":",
"str",
",",
"country",
":",
"str",
")",
"->",
"list",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'stations'",
",",
"params",
"=",
"{",... | Return a list of supported stations in a city. | [
"Return",
"a",
"list",
"of",
"supported",
"stations",
"in",
"a",
"city",
"."
] | 1d4809998d87f85d53bb281e1eb54d43acee06fa | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L32-L42 |
11,282 | ljcooke/see | see/output.py | column_width | def column_width(tokens):
"""
Return a suitable column width to display one or more strings.
"""
get_len = tools.display_len if PY3 else len
lens = sorted(map(get_len, tokens or [])) or [0]
width = lens[-1]
# adjust for disproportionately long strings
if width >= 18:
most = lens[int(len(lens) * 0.9)]
if most < width + 6:
return most
return width | python | def column_width(tokens):
get_len = tools.display_len if PY3 else len
lens = sorted(map(get_len, tokens or [])) or [0]
width = lens[-1]
# adjust for disproportionately long strings
if width >= 18:
most = lens[int(len(lens) * 0.9)]
if most < width + 6:
return most
return width | [
"def",
"column_width",
"(",
"tokens",
")",
":",
"get_len",
"=",
"tools",
".",
"display_len",
"if",
"PY3",
"else",
"len",
"lens",
"=",
"sorted",
"(",
"map",
"(",
"get_len",
",",
"tokens",
"or",
"[",
"]",
")",
")",
"or",
"[",
"0",
"]",
"width",
"=",
... | Return a suitable column width to display one or more strings. | [
"Return",
"a",
"suitable",
"column",
"width",
"to",
"display",
"one",
"or",
"more",
"strings",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L117-L131 |
11,283 | ljcooke/see | see/output.py | justify_token | def justify_token(tok, col_width):
"""
Justify a string to fill one or more columns.
"""
get_len = tools.display_len if PY3 else len
tok_len = get_len(tok)
diff_len = tok_len - len(tok) if PY3 else 0
cols = (int(math.ceil(float(tok_len) / col_width))
if col_width < tok_len + 4 else 1)
if cols > 1:
return tok.ljust((col_width * cols) + (4 * cols) - diff_len)
else:
return tok.ljust(col_width + 4 - diff_len) | python | def justify_token(tok, col_width):
get_len = tools.display_len if PY3 else len
tok_len = get_len(tok)
diff_len = tok_len - len(tok) if PY3 else 0
cols = (int(math.ceil(float(tok_len) / col_width))
if col_width < tok_len + 4 else 1)
if cols > 1:
return tok.ljust((col_width * cols) + (4 * cols) - diff_len)
else:
return tok.ljust(col_width + 4 - diff_len) | [
"def",
"justify_token",
"(",
"tok",
",",
"col_width",
")",
":",
"get_len",
"=",
"tools",
".",
"display_len",
"if",
"PY3",
"else",
"len",
"tok_len",
"=",
"get_len",
"(",
"tok",
")",
"diff_len",
"=",
"tok_len",
"-",
"len",
"(",
"tok",
")",
"if",
"PY3",
... | Justify a string to fill one or more columns. | [
"Justify",
"a",
"string",
"to",
"fill",
"one",
"or",
"more",
"columns",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L134-L148 |
11,284 | ljcooke/see | see/output.py | display_name | def display_name(name, obj, local):
"""
Get the display name of an object.
Keyword arguments (all required):
* ``name`` -- the name of the object as a string.
* ``obj`` -- the object itself.
* ``local`` -- a boolean value indicating whether the object is in local
scope or owned by an object.
"""
prefix = '' if local else '.'
if isinstance(obj, SeeError):
suffix = '?'
elif hasattr(obj, '__call__'):
suffix = '()'
else:
suffix = ''
return ''.join((prefix, name, suffix)) | python | def display_name(name, obj, local):
prefix = '' if local else '.'
if isinstance(obj, SeeError):
suffix = '?'
elif hasattr(obj, '__call__'):
suffix = '()'
else:
suffix = ''
return ''.join((prefix, name, suffix)) | [
"def",
"display_name",
"(",
"name",
",",
"obj",
",",
"local",
")",
":",
"prefix",
"=",
"''",
"if",
"local",
"else",
"'.'",
"if",
"isinstance",
"(",
"obj",
",",
"SeeError",
")",
":",
"suffix",
"=",
"'?'",
"elif",
"hasattr",
"(",
"obj",
",",
"'__call__... | Get the display name of an object.
Keyword arguments (all required):
* ``name`` -- the name of the object as a string.
* ``obj`` -- the object itself.
* ``local`` -- a boolean value indicating whether the object is in local
scope or owned by an object. | [
"Get",
"the",
"display",
"name",
"of",
"an",
"object",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L151-L172 |
11,285 | ljcooke/see | see/output.py | SeeResult.filter | def filter(self, pattern):
"""
Filter the results using a pattern.
This accepts a shell-style wildcard pattern (as used by the fnmatch_
module)::
>>> see([]).filter('*op*')
.copy() .pop()
It also accepts a regular expression. This may be a compiled regular
expression (from the re_ module) or a string that starts with a ``/``
(forward slash) character::
>>> see([]).filter('/[aeiou]{2}/')
.clear() .count()
.. _fnmatch: https://docs.python.org/3/library/fnmatch.html
.. _re: https://docs.python.org/3/library/re.html
"""
if isinstance(pattern, REGEX_TYPE):
func = tools.filter_regex
elif pattern.startswith('/'):
pattern = re.compile(pattern.strip('/'))
func = tools.filter_regex
else:
func = tools.filter_wildcard
return SeeResult(func(self, pattern)) | python | def filter(self, pattern):
if isinstance(pattern, REGEX_TYPE):
func = tools.filter_regex
elif pattern.startswith('/'):
pattern = re.compile(pattern.strip('/'))
func = tools.filter_regex
else:
func = tools.filter_wildcard
return SeeResult(func(self, pattern)) | [
"def",
"filter",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"REGEX_TYPE",
")",
":",
"func",
"=",
"tools",
".",
"filter_regex",
"elif",
"pattern",
".",
"startswith",
"(",
"'/'",
")",
":",
"pattern",
"=",
"re",
".",
... | Filter the results using a pattern.
This accepts a shell-style wildcard pattern (as used by the fnmatch_
module)::
>>> see([]).filter('*op*')
.copy() .pop()
It also accepts a regular expression. This may be a compiled regular
expression (from the re_ module) or a string that starts with a ``/``
(forward slash) character::
>>> see([]).filter('/[aeiou]{2}/')
.clear() .count()
.. _fnmatch: https://docs.python.org/3/library/fnmatch.html
.. _re: https://docs.python.org/3/library/re.html | [
"Filter",
"the",
"results",
"using",
"a",
"pattern",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L62-L90 |
11,286 | ljcooke/see | see/output.py | SeeResult.filter_ignoring_case | def filter_ignoring_case(self, pattern):
"""
Like ``filter`` but case-insensitive.
Expects a regular expression string without the surrounding ``/``
characters.
>>> see().filter('^my', ignore_case=True)
MyClass()
"""
return self.filter(re.compile(pattern, re.I)) | python | def filter_ignoring_case(self, pattern):
return self.filter(re.compile(pattern, re.I)) | [
"def",
"filter_ignoring_case",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"self",
".",
"filter",
"(",
"re",
".",
"compile",
"(",
"pattern",
",",
"re",
".",
"I",
")",
")"
] | Like ``filter`` but case-insensitive.
Expects a regular expression string without the surrounding ``/``
characters.
>>> see().filter('^my', ignore_case=True)
MyClass() | [
"Like",
"filter",
"but",
"case",
"-",
"insensitive",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L92-L103 |
11,287 | ljcooke/see | see/term.py | term_width | def term_width():
"""
Return the column width of the terminal, or ``None`` if it can't be
determined.
"""
if fcntl and termios:
try:
winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ')
_, width = struct.unpack('hh', winsize)
return width
except IOError:
pass
elif windll and create_string_buffer: # pragma: no cover (windows)
stderr_handle, struct_size = -12, 22
handle = windll.kernel32.GetStdHandle(stderr_handle)
csbi = create_string_buffer(struct_size)
res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
if res:
(_, _, _, _, _, left, _, right, _,
_, _) = struct.unpack('hhhhHhhhhhh', csbi.raw)
return right - left + 1
else:
return 0 | python | def term_width():
if fcntl and termios:
try:
winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ')
_, width = struct.unpack('hh', winsize)
return width
except IOError:
pass
elif windll and create_string_buffer: # pragma: no cover (windows)
stderr_handle, struct_size = -12, 22
handle = windll.kernel32.GetStdHandle(stderr_handle)
csbi = create_string_buffer(struct_size)
res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
if res:
(_, _, _, _, _, left, _, right, _,
_, _) = struct.unpack('hhhhHhhhhhh', csbi.raw)
return right - left + 1
else:
return 0 | [
"def",
"term_width",
"(",
")",
":",
"if",
"fcntl",
"and",
"termios",
":",
"try",
":",
"winsize",
"=",
"fcntl",
".",
"ioctl",
"(",
"0",
",",
"termios",
".",
"TIOCGWINSZ",
",",
"' '",
")",
"_",
",",
"width",
"=",
"struct",
".",
"unpack",
"(",
"'hh... | Return the column width of the terminal, or ``None`` if it can't be
determined. | [
"Return",
"the",
"column",
"width",
"of",
"the",
"terminal",
"or",
"None",
"if",
"it",
"can",
"t",
"be",
"determined",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/term.py#L27-L49 |
11,288 | Autodesk/pyccc | pyccc/picklers.py | DepartingPickler.persistent_id | def persistent_id(self, obj):
""" Tags objects with a persistent ID, but do NOT emit it
"""
if getattr(obj, '_PERSIST_REFERENCES', None):
objid = id(obj)
obj._persistent_ref = objid
_weakmemos[objid] = obj
return None | python | def persistent_id(self, obj):
if getattr(obj, '_PERSIST_REFERENCES', None):
objid = id(obj)
obj._persistent_ref = objid
_weakmemos[objid] = obj
return None | [
"def",
"persistent_id",
"(",
"self",
",",
"obj",
")",
":",
"if",
"getattr",
"(",
"obj",
",",
"'_PERSIST_REFERENCES'",
",",
"None",
")",
":",
"objid",
"=",
"id",
"(",
"obj",
")",
"obj",
".",
"_persistent_ref",
"=",
"objid",
"_weakmemos",
"[",
"objid",
"... | Tags objects with a persistent ID, but do NOT emit it | [
"Tags",
"objects",
"with",
"a",
"persistent",
"ID",
"but",
"do",
"NOT",
"emit",
"it"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/picklers.py#L35-L42 |
11,289 | ljcooke/see | see/inspector.py | handle_deprecated_args | def handle_deprecated_args(tokens, args, kwargs):
"""
Backwards compatibility with deprecated arguments ``pattern`` and ``r``.
"""
num_args = len(args)
pattern = args[0] if num_args else kwargs.get('pattern', None)
regex = args[1] if num_args > 1 else kwargs.get('r', None)
if pattern is not None:
tokens = tools.filter_wildcard(tokens, pattern)
sys.stderr.write(
'Please use see().match() now. The "pattern" argument is '
'deprecated and will be removed in a later release. \n')
if regex is not None:
tokens = tools.filter_regex(tokens, re.compile(regex))
sys.stderr.write(
'Please use see().match() now. The "r" argument is '
'deprecated and will be removed in a later release. \n')
return tokens | python | def handle_deprecated_args(tokens, args, kwargs):
num_args = len(args)
pattern = args[0] if num_args else kwargs.get('pattern', None)
regex = args[1] if num_args > 1 else kwargs.get('r', None)
if pattern is not None:
tokens = tools.filter_wildcard(tokens, pattern)
sys.stderr.write(
'Please use see().match() now. The "pattern" argument is '
'deprecated and will be removed in a later release. \n')
if regex is not None:
tokens = tools.filter_regex(tokens, re.compile(regex))
sys.stderr.write(
'Please use see().match() now. The "r" argument is '
'deprecated and will be removed in a later release. \n')
return tokens | [
"def",
"handle_deprecated_args",
"(",
"tokens",
",",
"args",
",",
"kwargs",
")",
":",
"num_args",
"=",
"len",
"(",
"args",
")",
"pattern",
"=",
"args",
"[",
"0",
"]",
"if",
"num_args",
"else",
"kwargs",
".",
"get",
"(",
"'pattern'",
",",
"None",
")",
... | Backwards compatibility with deprecated arguments ``pattern`` and ``r``. | [
"Backwards",
"compatibility",
"with",
"deprecated",
"arguments",
"pattern",
"and",
"r",
"."
] | 4cbc67a31c92367977ecb4bbb1f0736fa688a6ba | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/inspector.py#L44-L64 |
11,290 | Autodesk/pyccc | pyccc/source_inspections.py | get_global_vars | def get_global_vars(func):
""" Store any methods or variables bound from the function's closure
Args:
func (function): function to inspect
Returns:
dict: mapping of variable names to globally bound VARIABLES
"""
closure = getclosurevars(func)
if closure['nonlocal']:
raise TypeError("Can't launch a job with closure variables: %s" %
closure['nonlocals'].keys())
globalvars = dict(modules={},
functions={},
vars={})
for name, value in closure['global'].items():
if inspect.ismodule(value): # TODO: deal FUNCTIONS from closure
globalvars['modules'][name] = value.__name__
elif inspect.isfunction(value) or inspect.ismethod(value):
globalvars['functions'][name] = value
else:
globalvars['vars'][name] = value
return globalvars | python | def get_global_vars(func):
closure = getclosurevars(func)
if closure['nonlocal']:
raise TypeError("Can't launch a job with closure variables: %s" %
closure['nonlocals'].keys())
globalvars = dict(modules={},
functions={},
vars={})
for name, value in closure['global'].items():
if inspect.ismodule(value): # TODO: deal FUNCTIONS from closure
globalvars['modules'][name] = value.__name__
elif inspect.isfunction(value) or inspect.ismethod(value):
globalvars['functions'][name] = value
else:
globalvars['vars'][name] = value
return globalvars | [
"def",
"get_global_vars",
"(",
"func",
")",
":",
"closure",
"=",
"getclosurevars",
"(",
"func",
")",
"if",
"closure",
"[",
"'nonlocal'",
"]",
":",
"raise",
"TypeError",
"(",
"\"Can't launch a job with closure variables: %s\"",
"%",
"closure",
"[",
"'nonlocals'",
"... | Store any methods or variables bound from the function's closure
Args:
func (function): function to inspect
Returns:
dict: mapping of variable names to globally bound VARIABLES | [
"Store",
"any",
"methods",
"or",
"variables",
"bound",
"from",
"the",
"function",
"s",
"closure"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/source_inspections.py#L34-L58 |
11,291 | Autodesk/pyccc | pyccc/source_inspections.py | getsource | def getsource(classorfunc):
""" Return the source code for a class or function.
Notes:
Returned source will not include any decorators for the object.
This will only return the explicit declaration of the object, not any dependencies
Args:
classorfunc (type or function): the object to get the source code for
Returns:
str: text of source code (without any decorators). Note: in python 2, this returns unicode
"""
if _isbuiltin(classorfunc):
return ''
try:
source = inspect.getsource(classorfunc)
except TypeError: # raised if defined in __main__ - use fallback to get the source instead
source = getsourcefallback(classorfunc)
declaration = []
lines = source.splitlines()
if PY2 and not isinstance(source, unicode):
encoding = detect_encoding(iter(lines).next)[0]
sourcelines = (s.decode(encoding) for s in lines)
else:
sourcelines = iter(lines)
# First, get the declaration
found_keyword = False
for line in sourcelines:
words = line.split()
if not words:
continue
if words[0] in ('def', 'class'):
found_keyword = True
if found_keyword:
cind = line.find(':')
if cind > 0:
declaration.append(line[:cind + 1])
after_decl = line[cind + 1:].strip()
break
else:
declaration.append(line)
bodylines = list(sourcelines) # the rest of the lines are body
# If it's a class, make sure we import its superclasses
# Unfortunately, we need to modify the code to make sure the
# parent classes have the correct names
# TODO: find a better way to do this without having to parse code
if type(classorfunc) == type:
cls = classorfunc
base_imports = {}
for base in cls.__bases__:
if base.__name__ == 'object' and base.__module__ == 'builtins': # don't import `object`
continue
if base in base_imports:
continue
if base.__module__ == '__main__':
continue
base_imports[base] = 'from %s import %s' % (base.__module__, base.__name__)
cind = declaration[0].index('class ')
declstring = declaration[0][:cind] + 'class %s(%s):%s' % (
cls.__name__,
','.join([base.__name__ for base in cls.__bases__]),
after_decl)
declaration = [impstring for c, impstring in base_imports.items()
if c.__module__ != '__builtin__']
declaration.append(declstring)
else:
declaration[-1] += after_decl
return '\n'.join(declaration + bodylines) | python | def getsource(classorfunc):
if _isbuiltin(classorfunc):
return ''
try:
source = inspect.getsource(classorfunc)
except TypeError: # raised if defined in __main__ - use fallback to get the source instead
source = getsourcefallback(classorfunc)
declaration = []
lines = source.splitlines()
if PY2 and not isinstance(source, unicode):
encoding = detect_encoding(iter(lines).next)[0]
sourcelines = (s.decode(encoding) for s in lines)
else:
sourcelines = iter(lines)
# First, get the declaration
found_keyword = False
for line in sourcelines:
words = line.split()
if not words:
continue
if words[0] in ('def', 'class'):
found_keyword = True
if found_keyword:
cind = line.find(':')
if cind > 0:
declaration.append(line[:cind + 1])
after_decl = line[cind + 1:].strip()
break
else:
declaration.append(line)
bodylines = list(sourcelines) # the rest of the lines are body
# If it's a class, make sure we import its superclasses
# Unfortunately, we need to modify the code to make sure the
# parent classes have the correct names
# TODO: find a better way to do this without having to parse code
if type(classorfunc) == type:
cls = classorfunc
base_imports = {}
for base in cls.__bases__:
if base.__name__ == 'object' and base.__module__ == 'builtins': # don't import `object`
continue
if base in base_imports:
continue
if base.__module__ == '__main__':
continue
base_imports[base] = 'from %s import %s' % (base.__module__, base.__name__)
cind = declaration[0].index('class ')
declstring = declaration[0][:cind] + 'class %s(%s):%s' % (
cls.__name__,
','.join([base.__name__ for base in cls.__bases__]),
after_decl)
declaration = [impstring for c, impstring in base_imports.items()
if c.__module__ != '__builtin__']
declaration.append(declstring)
else:
declaration[-1] += after_decl
return '\n'.join(declaration + bodylines) | [
"def",
"getsource",
"(",
"classorfunc",
")",
":",
"if",
"_isbuiltin",
"(",
"classorfunc",
")",
":",
"return",
"''",
"try",
":",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"classorfunc",
")",
"except",
"TypeError",
":",
"# raised if defined in __main__ - us... | Return the source code for a class or function.
Notes:
Returned source will not include any decorators for the object.
This will only return the explicit declaration of the object, not any dependencies
Args:
classorfunc (type or function): the object to get the source code for
Returns:
str: text of source code (without any decorators). Note: in python 2, this returns unicode | [
"Return",
"the",
"source",
"code",
"for",
"a",
"class",
"or",
"function",
"."
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/source_inspections.py#L61-L138 |
11,292 | Autodesk/pyccc | pyccc/engines/dockerengine.py | Docker.get_job | def get_job(self, jobid):
""" Return a Job object for the requested job id.
The returned object will be suitable for retrieving output, but depending on the engine,
may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.)
Args:
jobid (str): container id
Returns:
pyccc.job.Job: job object for this container
Raises:
pyccc.exceptions.JobNotFound: if no job could be located for this jobid
"""
import shlex
from pyccc.job import Job
job = Job(engine=self)
job.jobid = job.rundata.containerid = jobid
try:
jobdata = self.client.inspect_container(job.jobid)
except docker.errors.NotFound:
raise exceptions.JobNotFound(
'The daemon could not find containter "%s"' % job.jobid)
cmd = jobdata['Config']['Cmd']
entrypoint = jobdata['Config']['Entrypoint']
if len(cmd) == 3 and cmd[0:2] == ['sh', '-c']:
cmd = cmd[2]
elif entrypoint is not None:
cmd = entrypoint + cmd
if isinstance(cmd, list):
cmd = ' '.join(shlex.quote(x) for x in cmd)
job.command = cmd
job.env = jobdata['Config']['Env']
job.workingdir = jobdata['Config']['WorkingDir']
job.rundata.container = jobdata
return job | python | def get_job(self, jobid):
import shlex
from pyccc.job import Job
job = Job(engine=self)
job.jobid = job.rundata.containerid = jobid
try:
jobdata = self.client.inspect_container(job.jobid)
except docker.errors.NotFound:
raise exceptions.JobNotFound(
'The daemon could not find containter "%s"' % job.jobid)
cmd = jobdata['Config']['Cmd']
entrypoint = jobdata['Config']['Entrypoint']
if len(cmd) == 3 and cmd[0:2] == ['sh', '-c']:
cmd = cmd[2]
elif entrypoint is not None:
cmd = entrypoint + cmd
if isinstance(cmd, list):
cmd = ' '.join(shlex.quote(x) for x in cmd)
job.command = cmd
job.env = jobdata['Config']['Env']
job.workingdir = jobdata['Config']['WorkingDir']
job.rundata.container = jobdata
return job | [
"def",
"get_job",
"(",
"self",
",",
"jobid",
")",
":",
"import",
"shlex",
"from",
"pyccc",
".",
"job",
"import",
"Job",
"job",
"=",
"Job",
"(",
"engine",
"=",
"self",
")",
"job",
".",
"jobid",
"=",
"job",
".",
"rundata",
".",
"containerid",
"=",
"j... | Return a Job object for the requested job id.
The returned object will be suitable for retrieving output, but depending on the engine,
may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.)
Args:
jobid (str): container id
Returns:
pyccc.job.Job: job object for this container
Raises:
pyccc.exceptions.JobNotFound: if no job could be located for this jobid | [
"Return",
"a",
"Job",
"object",
"for",
"the",
"requested",
"job",
"id",
"."
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L81-L123 |
11,293 | Autodesk/pyccc | pyccc/engines/dockerengine.py | Docker.submit | def submit(self, job):
""" Submit job to the engine
Args:
job (pyccc.job.Job): Job to submit
"""
self._check_job(job)
if job.workingdir is None:
job.workingdir = self.default_wdir
job.imageid = du.create_provisioned_image(self.client, job.image,
job.workingdir, job.inputs)
container_args = self._generate_container_args(job)
job.rundata.container = self.client.create_container(job.imageid, **container_args)
self.client.start(job.rundata.container)
job.rundata.containerid = job.rundata.container['Id']
job.jobid = job.rundata.containerid | python | def submit(self, job):
self._check_job(job)
if job.workingdir is None:
job.workingdir = self.default_wdir
job.imageid = du.create_provisioned_image(self.client, job.image,
job.workingdir, job.inputs)
container_args = self._generate_container_args(job)
job.rundata.container = self.client.create_container(job.imageid, **container_args)
self.client.start(job.rundata.container)
job.rundata.containerid = job.rundata.container['Id']
job.jobid = job.rundata.containerid | [
"def",
"submit",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"_check_job",
"(",
"job",
")",
"if",
"job",
".",
"workingdir",
"is",
"None",
":",
"job",
".",
"workingdir",
"=",
"self",
".",
"default_wdir",
"job",
".",
"imageid",
"=",
"du",
".",
"c... | Submit job to the engine
Args:
job (pyccc.job.Job): Job to submit | [
"Submit",
"job",
"to",
"the",
"engine"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L125-L143 |
11,294 | Autodesk/pyccc | pyccc/engines/dockerengine.py | Docker.dump_all_outputs | def dump_all_outputs(self, job, target, abspaths=None):
""" Specialized dumping strategy - copy the entire working directory, then discard
the input files that came along for the ride.
Not used if there are absolute paths
This is slow and wasteful if there are big input files
"""
import os
import shutil
from pathlib import Path
root = Path(native_str(target))
true_outputs = job.get_output()
if abspaths or len(true_outputs) < self.BULK_OUTPUT_FILE_THRESHOLD:
return super().dump_all_outputs(job, root, abspaths)
stagingdir = root / Path(native_str(job.workingdir)).name
workdir = job.get_directory(job.workingdir)
if not root.is_dir():
root.mkdir(parents=False)
if stagingdir.exists():
if PY2:
raise IOError('Path % exists' % stagingdir)
else:
raise FileExistsError(stagingdir)
workdir.put(str(root))
assert stagingdir.is_dir()
assert root in stagingdir.parents
for pathstr in true_outputs:
if os.path.isabs(pathstr):
continue
destpath = root / pathstr
currpath = stagingdir / pathstr
if not destpath.parent.is_dir():
destpath.parent.mkdir(parents=True)
currpath.rename(destpath)
shutil.rmtree(str(stagingdir)) | python | def dump_all_outputs(self, job, target, abspaths=None):
import os
import shutil
from pathlib import Path
root = Path(native_str(target))
true_outputs = job.get_output()
if abspaths or len(true_outputs) < self.BULK_OUTPUT_FILE_THRESHOLD:
return super().dump_all_outputs(job, root, abspaths)
stagingdir = root / Path(native_str(job.workingdir)).name
workdir = job.get_directory(job.workingdir)
if not root.is_dir():
root.mkdir(parents=False)
if stagingdir.exists():
if PY2:
raise IOError('Path % exists' % stagingdir)
else:
raise FileExistsError(stagingdir)
workdir.put(str(root))
assert stagingdir.is_dir()
assert root in stagingdir.parents
for pathstr in true_outputs:
if os.path.isabs(pathstr):
continue
destpath = root / pathstr
currpath = stagingdir / pathstr
if not destpath.parent.is_dir():
destpath.parent.mkdir(parents=True)
currpath.rename(destpath)
shutil.rmtree(str(stagingdir)) | [
"def",
"dump_all_outputs",
"(",
"self",
",",
"job",
",",
"target",
",",
"abspaths",
"=",
"None",
")",
":",
"import",
"os",
"import",
"shutil",
"from",
"pathlib",
"import",
"Path",
"root",
"=",
"Path",
"(",
"native_str",
"(",
"target",
")",
")",
"true_out... | Specialized dumping strategy - copy the entire working directory, then discard
the input files that came along for the ride.
Not used if there are absolute paths
This is slow and wasteful if there are big input files | [
"Specialized",
"dumping",
"strategy",
"-",
"copy",
"the",
"entire",
"working",
"directory",
"then",
"discard",
"the",
"input",
"files",
"that",
"came",
"along",
"for",
"the",
"ride",
"."
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L201-L241 |
11,295 | Autodesk/pyccc | pyccc/docker_utils.py | create_build_context | def create_build_context(image, inputs, wdir):
"""
Creates a tar archive with a dockerfile and a directory called "inputs"
The Dockerfile will copy the "inputs" directory to the chosen working directory
"""
assert os.path.isabs(wdir)
dockerlines = ["FROM %s" % image,
"RUN mkdir -p %s" % wdir]
build_context = {}
# This loop creates a Build Context for building the provisioned image
# We create a tar archive to be added to the root of the image filesystem
if inputs:
dockerlines.append('COPY root /')
for ifile, (path, obj) in enumerate(inputs.items()):
if not os.path.isabs(path):
path = os.path.join(wdir, path)
assert path[0] == '/'
build_context['root' + path] = obj
dockerstring = '\n'.join(dockerlines)
build_context['Dockerfile'] = pyccc.BytesContainer(dockerstring.encode('utf-8'))
return build_context | python | def create_build_context(image, inputs, wdir):
assert os.path.isabs(wdir)
dockerlines = ["FROM %s" % image,
"RUN mkdir -p %s" % wdir]
build_context = {}
# This loop creates a Build Context for building the provisioned image
# We create a tar archive to be added to the root of the image filesystem
if inputs:
dockerlines.append('COPY root /')
for ifile, (path, obj) in enumerate(inputs.items()):
if not os.path.isabs(path):
path = os.path.join(wdir, path)
assert path[0] == '/'
build_context['root' + path] = obj
dockerstring = '\n'.join(dockerlines)
build_context['Dockerfile'] = pyccc.BytesContainer(dockerstring.encode('utf-8'))
return build_context | [
"def",
"create_build_context",
"(",
"image",
",",
"inputs",
",",
"wdir",
")",
":",
"assert",
"os",
".",
"path",
".",
"isabs",
"(",
"wdir",
")",
"dockerlines",
"=",
"[",
"\"FROM %s\"",
"%",
"image",
",",
"\"RUN mkdir -p %s\"",
"%",
"wdir",
"]",
"build_conte... | Creates a tar archive with a dockerfile and a directory called "inputs"
The Dockerfile will copy the "inputs" directory to the chosen working directory | [
"Creates",
"a",
"tar",
"archive",
"with",
"a",
"dockerfile",
"and",
"a",
"directory",
"called",
"inputs",
"The",
"Dockerfile",
"will",
"copy",
"the",
"inputs",
"directory",
"to",
"the",
"chosen",
"working",
"directory"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L45-L68 |
11,296 | Autodesk/pyccc | pyccc/docker_utils.py | make_tar_stream | def make_tar_stream(build_context, buffer):
""" Write a tar stream of the build context to the provided buffer
Args:
build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references
buffer (io.BytesIO): writable binary mode buffer
"""
tf = tarfile.TarFile(fileobj=buffer, mode='w')
for context_path, fileobj in build_context.items():
if getattr(fileobj, 'localpath', None) is not None:
tf.add(fileobj.localpath, arcname=context_path)
else:
tar_add_bytes(tf, context_path, fileobj.read('rb'))
tf.close() | python | def make_tar_stream(build_context, buffer):
tf = tarfile.TarFile(fileobj=buffer, mode='w')
for context_path, fileobj in build_context.items():
if getattr(fileobj, 'localpath', None) is not None:
tf.add(fileobj.localpath, arcname=context_path)
else:
tar_add_bytes(tf, context_path, fileobj.read('rb'))
tf.close() | [
"def",
"make_tar_stream",
"(",
"build_context",
",",
"buffer",
")",
":",
"tf",
"=",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"buffer",
",",
"mode",
"=",
"'w'",
")",
"for",
"context_path",
",",
"fileobj",
"in",
"build_context",
".",
"items",
"(",
"... | Write a tar stream of the build context to the provided buffer
Args:
build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references
buffer (io.BytesIO): writable binary mode buffer | [
"Write",
"a",
"tar",
"stream",
"of",
"the",
"build",
"context",
"to",
"the",
"provided",
"buffer"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L124-L137 |
11,297 | Autodesk/pyccc | pyccc/docker_utils.py | tar_add_bytes | def tar_add_bytes(tf, filename, bytestring):
""" Add a file to a tar archive
Args:
tf (tarfile.TarFile): tarfile to add the file to
filename (str): path within the tar file
bytestring (bytes or str): file contents. Must be :class:`bytes` or
ascii-encodable :class:`str`
"""
if not isinstance(bytestring, bytes): # it hasn't been encoded yet
bytestring = bytestring.encode('ascii')
buff = io.BytesIO(bytestring)
tarinfo = tarfile.TarInfo(filename)
tarinfo.size = len(bytestring)
tf.addfile(tarinfo, buff) | python | def tar_add_bytes(tf, filename, bytestring):
if not isinstance(bytestring, bytes): # it hasn't been encoded yet
bytestring = bytestring.encode('ascii')
buff = io.BytesIO(bytestring)
tarinfo = tarfile.TarInfo(filename)
tarinfo.size = len(bytestring)
tf.addfile(tarinfo, buff) | [
"def",
"tar_add_bytes",
"(",
"tf",
",",
"filename",
",",
"bytestring",
")",
":",
"if",
"not",
"isinstance",
"(",
"bytestring",
",",
"bytes",
")",
":",
"# it hasn't been encoded yet",
"bytestring",
"=",
"bytestring",
".",
"encode",
"(",
"'ascii'",
")",
"buff",
... | Add a file to a tar archive
Args:
tf (tarfile.TarFile): tarfile to add the file to
filename (str): path within the tar file
bytestring (bytes or str): file contents. Must be :class:`bytes` or
ascii-encodable :class:`str` | [
"Add",
"a",
"file",
"to",
"a",
"tar",
"archive"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L140-L154 |
11,298 | Autodesk/pyccc | pyccc/static/run_job.py | MappedUnpickler.find_class | def find_class(self, module, name):
""" This override is here to help pickle find the modules that classes are defined in.
It does three things:
1) remaps the "PackagedFunction" class from pyccc to the `source.py` module.
2) Remaps any classes created in the client's '__main__' to the `source.py` module
3) Creates on-the-fly modules to store any other classes present in source.py
References:
This is a modified version of the 2-only recipe from
https://wiki.python.org/moin/UsingPickle/RenamingModules.
It's been modified for 2/3 cross-compatibility """
import pickle
modname = self.RENAMETABLE.get(module, module)
try:
# can't use ``super`` here (not 2/3 compatible)
klass = pickle.Unpickler.find_class(self, modname, name)
except (ImportError, RuntimeError):
definition = getattr(source, name)
newmod = _makemod(modname)
sys.modules[modname] = newmod
setattr(newmod, name, definition)
klass = pickle.Unpickler.find_class(self, newmod.__name__, name)
klass.__module__ = module
return klass | python | def find_class(self, module, name):
import pickle
modname = self.RENAMETABLE.get(module, module)
try:
# can't use ``super`` here (not 2/3 compatible)
klass = pickle.Unpickler.find_class(self, modname, name)
except (ImportError, RuntimeError):
definition = getattr(source, name)
newmod = _makemod(modname)
sys.modules[modname] = newmod
setattr(newmod, name, definition)
klass = pickle.Unpickler.find_class(self, newmod.__name__, name)
klass.__module__ = module
return klass | [
"def",
"find_class",
"(",
"self",
",",
"module",
",",
"name",
")",
":",
"import",
"pickle",
"modname",
"=",
"self",
".",
"RENAMETABLE",
".",
"get",
"(",
"module",
",",
"module",
")",
"try",
":",
"# can't use ``super`` here (not 2/3 compatible)",
"klass",
"=",
... | This override is here to help pickle find the modules that classes are defined in.
It does three things:
1) remaps the "PackagedFunction" class from pyccc to the `source.py` module.
2) Remaps any classes created in the client's '__main__' to the `source.py` module
3) Creates on-the-fly modules to store any other classes present in source.py
References:
This is a modified version of the 2-only recipe from
https://wiki.python.org/moin/UsingPickle/RenamingModules.
It's been modified for 2/3 cross-compatibility | [
"This",
"override",
"is",
"here",
"to",
"help",
"pickle",
"find",
"the",
"modules",
"that",
"classes",
"are",
"defined",
"in",
"."
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/static/run_job.py#L97-L124 |
11,299 | Autodesk/pyccc | pyccc/utils.py | gist_diff | def gist_diff():
"""Diff this file with the gist on github"""
remote_file = wget(RAW_GIST)
proc = subprocess.Popen(('diff - %s'%MY_PATH).split(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout, stderr = proc.communicate(remote_file)
return stdout | python | def gist_diff():
remote_file = wget(RAW_GIST)
proc = subprocess.Popen(('diff - %s'%MY_PATH).split(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout, stderr = proc.communicate(remote_file)
return stdout | [
"def",
"gist_diff",
"(",
")",
":",
"remote_file",
"=",
"wget",
"(",
"RAW_GIST",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"(",
"'diff - %s'",
"%",
"MY_PATH",
")",
".",
"split",
"(",
")",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"st... | Diff this file with the gist on github | [
"Diff",
"this",
"file",
"with",
"the",
"gist",
"on",
"github"
] | 011698e78d49a83ac332e0578a4a2a865b75ef8d | https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L34-L41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.