_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q53200 | SteamWebBrowser._store_oauth_access_token | train | def _store_oauth_access_token(self, oauth_access_token):
''' Called when login is complete to store the oauth access token
This implementation stores the oauth_access_token in a seperate cookie for domain steamwebbrowser.tld
'''
c = Cookie(version=0, name='oauth_access_token', value=... | python | {
"resource": ""
} |
q53201 | redef | train | def redef(obj, key, value, **kwargs):
'''A static constructor helper function'''
return Redef(obj, key, value=value, **kwargs) | python | {
"resource": ""
} |
q53202 | CallableWrapper._capture | train | def _capture(self, args, kwargs):
'''Store the input to the captured function'''
self.called = self.called + 1
self.method_args.append(args)
self.named_method_args.append(kwargs)
self.never_called = False | python | {
"resource": ""
} |
q53203 | init | train | def init(path=None):
'''Initialize the logging module. Construct the LogTee as the default
keeper. Initialize the flulog and append it to the tee.'''
default = get_default()
if default is not None and not isinstance(default, VoidLogKeeper):
return default
tee = LogTee()
set_default(tee)
... | python | {
"resource": ""
} |
q53204 | Storage.content_size_exceeded_max | train | def content_size_exceeded_max(self, content_bytes):
'''
`sys.getsizeof` works great for this use case because we have a byte
sequence, and not a recursive nested structure. The unit of Memcache
`item_size_max` is also bytes.
:rettype: tuple(bool, int)
'''
content... | python | {
"resource": ""
} |
q53205 | Storage.put | train | def put(self, content_bytes):
'''
Save the `bytes` under a key derived from `path` in Memcache.
:return: A string representing the content path if it is stored.
:rettype: string or None
'''
derived_path = self.context.request.url
over_max, content_size = self.con... | python | {
"resource": ""
} |
q53206 | Storage.get | train | def get(self, callback):
'''
Gets an item based on the path.
'''
derived_path = self.context.request.url
logger.debug('[{log_prefix}]: get.derived_path: {path}'.format(
log_prefix=LOG_PREFIX, path=derived_path))
callback(self.storage.get(self.result_key_for(de... | python | {
"resource": ""
} |
q53207 | Storage.last_updated | train | def last_updated(self):
'''
This is used only when SEND_IF_MODIFIED_LAST_MODIFIED_HEADERS is eet.
:return: A DateTime object
:rettype: datetime.datetime
'''
derived_path = self.context.request.url
timestamp_key = self.timestamp_key_for(derived_path)
if s... | python | {
"resource": ""
} |
q53208 | valuegetter | train | def valuegetter(*fieldspecs, **kwargs):
"""
Modelled after `operator.itemgetter`. Takes a variable
number of specs and returns a function, which applied to
any `pymarc.Record` returns the matching values.
Specs are in the form `field` or `field.subfield`, e.g.
`020` or `020.9`.
Example:
... | python | {
"resource": ""
} |
q53209 | Record.from_record | train | def from_record(cls, record):
"""
Factory methods to create Record from pymarc.Record object.
"""
if not isinstance(record, pymarc.Record):
raise TypeError('record must be of type pymarc.Record')
record.__class__ = Record
return record | python | {
"resource": ""
} |
q53210 | Record.remove | train | def remove(self, fieldspec):
"""
Removes fields or subfields according to `fieldspec`.
If a non-control field subfield removal leaves no other subfields,
delete the field entirely.
"""
pattern = r'(?P<field>[^.]+)(.(?P<subfield>[^.]+))?'
match = re.match(pattern... | python | {
"resource": ""
} |
q53211 | File.create_object | train | def create_object(self, api, metadata=None):
"""
Create an object using the CDSTAR API, with the file content as bitstream.
:param api:
:return:
"""
metadata = {k: v for k, v in (metadata or {}).items()}
metadata.setdefault('creator', '{0.__name__} {0.__version__... | python | {
"resource": ""
} |
q53212 | find_bar_plot | train | def find_bar_plot(ar, nth):
"Find the NTH barplot of the cluster in area AR."
for plot in ar.plots():
if isinstance(plot, T) and plot.cluster[0] == nth:
return plot
raise Exception("The %dth bar plot in the cluster not found." % nth) | python | {
"resource": ""
} |
q53213 | get_user_permissions | train | def get_user_permissions(user):
'''Returns the queryset of permissions for the given user.'''
permissions = SeedPermission.objects.all()
# User must be on a team that grants the permission
permissions = permissions.filter(seedteam__users=user)
# The team must be active
permissions = permissions.... | python | {
"resource": ""
} |
q53214 | find_permission | train | def find_permission(
permissions, permission_type, object_id=None, namespace=None):
'''Given a queryset of permissions, filters depending on the permission
type, and optionally an object id and namespace.'''
if object_id is not None:
return permissions.filter(
type=permission_typ... | python | {
"resource": ""
} |
q53215 | Generator._val_is_unique | train | def _val_is_unique(val, field):
"""
Currently only checks the field's uniqueness, not the model validation.
"""
if val is None:
return False
if not field.unique:
return True
field_name = field.name
return field.model.objects.filter(**{fie... | python | {
"resource": ""
} |
q53216 | Generator._generate_ipaddressfield | train | def _generate_ipaddressfield(self, **kwargs):
""" Currently only IPv4 fields. """
field = kwargs['field']
if field.default != NOT_PROVIDED:
return self._generate_field_with_default(**kwargs)
num_octets = 4
octets = [str(random.randint(0, 255)) for n in range(num_octet... | python | {
"resource": ""
} |
q53217 | Generator._generate_field_with_default | train | def _generate_field_with_default(**kwargs):
"""Only called if field.default != NOT_PROVIDED"""
field = kwargs['field']
if callable(field.default):
return field.default()
return field.default | python | {
"resource": ""
} |
q53218 | encode | train | def encode(arg, delimiter=None, encodeseq=None, encoded=tuple()):
'''Encode a single argument for the file-system'''
arg = coerce_unicode(arg, _c.FSQ_CHARSET)
new_arg = sep = u''
delimiter, encodeseq = delimiter_encodeseq(
_c.FSQ_DELIMITER if delimiter is None else delimiter,
_c.FSQ_ENCO... | python | {
"resource": ""
} |
q53219 | decode | train | def decode(arg, delimiter=None, encodeseq=None):
'''Decode a single argument from the file-system'''
arg = coerce_unicode(arg, _c.FSQ_CHARSET)
new_arg = sep = u''
delimiter, encodeseq = delimiter_encodeseq(
_c.FSQ_DELIMITER if delimiter is None else delimiter,
_c.FSQ_ENCODE if encodeseq ... | python | {
"resource": ""
} |
q53220 | log_errors | train | def log_errors(function):
"""Logs the exceptions raised by the decorated function
without interfering. For debugging purpose."""
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except BaseException as e:
handle_exception(None, e, "Exception in fun... | python | {
"resource": ""
} |
q53221 | print_errors | train | def print_errors(function):
"""Prints the exceptions raised by the decorated function
without interfering. For debugging purpose."""
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except BaseException as e:
print ("Exception raise calling %s: %s"... | python | {
"resource": ""
} |
q53222 | clean_traceback | train | def clean_traceback(tb):
'''Fixes up the traceback to remove the from the file paths the part
preceeding the project root.
@param tb: C{str}
@rtype: C{str}'''
prefix = __file__[:__file__.find("feat/common/error.py")]
regex = re.compile("(\s*File\s*\")(%s)([a-zA-Z-_\. \\/]*)(\".*)"
... | python | {
"resource": ""
} |
q53223 | is_node_destroyable | train | def is_node_destroyable(name, prefixes=DESTROYABLE_PREFIXES):
"""Return True if name starts with a destroyable prefix"""
return any([name.startswith(p) for p in prefixes]) | python | {
"resource": ""
} |
q53224 | handle_errors | train | def handle_errors(callback, parsed=None, out=sys.stderr):
"""Execute the callback, optionally passing it parsed, and return
its return value. If an exception occurs, determine which kind it
is, output an appropriate message, and return the corresponding
error code."""
try:
if parsed:
... | python | {
"resource": ""
} |
q53225 | new_bundle | train | def new_bundle(name, scriptmap, filemap=None):
"""Create a bundle and add to available bundles"""
#logger.debug('new bundle %s' % name)
if name in BUNDLEMAP:
logger.warn('overwriting bundle %s' % name)
BUNDLEMAP[name] = Bundle(scriptmap, filemap) | python | {
"resource": ""
} |
q53226 | import_by_path | train | def import_by_path(path):
"""Append the path to sys.path, then attempt to import module with
path's basename, finally making certain to remove appended path.
http://stackoverflow.com/questions/1096216/override-namespace-in-python"""
sys.path.append(os.path.dirname(path))
try:
return __imp... | python | {
"resource": ""
} |
q53227 | load_pubkeys | train | def load_pubkeys(loadpath, pubkeys):
"""Append the file contents in loadpath directory onto pubkeys list"""
filenames = os.listdir(loadpath)
logger.debug('loading authorized pubkeys {0}'.format(filenames))
for filename in filenames:
pubkeys.append(open(join(loadpath, filename)).read()) | python | {
"resource": ""
} |
q53228 | normalize_path | train | def normalize_path(path, relative_to=os.getcwd()):
"""Return normalized path. If path is not user-expandable or
absolute, treat it relative to relative_to"""
path = os.path.expanduser(os.path.normpath(path))
if os.path.isabs(path):
return path
else:
return join(relative_to, path) | python | {
"resource": ""
} |
q53229 | configure | train | def configure(paths, relative_to):
"""Iterate on each configuration path, collecting all public keys
destined for the new node's root account's authorized keys.
Additionally attempt to import path as python module."""
if not paths:
return
for path in [normalize_path(p, relative_to) for p i... | python | {
"resource": ""
} |
q53230 | parser | train | def parser():
"""Return a parser for setting one or more configuration paths"""
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config_paths', default=[], action='append',
help='path to a configuration directory')
return parser | python | {
"resource": ""
} |
q53231 | add_auth_args | train | def add_auth_args(parser, config):
"""Return a parser for configuring authentication parameters"""
parser.add_argument('-p', '--provider', default=config.DEFAULT_PROVIDER)
parser.add_argument('-u', '--userid', default=config.DEFAULT_USERID)
parser.add_argument('-k', '--secret_key', default=config.DEFA... | python | {
"resource": ""
} |
q53232 | detect_language | train | def detect_language(index_page):
"""
Detect `languages` using `langdetect` library.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
obj: One :class:`.SourceString` object.
"""
dom = dhtmlparser.parseString(index_page)
clean_content = dhtmlpar... | python | {
"resource": ""
} |
q53233 | get_lang_tags | train | def get_lang_tags(index_page):
"""
Collect informations about language of the page from HTML and Dublin core
tags and langdetect guesses.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
dom = d... | python | {
"resource": ""
} |
q53234 | deblind | train | def deblind(rInv,y):
"""
Removes blinding using ephemeral key @rInv on (intermediate result)
@y \in Gt.
"""
# Verify types, then deblind using the values provided.
assertScalarType(rInv)
assertType(y, GtElement)
return y ** rInv | python | {
"resource": ""
} |
q53235 | _get_plugin_dirs | train | def _get_plugin_dirs():
"""Return a list of directories where plugins may be located.
"""
plugin_dirs = [
os.path.expanduser(os.path.join(USER_CONFIG_DIR, "plugins")),
os.path.join("rapport", "plugins") # Local dev tree
]
return plugin_dirs | python | {
"resource": ""
} |
q53236 | discover | train | def discover():
"""Find and load all available plugins.
"""
plugin_files = []
for plugin_dir in _get_plugin_dirs():
if os.path.isdir(plugin_dir):
for plugin_file in os.listdir(plugin_dir):
if plugin_file.endswith(".py") and not plugin_file == "__init__.py":
... | python | {
"resource": ""
} |
q53237 | register | train | def register(name, klass):
"""Add a plugin to the plugin catalog.
"""
if rapport.config.get_int("rapport", "verbosity") >= 1:
print("Registered plugin: {0}".format(name))
_PLUGIN_CATALOG[name] = klass | python | {
"resource": ""
} |
q53238 | init | train | def init(name, *args, **kwargs):
"""Instantiate a plugin from the catalog.
"""
if name in _PLUGIN_CATALOG:
if rapport.config.get_int("rapport", "verbosity") >= 2:
print("Initialize plugin {0}: {1} {2}".format(name, args, kwargs))
try:
return _PLUGIN_CATALOG[name](*arg... | python | {
"resource": ""
} |
q53239 | Plugin._results | train | def _results(self, dict={}):
"""Helper to merge a dict with cross-plugin defaults.
All plugin sub-classes share some config values, i.e. alias, url,
login and password. This help should be used in the :collect: method
of any Plugin implementation.
>>> import rapport.plugin
... | python | {
"resource": ""
} |
q53240 | beautify | train | def beautify(string, *args, **kwargs):
"""
Convenient interface to the ecstasy package.
Arguments:
string (str): The string to beautify with ecstasy.
args (list): The positional arguments.
kwargs (dict): The keyword ('always') arguments.
"""
parser = Parser(args, kwargs)
return parser.beautify(string... | python | {
"resource": ""
} |
q53241 | Parser.parse | train | def parse(self, string, root=None):
"""
Parses a string to handle escaped tags and retrieve phrases.
This method works recursively to parse nested tags. When escaped
tags are found, those are removed from the string. Also argument
sequences are removed from the string. The string returned can
thus be quit... | python | {
"resource": ""
} |
q53242 | Parser.escape_meta | train | def escape_meta(self, string, pos):
"""
Checks if a meta character is escaped or else warns about it.
If the meta character has an escape character ('\') preceding it,
the meta character is escaped. If it does not, a warning is emitted
that the user should escape it.
Arguments:
string (str): The relev... | python | {
"resource": ""
} |
q53243 | Parser.handle_arguments | train | def handle_arguments(self, string, root, opening, closing):
"""
Handles phrase-arguments.
Sets the override and increment flags if found. Also makes
sure that the argument sequence is at the start of the phrase
and else warns about the unescaped meta characters. If the
arguments are indeed at the start bu... | python | {
"resource": ""
} |
q53244 | Parser.stringify | train | def stringify(self, string, phrases, parent=None):
"""
Stringifies phrases.
After parsing of the string via self.parse(), this method takes the
escaped string and the list of phrases returned by self.parse() and
replaces the original phrases (with tags) with the Phrase-objects in
the list and adds the app... | python | {
"resource": ""
} |
q53245 | Parser.raise_not_enough_arguments | train | def raise_not_enough_arguments(self, string):
"""
Raises an errors.ArgumentError if not enough arguments were supplied.
Takes care of formatting for detailed error messages.
Arguments:
string (str): The string of the phrase for which there weren't enough
arguments.
Raises:
errors.ArgumentErr... | python | {
"resource": ""
} |
q53246 | get_entry | train | def get_entry(key):
"""
Get a configuration entry
:param key: key name
:returns: mixed value
:raises KeyError: if key has not been found
:raises TypeError: if key is not str
"""
if type(key) != str:
raise TypeError("key must be str")
if key not in _config:
raise KeyE... | python | {
"resource": ""
} |
q53247 | set_entry | train | def set_entry(key, value):
"""
Set a configuration entry
:param key: key name
:param value: value for this key
:raises KeyError: if key is not str
"""
if type(key) != str:
raise KeyError('key must be str')
_config[key] = value | python | {
"resource": ""
} |
q53248 | _list_merge | train | def _list_merge(src, dest):
"""
Merge the contents coming from src into dest
:param src: source dictionary
:param dest: destination dictionary
"""
for k in src:
if type(src[k]) != dict:
dest[k] = src[k]
else:
# ---
# src could have a key whose... | python | {
"resource": ""
} |
q53249 | set_from_file | train | def set_from_file(file_name):
"""
Merge configuration from a file with JSON data
:param file_name: name of the file to be read
:raises TypeError: if file_name is not str
"""
if type(file_name) != str:
raise TypeError('file_name must be str')
global _config_file_name
_config_file... | python | {
"resource": ""
} |
q53250 | get_dc_keywords | train | def get_dc_keywords(index_page):
"""
Return list of `keywords` parsed from Dublin core.
Args:
index_page (str): Content of the page as UTF-8 string
Returns:
list: List of :class:`.SourceString` objects.
"""
keyword_lists = (
keyword_list.split()
for keyword_list... | python | {
"resource": ""
} |
q53251 | extract_keywords_from_text | train | def extract_keywords_from_text(index_page, no_items=5):
"""
Try to process text on the `index_page` deduce the keywords and then try
to match them on the Aleph's dataset.
Function returns maximally `no_items` items, to prevent spamming the user.
Args:
index_page (str): Content of the page ... | python | {
"resource": ""
} |
q53252 | MLStripper.strip_tags | train | def strip_tags(cls, html):
"""
This function may be used to remove HTML tags from data.
"""
s = cls()
s.feed(html)
return s.get_data() | python | {
"resource": ""
} |
q53253 | CallDescriptor.save | train | def save( self ):
"""
Save method for the CallDescriptor.
If the CallDescriptor matches a past CallDescriptor it updates the existing
database record corresponding to the hash. If it doesn't already exist it'll
be INSERT'd.
"""
packets = self.__enumerate_packets(... | python | {
"resource": ""
} |
q53254 | Deleted.from_int | train | def from_int(cls, integer):
"""
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8
"""
bin_string = bin... | python | {
"resource": ""
} |
q53255 | Hyphenator.hyphenate_word | train | def hyphenate_word(self, word):
""" Given a word, returns a list of pieces, broken at the possible
hyphenation points.
"""
# Short words aren't hyphenated.
if len(word) <= 4:
return [word]
# If the word is an exception, get the stored points.
if wo... | python | {
"resource": ""
} |
q53256 | T.add_arrow | train | def add_arrow(self, tipLoc, tail=None, arrow=arrow.default):
"""This method adds a straight arrow that points to
@var{TIPLOC}, which is a tuple of integers. @var{TAIL}
specifies the starting point of the arrow. It is either None
or a string consisting of the following letters: 'l', 'c',
... | python | {
"resource": ""
} |
q53257 | get_object | train | def get_object(context):
"""
Get an object from the context or view.
"""
object = None
view = context.get('view')
if view:
# View is more reliable then an 'object' variable in the context.
# Works if this is a SingleObjectMixin
object = getattr(view, 'object', None)
... | python | {
"resource": ""
} |
q53258 | Group.get_rows | train | def get_rows(self, request, context):
"""
Get all rows as HTML
"""
from staff_toolbar.loading import load_toolbar_item
rows = []
for i, hook in enumerate(self.children):
# Allow dotted paths in groups too, loads on demand (get import errors otherwise).
... | python | {
"resource": ""
} |
q53259 | Group.render | train | def render(self, rows):
"""
Join the HTML rows.
"""
if not rows:
return ''
li_tags = mark_safe(u"\n".join(format_html(u'<li>{0}</li>', force_text(row)) for row in rows))
if self.title:
return format_html(u'<div class="toolbar-title">{0}</div>\n<ul... | python | {
"resource": ""
} |
q53260 | Authentication.set_json | train | def set_json(self, json):
"""Set all attributes based on JSON response."""
import time
if 'access_token' in json:
self.access_token = json['access_token']
self.refresh_token = json['refresh_token']
self.expires_in = json['expires_in']
if 'authent... | python | {
"resource": ""
} |
q53261 | Authentication._check | train | def _check(self):
"""Check if the access token is expired or not."""
import time
if self.expires_in is None or self.authenticated is None:
return False
current = time.time()
expire_time = self.authenticated + self.expires_in
return expire_time > current | python | {
"resource": ""
} |
q53262 | PlokamosPlugin.r_plokamos_proxy | train | def r_plokamos_proxy(self):
""" Proxy to write to the annotation store
:return: response from the remote query store
:rtype: {str: Any}
"""
query = request.data
if self.is_authorized(query,NemoOauthPlugin.current_user()['uri']):
try:
resp = ... | python | {
"resource": ""
} |
q53263 | Extension.init_app | train | def init_app(self, app):
"""Initialize extension to the given application.
Extension will be registered to `app.extensions` with lower classname
as key and instance as value.
:param app: Flask application.
"""
self.init_extension(app)
if not hasattr(app, 'exten... | python | {
"resource": ""
} |
q53264 | Extension.context | train | def context(self, key, method):
"""A helper method to attach a value within context.
:param key: the key attached to the context.
:param method: the constructor function.
:return: the value attached to the context.
"""
ctx = stack.top
if ctx is not None:
... | python | {
"resource": ""
} |
q53265 | main_ | train | def main_(*,
config: 'c' = 'config.yml',
debug: 'd' = False,
extra: ('e', str, parameters.multi()) = None,
optimistic = False,
quiet: 'q' = False,
vim_is_fucking_retarded: Parameter.UNDOCUMENTED = False):
"""
Run cms7.
config: Path to project conf... | python | {
"resource": ""
} |
q53266 | export_shell | train | def export_shell(file_index, to_dir):
"""
Export all shell commands from files in the file index into given directory
"""
if not exists(to_dir):
makedirs(to_dir)
for _, file_data in file_index.files.items():
export_from_file(file_data, to_dir) | python | {
"resource": ""
} |
q53267 | parameters_present | train | def parameters_present(options, **kwargs):
"""
Analysis function
Check whether all calls contain a given parameters or their synonyms
"""
synonyms = options['synonyms']
call_graph = options['call_graph']
result = _Result()
for node, edges in call_graph:
for edge in edges:
... | python | {
"resource": ""
} |
q53268 | replay | train | def replay(journal_entry, function, *args, **kwargs):
'''
Calls method in replay context so that no journal entries are created,
expected_side_effects are checked, and no asynchronous task is started.
The journal entry is only used to fetch side-effects results.
'''
# Starts the fiber section
... | python | {
"resource": ""
} |
q53269 | add_effect | train | def add_effect(effect_id, *args, **kwargs):
'''If inside a side-effect, adds an effect to it.'''
effect = fiber.get_stack_var(SIDE_EFFECT_TAG)
if effect is None:
return False
effect.add_effect(effect_id, *args, **kwargs)
return True | python | {
"resource": ""
} |
q53270 | tangle | train | def tangle(*args, **kwargs):
"""
Shortcut to create a new, custom Tangle model. Use instead of directly
subclassing `Tangle`.
A new, custom Widget class is created, with each of `kwargs` as a traitlet.
Returns an instance of the new class with default values.
`kwargs` options
- primitive ... | python | {
"resource": ""
} |
q53271 | _EndRecData64 | train | def _EndRecData64(fpin, offset, endrec):
"""
Read the ZIP64 end-of-archive records and use that to update endrec
"""
try:
fpin.seek(offset - sizeEndCentDir64Locator, 2)
except IOError:
# If the seek fails, the file is not large enough to contain a ZIP64
# end-of-archive recor... | python | {
"resource": ""
} |
q53272 | ADUser.user | train | def user(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False):
"""Produces a single, populated ADUser object through the object factory.
Does not populate attributes for the caller instance.
:param str base_dn: The base DN to search within
:param str samaccountn... | python | {
"resource": ""
} |
q53273 | ADUser.users | train | def users(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False):
"""Gathers a list of ADUser objects
:param str base_dn: The base DN to search within
:param list attributes: Object attributes to populate, defaults to all
:param list samaccountnames: A list of... | python | {
"resource": ""
} |
q53274 | canonizePath | train | def canonizePath(path):
"""Returns the absolute, normalized, real path of something.
This takes care of symbolic links, redundant separators, etc."""
return os.path.abspath(os.path.normpath(os.path.realpath(path))) | python | {
"resource": ""
} |
q53275 | signal | train | def signal(sig, action):
"""
The point of this module and method is to decouple signal handlers from
each other. Standard way to deal with handlers is to always store the old
handler and call it. It creates a chain of handlers, making it impossible
to later remove the handler.
This method behav... | python | {
"resource": ""
} |
q53276 | reset | train | def reset():
"""
Clear global data and remove the handlers.
CAUSION! This method sets as a signal handlers the ones which it has
noticed on initialization time. If there has been another handler installed
on top of us it will get removed by this method call.
"""
global _handlers, python_sign... | python | {
"resource": ""
} |
q53277 | Cmd.safe_mkdir | train | def safe_mkdir(self, d):
"""If a directory doesn't exist, create it.
If it does exist, print a warning to the logger.
If it exists as a file, rais a FileExistsError
:param d: directory path to create
:type d: str
"""
if os.path.isfile(d):
raise FileE... | python | {
"resource": ""
} |
q53278 | Cmd.mk_tmpl | train | def mk_tmpl(self, path, tmpl, ctx, mode=None):
"""Create a file from a template if it doesn't already exist.
"""
path = os.path.abspath(path)
if os.path.isfile(path):
logger.warning("File %s already exists, not creating it.", tmpl)
with open(path, 'w') as fd:
... | python | {
"resource": ""
} |
q53279 | Wait.until | train | def until(self, condition, is_true=None, message=""):
"""Repeatedly runs condition until its return value evalutes to true,
or its timeout expires or the predicate evaluates to true.
This will poll at the given interval until the given timeout
is reached, or the predicate or conditions ... | python | {
"resource": ""
} |
q53280 | gzipped | train | def gzipped(fn):
"""
Decorator used to pack data returned from the Bottle function to GZIP.
The decorator adds GZIP compression only if the browser accepts GZIP in
it's ``Accept-Encoding`` headers. In that case, also the correct
``Content-Encoding`` is used.
"""
def gzipped_wrapper(*args, *... | python | {
"resource": ""
} |
q53281 | gzip_cache | train | def gzip_cache(path):
"""
Another GZIP handler for Bottle functions. This may be used to cache the
files statically on the disc on given `path`.
If the browser accepts GZIP and there is file at ``path + ".gz"``, this
file is returned, correct headers are set (Content-Encoding, Last-Modified,
Co... | python | {
"resource": ""
} |
q53282 | in_template_path | train | def in_template_path(fn):
"""
Return `fn` in template context, or in other words add `fn` to template
path, so you don't need to write absolute path of `fn` in template
directory manually.
Args:
fn (str): Name of the file in template dir.
Return:
str: Absolute path to the file.... | python | {
"resource": ""
} |
q53283 | getcolor | train | def getcolor(spec):
"""
Turn optional color string spec into an array.
"""
if isinstance(spec, str):
from matplotlib import colors
return asarray(colors.hex2color(colors.cnames[spec]))
else:
return spec | python | {
"resource": ""
} |
q53284 | getcolors | train | def getcolors(spec, n, cmap=None, value=None):
"""
Turn list of color specs into list of arrays.
"""
if cmap is not None and spec is not None:
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.cm import get_cmap
if isinstance(cmap, LinearSegmentedColormap):
... | python | {
"resource": ""
} |
q53285 | getbase | train | def getbase(base=None, dims=None, extent=None, background=None):
"""
Construct a base array from optional arguments.
"""
if dims is not None:
extent = dims
if base is None and background is None:
return ones(tuple(extent) + (3,))
elif base is None and background is not None:
... | python | {
"resource": ""
} |
q53286 | one.hull | train | def hull(self):
"""
Bounding polygon as a convex hull.
"""
from scipy.spatial import ConvexHull
if len(self.coordinates) >= 4:
inds = ConvexHull(self.coordinates).vertices
return self.coordinates[inds]
else:
return self.coordinates | python | {
"resource": ""
} |
q53287 | one.bbox | train | def bbox(self):
"""
Bounding box as minimum and maximum coordinates.
"""
mn = amin(self.coordinates, axis=0)
mx = amax(self.coordinates, axis=0)
return concatenate((mn, mx)) | python | {
"resource": ""
} |
q53288 | one.distance | train | def distance(self, other):
"""
Distance between the center of this region and another.
Parameters
----------
other : one region, or array-like
Either another region, or the center of another region.
"""
from numpy.linalg import norm
if isinsta... | python | {
"resource": ""
} |
q53289 | one.merge | train | def merge(self, other):
"""
Combine this region with other.
"""
if not isinstance(other, one):
other = one(other)
new = concatenate((self.coordinates, other.coordinates))
unique = set([tuple(x) for x in new.tolist()])
final = asarray([list(x) for x in ... | python | {
"resource": ""
} |
q53290 | one.crop | train | def crop(self, min, max):
"""
Crop a region by removing coordinates outside bounds.
Follows normal slice indexing conventions.
Parameters
----------
min : tuple
Minimum or starting bounds for each axis.
max : tuple
Maximum or ending boun... | python | {
"resource": ""
} |
q53291 | one.inbounds | train | def inbounds(self, min, max):
"""
Check if a region falls entirely inside bounds.
Parameters
----------
min : tuple
Minimum bound to check for each axis.
max : tuple
Maximum bound to check for each axis.
"""
mincheck = sum(self.co... | python | {
"resource": ""
} |
q53292 | one.overlap | train | def overlap(self, other, method='fraction'):
"""
Compute the overlap between this region and another.
Optional methods are a symmetric measure of overlap based on the fraction
of intersecting pixels relative to the union ('fraction'),
or an assymmetric measure of overlap using ... | python | {
"resource": ""
} |
q53293 | one.dilate | train | def dilate(self, size):
"""
Dilate a region using morphological operators.
Parameters
----------
size : int
Size of dilation in pixels
"""
if size > 0:
from scipy.ndimage.morphology import binary_dilation
size = (size * 2) + 1
... | python | {
"resource": ""
} |
q53294 | one.exclude | train | def exclude(self, other):
"""
Remove coordinates from another region or an array.
If other is an array, will remove coordinates of all
non-zero elements from this region. If other is a region,
will remove any matching coordinates.
Parameters
----------
o... | python | {
"resource": ""
} |
q53295 | one.outline | train | def outline(self, inner, outer):
"""
Compute region outline by differencing two dilations.
Parameters
----------
inner : int
Size of inner outline boundary (in pixels)
outer : int
Size of outer outline boundary (in pixels)
"""
ret... | python | {
"resource": ""
} |
q53296 | PlaceholderHandler.set_placeholder_dropdown | train | def set_placeholder_dropdown(cls, input_el):
"""
Set the element to show the multiple choice text.
"""
text = cls.get_placeholder_text(input_el)
cls.set_placeholder_text(
input_el=input_el,
text=text + cls._dropdown_text
) | python | {
"resource": ""
} |
q53297 | PlaceholderHandler.reset_placeholder_dropdown | train | def reset_placeholder_dropdown(cls, input_el):
"""
Reset the element back to default.
"""
text = cls.get_placeholder_text(input_el)
cls.set_placeholder_text(
input_el=input_el,
text=text.replace(cls._dropdown_text, "")
) | python | {
"resource": ""
} |
q53298 | DefaultRenderer.addOption | train | def addOption(classobj, name, default, dtype=str, doc=None):
"""Adds a renderer option named 'name', with the given default value.
'dtype' must be a callable to convert a string to an option.
'doc' is a doc string.
Options will be initialized from config file here.
"""
# ... | python | {
"resource": ""
} |
q53299 | get_site_decorator | train | def get_site_decorator(site_param='site', obj_param='obj', context_param='context'):
''' It is a function that returns decorator factory useful for PluggableSite
views. This decorator factory returns decorator that do some
boilerplate work and make writing PluggableSite views easier.
It pass... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.