_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11200 | render_entry | train | 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 | python | {
"resource": ""
} |
q11201 | render_transparent_chit | train | 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(
| python | {
"resource": ""
} |
q11202 | retrieve_asset | train | 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 | python | {
"resource": ""
} |
q11203 | Maintenance.run | train | 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 | python | {
"resource": ""
} |
q11204 | _get_asset | train | 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:
| python | {
"resource": ""
} |
q11205 | get_image | train | 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)
| python | {
"resource": ""
} |
q11206 | parse_arglist | train | 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] | python | {
"resource": ""
} |
q11207 | parse_alt_text | train | 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:
| python | {
"resource": ""
} |
q11208 | parse_image_spec | train | 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:
| python | {
"resource": ""
} |
q11209 | get_spec_list | train | 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 | python | {
"resource": ""
} |
q11210 | get_async | train | 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,
| python | {
"resource": ""
} |
q11211 | Image.get_css_background | train | 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
| python | {
"resource": ""
} |
q11212 | Image.get_fullsize | train | 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
| python | {
"resource": ""
} |
q11213 | set_alias | train | 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}
| python | {
"resource": ""
} |
q11214 | remove_alias | train | def remove_alias(path):
""" Remove a path alias.
Arguments:
path -- the | python | {
"resource": ""
} |
q11215 | remove_aliases | train | 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):
| python | {
"resource": ""
} |
q11216 | get_alias | train | 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
| python | {
"resource": ""
} |
q11217 | get_redirect | train | 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)
| python | {
"resource": ""
} |
q11218 | LocalImage.thread_pool | train | def thread_pool():
""" Get the rendition threadpool """
if not LocalImage._thread_pool:
logger.info("Starting LocalImage | python | {
"resource": ""
} |
q11219 | LocalImage._adjust_crop_box | train | 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],
| python | {
"resource": ""
} |
q11220 | LocalImage.get_rendition_size | train | 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)
| python | {
"resource": ""
} |
q11221 | LocalImage.get_rendition_fit_size | train | 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')
| python | {
"resource": ""
} |
q11222 | LocalImage.flatten | train | def flatten(image, bgcolor=None):
""" Flatten an image, with an optional background color """
if bgcolor:
background = PIL.Image.new('RGB', image.size, bgcolor)
| python | {
"resource": ""
} |
q11223 | LocalImage._get_renditions | train | 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"}))
| python | {
"resource": ""
} |
q11224 | LocalImage._css_background | train | 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:
| python | {
"resource": ""
} |
q11225 | process | train | 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 | python | {
"resource": ""
} |
q11226 | HTMLEntry._handle_tag | train | 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')):
| python | {
"resource": ""
} |
q11227 | last_modified | train | def last_modified():
""" information about the most recently modified file """
files = model.FileFingerprint.select().order_by(
orm.desc(model.FileFingerprint.file_mtime)) | python | {
"resource": ""
} |
q11228 | scan_file | train | 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)
| python | {
"resource": ""
} |
q11229 | get_last_fingerprint | train | def get_last_fingerprint(fullpath):
""" Get the last known modification time for a file | python | {
"resource": ""
} |
q11230 | set_fingerprint | train | 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,
| python | {
"resource": ""
} |
q11231 | background_scan | train | def background_scan(content_dir):
""" Start background scanning a directory for changes """
observer = watchdog.observers.Observer()
observer.schedule(IndexWatchdog(content_dir),
| python | {
"resource": ""
} |
q11232 | prune_missing | train | def prune_missing(table):
""" Prune any files which are missing from the specified table """
try:
for item in table.select():
if not | python | {
"resource": ""
} |
q11233 | scan_index | train | 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: | python | {
"resource": ""
} |
q11234 | ConcurrentSet.add | train | 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:
| python | {
"resource": ""
} |
q11235 | ConcurrentSet.remove | train | def remove(self, item):
""" Remove an item from the set, returning if it was present """
with self.lock:
if item in self.set:
| python | {
"resource": ""
} |
q11236 | IndexWatchdog.update_file | train | def update_file(self, fullpath):
""" Update a file """
if SCHEDULED_FILES.add(fullpath):
logger.debug("Scheduling reindex of %s", fullpath)
relpath = | python | {
"resource": ""
} |
q11237 | parse_view_spec | train | 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:
| python | {
"resource": ""
} |
q11238 | View.deleted | train | def deleted(self):
""" Gets the deleted entries from the view """
query = queries.build_query({**self.spec,
| python | {
"resource": ""
} |
q11239 | View.last_modified | train | def last_modified(self):
""" Gets the most recent modification time for all entries in the view """
if self.entries:
latest | python | {
"resource": ""
} |
q11240 | View.previous | train | def previous(self):
""" Gets the previous page, respecting sort order """
if self._order_by == 'oldest':
return self.older
| python | {
"resource": ""
} |
q11241 | View.next | train | def next(self):
""" Gets the next page, respecting sort order """
if self._order_by == 'oldest':
return self.newer
| python | {
"resource": ""
} |
q11242 | View.newest | train | def newest(self):
""" Gets the newest entry in the view, regardless of sort order """
if self._order_by == 'newest': | python | {
"resource": ""
} |
q11243 | View.oldest | train | def oldest(self):
""" Gets the oldest entry in the view, regardless of sort order """
if self._order_by == 'newest': | python | {
"resource": ""
} |
q11244 | View.pages | train | def pages(self):
""" Gets a list of all pages for this view """
cur = self
pages = []
| python | {
"resource": ""
} |
q11245 | View.tags | train | def tags(self):
""" Returns a list of all the tags applied to this view """
tag_list = self.spec.get('tag', [])
| python | {
"resource": ""
} |
q11246 | View._pagination | train | 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,
| python | {
"resource": ""
} |
q11247 | View._get_date_pagination | train | 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:
| python | {
"resource": ""
} |
q11248 | View._get_count_pagination | train | 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,
| python | {
"resource": ""
} |
q11249 | View.tag_add | train | def tag_add(self, *tags):
""" Return a view with the specified tags added """
| python | {
"resource": ""
} |
q11250 | View.tag_remove | train | def tag_remove(self, *tags):
""" Return a view with the specified tags removed """
| python | {
"resource": ""
} |
q11251 | View.tag_toggle | train | def tag_toggle(self, *tags):
""" Return a view with the specified tags toggled """
| python | {
"resource": ""
} |
q11252 | to_html | train | def to_html(text, config, search_path):
""" Convert Markdown text to HTML """
processor = misaka.Markdown(HtmlRenderer(config, search_path),
extensions=ENABLED_EXTENSIONS)
| python | {
"resource": ""
} |
q11253 | render_title | train | 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(),
| python | {
"resource": ""
} |
q11254 | HtmlRenderer.image | train | 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,
| python | {
"resource": ""
} |
q11255 | HtmlRenderer.blockcode | train | 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)
| python | {
"resource": ""
} |
q11256 | HtmlRenderer.link | train | 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'))
| python | {
"resource": ""
} |
q11257 | HtmlRenderer.paragraph | train | 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>'):
| python | {
"resource": ""
} |
q11258 | resolve | train | 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:
| python | {
"resource": ""
} |
q11259 | do_not_cache | train | 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 | python | {
"resource": ""
} |
q11260 | where_entry_visible | train | 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
| python | {
"resource": ""
} |
q11261 | where_entry_visible_future | train | def where_entry_visible_future(query):
""" Generate a where clause for entries that are visible now or in the future """
| python | {
"resource": ""
} |
q11262 | where_entry_deleted | train | def where_entry_deleted(query):
""" Generate a where clause for entries that have been deleted """
return orm.select(
e | python | {
"resource": ""
} |
q11263 | where_entry_category | train | 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(
| python | {
"resource": ""
} |
q11264 | where_before_entry | train | def where_before_entry(query, ref):
""" Generate a where clause for prior entries
ref -- The entry of reference
| python | {
"resource": ""
} |
q11265 | where_after_entry | train | def where_after_entry(query, ref):
""" Generate a where clause for later entries
ref -- the entry of reference
| python | {
"resource": ""
} |
q11266 | where_entry_last | train | def where_entry_last(query, ref):
""" Generate a where clause where this is the last entry
ref -- the entry of reference
| python | {
"resource": ""
} |
q11267 | where_entry_first | train | def where_entry_first(query, ref):
""" Generate a where clause where this is the first entry
ref -- the entry of reference
| python | {
"resource": ""
} |
q11268 | where_entry_type | train | 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)):
| python | {
"resource": ""
} |
q11269 | where_entry_tag | train | def where_entry_tag(query, tag):
""" Generate a where clause for entries with the given tag """
if isinstance(tag, (list, set, tuple)):
| python | {
"resource": ""
} |
q11270 | where_entry_date | train | 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)
| python | {
"resource": ""
} |
q11271 | get_entry | train | 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)):
| python | {
"resource": ""
} |
q11272 | build_query | train | 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):
| python | {
"resource": ""
} |
q11273 | create_templates_static_files | train | 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)
| python | {
"resource": ""
} |
q11274 | init | train | 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)
| python | {
"resource": ""
} |
q11275 | startproject | train | 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,
| python | {
"resource": ""
} |
q11276 | raise_error | train | 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 | python | {
"resource": ""
} |
q11277 | _raise_on_error | train | def _raise_on_error(data: Union[str, dict]) -> None:
"""Raise the appropriate exception on error."""
if isinstance(data, str):
raise_error(data)
| python | {
"resource": ""
} |
q11278 | API.city | train | async def city(self, city: str, state: str, country: str) -> dict:
"""Return data for the specified city."""
data = await self._request(
'get',
'city',
| python | {
"resource": ""
} |
q11279 | API.node | train | async def node(self, node_id: str) -> dict:
"""Return data from a | python | {
"resource": ""
} |
q11280 | Supported.states | train | async def states(self, country: str) -> list:
"""Return a list of supported states in a country."""
data = await self._request(
| python | {
"resource": ""
} |
q11281 | Supported.stations | train | 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,
| python | {
"resource": ""
} |
q11282 | column_width | train | 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]
| python | {
"resource": ""
} |
q11283 | justify_token | train | 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 | python | {
"resource": ""
} |
q11284 | display_name | train | 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 = '' | python | {
"resource": ""
} |
q11285 | SeeResult.filter | train | 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 | python | {
"resource": ""
} |
q11286 | SeeResult.filter_ignoring_case | train | def filter_ignoring_case(self, pattern):
"""
Like ``filter`` but case-insensitive.
Expects a regular expression string without the surrounding ``/``
characters.
| python | {
"resource": ""
} |
q11287 | term_width | train | 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:
| python | {
"resource": ""
} |
q11288 | DepartingPickler.persistent_id | train | def persistent_id(self, obj):
""" Tags objects with a persistent ID, but do NOT emit it
"""
if getattr(obj, '_PERSIST_REFERENCES', None):
objid | python | {
"resource": ""
} |
q11289 | handle_deprecated_args | train | 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 | python | {
"resource": ""
} |
q11290 | get_global_vars | train | 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={},
| python | {
"resource": ""
} |
q11291 | getsource | train | 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 = {}
| python | {
"resource": ""
} |
q11292 | Docker.get_job | train | 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
| python | {
"resource": ""
} |
q11293 | Docker.submit | train | 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)
| python | {
"resource": ""
} |
q11294 | Docker.dump_all_outputs | train | 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)
| python | {
"resource": ""
} |
q11295 | create_build_context | train | 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 | python | {
"resource": ""
} |
q11296 | make_tar_stream | train | 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, | python | {
"resource": ""
} |
q11297 | tar_add_bytes | train | 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 | python | {
"resource": ""
} |
q11298 | MappedUnpickler.find_class | train | 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)
| python | {
"resource": ""
} |
q11299 | gist_diff | train | 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,
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.