repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
load-tools/netort | netort/process.py | execute | def execute(cmd, shell=False, poll_period=1.0, catch_out=False):
"""Execute UNIX command and wait for its completion
Args:
cmd (str or list): command to execute
shell (bool): invoke inside shell environment
catch_out (bool): collect process' output
Returns:
returncode (... | python | def execute(cmd, shell=False, poll_period=1.0, catch_out=False):
"""Execute UNIX command and wait for its completion
Args:
cmd (str or list): command to execute
shell (bool): invoke inside shell environment
catch_out (bool): collect process' output
Returns:
returncode (... | [
"def",
"execute",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"poll_period",
"=",
"1.0",
",",
"catch_out",
"=",
"False",
")",
":",
"# FIXME: move to module level",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log",
".",
"debug",
"(",
... | Execute UNIX command and wait for its completion
Args:
cmd (str or list): command to execute
shell (bool): invoke inside shell environment
catch_out (bool): collect process' output
Returns:
returncode (int): process return code
stdout (str): collected process stdout... | [
"Execute",
"UNIX",
"command",
"and",
"wait",
"for",
"its",
"completion"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/process.py#L8-L49 |
sdispater/cachy | cachy/stores/file_store.py | FileStore._get_payload | def _get_payload(self, key):
"""
Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict
"""
path = self._path(key)
# If the file doesn't exists, we obviously can't return the cache so we will
... | python | def _get_payload(self, key):
"""
Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict
"""
path = self._path(key)
# If the file doesn't exists, we obviously can't return the cache so we will
... | [
"def",
"_get_payload",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"self",
".",
"_path",
"(",
"key",
")",
"# If the file doesn't exists, we obviously can't return the cache so we will",
"# just return null. Otherwise, we'll get the contents of the file and get",
"# the expira... | Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict | [
"Retrieve",
"an",
"item",
"and",
"expiry",
"time",
"from",
"the",
"cache",
"by",
"key",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L45-L82 |
sdispater/cachy | cachy/stores/file_store.py | FileStore.put | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"value",
"=",
"encode",
"(",
"str",
"(",
"self",
".",
"_expiration",
"(",
"minutes",
")",
")",
")",
"+",
"encode",
"(",
"self",
".",
"serialize",
"(",
"value",
")",
")... | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L84-L103 |
sdispater/cachy | cachy/stores/file_store.py | FileStore.increment | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
raw = self._get_payload(key)
integer... | python | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
raw = self._get_payload(key)
integer... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"raw",
"=",
"self",
".",
"_get_payload",
"(",
"key",
")",
"integer",
"=",
"int",
"(",
"raw",
"[",
"'data'",
"]",
")",
"+",
"value",
"self",
".",
"put",
"(",
"key",
"... | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | [
"Increment",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L114-L132 |
sdispater/cachy | cachy/stores/file_store.py | FileStore.forget | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
path = self._path(key)
if os.path.exists(path):
os.remove(path)
return True
return False | python | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
path = self._path(key)
if os.path.exists(path):
os.remove(path)
return True
return False | [
"def",
"forget",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"self",
".",
"_path",
"(",
"key",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")",
"return",
"True",
"return",
"False"
] | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | [
"Remove",
"an",
"item",
"from",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L160-L176 |
sdispater/cachy | cachy/stores/file_store.py | FileStore.flush | def flush(self):
"""
Remove all items from the cache.
"""
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name ... | python | def flush(self):
"""
Remove all items from the cache.
"""
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name ... | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"_directory",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"_directory",
",",
"topdown",
"=",
"False... | Remove all items from the cache. | [
"Remove",
"all",
"items",
"from",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L178-L188 |
sdispater/cachy | cachy/stores/file_store.py | FileStore._path | def _path(self, key):
"""
Get the full path for the given cache key.
:param key: The cache key
:type key: str
:rtype: str
"""
hash_type, parts_count = self._HASHES[self._hash_type]
h = hash_type(encode(key)).hexdigest()
parts = [h[i:i+2] for i i... | python | def _path(self, key):
"""
Get the full path for the given cache key.
:param key: The cache key
:type key: str
:rtype: str
"""
hash_type, parts_count = self._HASHES[self._hash_type]
h = hash_type(encode(key)).hexdigest()
parts = [h[i:i+2] for i i... | [
"def",
"_path",
"(",
"self",
",",
"key",
")",
":",
"hash_type",
",",
"parts_count",
"=",
"self",
".",
"_HASHES",
"[",
"self",
".",
"_hash_type",
"]",
"h",
"=",
"hash_type",
"(",
"encode",
"(",
"key",
")",
")",
".",
"hexdigest",
"(",
")",
"parts",
"... | Get the full path for the given cache key.
:param key: The cache key
:type key: str
:rtype: str | [
"Get",
"the",
"full",
"path",
"for",
"the",
"given",
"cache",
"key",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/file_store.py#L190-L204 |
load-tools/netort | netort/resource.py | ResourceManager.resource_string | def resource_string(self, path):
"""
Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
string, file content
"""
opener = self.get_opener(path)
filename = opener.get_filename
try:
size = os.pat... | python | def resource_string(self, path):
"""
Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
string, file content
"""
opener = self.get_opener(path)
filename = opener.get_filename
try:
size = os.pat... | [
"def",
"resource_string",
"(",
"self",
",",
"path",
")",
":",
"opener",
"=",
"self",
".",
"get_opener",
"(",
"path",
")",
"filename",
"=",
"opener",
".",
"get_filename",
"try",
":",
"size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
... | Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
string, file content | [
"Args",
":",
"path",
":",
"str",
"resource",
"file",
"url",
"or",
"resource",
"file",
"absolute",
"/",
"relative",
"path",
"."
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/resource.py#L63-L83 |
load-tools/netort | netort/resource.py | ResourceManager.get_opener | def get_opener(self, path):
"""
Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
file object
"""
self.path = path
opener = None
# FIXME this parser/matcher should use `urlparse` stdlib
for opener... | python | def get_opener(self, path):
"""
Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
file object
"""
self.path = path
opener = None
# FIXME this parser/matcher should use `urlparse` stdlib
for opener... | [
"def",
"get_opener",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"path",
"=",
"path",
"opener",
"=",
"None",
"# FIXME this parser/matcher should use `urlparse` stdlib",
"for",
"opener_name",
",",
"signature",
"in",
"self",
".",
"openers",
".",
"items",
"(",... | Args:
path: str, resource file url or resource file absolute/relative path.
Returns:
file object | [
"Args",
":",
"path",
":",
"str",
"resource",
"file",
"url",
"or",
"resource",
"file",
"absolute",
"/",
"relative",
"path",
"."
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/resource.py#L85-L102 |
sdispater/cachy | cachy/contracts/taggable_store.py | TaggableStore.tags | def tags(self, *names):
"""
Begin executing a new tags operation.
:param names: The tags
:type names: tuple
:rtype: cachy.tagged_cache.TaggedCache
"""
if len(names) == 1 and isinstance(names[0], list):
names = names[0]
return TaggedCache(sel... | python | def tags(self, *names):
"""
Begin executing a new tags operation.
:param names: The tags
:type names: tuple
:rtype: cachy.tagged_cache.TaggedCache
"""
if len(names) == 1 and isinstance(names[0], list):
names = names[0]
return TaggedCache(sel... | [
"def",
"tags",
"(",
"self",
",",
"*",
"names",
")",
":",
"if",
"len",
"(",
"names",
")",
"==",
"1",
"and",
"isinstance",
"(",
"names",
"[",
"0",
"]",
",",
"list",
")",
":",
"names",
"=",
"names",
"[",
"0",
"]",
"return",
"TaggedCache",
"(",
"se... | Begin executing a new tags operation.
:param names: The tags
:type names: tuple
:rtype: cachy.tagged_cache.TaggedCache | [
"Begin",
"executing",
"a",
"new",
"tags",
"operation",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/contracts/taggable_store.py#L10-L22 |
inveniosoftware/invenio-logging | invenio_logging/sentry6.py | Sentry6.get_user_info | def get_user_info(self, request):
"""Implement custom getter."""
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY... | python | def get_user_info(self, request):
"""Implement custom getter."""
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY... | [
"def",
"get_user_info",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"{",
"}",
"user_info",
"=",
"{",
"'id'",
":",
"current_user",
".",
"get_id",
"(",
")",
",",
"}",
"if",
"'SENTRY_USER_ATTRS'"... | Implement custom getter. | [
"Implement",
"custom",
"getter",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/sentry6.py#L21-L35 |
load-tools/netort | netort/data_manager/clients/luna.py | LunaClient.create_job | def create_job(self):
""" Create public Luna job
Returns:
job_id (basestring): Luna job id
"""
my_user_agent = None
try:
my_user_agent = pkg_resources.require('netort')[0].version
except pkg_resources.DistributionNotFound:
my_user_agen... | python | def create_job(self):
""" Create public Luna job
Returns:
job_id (basestring): Luna job id
"""
my_user_agent = None
try:
my_user_agent = pkg_resources.require('netort')[0].version
except pkg_resources.DistributionNotFound:
my_user_agen... | [
"def",
"create_job",
"(",
"self",
")",
":",
"my_user_agent",
"=",
"None",
"try",
":",
"my_user_agent",
"=",
"pkg_resources",
".",
"require",
"(",
"'netort'",
")",
"[",
"0",
"]",
".",
"version",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"my... | Create public Luna job
Returns:
job_id (basestring): Luna job id | [
"Create",
"public",
"Luna",
"job"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/clients/luna.py#L89-L130 |
load-tools/netort | netort/data_manager/manager.py | DataManager.new_metric | def new_metric(self, meta):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
type_ = meta.get('type')
if not type_:
raise ValueEr... | python | def new_metric(self, meta):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
type_ = meta.get('type')
if not type_:
raise ValueEr... | [
"def",
"new_metric",
"(",
"self",
",",
"meta",
")",
":",
"type_",
"=",
"meta",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"type_",
":",
"raise",
"ValueError",
"(",
"'Metric type should be defined.'",
")",
"if",
"type_",
"in",
"available_metrics",
":",
"m... | Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric | [
"Create",
"and",
"register",
"metric",
"find",
"subscribers",
"for",
"this",
"metric",
"(",
"using",
"meta",
"as",
"filter",
")",
"and",
"subscribe"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/manager.py#L172-L203 |
load-tools/netort | netort/data_manager/manager.py | DataManager.new_tank_metric | def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
if not _type:
... | python | def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw):
"""
Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric
"""
if not _type:
... | [
"def",
"new_tank_metric",
"(",
"self",
",",
"_type",
",",
"name",
",",
"hostname",
"=",
"None",
",",
"group",
"=",
"None",
",",
"source",
"=",
"None",
",",
"*",
"kw",
")",
":",
"if",
"not",
"_type",
":",
"raise",
"ValueError",
"(",
"'Metric type should... | Create and register metric,
find subscribers for this metric (using meta as filter) and subscribe
Return:
metric (available_metrics[0]): one of Metric | [
"Create",
"and",
"register",
"metric",
"find",
"subscribers",
"for",
"this",
"metric",
"(",
"using",
"meta",
"as",
"filter",
")",
"and",
"subscribe"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/manager.py#L206-L243 |
load-tools/netort | netort/data_manager/manager.py | DataManager.subscribe | def subscribe(self, callback, filter_):
"""
Create and register metric subscriber,
find metrics for this subscriber (using filter_) and subscribe
Args:
callback (object method): subscriber's callback
filter_ (dict): filter dict
filter sample:
... | python | def subscribe(self, callback, filter_):
"""
Create and register metric subscriber,
find metrics for this subscriber (using filter_) and subscribe
Args:
callback (object method): subscriber's callback
filter_ (dict): filter dict
filter sample:
... | [
"def",
"subscribe",
"(",
"self",
",",
"callback",
",",
"filter_",
")",
":",
"sub_id",
"=",
"\"subscriber_{uuid}\"",
".",
"format",
"(",
"uuid",
"=",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# register subscriber in manager",
"sub",
"=",
"pd",
".",
"DataFrame",
... | Create and register metric subscriber,
find metrics for this subscriber (using filter_) and subscribe
Args:
callback (object method): subscriber's callback
filter_ (dict): filter dict
filter sample:
{'type': 'metrics', 'source': 'gun'} | [
"Create",
"and",
"register",
"metric",
"subscriber",
"find",
"metrics",
"for",
"this",
"subscriber",
"(",
"using",
"filter_",
")",
"and",
"subscribe"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/manager.py#L245-L273 |
load-tools/netort | netort/data_manager/manager.py | DataManager.__filter | def __filter(filterable, filter_, logic_operation='and'):
""" filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion"""
condition = []
if not filter_:
return filterable
elif filter_.get('ty... | python | def __filter(filterable, filter_, logic_operation='and'):
""" filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion"""
condition = []
if not filter_:
return filterable
elif filter_.get('ty... | [
"def",
"__filter",
"(",
"filterable",
",",
"filter_",
",",
"logic_operation",
"=",
"'and'",
")",
":",
"condition",
"=",
"[",
"]",
"if",
"not",
"filter_",
":",
"return",
"filterable",
"elif",
"filter_",
".",
"get",
"(",
"'type'",
")",
"==",
"'__ANY__'",
"... | filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion | [
"filtering",
"DataFrame",
"using",
"filter_",
"key",
"-",
"value",
"conditions",
"applying",
"logic_operation",
"only",
"find",
"rows",
"strictly",
"fitting",
"the",
"filter_",
"criterion"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/manager.py#L279-L295 |
load-tools/netort | netort/data_manager/manager.py | DataManager.__reversed_filter | def __reversed_filter(filterable, filter_, logic_operation='and'):
""" reverse filtering DataFrame using filter_ key-value conditions applying logic_operation
find rows where existing filterable columns (and its values) fitting the filter_ criterion"""
condition = []
try:
sub... | python | def __reversed_filter(filterable, filter_, logic_operation='and'):
""" reverse filtering DataFrame using filter_ key-value conditions applying logic_operation
find rows where existing filterable columns (and its values) fitting the filter_ criterion"""
condition = []
try:
sub... | [
"def",
"__reversed_filter",
"(",
"filterable",
",",
"filter_",
",",
"logic_operation",
"=",
"'and'",
")",
":",
"condition",
"=",
"[",
"]",
"try",
":",
"subscribers_for_any",
"=",
"filterable",
".",
"query",
"(",
"'type == \"__ANY__\"'",
")",
"except",
"pd",
".... | reverse filtering DataFrame using filter_ key-value conditions applying logic_operation
find rows where existing filterable columns (and its values) fitting the filter_ criterion | [
"reverse",
"filtering",
"DataFrame",
"using",
"filter_",
"key",
"-",
"value",
"conditions",
"applying",
"logic_operation",
"find",
"rows",
"where",
"existing",
"filterable",
"columns",
"(",
"and",
"its",
"values",
")",
"fitting",
"the",
"filter_",
"criterion"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_manager/manager.py#L298-L318 |
inveniosoftware/invenio-logging | invenio_logging/sentry.py | InvenioLoggingSentry.install_handler | def install_handler(self, app):
"""Install log handler."""
from raven.contrib.celery import register_logger_signal, \
register_signal
from raven.contrib.flask import Sentry, make_client
from raven.handlers.logging import SentryHandler
# Installs sentry in app.extensi... | python | def install_handler(self, app):
"""Install log handler."""
from raven.contrib.celery import register_logger_signal, \
register_signal
from raven.contrib.flask import Sentry, make_client
from raven.handlers.logging import SentryHandler
# Installs sentry in app.extensi... | [
"def",
"install_handler",
"(",
"self",
",",
"app",
")",
":",
"from",
"raven",
".",
"contrib",
".",
"celery",
"import",
"register_logger_signal",
",",
"register_signal",
"from",
"raven",
".",
"contrib",
".",
"flask",
"import",
"Sentry",
",",
"make_client",
"fro... | Install log handler. | [
"Install",
"log",
"handler",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/sentry.py#L56-L103 |
inveniosoftware/invenio-logging | invenio_logging/sentry.py | RequestIdProcessor.process | def process(self, data, **kwargs):
"""Process event data."""
data = super(RequestIdProcessor, self).process(data, **kwargs)
if g and hasattr(g, 'request_id'):
tags = data.get('tags', {})
tags['request_id'] = g.request_id
data['tags'] = tags
return data | python | def process(self, data, **kwargs):
"""Process event data."""
data = super(RequestIdProcessor, self).process(data, **kwargs)
if g and hasattr(g, 'request_id'):
tags = data.get('tags', {})
tags['request_id'] = g.request_id
data['tags'] = tags
return data | [
"def",
"process",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
"RequestIdProcessor",
",",
"self",
")",
".",
"process",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"g",
"and",
"hasattr",
"(",
"g",
",... | Process event data. | [
"Process",
"event",
"data",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/sentry.py#L109-L116 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.get | def get(self, key):
"""
Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value
"""
value = self._redis.get(self._prefix + key)
if value is not None:
return self.unserialize(value) | python | def get(self, key):
"""
Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value
"""
value = self._redis.get(self._prefix + key)
if value is not None:
return self.unserialize(value) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"_redis",
".",
"get",
"(",
"self",
".",
"_prefix",
"+",
"key",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"self",
".",
"unserialize",
"(",
"value",
")"
] | Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value | [
"Retrieve",
"an",
"item",
"from",
"the",
"cache",
"by",
"key",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L27-L39 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.put | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"value",
"=",
"self",
".",
"serialize",
"(",
"value",
")",
"minutes",
"=",
"max",
"(",
"1",
",",
"minutes",
")",
"self",
".",
"_redis",
".",
"setex",
"(",
"self",
".",... | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L41-L58 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.increment | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
return self._redis.incrby(self._prefix + key,... | python | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
return self._redis.incrby(self._prefix + key,... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"return",
"self",
".",
"_redis",
".",
"incrby",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
")"
] | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | [
"Increment",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L60-L72 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.decrement | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._redis.decr(self._prefix + key, v... | python | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._redis.decr(self._prefix + key, v... | [
"def",
"decrement",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"return",
"self",
".",
"_redis",
".",
"decr",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
")"
] | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool | [
"Decrement",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L74-L86 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.forever | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value to store
:type value: mixed
"""
value = self.serialize(value)
self._redis.set(self._prefix + key, value) | python | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value to store
:type value: mixed
"""
value = self.serialize(value)
self._redis.set(self._prefix + key, value) | [
"def",
"forever",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"serialize",
"(",
"value",
")",
"self",
".",
"_redis",
".",
"set",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
")"
] | Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value to store
:type value: mixed | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"indefinitely",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L88-L100 |
sdispater/cachy | cachy/stores/redis_store.py | RedisStore.forget | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
return bool(self._redis.delete(self._prefix + key)) | python | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
return bool(self._redis.delete(self._prefix + key)) | [
"def",
"forget",
"(",
"self",
",",
"key",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_redis",
".",
"delete",
"(",
"self",
".",
"_prefix",
"+",
"key",
")",
")"
] | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | [
"Remove",
"an",
"item",
"from",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/redis_store.py#L102-L111 |
sdispater/cachy | cachy/repository.py | Repository.get | def get(self, key, default=None):
"""
Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:param default: The default value to return
:type default: mixed
:rtype: mixed
"""
val = self._store.get(key)
if val ... | python | def get(self, key, default=None):
"""
Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:param default: The default value to return
:type default: mixed
:rtype: mixed
"""
val = self._store.get(key)
if val ... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"_store",
".",
"get",
"(",
"key",
")",
"if",
"val",
"is",
"None",
":",
"return",
"value",
"(",
"default",
")",
"return",
"val"
] | Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:param default: The default value to return
:type default: mixed
:rtype: mixed | [
"Retrieve",
"an",
"item",
"from",
"the",
"cache",
"by",
"key",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/repository.py#L35-L52 |
sdispater/cachy | cachy/repository.py | Repository.put | def put(self, key, val, minutes):
"""
Store an item in the cache.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime
"""
... | python | def put(self, key, val, minutes):
"""
Store an item in the cache.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime
"""
... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"val",
",",
"minutes",
")",
":",
"minutes",
"=",
"self",
".",
"_get_minutes",
"(",
"minutes",
")",
"if",
"minutes",
"is",
"not",
"None",
":",
"self",
".",
"_store",
".",
"put",
"(",
"key",
",",
"val",
"... | Store an item in the cache.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/repository.py#L72-L88 |
sdispater/cachy | cachy/repository.py | Repository.add | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|d... | python | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|d... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
",",
"minutes",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_store",
",",
"'add'",
")",
":",
"return",
"self",
".",
"_store",
".",
"add",
"(",
"key",
",",
"val",
",",
"self",
".",
"_get_minutes... | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime
:rtype: bool | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/repository.py#L90-L113 |
sdispater/cachy | cachy/repository.py | Repository._get_key | def _get_key(self, fn, args, kwargs):
"""
Calculate a cache key given a function, args and kwargs.
:param fn: The function
:type fn: callable or str
:param args: The function args
:type args: tuple
:param kwargs: The function kwargs
:type kwargs: dict
... | python | def _get_key(self, fn, args, kwargs):
"""
Calculate a cache key given a function, args and kwargs.
:param fn: The function
:type fn: callable or str
:param args: The function args
:type args: tuple
:param kwargs: The function kwargs
:type kwargs: dict
... | [
"def",
"_get_key",
"(",
"self",
",",
"fn",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"args",
":",
"serialized_arguments",
"=",
"(",
"self",
".",
"_store",
".",
"serialize",
"(",
"args",
"[",
"1",
":",
"]",
")",
"+",
"self",
".",
"_store",
".",
... | Calculate a cache key given a function, args and kwargs.
:param fn: The function
:type fn: callable or str
:param args: The function args
:type args: tuple
:param kwargs: The function kwargs
:type kwargs: dict
:rtype: str | [
"Calculate",
"a",
"cache",
"key",
"given",
"a",
"function",
"args",
"and",
"kwargs",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/repository.py#L262-L297 |
openprocurement/openprocurement.client.python | openprocurement_client/client.py | APIBaseClient.patch | def patch(self, path=None, payload=None, headers=None,
params_dict=None, **params):
""" HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP requ... | python | def patch(self, path=None, payload=None, headers=None,
params_dict=None, **params):
""" HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP requ... | [
"def",
"patch",
"(",
"self",
",",
"path",
"=",
"None",
",",
"payload",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"params_dict",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"PATCH\"",
",",
"path",
"=... | HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request | [
"HTTP",
"PATCH"
] | train | https://github.com/openprocurement/openprocurement.client.python/blob/5dcd0bfac53dc802ae8f144361586278e3cee5ac/openprocurement_client/client.py#L96-L108 |
openprocurement/openprocurement.client.python | openprocurement_client/client.py | APIBaseClient.delete | def delete(self, path=None, headers=None):
""" HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("DELETE",... | python | def delete(self, path=None, headers=None):
""" HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("DELETE",... | [
"def",
"delete",
"(",
"self",
",",
"path",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"DELETE\"",
",",
"path",
"=",
"path",
",",
"headers",
"=",
"headers",
")"
] | HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request | [
"HTTP",
"DELETE",
"-",
"path",
":",
"string",
"additionnal",
"path",
"to",
"the",
"uri",
"-",
"headers",
":",
"dict",
"optionnal",
"headers",
"that",
"will",
"be",
"added",
"to",
"HTTP",
"request",
".",
"-",
"params",
":",
"Optionnal",
"parameterss",
"adde... | train | https://github.com/openprocurement/openprocurement.client.python/blob/5dcd0bfac53dc802ae8f144361586278e3cee5ac/openprocurement_client/client.py#L110-L117 |
xlcteam/pynxc | pynxc/second_pass.py | SecondPassVisitor.flush_main | def flush_main(self):
"""Flushes the implicit main function if there is no main
function defined."""
if self.has_main:
return
self.in_main = True
self.write('task main()')
self.INDENT()
if self.debug:
print 'Flushing main:', self.fv.mai... | python | def flush_main(self):
"""Flushes the implicit main function if there is no main
function defined."""
if self.has_main:
return
self.in_main = True
self.write('task main()')
self.INDENT()
if self.debug:
print 'Flushing main:', self.fv.mai... | [
"def",
"flush_main",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_main",
":",
"return",
"self",
".",
"in_main",
"=",
"True",
"self",
".",
"write",
"(",
"'task main()'",
")",
"self",
".",
"INDENT",
"(",
")",
"if",
"self",
".",
"debug",
":",
"print",... | Flushes the implicit main function if there is no main
function defined. | [
"Flushes",
"the",
"implicit",
"main",
"function",
"if",
"there",
"is",
"no",
"main",
"function",
"defined",
"."
] | train | https://github.com/xlcteam/pynxc/blob/8932d3a7c0962577c8ead220621f63f800e3b411/pynxc/second_pass.py#L659-L679 |
sdispater/cachy | cachy/stores/memcached_store.py | MemcachedStore.put | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"self",
".",
"_memcache",
".",
"set",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
",",
"minutes",
"*",
"60",
")"
] | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/memcached_store.py#L34-L47 |
sdispater/cachy | cachy/stores/memcached_store.py | MemcachedStore.add | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
... | python | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
",",
"minutes",
")",
":",
"return",
"self",
".",
"_memcache",
".",
"add",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"val",
",",
"minutes",
"*",
"60",
")"
] | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
:rtype: bool | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/memcached_store.py#L49-L64 |
sdispater/cachy | cachy/stores/memcached_store.py | MemcachedStore.increment | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
return self._memcache.incr(self._prefix + key... | python | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
return self._memcache.incr(self._prefix + key... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"return",
"self",
".",
"_memcache",
".",
"incr",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
")"
] | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | [
"Increment",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/memcached_store.py#L66-L78 |
sdispater/cachy | cachy/stores/memcached_store.py | MemcachedStore.decrement | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._memcache.decr(self._prefix + key... | python | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._memcache.decr(self._prefix + key... | [
"def",
"decrement",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"return",
"self",
".",
"_memcache",
".",
"decr",
"(",
"self",
".",
"_prefix",
"+",
"key",
",",
"value",
")"
] | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool | [
"Decrement",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/memcached_store.py#L80-L92 |
load-tools/netort | netort/data_processing.py | get_nowait_from_queue | def get_nowait_from_queue(queue):
""" Collect all immediately available items from a queue """
data = []
for _ in range(queue.qsize()):
try:
data.append(queue.get_nowait())
except q.Empty:
break
return data | python | def get_nowait_from_queue(queue):
""" Collect all immediately available items from a queue """
data = []
for _ in range(queue.qsize()):
try:
data.append(queue.get_nowait())
except q.Empty:
break
return data | [
"def",
"get_nowait_from_queue",
"(",
"queue",
")",
":",
"data",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"queue",
".",
"qsize",
"(",
")",
")",
":",
"try",
":",
"data",
".",
"append",
"(",
"queue",
".",
"get_nowait",
"(",
")",
")",
"except",
... | Collect all immediately available items from a queue | [
"Collect",
"all",
"immediately",
"available",
"items",
"from",
"a",
"queue"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_processing.py#L10-L18 |
sdispater/cachy | cachy/redis_tagged_cache.py | RedisTaggedCache.forever | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed
"""
namespace = self._tags.get_namespace()
self._push_forever_keys(namespace, key)
... | python | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed
"""
namespace = self._tags.get_namespace()
self._push_forever_keys(namespace, key)
... | [
"def",
"forever",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"namespace",
"=",
"self",
".",
"_tags",
".",
"get_namespace",
"(",
")",
"self",
".",
"_push_forever_keys",
"(",
"namespace",
",",
"key",
")",
"self",
".",
"_store",
".",
"forever",
"(",... | Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"indefinitely",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/redis_tagged_cache.py#L10-L27 |
sdispater/cachy | cachy/redis_tagged_cache.py | RedisTaggedCache._push_forever_keys | def _push_forever_keys(self, namespace, key):
"""
Store a copy of the full key for each namespace segment.
:type namespace: str
:type key: str
"""
full_key = '%s%s:%s' % (self.get_prefix(),
hashlib.sha1(encode(self._tags.get_namespace())).... | python | def _push_forever_keys(self, namespace, key):
"""
Store a copy of the full key for each namespace segment.
:type namespace: str
:type key: str
"""
full_key = '%s%s:%s' % (self.get_prefix(),
hashlib.sha1(encode(self._tags.get_namespace())).... | [
"def",
"_push_forever_keys",
"(",
"self",
",",
"namespace",
",",
"key",
")",
":",
"full_key",
"=",
"'%s%s:%s'",
"%",
"(",
"self",
".",
"get_prefix",
"(",
")",
",",
"hashlib",
".",
"sha1",
"(",
"encode",
"(",
"self",
".",
"_tags",
".",
"get_namespace",
... | Store a copy of the full key for each namespace segment.
:type namespace: str
:type key: str | [
"Store",
"a",
"copy",
"of",
"the",
"full",
"key",
"for",
"each",
"namespace",
"segment",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/redis_tagged_cache.py#L37-L49 |
sdispater/cachy | cachy/redis_tagged_cache.py | RedisTaggedCache._delete_forever_keys | def _delete_forever_keys(self):
"""
Delete all of the items that were stored forever.
"""
for segment in self._tags.get_namespace().split('|'):
segment = self._forever_key(segment)
self._delete_forever_values(segment)
self._store.connection().delete(s... | python | def _delete_forever_keys(self):
"""
Delete all of the items that were stored forever.
"""
for segment in self._tags.get_namespace().split('|'):
segment = self._forever_key(segment)
self._delete_forever_values(segment)
self._store.connection().delete(s... | [
"def",
"_delete_forever_keys",
"(",
"self",
")",
":",
"for",
"segment",
"in",
"self",
".",
"_tags",
".",
"get_namespace",
"(",
")",
".",
"split",
"(",
"'|'",
")",
":",
"segment",
"=",
"self",
".",
"_forever_key",
"(",
"segment",
")",
"self",
".",
"_del... | Delete all of the items that were stored forever. | [
"Delete",
"all",
"of",
"the",
"items",
"that",
"were",
"stored",
"forever",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/redis_tagged_cache.py#L51-L59 |
sdispater/cachy | cachy/redis_tagged_cache.py | RedisTaggedCache._delete_forever_values | def _delete_forever_values(self, forever_key):
"""
Delete all of the keys that have been stored forever.
:type forever_key: str
"""
forever = self._store.connection().lrange(forever_key, 0, -1)
if len(forever) > 0:
self._store.connection().delete(*forever) | python | def _delete_forever_values(self, forever_key):
"""
Delete all of the keys that have been stored forever.
:type forever_key: str
"""
forever = self._store.connection().lrange(forever_key, 0, -1)
if len(forever) > 0:
self._store.connection().delete(*forever) | [
"def",
"_delete_forever_values",
"(",
"self",
",",
"forever_key",
")",
":",
"forever",
"=",
"self",
".",
"_store",
".",
"connection",
"(",
")",
".",
"lrange",
"(",
"forever_key",
",",
"0",
",",
"-",
"1",
")",
"if",
"len",
"(",
"forever",
")",
">",
"0... | Delete all of the keys that have been stored forever.
:type forever_key: str | [
"Delete",
"all",
"of",
"the",
"keys",
"that",
"have",
"been",
"stored",
"forever",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/redis_tagged_cache.py#L61-L70 |
inveniosoftware/invenio-logging | invenio_logging/ext.py | InvenioLoggingBase.capture_pywarnings | def capture_pywarnings(handler):
"""Log python system warnings."""
logger = logging.getLogger('py.warnings')
# Check for previously installed handlers.
for h in logger.handlers:
if isinstance(h, handler.__class__):
return
logger.addHandler(handler)
... | python | def capture_pywarnings(handler):
"""Log python system warnings."""
logger = logging.getLogger('py.warnings')
# Check for previously installed handlers.
for h in logger.handlers:
if isinstance(h, handler.__class__):
return
logger.addHandler(handler)
... | [
"def",
"capture_pywarnings",
"(",
"handler",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'py.warnings'",
")",
"# Check for previously installed handlers.",
"for",
"h",
"in",
"logger",
".",
"handlers",
":",
"if",
"isinstance",
"(",
"h",
",",
"hand... | Log python system warnings. | [
"Log",
"python",
"system",
"warnings",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/ext.py#L34-L42 |
sdispater/cachy | cachy/stores/dict_store.py | DictStore._get_payload | def _get_payload(self, key):
"""
Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict
"""
payload = self._storage.get(key)
# If the key does not exist, we return nothing
if not payload:
... | python | def _get_payload(self, key):
"""
Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict
"""
payload = self._storage.get(key)
# If the key does not exist, we return nothing
if not payload:
... | [
"def",
"_get_payload",
"(",
"self",
",",
"key",
")",
":",
"payload",
"=",
"self",
".",
"_storage",
".",
"get",
"(",
"key",
")",
"# If the key does not exist, we return nothing",
"if",
"not",
"payload",
":",
"return",
"(",
"None",
",",
"None",
")",
"expire",
... | Retrieve an item and expiry time from the cache by key.
:param key: The cache key
:type key: str
:rtype: dict | [
"Retrieve",
"an",
"item",
"and",
"expiry",
"time",
"from",
"the",
"cache",
"by",
"key",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/dict_store.py#L27-L58 |
sdispater/cachy | cachy/stores/dict_store.py | DictStore.put | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"self",
".",
"_storage",
"[",
"key",
"]",
"=",
"(",
"self",
".",
"_expiration",
"(",
"minutes",
")",
",",
"value",
")"
] | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/dict_store.py#L60-L73 |
sdispater/cachy | cachy/stores/dict_store.py | DictStore.increment | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
data, time_ = self._get_payload(key)
... | python | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
data, time_ = self._get_payload(key)
... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"data",
",",
"time_",
"=",
"self",
".",
"_get_payload",
"(",
"key",
")",
"integer",
"=",
"int",
"(",
"data",
")",
"+",
"value",
"self",
".",
"put",
"(",
"key",
",",
... | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | [
"Increment",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/dict_store.py#L75-L93 |
sdispater/cachy | cachy/stores/dict_store.py | DictStore.forget | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
if key in self._storage:
del self._storage[key]
return True
return False | python | def forget(self, key):
"""
Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool
"""
if key in self._storage:
del self._storage[key]
return True
return False | [
"def",
"forget",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_storage",
":",
"del",
"self",
".",
"_storage",
"[",
"key",
"]",
"return",
"True",
"return",
"False"
] | Remove an item from the cache.
:param key: The cache key
:type key: str
:rtype: bool | [
"Remove",
"an",
"item",
"from",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/stores/dict_store.py#L121-L135 |
fabaff/python-netdata | netdata/__init__.py | Netdata.get_data | async def get_data(self, resource):
"""Get detail for a resource from the data endpoint."""
url = '{}{}'.format(
self.base_url, self.endpoint.format(resource=resource))
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.ge... | python | async def get_data(self, resource):
"""Get detail for a resource from the data endpoint."""
url = '{}{}'.format(
self.base_url, self.endpoint.format(resource=resource))
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.ge... | [
"async",
"def",
"get_data",
"(",
"self",
",",
"resource",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"endpoint",
".",
"format",
"(",
"resource",
"=",
"resource",
")",
")",
"try",
":",
"with",
"async... | Get detail for a resource from the data endpoint. | [
"Get",
"detail",
"for",
"a",
"resource",
"from",
"the",
"data",
"endpoint",
"."
] | train | https://github.com/fabaff/python-netdata/blob/bca5d58f84a0fc849b9bb16a00959a0b33d13a67/netdata/__init__.py#L39-L57 |
fabaff/python-netdata | netdata/__init__.py | Netdata.get_alarms | async def get_alarms(self):
"""Get alarms for a Netdata instance."""
url = '{}{}'.format(self.base_url, self.endpoint)
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(url)
_LOGGER.debug(
"Response f... | python | async def get_alarms(self):
"""Get alarms for a Netdata instance."""
url = '{}{}'.format(self.base_url, self.endpoint)
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(url)
_LOGGER.debug(
"Response f... | [
"async",
"def",
"get_alarms",
"(",
"self",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"endpoint",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
",",
"loop",
"=",
"self",
".",
... | Get alarms for a Netdata instance. | [
"Get",
"alarms",
"for",
"a",
"Netdata",
"instance",
"."
] | train | https://github.com/fabaff/python-netdata/blob/bca5d58f84a0fc849b9bb16a00959a0b33d13a67/netdata/__init__.py#L59-L75 |
inveniosoftware/invenio-logging | invenio_logging/utils.py | AddRequestIdFilter.filter | def filter(self, record):
"""If request_id is set in flask.g, add it to log record."""
if g and hasattr(g, 'request_id'):
record.request_id = g.request_id
return True | python | def filter(self, record):
"""If request_id is set in flask.g, add it to log record."""
if g and hasattr(g, 'request_id'):
record.request_id = g.request_id
return True | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"if",
"g",
"and",
"hasattr",
"(",
"g",
",",
"'request_id'",
")",
":",
"record",
".",
"request_id",
"=",
"g",
".",
"request_id",
"return",
"True"
] | If request_id is set in flask.g, add it to log record. | [
"If",
"request_id",
"is",
"set",
"in",
"flask",
".",
"g",
"add",
"it",
"to",
"log",
"record",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/utils.py#L19-L23 |
load-tools/netort | netort/logging_and_signals.py | init_logging | def init_logging(log_filename, verbose, quiet):
"""Set up logging with default parameters:
* default console logging level is INFO
* ERROR, WARNING and CRITICAL are redirected to stderr
Args:
log_filename (str): if set, will write DEBUG log there
verbose (bool): DEBUG level in console, ... | python | def init_logging(log_filename, verbose, quiet):
"""Set up logging with default parameters:
* default console logging level is INFO
* ERROR, WARNING and CRITICAL are redirected to stderr
Args:
log_filename (str): if set, will write DEBUG log there
verbose (bool): DEBUG level in console, ... | [
"def",
"init_logging",
"(",
"log_filename",
",",
"verbose",
",",
"quiet",
")",
":",
"# TODO: consider making one verbosity parameter instead of two mutually exclusive",
"# TODO: default values for parameters",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"''",
")",
"logge... | Set up logging with default parameters:
* default console logging level is INFO
* ERROR, WARNING and CRITICAL are redirected to stderr
Args:
log_filename (str): if set, will write DEBUG log there
verbose (bool): DEBUG level in console, overrides 'quiet'
quiet (bool): WARNING level i... | [
"Set",
"up",
"logging",
"with",
"default",
"parameters",
":",
"*",
"default",
"console",
"logging",
"level",
"is",
"INFO",
"*",
"ERROR",
"WARNING",
"and",
"CRITICAL",
"are",
"redirected",
"to",
"stderr"
] | train | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/logging_and_signals.py#L34-L100 |
sdispater/cachy | cachy/cache_manager.py | CacheManager.store | def store(self, name=None):
"""
Get a cache store instance by name.
:param name: The cache store name
:type name: str
:rtype: Repository
"""
if name is None:
name = self.get_default_driver()
self._stores[name] = self._get(name)
retu... | python | def store(self, name=None):
"""
Get a cache store instance by name.
:param name: The cache store name
:type name: str
:rtype: Repository
"""
if name is None:
name = self.get_default_driver()
self._stores[name] = self._get(name)
retu... | [
"def",
"store",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"get_default_driver",
"(",
")",
"self",
".",
"_stores",
"[",
"name",
"]",
"=",
"self",
".",
"_get",
"(",
"name",
")",
"ret... | Get a cache store instance by name.
:param name: The cache store name
:type name: str
:rtype: Repository | [
"Get",
"a",
"cache",
"store",
"instance",
"by",
"name",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L43-L57 |
sdispater/cachy | cachy/cache_manager.py | CacheManager._get | def _get(self, name):
"""
Attempt to get the store from the local cache.
:param name: The store name
:type name: str
:rtype: Repository
"""
return self._stores.get(name, self._resolve(name)) | python | def _get(self, name):
"""
Attempt to get the store from the local cache.
:param name: The store name
:type name: str
:rtype: Repository
"""
return self._stores.get(name, self._resolve(name)) | [
"def",
"_get",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_stores",
".",
"get",
"(",
"name",
",",
"self",
".",
"_resolve",
"(",
"name",
")",
")"
] | Attempt to get the store from the local cache.
:param name: The store name
:type name: str
:rtype: Repository | [
"Attempt",
"to",
"get",
"the",
"store",
"from",
"the",
"local",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L70-L79 |
sdispater/cachy | cachy/cache_manager.py | CacheManager._resolve | def _resolve(self, name):
"""
Resolve the given store
:param name: The store to resolve
:type name: str
:rtype: Repository
"""
config = self._get_config(name)
if not config:
raise RuntimeError('Cache store [%s] is not defined.' % name)
... | python | def _resolve(self, name):
"""
Resolve the given store
:param name: The store to resolve
:type name: str
:rtype: Repository
"""
config = self._get_config(name)
if not config:
raise RuntimeError('Cache store [%s] is not defined.' % name)
... | [
"def",
"_resolve",
"(",
"self",
",",
"name",
")",
":",
"config",
"=",
"self",
".",
"_get_config",
"(",
"name",
")",
"if",
"not",
"config",
":",
"raise",
"RuntimeError",
"(",
"'Cache store [%s] is not defined.'",
"%",
"name",
")",
"if",
"config",
"[",
"'dri... | Resolve the given store
:param name: The store to resolve
:type name: str
:rtype: Repository | [
"Resolve",
"the",
"given",
"store"
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L81-L107 |
sdispater/cachy | cachy/cache_manager.py | CacheManager._call_custom_creator | def _call_custom_creator(self, config):
"""
Call a custom driver creator.
:param config: The driver configuration
:type config: dict
:rtype: Repository
"""
creator = self._custom_creators[config['driver']](config)
if isinstance(creator, Store):
... | python | def _call_custom_creator(self, config):
"""
Call a custom driver creator.
:param config: The driver configuration
:type config: dict
:rtype: Repository
"""
creator = self._custom_creators[config['driver']](config)
if isinstance(creator, Store):
... | [
"def",
"_call_custom_creator",
"(",
"self",
",",
"config",
")",
":",
"creator",
"=",
"self",
".",
"_custom_creators",
"[",
"config",
"[",
"'driver'",
"]",
"]",
"(",
"config",
")",
"if",
"isinstance",
"(",
"creator",
",",
"Store",
")",
":",
"creator",
"="... | Call a custom driver creator.
:param config: The driver configuration
:type config: dict
:rtype: Repository | [
"Call",
"a",
"custom",
"driver",
"creator",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L109-L126 |
sdispater/cachy | cachy/cache_manager.py | CacheManager._create_file_driver | def _create_file_driver(self, config):
"""
Create an instance of the file cache driver.
:param config: The driver configuration
:type config: dict
:rtype: Repository
"""
kwargs = {
'directory': config['path']
}
if 'hash_type' in conf... | python | def _create_file_driver(self, config):
"""
Create an instance of the file cache driver.
:param config: The driver configuration
:type config: dict
:rtype: Repository
"""
kwargs = {
'directory': config['path']
}
if 'hash_type' in conf... | [
"def",
"_create_file_driver",
"(",
"self",
",",
"config",
")",
":",
"kwargs",
"=",
"{",
"'directory'",
":",
"config",
"[",
"'path'",
"]",
"}",
"if",
"'hash_type'",
"in",
"config",
":",
"kwargs",
"[",
"'hash_type'",
"]",
"=",
"config",
"[",
"'hash_type'",
... | Create an instance of the file cache driver.
:param config: The driver configuration
:type config: dict
:rtype: Repository | [
"Create",
"an",
"instance",
"of",
"the",
"file",
"cache",
"driver",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L139-L155 |
sdispater/cachy | cachy/cache_manager.py | CacheManager.get_default_driver | def get_default_driver(self):
"""
Get the default cache driver name.
:rtype: str
:raises: RuntimeError
"""
if 'default' in self._config:
return self._config['default']
if len(self._config['stores']) == 1:
return list(self._config['stores... | python | def get_default_driver(self):
"""
Get the default cache driver name.
:rtype: str
:raises: RuntimeError
"""
if 'default' in self._config:
return self._config['default']
if len(self._config['stores']) == 1:
return list(self._config['stores... | [
"def",
"get_default_driver",
"(",
"self",
")",
":",
"if",
"'default'",
"in",
"self",
".",
"_config",
":",
"return",
"self",
".",
"_config",
"[",
"'default'",
"]",
"if",
"len",
"(",
"self",
".",
"_config",
"[",
"'stores'",
"]",
")",
"==",
"1",
":",
"r... | Get the default cache driver name.
:rtype: str
:raises: RuntimeError | [
"Get",
"the",
"default",
"cache",
"driver",
"name",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L214-L228 |
sdispater/cachy | cachy/cache_manager.py | CacheManager._resolve_serializer | def _resolve_serializer(self, serializer):
"""
Resolve the given serializer.
:param serializer: The serializer to resolve
:type serializer: str or Serializer
:rtype: Serializer
"""
if isinstance(serializer, Serializer):
return serializer
if ... | python | def _resolve_serializer(self, serializer):
"""
Resolve the given serializer.
:param serializer: The serializer to resolve
:type serializer: str or Serializer
:rtype: Serializer
"""
if isinstance(serializer, Serializer):
return serializer
if ... | [
"def",
"_resolve_serializer",
"(",
"self",
",",
"serializer",
")",
":",
"if",
"isinstance",
"(",
"serializer",
",",
"Serializer",
")",
":",
"return",
"serializer",
"if",
"serializer",
"in",
"self",
".",
"_serializers",
":",
"return",
"self",
".",
"_serializers... | Resolve the given serializer.
:param serializer: The serializer to resolve
:type serializer: str or Serializer
:rtype: Serializer | [
"Resolve",
"the",
"given",
"serializer",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/cache_manager.py#L255-L270 |
SamLau95/nbinteract | nbinteract/questions.py | multiple_choice | def multiple_choice(question, choices, answers):
"""
Generates a multiple choice question that allows the user to select an
answer choice and shows whether choice was correct.
Args:
question (str): Question text displayed above choices.
choices (list str): Answer choices that user can ... | python | def multiple_choice(question, choices, answers):
"""
Generates a multiple choice question that allows the user to select an
answer choice and shows whether choice was correct.
Args:
question (str): Question text displayed above choices.
choices (list str): Answer choices that user can ... | [
"def",
"multiple_choice",
"(",
"question",
",",
"choices",
",",
"answers",
")",
":",
"if",
"not",
"isinstance",
"(",
"answers",
",",
"(",
"int",
",",
"collections",
".",
"Iterable",
")",
")",
":",
"raise",
"TypeError",
"(",
"'The `answers` arg is expected to b... | Generates a multiple choice question that allows the user to select an
answer choice and shows whether choice was correct.
Args:
question (str): Question text displayed above choices.
choices (list str): Answer choices that user can select.
answers (int | iterable int): Either an inte... | [
"Generates",
"a",
"multiple",
"choice",
"question",
"that",
"allows",
"the",
"user",
"to",
"select",
"an",
"answer",
"choice",
"and",
"shows",
"whether",
"choice",
"was",
"correct",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/questions.py#L15-L75 |
SamLau95/nbinteract | nbinteract/questions.py | short_answer | def short_answer(question, answers, explanation=None):
"""
Generates a short answer question that allows user to input an answer in
a textbox and a submit button to check the answer.
Args:
question (str): The question being asked.
answers (str | list str | func): If a string, only tha... | python | def short_answer(question, answers, explanation=None):
"""
Generates a short answer question that allows user to input an answer in
a textbox and a submit button to check the answer.
Args:
question (str): The question being asked.
answers (str | list str | func): If a string, only tha... | [
"def",
"short_answer",
"(",
"question",
",",
"answers",
",",
"explanation",
"=",
"None",
")",
":",
"# Input textbox",
"textbox",
"=",
"widgets",
".",
"Text",
"(",
"placeholder",
"=",
"'Write your answer here'",
")",
"# Submit button",
"submit_button",
"=",
"widget... | Generates a short answer question that allows user to input an answer in
a textbox and a submit button to check the answer.
Args:
question (str): The question being asked.
answers (str | list str | func): If a string, only that string will be
marked correct. If a list of string, a... | [
"Generates",
"a",
"short",
"answer",
"question",
"that",
"allows",
"user",
"to",
"input",
"an",
"answer",
"in",
"a",
"textbox",
"and",
"a",
"submit",
"button",
"to",
"check",
"the",
"answer",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/questions.py#L88-L159 |
SamLau95/nbinteract | nbinteract/exporters.py | publish | def publish(spec, nb_name, template='full', save_first=True):
"""
Converts nb_name to an HTML file. Preserves widget functionality.
Outputs a link to download HTML file after conversion if called in a
notebook environment.
Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line.
... | python | def publish(spec, nb_name, template='full', save_first=True):
"""
Converts nb_name to an HTML file. Preserves widget functionality.
Outputs a link to download HTML file after conversion if called in a
notebook environment.
Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line.
... | [
"def",
"publish",
"(",
"spec",
",",
"nb_name",
",",
"template",
"=",
"'full'",
",",
"save_first",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"nb_name",
")",
":",
"raise",
"ValueError",
"(",
"\"{} isn't a path to a file. Doub... | Converts nb_name to an HTML file. Preserves widget functionality.
Outputs a link to download HTML file after conversion if called in a
notebook environment.
Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line.
Args:
spec (str): BinderHub spec for Jupyter image. Must be i... | [
"Converts",
"nb_name",
"to",
"an",
"HTML",
"file",
".",
"Preserves",
"widget",
"functionality",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/exporters.py#L154-L215 |
SamLau95/nbinteract | nbinteract/exporters.py | _save_nb | def _save_nb(nb_name):
"""
Attempts to save notebook. If unsuccessful, shows a warning.
"""
display(Javascript('IPython.notebook.save_checkpoint();'))
display(Javascript('IPython.notebook.save_notebook();'))
print('Saving notebook...', end=' ')
if _wait_for_save(nb_name):
print("Sav... | python | def _save_nb(nb_name):
"""
Attempts to save notebook. If unsuccessful, shows a warning.
"""
display(Javascript('IPython.notebook.save_checkpoint();'))
display(Javascript('IPython.notebook.save_notebook();'))
print('Saving notebook...', end=' ')
if _wait_for_save(nb_name):
print("Sav... | [
"def",
"_save_nb",
"(",
"nb_name",
")",
":",
"display",
"(",
"Javascript",
"(",
"'IPython.notebook.save_checkpoint();'",
")",
")",
"display",
"(",
"Javascript",
"(",
"'IPython.notebook.save_notebook();'",
")",
")",
"print",
"(",
"'Saving notebook...'",
",",
"end",
"... | Attempts to save notebook. If unsuccessful, shows a warning. | [
"Attempts",
"to",
"save",
"notebook",
".",
"If",
"unsuccessful",
"shows",
"a",
"warning",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/exporters.py#L218-L233 |
SamLau95/nbinteract | nbinteract/exporters.py | _wait_for_save | def _wait_for_save(nb_name, timeout=5):
"""Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise.
"""
modification_time = os.path.getmtime(nb_name)
start_time = time.time()
while time.time() < start_time + timeout:
if (
... | python | def _wait_for_save(nb_name, timeout=5):
"""Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise.
"""
modification_time = os.path.getmtime(nb_name)
start_time = time.time()
while time.time() < start_time + timeout:
if (
... | [
"def",
"_wait_for_save",
"(",
"nb_name",
",",
"timeout",
"=",
"5",
")",
":",
"modification_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"nb_name",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
... | Waits for nb_name to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise. | [
"Waits",
"for",
"nb_name",
"to",
"update",
"waiting",
"up",
"to",
"TIMEOUT",
"seconds",
".",
"Returns",
"True",
"if",
"a",
"save",
"was",
"detected",
"and",
"False",
"otherwise",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/exporters.py#L236-L249 |
SamLau95/nbinteract | nbinteract/util.py | maybe_call | def maybe_call(maybe_fn, kwargs: dict, prefix: str = None) -> 'Any':
"""
If maybe_fn is a function, get its arguments from kwargs and call it, also
searching for prefixed kwargs if prefix is specified. Otherwise, return
maybe_fn.
Used to allow both functions and iterables to be passed into plotting... | python | def maybe_call(maybe_fn, kwargs: dict, prefix: str = None) -> 'Any':
"""
If maybe_fn is a function, get its arguments from kwargs and call it, also
searching for prefixed kwargs if prefix is specified. Otherwise, return
maybe_fn.
Used to allow both functions and iterables to be passed into plotting... | [
"def",
"maybe_call",
"(",
"maybe_fn",
",",
"kwargs",
":",
"dict",
",",
"prefix",
":",
"str",
"=",
"None",
")",
"->",
"'Any'",
":",
"if",
"not",
"callable",
"(",
"maybe_fn",
")",
":",
"return",
"maybe_fn",
"args",
"=",
"get_fn_args",
"(",
"maybe_fn",
",... | If maybe_fn is a function, get its arguments from kwargs and call it, also
searching for prefixed kwargs if prefix is specified. Otherwise, return
maybe_fn.
Used to allow both functions and iterables to be passed into plotting
functions.
>>> def square(x): return x * x
>>> maybe_call(square, {... | [
"If",
"maybe_fn",
"is",
"a",
"function",
"get",
"its",
"arguments",
"from",
"kwargs",
"and",
"call",
"it",
"also",
"searching",
"for",
"prefixed",
"kwargs",
"if",
"prefix",
"is",
"specified",
".",
"Otherwise",
"return",
"maybe_fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L12-L33 |
SamLau95/nbinteract | nbinteract/util.py | maybe_curry | def maybe_curry(maybe_fn, first_arg) -> 'Function | Any':
"""
If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn.
"""
if not callable(maybe_fn):
return maybe_fn
return tz.curry(maybe_fn)(first_arg) | python | def maybe_curry(maybe_fn, first_arg) -> 'Function | Any':
"""
If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn.
"""
if not callable(maybe_fn):
return maybe_fn
return tz.curry(maybe_fn)(first_arg) | [
"def",
"maybe_curry",
"(",
"maybe_fn",
",",
"first_arg",
")",
"->",
"'Function | Any'",
":",
"if",
"not",
"callable",
"(",
"maybe_fn",
")",
":",
"return",
"maybe_fn",
"return",
"tz",
".",
"curry",
"(",
"maybe_fn",
")",
"(",
"first_arg",
")"
] | If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn. | [
"If",
"maybe_fn",
"is",
"a",
"function",
"curries",
"it",
"and",
"passes",
"in",
"first_arg",
".",
"Otherwise",
"returns",
"maybe_fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L36-L43 |
SamLau95/nbinteract | nbinteract/util.py | get_fn_args | def get_fn_args(fn, kwargs: dict, prefix: str = None):
"""
Given function and a dict of kwargs return a dict containing only the args
used by the function.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if a require... | python | def get_fn_args(fn, kwargs: dict, prefix: str = None):
"""
Given function and a dict of kwargs return a dict containing only the args
used by the function.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if a require... | [
"def",
"get_fn_args",
"(",
"fn",
",",
"kwargs",
":",
"dict",
",",
"prefix",
":",
"str",
"=",
"None",
")",
":",
"all_args",
"=",
"get_all_args",
"(",
"fn",
")",
"required_args",
"=",
"get_required_args",
"(",
"fn",
")",
"fn_kwargs",
"=",
"pick_kwargs",
"(... | Given function and a dict of kwargs return a dict containing only the args
used by the function.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if a required arg is missing from the kwargs.
Raises ValueError if both pr... | [
"Given",
"function",
"and",
"a",
"dict",
"of",
"kwargs",
"return",
"a",
"dict",
"containing",
"only",
"the",
"args",
"used",
"by",
"the",
"function",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L51-L88 |
SamLau95/nbinteract | nbinteract/util.py | get_all_args | def get_all_args(fn) -> list:
"""
Returns a list of all arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_all_args(foo)
['x', 'y', 'z']
"""
sig = inspect.signature(fn)
return list(sig.parameters) | python | def get_all_args(fn) -> list:
"""
Returns a list of all arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_all_args(foo)
['x', 'y', 'z']
"""
sig = inspect.signature(fn)
return list(sig.parameters) | [
"def",
"get_all_args",
"(",
"fn",
")",
"->",
"list",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"fn",
")",
"return",
"list",
"(",
"sig",
".",
"parameters",
")"
] | Returns a list of all arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_all_args(foo)
['x', 'y', 'z'] | [
"Returns",
"a",
"list",
"of",
"all",
"arguments",
"for",
"the",
"function",
"fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L91-L100 |
SamLau95/nbinteract | nbinteract/util.py | get_required_args | def get_required_args(fn) -> list:
"""
Returns a list of required arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_required_args(foo)
['x', 'y']
>>> def bar(x, y=100, *args, **kwargs): return x
>>> get_required_args(bar)
['x']
"""
sig = inspect.... | python | def get_required_args(fn) -> list:
"""
Returns a list of required arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_required_args(foo)
['x', 'y']
>>> def bar(x, y=100, *args, **kwargs): return x
>>> get_required_args(bar)
['x']
"""
sig = inspect.... | [
"def",
"get_required_args",
"(",
"fn",
")",
"->",
"list",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"fn",
")",
"return",
"[",
"name",
"for",
"name",
",",
"param",
"in",
"sig",
".",
"parameters",
".",
"items",
"(",
")",
"if",
"param",
".",
... | Returns a list of required arguments for the function fn.
>>> def foo(x, y, z=100): return x + y + z
>>> get_required_args(foo)
['x', 'y']
>>> def bar(x, y=100, *args, **kwargs): return x
>>> get_required_args(bar)
['x'] | [
"Returns",
"a",
"list",
"of",
"required",
"arguments",
"for",
"the",
"function",
"fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L103-L119 |
SamLau95/nbinteract | nbinteract/util.py | pick_kwargs | def pick_kwargs(kwargs: dict, required_args: list, prefix: str = None):
"""
Given a dict of kwargs and a list of required_args, return a dict
containing only the args in required_args.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
R... | python | def pick_kwargs(kwargs: dict, required_args: list, prefix: str = None):
"""
Given a dict of kwargs and a list of required_args, return a dict
containing only the args in required_args.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
R... | [
"def",
"pick_kwargs",
"(",
"kwargs",
":",
"dict",
",",
"required_args",
":",
"list",
",",
"prefix",
":",
"str",
"=",
"None",
")",
":",
"picked",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"... | Given a dict of kwargs and a list of required_args, return a dict
containing only the args in required_args.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if both prefixed and unprefixed arg are given in kwargs.
>>> f... | [
"Given",
"a",
"dict",
"of",
"kwargs",
"and",
"a",
"list",
"of",
"required_args",
"return",
"a",
"dict",
"containing",
"only",
"the",
"args",
"in",
"required_args",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/util.py#L122-L163 |
SamLau95/nbinteract | nbinteract/plotting.py | _update_option_docstring | def _update_option_docstring(func, allowed, indent=' ' * 3):
"""
Updates docstring of func, filling in appearance of {options} with a
description of the options.
>>> def f(): '''{options}'''
>>> f = _update_option_docstring(f, ['title', 'xlim'])
>>> print(f.__doc__)
options (dict): Optio... | python | def _update_option_docstring(func, allowed, indent=' ' * 3):
"""
Updates docstring of func, filling in appearance of {options} with a
description of the options.
>>> def f(): '''{options}'''
>>> f = _update_option_docstring(f, ['title', 'xlim'])
>>> print(f.__doc__)
options (dict): Optio... | [
"def",
"_update_option_docstring",
"(",
"func",
",",
"allowed",
",",
"indent",
"=",
"' '",
"*",
"3",
")",
":",
"if",
"not",
"(",
"func",
".",
"__doc__",
"and",
"'{options}'",
"in",
"func",
".",
"__doc__",
")",
":",
"return",
"func",
"descriptions",
"=... | Updates docstring of func, filling in appearance of {options} with a
description of the options.
>>> def f(): '''{options}'''
>>> f = _update_option_docstring(f, ['title', 'xlim'])
>>> print(f.__doc__)
options (dict): Options for the plot. Available options:
<BLANKLINE>
title: T... | [
"Updates",
"docstring",
"of",
"func",
"filling",
"in",
"appearance",
"of",
"{",
"options",
"}",
"with",
"a",
"description",
"of",
"the",
"options",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L98-L120 |
SamLau95/nbinteract | nbinteract/plotting.py | use_options | def use_options(allowed):
"""
Decorator that logs warnings when unpermitted options are passed into its
wrapped function.
Requires that wrapped function has an keyword-only argument named
`options`. If wrapped function has {options} in its docstring, fills in
with the docs for allowed options.
... | python | def use_options(allowed):
"""
Decorator that logs warnings when unpermitted options are passed into its
wrapped function.
Requires that wrapped function has an keyword-only argument named
`options`. If wrapped function has {options} in its docstring, fills in
with the docs for allowed options.
... | [
"def",
"use_options",
"(",
"allowed",
")",
":",
"def",
"update_docstring",
"(",
"f",
")",
":",
"_update_option_docstring",
"(",
"f",
",",
"allowed",
")",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"check_options",
"(",
"*",
"args",
",",
"*",
... | Decorator that logs warnings when unpermitted options are passed into its
wrapped function.
Requires that wrapped function has an keyword-only argument named
`options`. If wrapped function has {options} in its docstring, fills in
with the docs for allowed options.
Args:
allowed (list str):... | [
"Decorator",
"that",
"logs",
"warnings",
"when",
"unpermitted",
"options",
"are",
"passed",
"into",
"its",
"wrapped",
"function",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L123-L172 |
SamLau95/nbinteract | nbinteract/plotting.py | hist | def hist(hist_function, *, options={}, **interact_params):
"""
Generates an interactive histogram that allows users to change the
parameters of the input hist_function.
Args:
hist_function (Array | (*args -> Array int | Array float)):
Function that takes in parameters to interact wi... | python | def hist(hist_function, *, options={}, **interact_params):
"""
Generates an interactive histogram that allows users to change the
parameters of the input hist_function.
Args:
hist_function (Array | (*args -> Array int | Array float)):
Function that takes in parameters to interact wi... | [
"def",
"hist",
"(",
"hist_function",
",",
"*",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"interact_params",
")",
":",
"params",
"=",
"{",
"'marks'",
":",
"[",
"{",
"'sample'",
":",
"_array_or_placeholder",
"(",
"hist_function",
")",
",",
"'bins'",
... | Generates an interactive histogram that allows users to change the
parameters of the input hist_function.
Args:
hist_function (Array | (*args -> Array int | Array float)):
Function that takes in parameters to interact with and returns an
array of numbers. These numbers will be p... | [
"Generates",
"an",
"interactive",
"histogram",
"that",
"allows",
"users",
"to",
"change",
"the",
"parameters",
"of",
"the",
"input",
"hist_function",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L182-L229 |
SamLau95/nbinteract | nbinteract/plotting.py | bar | def bar(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive bar chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for categories of ba... | python | def bar(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive bar chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for categories of ba... | [
"def",
"bar",
"(",
"x_fn",
",",
"y_fn",
",",
"*",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"interact_params",
")",
":",
"params",
"=",
"{",
"'marks'",
":",
"[",
"{",
"'x'",
":",
"_array_or_placeholder",
"(",
"x_fn",
",",
"PLACEHOLDER_RANGE",
")"... | Generates an interactive bar chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for categories of bar chart.
If function, must take parameters to interact... | [
"Generates",
"an",
"interactive",
"bar",
"chart",
"that",
"allows",
"users",
"to",
"change",
"the",
"parameters",
"of",
"the",
"inputs",
"x_fn",
"and",
"y_fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L235-L305 |
SamLau95/nbinteract | nbinteract/plotting.py | scatter_drag | def scatter_drag(
x_points: 'Array',
y_points: 'Array',
*,
fig=None,
show_eqn=True,
options={}
):
"""
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
... | python | def scatter_drag(
x_points: 'Array',
y_points: 'Array',
*,
fig=None,
show_eqn=True,
options={}
):
"""
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
... | [
"def",
"scatter_drag",
"(",
"x_points",
":",
"'Array'",
",",
"y_points",
":",
"'Array'",
",",
"*",
",",
"fig",
"=",
"None",
",",
"show_eqn",
"=",
"True",
",",
"options",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'marks'",
":",
"[",
"{",
"'x'",
... | Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
x_points (Array Number): x-values of points to plot
y_points (Array Number): y-values of points to plot
Kwargs:
... | [
"Generates",
"an",
"interactive",
"scatter",
"plot",
"with",
"the",
"best",
"fit",
"line",
"plotted",
"over",
"the",
"points",
".",
"The",
"points",
"can",
"be",
"dragged",
"by",
"the",
"user",
"and",
"the",
"line",
"will",
"automatically",
"update",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L312-L377 |
SamLau95/nbinteract | nbinteract/plotting.py | scatter | def scatter(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive scatter chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordi... | python | def scatter(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive scatter chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordi... | [
"def",
"scatter",
"(",
"x_fn",
",",
"y_fn",
",",
"*",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"interact_params",
")",
":",
"params",
"=",
"{",
"'marks'",
":",
"[",
"{",
"'x'",
":",
"_array_or_placeholder",
"(",
"x_fn",
")",
",",
"'y'",
":",
... | Generates an interactive scatter chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with ... | [
"Generates",
"an",
"interactive",
"scatter",
"chart",
"that",
"allows",
"users",
"to",
"change",
"the",
"parameters",
"of",
"the",
"inputs",
"x_fn",
"and",
"y_fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L384-L444 |
SamLau95/nbinteract | nbinteract/plotting.py | line | def line(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.... | python | def line(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.... | [
"def",
"line",
"(",
"x_fn",
",",
"y_fn",
",",
"*",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"interact_params",
")",
":",
"fig",
"=",
"options",
".",
"get",
"(",
"'_fig'",
",",
"False",
")",
"or",
"_create_fig",
"(",
"options",
"=",
"options",
... | Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and... | [
"Generates",
"an",
"interactive",
"line",
"chart",
"that",
"allows",
"users",
"to",
"change",
"the",
"parameters",
"of",
"the",
"inputs",
"x_fn",
"and",
"y_fn",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L451-L506 |
SamLau95/nbinteract | nbinteract/plotting.py | _merge_with_defaults | def _merge_with_defaults(params):
"""
Performs a 2-level deep merge of params with _default_params with corrent
merging of params for each mark.
This is a bit complicated since params['marks'] is a list and we need to
make sure each mark gets the default params.
"""
marks_params = [
... | python | def _merge_with_defaults(params):
"""
Performs a 2-level deep merge of params with _default_params with corrent
merging of params for each mark.
This is a bit complicated since params['marks'] is a list and we need to
make sure each mark gets the default params.
"""
marks_params = [
... | [
"def",
"_merge_with_defaults",
"(",
"params",
")",
":",
"marks_params",
"=",
"[",
"tz",
".",
"merge",
"(",
"default",
",",
"param",
")",
"for",
"default",
",",
"param",
"in",
"zip",
"(",
"itertools",
".",
"repeat",
"(",
"_default_params",
"[",
"'marks'",
... | Performs a 2-level deep merge of params with _default_params with corrent
merging of params for each mark.
This is a bit complicated since params['marks'] is a list and we need to
make sure each mark gets the default params. | [
"Performs",
"a",
"2",
"-",
"level",
"deep",
"merge",
"of",
"params",
"with",
"_default_params",
"with",
"corrent",
"merging",
"of",
"params",
"for",
"each",
"mark",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L636-L654 |
SamLau95/nbinteract | nbinteract/plotting.py | _create_fig | def _create_fig(
*,
x_sc=bq.LinearScale,
y_sc=bq.LinearScale,
x_ax=bq.Axis,
y_ax=bq.Axis,
fig=bq.Figure,
options={},
params={}
):
"""
Initializes scales and axes for a bqplot figure and returns the resulting
blank figure. Each plot component is passed in as a class. The plot ... | python | def _create_fig(
*,
x_sc=bq.LinearScale,
y_sc=bq.LinearScale,
x_ax=bq.Axis,
y_ax=bq.Axis,
fig=bq.Figure,
options={},
params={}
):
"""
Initializes scales and axes for a bqplot figure and returns the resulting
blank figure. Each plot component is passed in as a class. The plot ... | [
"def",
"_create_fig",
"(",
"*",
",",
"x_sc",
"=",
"bq",
".",
"LinearScale",
",",
"y_sc",
"=",
"bq",
".",
"LinearScale",
",",
"x_ax",
"=",
"bq",
".",
"Axis",
",",
"y_ax",
"=",
"bq",
".",
"Axis",
",",
"fig",
"=",
"bq",
".",
"Figure",
",",
"options"... | Initializes scales and axes for a bqplot figure and returns the resulting
blank figure. Each plot component is passed in as a class. The plot options
should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { plot_component: { trait: val... | [
"Initializes",
"scales",
"and",
"axes",
"for",
"a",
"bqplot",
"figure",
"and",
"returns",
"the",
"resulting",
"blank",
"figure",
".",
"Each",
"plot",
"component",
"is",
"passed",
"in",
"as",
"a",
"class",
".",
"The",
"plot",
"options",
"should",
"be",
"pas... | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L657-L694 |
SamLau95/nbinteract | nbinteract/plotting.py | _create_marks | def _create_marks(fig, marks=[bq.Mark], options={}, params={}):
"""
Initializes and returns marks for a figure as a list. Each mark is passed
in as a class. The plot options should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { ... | python | def _create_marks(fig, marks=[bq.Mark], options={}, params={}):
"""
Initializes and returns marks for a figure as a list. Each mark is passed
in as a class. The plot options should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { ... | [
"def",
"_create_marks",
"(",
"fig",
",",
"marks",
"=",
"[",
"bq",
".",
"Mark",
"]",
",",
"options",
"=",
"{",
"}",
",",
"params",
"=",
"{",
"}",
")",
":",
"params",
"=",
"_merge_with_defaults",
"(",
"params",
")",
"# Although fig provides scale_x and scale... | Initializes and returns marks for a figure as a list. Each mark is passed
in as a class. The plot options should be passed into options.
Any additional parameters to initialize plot components are passed into
params as a dict of { 'mark': [{ trait: value, ... }, ...] }
For example, when initializing t... | [
"Initializes",
"and",
"returns",
"marks",
"for",
"a",
"figure",
"as",
"a",
"list",
".",
"Each",
"mark",
"is",
"passed",
"in",
"as",
"a",
"class",
".",
"The",
"plot",
"options",
"should",
"be",
"passed",
"into",
"options",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L697-L733 |
SamLau95/nbinteract | nbinteract/plotting.py | _array_or_placeholder | def _array_or_placeholder(
maybe_iterable, placeholder=PLACEHOLDER_ZEROS
) -> np.array:
"""
Return maybe_iterable's contents or a placeholder array.
Used to give bqplot its required initial points to plot even if we're using
a function to generate points.
"""
if isinstance(maybe_iterable, c... | python | def _array_or_placeholder(
maybe_iterable, placeholder=PLACEHOLDER_ZEROS
) -> np.array:
"""
Return maybe_iterable's contents or a placeholder array.
Used to give bqplot its required initial points to plot even if we're using
a function to generate points.
"""
if isinstance(maybe_iterable, c... | [
"def",
"_array_or_placeholder",
"(",
"maybe_iterable",
",",
"placeholder",
"=",
"PLACEHOLDER_ZEROS",
")",
"->",
"np",
".",
"array",
":",
"if",
"isinstance",
"(",
"maybe_iterable",
",",
"collections",
".",
"Iterable",
")",
":",
"return",
"np",
".",
"array",
"("... | Return maybe_iterable's contents or a placeholder array.
Used to give bqplot its required initial points to plot even if we're using
a function to generate points. | [
"Return",
"maybe_iterable",
"s",
"contents",
"or",
"a",
"placeholder",
"array",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L743-L754 |
SamLau95/nbinteract | nbinteract/cli.py | binder_spec_from_github_url | def binder_spec_from_github_url(github_url):
"""
Converts GitHub origin into a Binder spec.
For example:
git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master
https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master
"""
tokens = re.split(r'/|:', github_url.rep... | python | def binder_spec_from_github_url(github_url):
"""
Converts GitHub origin into a Binder spec.
For example:
git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master
https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master
"""
tokens = re.split(r'/|:', github_url.rep... | [
"def",
"binder_spec_from_github_url",
"(",
"github_url",
")",
":",
"tokens",
"=",
"re",
".",
"split",
"(",
"r'/|:'",
",",
"github_url",
".",
"replace",
"(",
"'.git'",
",",
"''",
")",
")",
"# The username and reponame are the last two tokens",
"return",
"'{}/{}/maste... | Converts GitHub origin into a Binder spec.
For example:
git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master
https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master | [
"Converts",
"GitHub",
"origin",
"into",
"a",
"Binder",
"spec",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L93-L103 |
SamLau95/nbinteract | nbinteract/cli.py | yes_or_no | def yes_or_no(question, default="yes"):
"""Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is requ... | python | def yes_or_no(question, default="yes"):
"""Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is requ... | [
"def",
"yes_or_no",
"(",
"question",
",",
"default",
"=",
"\"yes\"",
")",
":",
"valid",
"=",
"{",
"\"yes\"",
":",
"True",
",",
"\"y\"",
":",
"True",
",",
"\"ye\"",
":",
"True",
",",
"\"no\"",
":",
"False",
",",
"\"n\"",
":",
"False",
"}",
"if",
"de... | Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return val... | [
"Ask",
"a",
"yes",
"/",
"no",
"question",
"via",
"input",
"()",
"and",
"return",
"their",
"answer",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L126-L159 |
SamLau95/nbinteract | nbinteract/cli.py | main | def main():
"""
Parses command line options and runs nbinteract.
"""
arguments = docopt(__doc__)
if arguments['init']:
return_code = init()
sys.exit(return_code)
run_converter(arguments) | python | def main():
"""
Parses command line options and runs nbinteract.
"""
arguments = docopt(__doc__)
if arguments['init']:
return_code = init()
sys.exit(return_code)
run_converter(arguments) | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
")",
"if",
"arguments",
"[",
"'init'",
"]",
":",
"return_code",
"=",
"init",
"(",
")",
"sys",
".",
"exit",
"(",
"return_code",
")",
"run_converter",
"(",
"arguments",
")"
] | Parses command line options and runs nbinteract. | [
"Parses",
"command",
"line",
"options",
"and",
"runs",
"nbinteract",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L162-L171 |
SamLau95/nbinteract | nbinteract/cli.py | run_converter | def run_converter(arguments):
"""
Converts notebooks to HTML files. Returns list of output file paths
"""
# Get spec from config file
if os.path.isfile(CONFIG_FILE):
with open(CONFIG_FILE, encoding='utf-8') as f:
config = json.load(f)
arguments['--spec'] = arguments['... | python | def run_converter(arguments):
"""
Converts notebooks to HTML files. Returns list of output file paths
"""
# Get spec from config file
if os.path.isfile(CONFIG_FILE):
with open(CONFIG_FILE, encoding='utf-8') as f:
config = json.load(f)
arguments['--spec'] = arguments['... | [
"def",
"run_converter",
"(",
"arguments",
")",
":",
"# Get spec from config file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"CONFIG_FILE",
")",
":",
"with",
"open",
"(",
"CONFIG_FILE",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"config",
"="... | Converts notebooks to HTML files. Returns list of output file paths | [
"Converts",
"notebooks",
"to",
"HTML",
"files",
".",
"Returns",
"list",
"of",
"output",
"file",
"paths"
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L174-L218 |
SamLau95/nbinteract | nbinteract/cli.py | init | def init():
'''
Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed.
... | python | def init():
'''
Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed.
... | [
"def",
"init",
"(",
")",
":",
"log",
"(",
"'Initializing folder for nbinteract.'",
")",
"log",
"(",
")",
"log",
"(",
"'Checking to see if this folder is the root folder of a git project.'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"'.git'",
")",
":",
"log"... | Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed. | [
"Initializes",
"git",
"repo",
"for",
"nbinteract",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L221-L325 |
SamLau95/nbinteract | nbinteract/cli.py | expand_folder | def expand_folder(notebook_or_folder, recursive=False):
"""
If notebook_or_folder is a folder, returns a list containing all notebooks
in the folder. Otherwise, returns a list containing the notebook name.
If recursive is True, recurses into subdirectories.
"""
is_file = os.path.isfile(notebook... | python | def expand_folder(notebook_or_folder, recursive=False):
"""
If notebook_or_folder is a folder, returns a list containing all notebooks
in the folder. Otherwise, returns a list containing the notebook name.
If recursive is True, recurses into subdirectories.
"""
is_file = os.path.isfile(notebook... | [
"def",
"expand_folder",
"(",
"notebook_or_folder",
",",
"recursive",
"=",
"False",
")",
":",
"is_file",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"notebook_or_folder",
")",
"is_dir",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"notebook_or_folder",
")",
"... | If notebook_or_folder is a folder, returns a list containing all notebooks
in the folder. Otherwise, returns a list containing the notebook name.
If recursive is True, recurses into subdirectories. | [
"If",
"notebook_or_folder",
"is",
"a",
"folder",
"returns",
"a",
"list",
"containing",
"all",
"notebooks",
"in",
"the",
"folder",
".",
"Otherwise",
"returns",
"a",
"list",
"containing",
"the",
"notebook",
"name",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L360-L389 |
SamLau95/nbinteract | nbinteract/cli.py | init_exporter | def init_exporter(extract_images, execute, **exporter_config):
"""
Returns an initialized exporter.
"""
config = Config(InteractExporter=exporter_config)
preprocessors = []
if extract_images:
# Use ExtractOutputPreprocessor to extract the images to separate files
preprocessors.a... | python | def init_exporter(extract_images, execute, **exporter_config):
"""
Returns an initialized exporter.
"""
config = Config(InteractExporter=exporter_config)
preprocessors = []
if extract_images:
# Use ExtractOutputPreprocessor to extract the images to separate files
preprocessors.a... | [
"def",
"init_exporter",
"(",
"extract_images",
",",
"execute",
",",
"*",
"*",
"exporter_config",
")",
":",
"config",
"=",
"Config",
"(",
"InteractExporter",
"=",
"exporter_config",
")",
"preprocessors",
"=",
"[",
"]",
"if",
"extract_images",
":",
"# Use ExtractO... | Returns an initialized exporter. | [
"Returns",
"an",
"initialized",
"exporter",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L392-L412 |
SamLau95/nbinteract | nbinteract/cli.py | make_exporter_resources | def make_exporter_resources(nb_name, out_folder, images_folder=None):
"""
Creates resources dict for the exporter
"""
resources = defaultdict(str)
resources['metadata'] = defaultdict(str)
resources['metadata']['name'] = nb_name
resources['metadata']['path'] = out_folder
# This results i... | python | def make_exporter_resources(nb_name, out_folder, images_folder=None):
"""
Creates resources dict for the exporter
"""
resources = defaultdict(str)
resources['metadata'] = defaultdict(str)
resources['metadata']['name'] = nb_name
resources['metadata']['path'] = out_folder
# This results i... | [
"def",
"make_exporter_resources",
"(",
"nb_name",
",",
"out_folder",
",",
"images_folder",
"=",
"None",
")",
":",
"resources",
"=",
"defaultdict",
"(",
"str",
")",
"resources",
"[",
"'metadata'",
"]",
"=",
"defaultdict",
"(",
"str",
")",
"resources",
"[",
"'... | Creates resources dict for the exporter | [
"Creates",
"resources",
"dict",
"for",
"the",
"exporter"
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L415-L428 |
SamLau95/nbinteract | nbinteract/cli.py | convert | def convert(notebook_path, exporter, output_folder=None, images_folder=None):
"""
Converts notebook into an HTML file, outputting notebooks into
output_folder if set and images into images_folder if set.
Returns the path to the resulting HTML file.
"""
if output_folder:
os.makedirs(outp... | python | def convert(notebook_path, exporter, output_folder=None, images_folder=None):
"""
Converts notebook into an HTML file, outputting notebooks into
output_folder if set and images into images_folder if set.
Returns the path to the resulting HTML file.
"""
if output_folder:
os.makedirs(outp... | [
"def",
"convert",
"(",
"notebook_path",
",",
"exporter",
",",
"output_folder",
"=",
"None",
",",
"images_folder",
"=",
"None",
")",
":",
"if",
"output_folder",
":",
"os",
".",
"makedirs",
"(",
"output_folder",
",",
"exist_ok",
"=",
"True",
")",
"if",
"imag... | Converts notebook into an HTML file, outputting notebooks into
output_folder if set and images into images_folder if set.
Returns the path to the resulting HTML file. | [
"Converts",
"notebook",
"into",
"an",
"HTML",
"file",
"outputting",
"notebooks",
"into",
"output_folder",
"if",
"set",
"and",
"images",
"into",
"images_folder",
"if",
"set",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/cli.py#L431-L472 |
SamLau95/nbinteract | docs/convert_notebooks_to_html_partial.py | convert_notebooks_to_html_partial | def convert_notebooks_to_html_partial(notebook_paths, url_map):
"""
Converts notebooks in notebook_paths to HTML partials
"""
for notebook_path in notebook_paths:
# Computes <name>.ipynb from notebooks/01/<name>.ipynb
path, filename = os.path.split(notebook_path)
# Computes examp... | python | def convert_notebooks_to_html_partial(notebook_paths, url_map):
"""
Converts notebooks in notebook_paths to HTML partials
"""
for notebook_path in notebook_paths:
# Computes <name>.ipynb from notebooks/01/<name>.ipynb
path, filename = os.path.split(notebook_path)
# Computes examp... | [
"def",
"convert_notebooks_to_html_partial",
"(",
"notebook_paths",
",",
"url_map",
")",
":",
"for",
"notebook_path",
"in",
"notebook_paths",
":",
"# Computes <name>.ipynb from notebooks/01/<name>.ipynb",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"("... | Converts notebooks in notebook_paths to HTML partials | [
"Converts",
"notebooks",
"in",
"notebook_paths",
"to",
"HTML",
"partials"
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/docs/convert_notebooks_to_html_partial.py#L73-L135 |
SamLau95/nbinteract | docs/convert_notebooks_to_html_partial.py | _preamble_cell | def _preamble_cell(path):
"""
This cell is inserted at the start of each notebook to set the working
directory to the correct folder.
"""
code = dedent(
'''
# HIDDEN
# Clear previously defined variables
%reset -f
'''.format(path)
)
return nbformat.v4.new_code_cell(sou... | python | def _preamble_cell(path):
"""
This cell is inserted at the start of each notebook to set the working
directory to the correct folder.
"""
code = dedent(
'''
# HIDDEN
# Clear previously defined variables
%reset -f
'''.format(path)
)
return nbformat.v4.new_code_cell(sou... | [
"def",
"_preamble_cell",
"(",
"path",
")",
":",
"code",
"=",
"dedent",
"(",
"'''\n # HIDDEN\n # Clear previously defined variables\n %reset -f\n '''",
".",
"format",
"(",
"path",
")",
")",
"return",
"nbformat",
".",
"v4",
".",
"new_code_cell",
"(",
"source... | This cell is inserted at the start of each notebook to set the working
directory to the correct folder. | [
"This",
"cell",
"is",
"inserted",
"at",
"the",
"start",
"of",
"each",
"notebook",
"to",
"set",
"the",
"working",
"directory",
"to",
"the",
"correct",
"folder",
"."
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/docs/convert_notebooks_to_html_partial.py#L138-L150 |
SamLau95/nbinteract | docs/convert_notebooks_to_html_partial.py | generate_url_map | def generate_url_map(yaml_path=TOC_PATH) -> dict:
"""
Generates mapping from each URL to its previous and next URLs in the
textbook. The dictionary looks like:
{
'ch/10/some_page.html' : {
'prev': 'ch/09/foo.html',
'next': 'ch/10/bar.html',
},
...
}
... | python | def generate_url_map(yaml_path=TOC_PATH) -> dict:
"""
Generates mapping from each URL to its previous and next URLs in the
textbook. The dictionary looks like:
{
'ch/10/some_page.html' : {
'prev': 'ch/09/foo.html',
'next': 'ch/10/bar.html',
},
...
}
... | [
"def",
"generate_url_map",
"(",
"yaml_path",
"=",
"TOC_PATH",
")",
"->",
"dict",
":",
"with",
"open",
"(",
"yaml_path",
")",
"as",
"f",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"pipeline",
"=",
"[",
"t",
".",
"remove",
"(",
"_not_interna... | Generates mapping from each URL to its previous and next URLs in the
textbook. The dictionary looks like:
{
'ch/10/some_page.html' : {
'prev': 'ch/09/foo.html',
'next': 'ch/10/bar.html',
},
...
} | [
"Generates",
"mapping",
"from",
"each",
"URL",
"to",
"its",
"previous",
"and",
"next",
"URLs",
"in",
"the",
"textbook",
".",
"The",
"dictionary",
"looks",
"like",
":"
] | train | https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/docs/convert_notebooks_to_html_partial.py#L197-L220 |
kylef/refract.py | refract/registry.py | Registry.find_element_class | def find_element_class(self, element_name):
"""
Finds an element class for the given element name contained within the
registry.
Returns Element when there is no matching element subclass.
>>> registry.find_element_class('string')
String
>>> registry.find_eleme... | python | def find_element_class(self, element_name):
"""
Finds an element class for the given element name contained within the
registry.
Returns Element when there is no matching element subclass.
>>> registry.find_element_class('string')
String
>>> registry.find_eleme... | [
"def",
"find_element_class",
"(",
"self",
",",
"element_name",
")",
":",
"for",
"element",
"in",
"self",
".",
"elements",
":",
"if",
"element",
".",
"element",
"==",
"element_name",
":",
"return",
"element",
"return",
"Element"
] | Finds an element class for the given element name contained within the
registry.
Returns Element when there is no matching element subclass.
>>> registry.find_element_class('string')
String
>>> registry.find_element_class('unknown')
Element | [
"Finds",
"an",
"element",
"class",
"for",
"the",
"given",
"element",
"name",
"contained",
"within",
"the",
"registry",
"."
] | train | https://github.com/kylef/refract.py/blob/f58ddf619038b580ab50c2e7f867d59d153eabbb/refract/registry.py#L39-L57 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | _transform | def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T:
"""Transform data to a new type.
Args:
transformer_chain: A sequence of (transformer, type) pairs to convert the data.
data: The data to be transformed.
context: The... | python | def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T:
"""Transform data to a new type.
Args:
transformer_chain: A sequence of (transformer, type) pairs to convert the data.
data: The data to be transformed.
context: The... | [
"def",
"_transform",
"(",
"transformer_chain",
":",
"Sequence",
"[",
"Tuple",
"[",
"DataTransformer",
",",
"Type",
"]",
"]",
",",
"data",
":",
"S",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"T",
":",
"for",
"transformer",
",",
"targ... | Transform data to a new type.
Args:
transformer_chain: A sequence of (transformer, type) pairs to convert the data.
data: The data to be transformed.
context: The context of the transformations (mutable).
Returns:
The transformed data. | [
"Transform",
"data",
"to",
"a",
"new",
"type",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L100-L114 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | _SinkHandler.put | def put(self, item: T, context: PipelineContext = None) -> None:
"""Puts an objects into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
item: The objects to be inserted into the data sink.
context: The context of the insertion (mu... | python | def put(self, item: T, context: PipelineContext = None) -> None:
"""Puts an objects into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
item: The objects to be inserted into the data sink.
context: The context of the insertion (mu... | [
"def",
"put",
"(",
"self",
",",
"item",
":",
"T",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"None",
":",
"LOGGER",
".",
"info",
"(",
"\"Converting item \\\"{item}\\\" for sink \\\"{sink}\\\"\"",
".",
"format",
"(",
"item",
"=",
"item",
... | Puts an objects into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
item: The objects to be inserted into the data sink.
context: The context of the insertion (mutable). | [
"Puts",
"an",
"objects",
"into",
"the",
"data",
"sink",
".",
"The",
"objects",
"may",
"be",
"transformed",
"into",
"a",
"new",
"type",
"for",
"insertion",
"if",
"necessary",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L130-L140 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | _SinkHandler.put_many | def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None:
"""Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the d... | python | def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None:
"""Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the d... | [
"def",
"put_many",
"(",
"self",
",",
"items",
":",
"Iterable",
"[",
"T",
"]",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"None",
":",
"LOGGER",
".",
"info",
"(",
"\"Creating transform generator for items \\\"{items}\\\" for sink \\\"{sink}\\\"\"... | Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the data sink.
context: The context of the insertions (mutable). | [
"Puts",
"multiple",
"objects",
"of",
"the",
"same",
"type",
"into",
"the",
"data",
"sink",
".",
"The",
"objects",
"may",
"be",
"transformed",
"into",
"a",
"new",
"type",
"for",
"insertion",
"if",
"necessary",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L142-L152 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | _SourceHandler.get | def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) I... | python | def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) I... | [
"def",
"get",
"(",
"self",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"T",
":",
"result",
"=",
"self",
".",
"_source",
".",
"get",
"(",
"self",
".",
"_source_type",
","... | Gets a query from the data source.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the result into the requested type if it wasn't already.
4) Inserts the transformed result into any data sinks.
Args:
query: The q... | [
"Gets",
"a",
"query",
"from",
"the",
"data",
"source",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L170-L199 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | _SourceHandler.get_many | def get_many(self, query: Mapping[str, Any], context: PipelineContext = None, streaming: bool = False) -> Iterable[T]:
"""Gets a query from the data source, where the query contains multiple elements to be extracted.
1) Extracts the query from the data source.
2) Inserts the result into any dat... | python | def get_many(self, query: Mapping[str, Any], context: PipelineContext = None, streaming: bool = False) -> Iterable[T]:
"""Gets a query from the data source, where the query contains multiple elements to be extracted.
1) Extracts the query from the data source.
2) Inserts the result into any dat... | [
"def",
"get_many",
"(",
"self",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"context",
":",
"PipelineContext",
"=",
"None",
",",
"streaming",
":",
"bool",
"=",
"False",
")",
"->",
"Iterable",
"[",
"T",
"]",
":",
"result",
"=",
"... | Gets a query from the data source, where the query contains multiple elements to be extracted.
1) Extracts the query from the data source.
2) Inserts the result into any data sinks.
3) Transforms the results into the requested type if it wasn't already.
4) Inserts the transformed result... | [
"Gets",
"a",
"query",
"from",
"the",
"data",
"source",
"where",
"the",
"query",
"contains",
"multiple",
"elements",
"to",
"be",
"extracted",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L216-L253 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | DataPipeline.get | def get(self, type: Type[T], query: Mapping[str, Any]) -> T:
"""Gets a query from the data pipeline.
1) Extracts the query the sequence of data sources.
2) Inserts the result into the data sinks (if appropriate).
3) Transforms the result into the requested type if it wasn't already.
... | python | def get(self, type: Type[T], query: Mapping[str, Any]) -> T:
"""Gets a query from the data pipeline.
1) Extracts the query the sequence of data sources.
2) Inserts the result into the data sinks (if appropriate).
3) Transforms the result into the requested type if it wasn't already.
... | [
"def",
"get",
"(",
"self",
",",
"type",
":",
"Type",
"[",
"T",
"]",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"T",
":",
"LOGGER",
".",
"info",
"(",
"\"Getting SourceHandlers for \\\"{type}\\\"\"",
".",
"format",
"(",
"type",... | Gets a query from the data pipeline.
1) Extracts the query the sequence of data sources.
2) Inserts the result into the data sinks (if appropriate).
3) Transforms the result into the requested type if it wasn't already.
4) Inserts the transformed result into any data sinks.
Arg... | [
"Gets",
"a",
"query",
"from",
"the",
"data",
"pipeline",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L424-L463 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | DataPipeline.get_many | def get_many(self, type: Type[T], query: Mapping[str, Any], streaming: bool = False) -> Iterable[T]:
"""Gets a query from the data pipeline, which contains a request for multiple objects.
1) Extracts the query the sequence of data sources.
2) Inserts the results into the data sinks (if appropri... | python | def get_many(self, type: Type[T], query: Mapping[str, Any], streaming: bool = False) -> Iterable[T]:
"""Gets a query from the data pipeline, which contains a request for multiple objects.
1) Extracts the query the sequence of data sources.
2) Inserts the results into the data sinks (if appropri... | [
"def",
"get_many",
"(",
"self",
",",
"type",
":",
"Type",
"[",
"T",
"]",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"streaming",
":",
"bool",
"=",
"False",
")",
"->",
"Iterable",
"[",
"T",
"]",
":",
"LOGGER",
".",
"info",
"... | Gets a query from the data pipeline, which contains a request for multiple objects.
1) Extracts the query the sequence of data sources.
2) Inserts the results into the data sinks (if appropriate).
3) Transforms the results into the requested type if it wasn't already.
4) Inserts the tra... | [
"Gets",
"a",
"query",
"from",
"the",
"data",
"pipeline",
"which",
"contains",
"a",
"request",
"for",
"multiple",
"objects",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L465-L505 |
meraki-analytics/datapipelines-python | datapipelines/pipelines.py | DataPipeline.put | def put(self, type: Type[T], item: T) -> None:
"""Puts an objects into the data pipeline. The object may be transformed into a new type for insertion if necessary.
Args:
item: The object to be inserted into the data pipeline.
"""
LOGGER.info("Getting SinkHandlers for \"{type... | python | def put(self, type: Type[T], item: T) -> None:
"""Puts an objects into the data pipeline. The object may be transformed into a new type for insertion if necessary.
Args:
item: The object to be inserted into the data pipeline.
"""
LOGGER.info("Getting SinkHandlers for \"{type... | [
"def",
"put",
"(",
"self",
",",
"type",
":",
"Type",
"[",
"T",
"]",
",",
"item",
":",
"T",
")",
"->",
"None",
":",
"LOGGER",
".",
"info",
"(",
"\"Getting SinkHandlers for \\\"{type}\\\"\"",
".",
"format",
"(",
"type",
"=",
"type",
".",
"__name__",
")",... | Puts an objects into the data pipeline. The object may be transformed into a new type for insertion if necessary.
Args:
item: The object to be inserted into the data pipeline. | [
"Puts",
"an",
"objects",
"into",
"the",
"data",
"pipeline",
".",
"The",
"object",
"may",
"be",
"transformed",
"into",
"a",
"new",
"type",
"for",
"insertion",
"if",
"necessary",
"."
] | train | https://github.com/meraki-analytics/datapipelines-python/blob/dc38d7976a012039a15d67cd8b07ae77eb1e4a4c/datapipelines/pipelines.py#L507-L530 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.