_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10700 | Lexer.scan | train | def scan(self, text):
"""Analyse some data
Analyse the passed content. Each time a token is recognized, a
2-uple containing its name and parsed value is raised (via
yield).
On error, a ParseError exception is raised.
:param text: a binary string containing the data to ... | python | {
"resource": ""
} |
q10701 | Parser.__reset_parser | train | def __reset_parser(self):
"""Reset parser's internal variables
Restore the parser to an initial state. Useful when creating a
new parser or reusing an existing one.
"""
self.result = []
self.hash_comments = []
self.__cstate = None
self.__curcommand = Non... | python | {
"resource": ""
} |
q10702 | Parser.__up | train | def __up(self, onlyrecord=False):
"""Return to the current command's parent
This method should be called each time a command is
complete. In case of a top level command (no parent), it is
recorded into a specific list for further usage.
:param onlyrecord: tell to only record th... | python | {
"resource": ""
} |
q10703 | Parser.__stringlist | train | def __stringlist(self, ttype, tvalue):
"""Specific method to parse the 'string-list' type
Syntax:
string-list = "[" string *("," string) "]" / string
; if there is only a single string, the brackets
; are optional
"""
i... | python | {
"resource": ""
} |
q10704 | Parser.__argument | train | def __argument(self, ttype, tvalue):
"""Argument parsing method
This method acts as an entry point for 'argument' parsing.
Syntax:
string-list / number / tag
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is e... | python | {
"resource": ""
} |
q10705 | Parser.__arguments | train | def __arguments(self, ttype, tvalue):
"""Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: cu... | python | {
"resource": ""
} |
q10706 | Parser.__command | train | def __command(self, ttype, tvalue):
"""Command parsing method
Entry point for command parsing. Here is expected behaviour:
* Handle command beginning if detected,
* Call the appropriate sub-method (specified by __cstate) to
handle the body,
* Handle command ending ... | python | {
"resource": ""
} |
q10707 | Parser.parse | train | def parse(self, text):
"""The parser entry point.
Parse the provided text to check for its validity.
On success, the parsing tree is available into the result
attribute. It is a list of sievecommands.Command objects (see
the module documentation for specific information).
... | python | {
"resource": ""
} |
q10708 | Parser.parse_file | train | def parse_file(self, name):
"""Parse the content of a file.
See 'parse' method for information.
:param name: the pathname of the file to parse
:return: True on success (no error detected), False otherwise
"""
with open(name, "rb") as fp:
return self.parse(fp... | python | {
"resource": ""
} |
q10709 | Parser.dump | train | def dump(self, target=sys.stdout):
"""Dump the parsing tree.
This method displays the parsing tree on the standard output.
"""
for r in self.result:
r.dump(target=target) | python | {
"resource": ""
} |
q10710 | get_command_instance | train | def get_command_instance(name, parent=None, checkexists=True):
"""Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded usin... | python | {
"resource": ""
} |
q10711 | Command.tosieve | train | def tosieve(self, indentlevel=0, target=sys.stdout):
"""Generate the sieve syntax corresponding to this command
Recursive method.
:param indentlevel: current indentation level
:param target: opened file pointer where the content will be printed
"""
self.__print(self.nam... | python | {
"resource": ""
} |
q10712 | Command.dump | train | def dump(self, indentlevel=0, target=sys.stdout):
"""Display the command
Pretty printing of this command and its eventual arguments and
children. (recursively)
:param indentlevel: integer that indicates indentation level to apply
"""
self.__print(self, indentlevel, targ... | python | {
"resource": ""
} |
q10713 | Command.walk | train | def walk(self):
"""Walk through commands."""
yield self
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
if type(value) == l... | python | {
"resource": ""
} |
q10714 | Command.addchild | train | def addchild(self, child):
"""Add a new child to the command
A child corresponds to a command located into a block (this
command's block). It can be either an action or a control.
:param child: the new child
:return: True on succes, False otherwise
"""
if not se... | python | {
"resource": ""
} |
q10715 | Command.iscomplete | train | def iscomplete(self, atype=None, avalue=None):
"""Check if the command is complete
Check if all required arguments have been encountered. For
commands that allow an undefined number of arguments, this
method always returns False.
:return: True if command is complete, False othe... | python | {
"resource": ""
} |
q10716 | Command.__is_valid_value_for_arg | train | def __is_valid_value_for_arg(self, arg, value, check_extension=True):
"""Check if value is allowed for arg
Some commands only allow a limited set of values. The method
always returns True for methods that do not provide such a
set.
:param arg: the argument's name
:param... | python | {
"resource": ""
} |
q10717 | Command.__is_valid_type | train | def __is_valid_type(self, typ, typlist):
""" Check if type is valid based on input type list
"string" is special because it can be used for stringlist
:param typ: the type to check
:param typlist: the list of type to check
:return: True on success, False otherwise
""... | python | {
"resource": ""
} |
q10718 | Command.check_next_arg | train | def check_next_arg(self, atype, avalue, add=True, check_extension=True):
"""Argument validity checking
This method is usually used by the parser to check if detected
argument is allowed for this command.
We make a distinction between required and optional
arguments. Optional (o... | python | {
"resource": ""
} |
q10719 | HasflagCommand.reassign_arguments | train | def reassign_arguments(self):
"""Deal with optional stringlist before a required one."""
condition = (
"variable-list" in self.arguments and
"list-of-flags" not in self.arguments
)
if condition:
self.arguments["list-of-flags"] = (
self.... | python | {
"resource": ""
} |
q10720 | to_bytes | train | def to_bytes(s, encoding="utf-8"):
"""Convert a string to bytes."""
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding) | python | {
"resource": ""
} |
q10721 | to_list | train | def to_list(stringlist, unquote=True):
"""Convert a string representing a list to real list."""
stringlist = stringlist[1:-1]
return [
string.strip('"') if unquote else string
for string in stringlist.split(",")
] | python | {
"resource": ""
} |
q10722 | monkeypatch_i18n | train | def monkeypatch_i18n():
"""Alleviates problems with extraction for trans blocks
Jinja2 has a ``babel_extract`` function which sets up a Jinja2
environment to parse Jinja2 templates to extract strings for
translation. That's awesome! Yay! However, when it goes to
set up the environment, it checks to... | python | {
"resource": ""
} |
q10723 | generate_keywords | train | def generate_keywords(additional_keywords=None):
"""Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
... | python | {
"resource": ""
} |
q10724 | collapse_whitespace | train | def collapse_whitespace(message):
"""Collapses consecutive whitespace into a single space"""
return u' '.join(map(lambda s: s.strip(),
filter(None, message.strip().splitlines()))) | python | {
"resource": ""
} |
q10725 | generate_options_map | train | def generate_options_map():
"""Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
This allows developers to expl... | python | {
"resource": ""
} |
q10726 | extract_command | train | def extract_command(outputdir, domain_methods, text_domain, keywords,
comment_tags, base_dir, project, version,
msgid_bugs_address):
"""Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir f... | python | {
"resource": ""
} |
q10727 | _msgmerge | train | def _msgmerge(po_path, pot_file, backup):
"""Merge an existing .po file with new translations.
:arg po_path: path to the .po file
:arg pot_file: a file-like object for the related templates
:arg backup: whether or not to create backup .po files
"""
pot_file.seek(0)
command = [
'msgm... | python | {
"resource": ""
} |
q10728 | QValkkaShmemProcess.preRun_ | train | def preRun_(self):
"""Create the shared memory client immediately after fork
"""
self.report("preRun_")
super().preRun_()
self.client = ShmemRGBClient(
name=self.shmem_name,
n_ringbuffer=self.n_buffer, # size of ring buffer
width=self.image_d... | python | {
"resource": ""
} |
q10729 | QValkkaShmemProcess2.activate_ | train | def activate_(self, n_buffer, image_dimensions, shmem_name):
"""Shared mem info is given. Now we can create the shmem client
"""
self.active = True
self.image_dimensions = image_dimensions
self.client = ShmemRGBClient(
name =shmem_name,
n_ringb... | python | {
"resource": ""
} |
q10730 | QValkkaShmemProcess2.deactivate_ | train | def deactivate_(self):
"""Init shmem variables to None
"""
self.preDeactivate_()
self.active = False
self.image_dimensions = None
self.client = None | python | {
"resource": ""
} |
q10731 | ExternalDetector.reset | train | def reset(self):
"""Tell the external analyzer to reset itself
"""
self.report("sending reset")
try:
self.p.stdin.write(bytes("T\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send reset command") | python | {
"resource": ""
} |
q10732 | ExternalDetector.close | train | def close(self):
"""Tell the process to exit
"""
try:
self.p.stdin.write(bytes("X\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send exit command")
self.p.wait() # wait until the process is closed
try:
... | python | {
"resource": ""
} |
q10733 | MVisionProcess.postActivate_ | train | def postActivate_(self):
"""Create temporary file for image dumps and the analyzer itself
"""
self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) # e.g. "/tmp/valkka-10968"
self.analyzer = ExternalDetector(
executable = self.executable,
image_... | python | {
"resource": ""
} |
q10734 | generate_pages_by_file | train | def generate_pages_by_file():
"""Generates custom pages of 'file' storage type."""
from veripress import app
from veripress.model import storage
from veripress.model.parsers import get_standard_format_name
from veripress.helpers import traverse_directory
deploy_dir = get_deploy_dir()
def c... | python | {
"resource": ""
} |
q10735 | DataModel.define | train | def define(self):
"""Define column patterns and collections
"""
self.collections = []
self.camera_collection = \
SimpleCollection(filename=os.path.join(self.directory, "devices.dat"),
row_classes=[
DataModel.EmptyRow,
... | python | {
"resource": ""
} |
q10736 | SiteCustomizeFile.inject | train | def inject(self):
"""inject code into sitecustomize.py that will inject pout into the builtins
so it will be available globally"""
if self.is_injected():
return False
with open(self, mode="a+") as fp:
fp.seek(0)
fp.write("\n".join([
""... | python | {
"resource": ""
} |
q10737 | Storage.fix_relative_url | train | def fix_relative_url(self, publish_type, rel_url):
"""
Fix post or page relative url to a standard, uniform format.
:param publish_type: publish type ('post' or 'page')
:param rel_url: relative url to fix
:return: tuple(fixed relative url or file path if exists else None,
... | python | {
"resource": ""
} |
q10738 | Storage.fix_post_relative_url | train | def fix_post_relative_url(rel_url):
"""
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-p... | python | {
"resource": ""
} |
q10739 | Storage._filter_result | train | def _filter_result(result, filter_functions=None):
"""
Filter result with given filter functions.
:param result: an iterable object
:param filter_functions: some filter functions
:return: a filter object (filtered result)
"""
if filter_functions is not None:
... | python | {
"resource": ""
} |
q10740 | Storage.get_posts_with_limits | train | def get_posts_with_limits(self, include_draft=False, **limits):
"""
Get all posts and filter them as needed.
:param include_draft: return draft posts or not
:param limits: other limits to the attrs of the result,
should be a dict with string or list values
... | python | {
"resource": ""
} |
q10741 | Storage.search_for | train | def search_for(self, query, include_draft=False):
"""
Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed).
"""
query = query.lower()
if n... | python | {
"resource": ""
} |
q10742 | FileStorage.fix_page_relative_url | train | def fix_page_relative_url(rel_url):
"""
Fix page relative url to a standard, uniform format.
Possible input:
- my-page
- my-page/
- my-page/index
- my-page/index.htm
- my-page/index.html
- my-page/specific.file
:param rel_url: relative ur... | python | {
"resource": ""
} |
q10743 | FileStorage.search_file | train | def search_file(search_root, search_filename,
instance_relative_root=False):
"""
Search for a filename in a specific search root dir.
:param search_root: root dir to search
:param search_filename: filename to search (no extension)
:param instance_relative_roo... | python | {
"resource": ""
} |
q10744 | FileStorage.read_file | train | def read_file(file_path):
"""
Read yaml head and raw body content from a file.
:param file_path: file path
:return: tuple(meta, raw_content)
"""
with open(file_path, 'r', encoding='utf-8') as f:
whole = f.read().strip()
if whole.startswith('---'):
... | python | {
"resource": ""
} |
q10745 | FileStorage.get_posts | train | def get_posts(self, include_draft=False, filter_functions=None):
"""
Get all posts from filesystem.
:param include_draft: return draft posts or not
:param filter_functions: filter to apply BEFORE result being sorted
:return: an iterable of Post objects (the first is the latest p... | python | {
"resource": ""
} |
q10746 | FileStorage.get_post | train | def get_post(self, rel_url, include_draft=False):
"""
Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:retu... | python | {
"resource": ""
} |
q10747 | FileStorage.get_tags | train | def get_tags(self):
"""
Get all tags and post count of each tag.
:return: dict_item(tag_name, Pair(count_all, count_published))
"""
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for tag_name in set(post.tags):
... | python | {
"resource": ""
} |
q10748 | FileStorage.get_categories | train | def get_categories(self):
"""
Get all categories and post count of each category.
:return dict_item(category_name, Pair(count_all, count_published))
"""
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for category_name in set... | python | {
"resource": ""
} |
q10749 | FileStorage.get_page | train | def get_page(self, rel_url, include_draft=False):
"""
Get custom page for given relative url from filesystem.
Possible input:
- my-page/
- my-page/index.html
- my-another-page.html
- a/b/c/
- a/b/c/d.html
:param rel_url: relative url
:par... | python | {
"resource": ""
} |
q10750 | FileStorage.get_widgets | train | def get_widgets(self, position=None, include_draft=False):
"""
Get widgets for given position from filesystem.
:param position: position or position list
:param include_draft: return draft widgets or not
:return: an iterable of Widget objects
"""
def widgets_gen... | python | {
"resource": ""
} |
q10751 | custom_render_template | train | def custom_render_template(template_name_or_list, **context):
"""
Try to render templates in the custom folder first,
if no custom templates, try the theme's default ones.
"""
response_str = render_template(
functools.reduce(lambda x, y: x + [os.path.join('custom', y), y],
... | python | {
"resource": ""
} |
q10752 | templated | train | def templated(template=None, *templates):
"""
Decorate a view function with one or more default template name.
This will try templates in the custom folder first,
the theme's original ones second.
:param template: template name or template name list
"""
def decorator(func):
@functo... | python | {
"resource": ""
} |
q10753 | copy_folder_content | train | def copy_folder_content(src, dst):
"""
Copy all content in src directory to dst directory.
The src and dst must exist.
"""
for file in os.listdir(src):
file_path = os.path.join(src, file)
dst_file_path = os.path.join(dst, file)
if os.path.isdir(file_path):
shutil.... | python | {
"resource": ""
} |
q10754 | remove_folder_content | train | def remove_folder_content(path, ignore_hidden_file=False):
"""
Remove all content in the given folder.
"""
for file in os.listdir(path):
if ignore_hidden_file and file.startswith('.'):
continue
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
... | python | {
"resource": ""
} |
q10755 | Alpr.unload | train | def unload(self):
"""
Unloads OpenALPR from memory.
:return: None
"""
if self.loaded:
self.loaded = False
self._openalprpy_lib.dispose(self.alpr_pointer) | python | {
"resource": ""
} |
q10756 | Alpr.recognize_file | train | def recognize_file(self, file_path):
"""
This causes OpenALPR to attempt to recognize an image by opening a file on
disk.
:param file_path: The path to the image that will be analyzed
:return: An OpenALPR analysis in the form of a response dictionary
"""
file_pat... | python | {
"resource": ""
} |
q10757 | Alpr.recognize_array | train | def recognize_array(self, byte_array):
"""
This causes OpenALPR to attempt to recognize an image passed in as a byte array.
:param byte_array: This should be a string (Python 2) or a bytes object (Python 3)
:return: An OpenALPR analysis in the form of a response dictionary
"""
... | python | {
"resource": ""
} |
q10758 | Alpr.recognize_ndarray | train | def recognize_ndarray(self, ndarray):
"""
This causes OpenALPR to attempt to recognize an image passed in as a numpy array.
:param ndarray: numpy.array as used in cv2 module
:return: An OpenALPR analysis in the form of a response dictionary
"""
if self._recognize_raw_ima... | python | {
"resource": ""
} |
q10759 | Alpr.get_version | train | def get_version(self):
"""
This gets the version of OpenALPR
:return: Version information
"""
ptr = self._get_version_func(self.alpr_pointer)
version_number = ctypes.cast(ptr, ctypes.c_char_p).value
version_number = _convert_from_charp(version_number)
se... | python | {
"resource": ""
} |
q10760 | Alpr.set_country | train | def set_country(self, country):
"""
This sets the country for detecting license plates. For example,
setting country to "us" for United States or "eu" for Europe.
:param country: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
coun... | python | {
"resource": ""
} |
q10761 | Alpr.set_prewarp | train | def set_prewarp(self, prewarp):
"""
Updates the prewarp configuration used to skew images in OpenALPR before
processing.
:param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
prewarp = _convert_to_charp(prewarp)
s... | python | {
"resource": ""
} |
q10762 | Alpr.set_default_region | train | def set_default_region(self, region):
"""
This sets the default region for detecting license plates. For example,
setting region to "md" for Maryland or "fr" for France.
:param region: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
... | python | {
"resource": ""
} |
q10763 | CallString.is_complete | train | def is_complete(self):
"""Return True if this call string is complete, meaning it has a function
name and balanced parens"""
try:
[t for t in self.tokens]
ret = True
logger.debug('CallString [{}] is complete'.format(self.strip()))
except tokenize.Toke... | python | {
"resource": ""
} |
q10764 | Call._find_calls | train | def _find_calls(self, ast_tree, called_module, called_func):
'''
scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
... | python | {
"resource": ""
} |
q10765 | Reflect._get_arg_info | train | def _get_arg_info(self):
'''
get all the info of a method call
this will find what arg names you passed into the method and tie them to their passed in values,
it will also find file and line number
return -- dict -- a bunch of info on the call
'''
ret_dict = {
... | python | {
"resource": ""
} |
q10766 | Reflect._find_entry_call | train | def _find_entry_call(self, frames):
"""attempts to auto-discover the correct frame"""
back_i = 0
pout_path = self._get_src_file(self.modname)
for frame_i, frame in enumerate(frames):
if frame[1] == pout_path:
back_i = frame_i
return Call(frames[back_... | python | {
"resource": ""
} |
q10767 | url_rule | train | def url_rule(blueprint_or_app, rules,
endpoint=None, view_func=None, **options):
"""
Add one or more url rules to the given Flask blueprint or app.
:param blueprint_or_app: Flask blueprint or app
:param rules: a single rule string or a list of rules
:param endpoint: endpoint
:param... | python | {
"resource": ""
} |
q10768 | to_list | train | def to_list(item_or_list):
"""
Convert a single item, a tuple, a generator or anything else to a list.
:param item_or_list: single item or iterable to convert
:return: a list
"""
if isinstance(item_or_list, list):
return item_or_list
elif isinstance(item_or_list, (str, bytes)):
... | python | {
"resource": ""
} |
q10769 | to_datetime | train | def to_datetime(date_or_datetime):
"""
Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object
"""
if isinstance(date_or_datetime, date) and \
not isinstance(date_or_dat... | python | {
"resource": ""
} |
q10770 | timezone_from_str | train | def timezone_from_str(tz_str):
"""
Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo)
"""
m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
if m:
# in format 'UTC±[hh]:[mm]'
... | python | {
"resource": ""
} |
q10771 | traverse_directory | train | def traverse_directory(dir_path, yield_dir=False):
"""
Traverse through a directory recursively.
:param dir_path: directory path
:param yield_dir: yield subdirectory or not
:return: a generator
"""
if not os.path.isdir(dir_path):
return
for item in os.listdir(dir_path):
... | python | {
"resource": ""
} |
q10772 | parse_toc | train | def parse_toc(html_content):
"""
Parse TOC of HTML content if the SHOW_TOC config is true.
:param html_content: raw HTML content
:return: tuple(processed HTML, toc list, toc HTML unordered list)
"""
from flask import current_app
from veripress.model.toc import HtmlTocParser
if current_... | python | {
"resource": ""
} |
q10773 | TreeModel.index | train | def index(self, row, column, parent):
""" Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex
"""
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not pare... | python | {
"resource": ""
} |
q10774 | TreeModel.columnCount | train | def columnCount(self, parent):
""" Returns the number of columns for the children of the given parent.
"""
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | python | {
"resource": ""
} |
q10775 | BaseInterface._str | train | def _str(self, name, val):
'''
return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
... | python | {
"resource": ""
} |
q10776 | LoggingInterface.loggers | train | def loggers(self):
"""Return all the loggers that should be activated"""
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name... | python | {
"resource": ""
} |
q10777 | TraceInterface._get_backtrace | train | def _get_backtrace(self, frames, inspect_packages=False, depth=0):
'''
get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in t... | python | {
"resource": ""
} |
q10778 | TraceInterface._get_call_summary | train | def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -... | python | {
"resource": ""
} |
q10779 | parser | train | def parser(format_name, ext_names=None):
"""
Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name
"""
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format... | python | {
"resource": ""
} |
q10780 | Parser.parse_preview | train | def parse_preview(self, raw_content):
"""
Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:pa... | python | {
"resource": ""
} |
q10781 | Parser.remove_read_more_sep | train | def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(ra... | python | {
"resource": ""
} |
q10782 | tofile | train | def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the f... | python | {
"resource": ""
} |
q10783 | v | train | def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
... | python | {
"resource": ""
} |
q10784 | vs | train | def vs(*args, **kwargs):
"""
exactly like v, but doesn't print variable names or file positions
.. seealso:: ss()
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
... | python | {
"resource": ""
} |
q10785 | h | train | def h(count=0, **kwargs):
'''
prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here"
'''
with Reflect.context(**kwargs) as r:
kwargs["count"] = count
instance = H_CLASS(... | python | {
"resource": ""
} |
q10786 | b | train | def b(*args, **kwargs):
'''
create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
... | python | {
"resource": ""
} |
q10787 | c | train | def c(*args, **kwargs):
'''
kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = C_CLASS(r... | python | {
"resource": ""
} |
q10788 | m | train | def m(name='', **kwargs):
"""
Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended
"""
with Reflect.context(**kwargs) as r:
... | python | {
"resource": ""
} |
q10789 | p | train | def p(name="", **kwargs):
'''
really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast... | python | {
"resource": ""
} |
q10790 | t | train | def t(inspect_packages=False, depth=0, **kwargs):
'''
print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrac... | python | {
"resource": ""
} |
q10791 | inject | train | def inject():
"""Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable
"""
try:
from .com... | python | {
"resource": ""
} |
q10792 | create_app | train | def create_app(config_filename, instance_path=None):
"""
Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object
"""
app... | python | {
"resource": ""
} |
q10793 | CustomFlask.send_static_file | train | def send_static_file(self, filename):
"""
Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object
"""
if self.config['MODE'] == 'api-only':
# i... | python | {
"resource": ""
} |
q10794 | VideoContainer.mouseGestureHandler | train | def mouseGestureHandler(self, info):
"""This is the callback for MouseClickContext. Passed to VideoWidget as a parameter
"""
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single cli... | python | {
"resource": ""
} |
q10795 | VideoContainer.handle_left_double_click | train | def handle_left_double_click(self, info):
"""Whatever we want to do, when the VideoWidget has been double-clicked with the left button
"""
if (self.double_click_focus == False): # turn focus on
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
... | python | {
"resource": ""
} |
q10796 | get_storage | train | def get_storage():
"""
Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported
"""
storage_ = getattr(g, '_storage', None)
if storage_ is None:
storage_type = cu... | python | {
"resource": ""
} |
q10797 | SlotFormSet.chooseForm_slot | train | def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List ... | python | {
"resource": ""
} |
q10798 | SlotFormSet.update_dropdown_list_slot | train | def update_dropdown_list_slot(self):
"""Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available
"""
self.dropdown_widget.clear() # this will trigger dropdown_changed_slot
self.row_instance_by_index = []
for i, key in enumerate(self.row_in... | python | {
"resource": ""
} |
q10799 | FilterChainGroup.get | train | def get(self, **kwargs):
"""Find correct filterchain based on generic variables
"""
for chain in self.chains:
for key in kwargs:
getter_name = "get_"+key
# scan all possible getters
if (hasattr(chain, getter_name)):
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.