_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q227100 | Quart.full_dispatch_websocket | train | async def full_dispatch_websocket(
self, websocket_context: Optional[WebsocketContext]=None,
) -> Optional[Response]:
"""Adds pre and post processing to the websocket dispatching.
Arguments:
websocket_context: The websocket context, optional to match
the Flask co... | python | {
"resource": ""
} |
q227101 | Quart.preprocess_websocket | train | async def preprocess_websocket(
self, websocket_context: Optional[WebsocketContext]=None,
) -> Optional[ResponseReturnValue]:
"""Preprocess the websocket i.e. call before_websocket functions.
Arguments:
websocket_context: The websocket context, optional as Flask
... | python | {
"resource": ""
} |
q227102 | Quart.dispatch_websocket | train | async def dispatch_websocket(
self, websocket_context: Optional[WebsocketContext]=None,
) -> None:
"""Dispatch the websocket to the view function.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention.
"""
web... | python | {
"resource": ""
} |
q227103 | Quart.postprocess_websocket | train | async def postprocess_websocket(
self,
response: Optional[Response],
websocket_context: Optional[WebsocketContext]=None,
) -> Response:
"""Postprocess the websocket acting on the response.
Arguments:
response: The response after the websocket is finalized.
... | python | {
"resource": ""
} |
q227104 | after_this_request | train | def after_this_request(func: Callable) -> Callable:
"""Schedule the func to be called after the current request.
This is useful in situations whereby you want an after request
function for a specific route or circumstance only, for example,
.. code-block:: python
def index():
@aft... | python | {
"resource": ""
} |
q227105 | after_this_websocket | train | def after_this_websocket(func: Callable) -> Callable:
"""Schedule the func to be called after the current websocket.
This is useful in situations whereby you want an after websocket
function for a specific route or circumstance only, for example,
.. note::
The response is an optional argument,... | python | {
"resource": ""
} |
q227106 | copy_current_app_context | train | def copy_current_app_context(func: Callable) -> Callable:
"""Share the current app context with the function decorated.
The app context is local per task and hence will not be available
in any other task. This decorator can be used to make the context
available,
.. code-block:: python
@co... | python | {
"resource": ""
} |
q227107 | copy_current_request_context | train | def copy_current_request_context(func: Callable) -> Callable:
"""Share the current request context with the function decorated.
The request context is local per task and hence will not be
available in any other task. This decorator can be used to make
the context available,
.. code-block:: python
... | python | {
"resource": ""
} |
q227108 | copy_current_websocket_context | train | def copy_current_websocket_context(func: Callable) -> Callable:
"""Share the current websocket context with the function decorated.
The websocket context is local per task and hence will not be
available in any other task. This decorator can be used to make
the context available,
.. code-block:: p... | python | {
"resource": ""
} |
q227109 | _BaseRequestWebsocketContext.match_request | train | def match_request(self) -> None:
"""Match the request against the adapter.
Override this method to configure request matching, it should
set the request url_rule and view_args and optionally a
routing_exception.
"""
try:
self.request_websocket.url_rule, self.... | python | {
"resource": ""
} |
q227110 | _AppCtxGlobals.get | train | def get(self, name: str, default: Optional[Any]=None) -> Any:
"""Get a named attribute of this instance, or return the default."""
return self.__dict__.get(name, default) | python | {
"resource": ""
} |
q227111 | _AppCtxGlobals.pop | train | def pop(self, name: str, default: Any=_sentinel) -> Any:
"""Pop, get and remove the named attribute of this instance."""
if default is _sentinel:
return self.__dict__.pop(name)
else:
return self.__dict__.pop(name, default) | python | {
"resource": ""
} |
q227112 | _AppCtxGlobals.setdefault | train | def setdefault(self, name: str, default: Any=None) -> Any:
"""Set an attribute with a default value."""
return self.__dict__.setdefault(name, default) | python | {
"resource": ""
} |
q227113 | SessionInterface.get_cookie_domain | train | def get_cookie_domain(self, app: 'Quart') -> Optional[str]:
"""Helper method to return the Cookie Domain for the App."""
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
elif app.config['SERVER_NAME'] is not None:
return '.' +... | python | {
"resource": ""
} |
q227114 | SessionInterface.get_expiration_time | train | def get_expiration_time(self, app: 'Quart', session: SessionMixin) -> Optional[datetime]:
"""Helper method to return the Session expiration time.
If the session is not 'permanent' it will expire as and when
the browser stops accessing the app.
"""
if session.permanent:
... | python | {
"resource": ""
} |
q227115 | SessionInterface.should_set_cookie | train | def should_set_cookie(self, app: 'Quart', session: SessionMixin) -> bool:
"""Helper method to return if the Set Cookie header should be present.
This triggers if the session is marked as modified or the app
is configured to always refresh the cookie.
"""
if session.modified:
... | python | {
"resource": ""
} |
q227116 | SecureCookieSessionInterface.get_signing_serializer | train | def get_signing_serializer(self, app: 'Quart') -> Optional[URLSafeTimedSerializer]:
"""Return a serializer for the session that also signs data.
This will return None if the app is not configured for secrets.
"""
if not app.secret_key:
return None
options = {
... | python | {
"resource": ""
} |
q227117 | SecureCookieSessionInterface.open_session | train | async def open_session(
self,
app: 'Quart',
request: BaseRequestWebsocket,
) -> Optional[SecureCookieSession]:
"""Open a secure cookie based session.
This will return None if a signing serializer is not availabe,
usually if the config SECRET_KEY is not se... | python | {
"resource": ""
} |
q227118 | SecureCookieSessionInterface.save_session | train | async def save_session( # type: ignore
self, app: 'Quart', session: SecureCookieSession, response: Response,
) -> None:
"""Saves the session to the response in a secure cookie."""
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
... | python | {
"resource": ""
} |
q227119 | Response.get_data | train | async def get_data(self, raw: bool=True) -> AnyStr:
"""Return the body data."""
if self.implicit_sequence_conversion:
self.response = self.data_body_class(await self.response.convert_to_sequence())
result = b'' if raw else ''
async with self.response as body: # type: ignore
... | python | {
"resource": ""
} |
q227120 | Response.set_data | train | def set_data(self, data: AnyStr) -> None:
"""Set the response data.
This will encode using the :attr:`charset`.
"""
if isinstance(data, str):
bytes_data = data.encode(self.charset)
else:
bytes_data = data
self.response = self.data_body_class(bytes... | python | {
"resource": ""
} |
q227121 | Response.make_conditional | train | async def make_conditional(
self,
request_range: Range,
max_partial_size: Optional[int]=None,
) -> None:
"""Make the response conditional to the
Arguments:
request_range: The range as requested by the request.
max_partial_size: The maximum... | python | {
"resource": ""
} |
q227122 | Response.set_cookie | train | def set_cookie( # type: ignore
self,
key: str,
value: AnyStr='',
max_age: Optional[Union[int, timedelta]]=None,
expires: Optional[datetime]=None,
path: str='/',
domain: Optional[str]=None,
secure: bool=False,
ht... | python | {
"resource": ""
} |
q227123 | Rule.match | train | def match(self, path: str) -> Tuple[Optional[Dict[str, Any]], bool]:
"""Check if the path matches this Rule.
If it does it returns a dict of matched and converted values,
otherwise None is returned.
"""
match = self._pattern.match(path)
if match is not None:
... | python | {
"resource": ""
} |
q227124 | Rule.provides_defaults_for | train | def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool:
"""Returns true if this rule provides defaults for the argument and values."""
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return ... | python | {
"resource": ""
} |
q227125 | Rule.build | train | def build(self, **values: Any) -> str:
"""Build this rule into a path using the values given."""
converted_values = {
key: self._converters[key].to_url(value)
for key, value in values.items()
if key in self._converters
}
result = self._builder.format(*... | python | {
"resource": ""
} |
q227126 | Rule.buildable | train | def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
"""Return True if this rule can build with the values and method."""
if method is not None and method not in self.methods:
return False
defaults_match = all(
values[key] == self.defaults... | python | {
"resource": ""
} |
q227127 | Rule.bind | train | def bind(self, map: Map) -> None:
"""Bind the Rule to a Map and compile it."""
if self.map is not None:
raise RuntimeError(f"{self!r} is already bound to {self.map!r}")
self.map = map
pattern = ''
builder = ''
full_rule = "{}\\|{}".format(self.host or '', se... | python | {
"resource": ""
} |
q227128 | Rule.match_key | train | def match_key(self) -> Tuple[bool, bool, int, List[WeightedPart]]:
"""A Key to sort the rules by weight for matching.
The key leads to ordering:
- By first order by defaults as they are simple rules without
conversions.
- Then on the complexity of the rule, i.e. does it ha... | python | {
"resource": ""
} |
q227129 | Rule.build_key | train | def build_key(self) -> Tuple[bool, int]:
"""A Key to sort the rules by weight for building.
The key leads to ordering:
- By routes with defaults first, as these must be evaulated
for building before ones without.
- Then the more complex routes (most converted parts).
... | python | {
"resource": ""
} |
q227130 | get_tile | train | def get_tile(tile_number):
"""
Returns a crop of `img` based on a sequence number `tile_number`.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises TileOutOfBoundsError: When `tile_number` exceeds `max_tiles`^2
:rtype PIL.Image:
"""
tile_number = int(tile_number... | python | {
"resource": ""
} |
q227131 | tile | train | async def tile(tile_number):
"""
Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2.
"""
try:
tile = get_tile(tile_number)
except TileOutOfBoundsError:
abort(404... | python | {
"resource": ""
} |
q227132 | JSONMixin.is_json | train | def is_json(self) -> bool:
"""Returns True if the content_type is json like."""
content_type = self.mimetype
if content_type == 'application/json' or (
content_type.startswith('application/') and content_type.endswith('+json')
):
return True
else:
... | python | {
"resource": ""
} |
q227133 | JSONMixin.get_json | train | async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
"""Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails,... | python | {
"resource": ""
} |
q227134 | _BaseRequestResponse.mimetype | train | def mimetype(self, value: str) -> None:
"""Set the mimetype to the value."""
if (
value.startswith('text/') or value == 'application/xml' or
(value.startswith('application/') and value.endswith('+xml'))
):
mimetype = f"{value}; charset={self.charset}"
... | python | {
"resource": ""
} |
q227135 | BaseRequestWebsocket.blueprint | train | def blueprint(self) -> Optional[str]:
"""Returns the blueprint the matched endpoint belongs to.
This can be None if the request has not been matched or the
endpoint is not in a blueprint.
"""
if self.endpoint is not None and '.' in self.endpoint:
return self.endpoint... | python | {
"resource": ""
} |
q227136 | BaseRequestWebsocket.base_url | train | def base_url(self) -> str:
"""Returns the base url without query string or fragments."""
return urlunparse(ParseResult(self.scheme, self.host, self.path, '', '', '')) | python | {
"resource": ""
} |
q227137 | BaseRequestWebsocket.url | train | def url(self) -> str:
"""Returns the full url requested."""
return urlunparse(
ParseResult(
self.scheme, self.host, self.path, '', self.query_string.decode('ascii'), '',
),
) | python | {
"resource": ""
} |
q227138 | BaseRequestWebsocket.cookies | train | def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()} | python | {
"resource": ""
} |
q227139 | Config.from_envvar | train | def from_envvar(self, variable_name: str, silent: bool=False) -> None:
"""Load the configuration from a location specified in the environment.
This will load a cfg file using :meth:`from_pyfile` from the
location specified in the environment, for example the two blocks
below are equival... | python | {
"resource": ""
} |
q227140 | Config.from_pyfile | train | def from_pyfile(self, filename: str, silent: bool=False) -> None:
"""Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then ove... | python | {
"resource": ""
} |
q227141 | Config.from_object | train | def from_object(self, instance: Union[object, str]) -> None:
"""Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_obj... | python | {
"resource": ""
} |
q227142 | Config.from_json | train | def from_json(self, filename: str, silent: bool=False) -> None:
"""Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filena... | python | {
"resource": ""
} |
q227143 | Config.from_mapping | train | def from_mapping(self, mapping: Optional[Mapping[str, Any]]=None, **kwargs: Any) -> None:
"""Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'FOO': 'bar'... | python | {
"resource": ""
} |
q227144 | Config.get_namespace | train | def get_namespace(
self,
namespace: str,
lowercase: bool=True,
trim_namespace: bool=True,
) -> Dict[str, Any]:
"""Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the
keys ``FOO_A, FOO_B... | python | {
"resource": ""
} |
q227145 | make_response | train | async def make_response(*args: Any) -> Response:
"""Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before
returning it, for example
.. code-block:: python
response = make_response(render_template('index.html'))
response.headers['X-H... | python | {
"resource": ""
} |
q227146 | get_flashed_messages | train | def get_flashed_messages(
with_categories: bool=False,
category_filter: List[str]=[],
) -> Union[List[str], List[Tuple[str, str]]]:
"""Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global
function, for example
.. code-b... | python | {
"resource": ""
} |
q227147 | url_for | train | def url_for(
endpoint: str,
*,
_anchor: Optional[str]=None,
_external: Optional[bool]=None,
_method: Optional[str]=None,
_scheme: Optional[str]=None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and ... | python | {
"resource": ""
} |
q227148 | stream_with_context | train | def stream_with_context(func: Callable) -> Callable:
"""Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
... | python | {
"resource": ""
} |
q227149 | safe_join | train | def safe_join(directory: FilePath, *paths: FilePath) -> Path:
"""Safely join the paths to the known directory to return a full path.
Raises:
NotFound: if the full path does not share a commonprefix with
the directory.
"""
try:
safe_path = file_path_to_path(directory).resolve(str... | python | {
"resource": ""
} |
q227150 | send_from_directory | train | async def send_from_directory(
directory: FilePath,
file_name: str,
*,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=True... | python | {
"resource": ""
} |
q227151 | send_file | train | async def send_file(
filename: FilePath,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=False,
last_modified: Optional[datetime]=N... | python | {
"resource": ""
} |
q227152 | Halo._render_frame | train | def _render_frame(self):
"""Renders the frame on the line after clearing it.
"""
frame = self.frame()
output = '\r{0}'.format(frame)
self.clear()
try:
self._stream.write(output)
except UnicodeEncodeError:
self._stream.write(encode_utf_8_tex... | python | {
"resource": ""
} |
q227153 | get_environment | train | def get_environment():
"""Get the environment in which halo is running
Returns
-------
str
Environment name
"""
try:
from IPython import get_ipython
except ImportError:
return 'terminal'
try:
shell = get_ipython().__class__.__name__
if shell == ... | python | {
"resource": ""
} |
q227154 | is_text_type | train | def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.strin... | python | {
"resource": ""
} |
q227155 | find_stateless_by_name | train | def find_stateless_by_name(name):
'''
Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created.
'''
try:
dsa_app = StatelessApp.objects.ge... | python | {
"resource": ""
} |
q227156 | StatelessApp.as_dash_app | train | def as_dash_app(self):
'''
Return a DjangoDash instance of the dash application
'''
dateless_dash_app = getattr(self, '_stateless_dash_app_instance', None)
if not dateless_dash_app:
dateless_dash_app = get_stateless_by_name(self.app_name)
setattr(self, '_s... | python | {
"resource": ""
} |
q227157 | DashApp.handle_current_state | train | def handle_current_state(self):
'''
Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance.
'''
if getattr(self, '_current_state_hydrated_changed', False) and self.sav... | python | {
"resource": ""
} |
q227158 | DashApp.have_current_state_entry | train | def have_current_state_entry(self, wid, key):
'Return True if there is a cached current state for this app'
cscoll = self.current_state()
c_state = cscoll.get(wid, {})
return key in c_state | python | {
"resource": ""
} |
q227159 | DashApp.current_state | train | def current_state(self):
'''
Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable.
'''
c_state = getattr(self, '_current_state_hydrated', None)
if not c_state:
... | python | {
"resource": ""
} |
q227160 | DashApp.as_dash_instance | train | def as_dash_instance(self, cache_id=None):
'Return a dash application instance for this model instance'
dash_app = self.stateless_app.as_dash_app() # pylint: disable=no-member
base = self.current_state()
return dash_app.do_form_dash_instance(replacements=base,
... | python | {
"resource": ""
} |
q227161 | DashApp._get_base_state | train | def _get_base_state(self):
'''
Get the base state of the object, as defined by the app.layout code, as a python dict
'''
base_app_inst = self.stateless_app.as_dash_app().as_dash_instance() # pylint: disable=no-member
# Get base layout response, from a base object
base_re... | python | {
"resource": ""
} |
q227162 | DashApp.populate_values | train | def populate_values(self):
'''
Add values from the underlying dash layout configuration
'''
obj = self._get_base_state()
self.base_state = json.dumps(obj) | python | {
"resource": ""
} |
q227163 | DashApp.locate_item | train | def locate_item(ident, stateless=False, cache_id=None):
'''Locate a dash application, given either the
slug of an instance or the name for a stateless app'''
if stateless:
dash_app = find_stateless_by_name(ident)
else:
dash_app = get_object_or_404(DashApp, slug=id... | python | {
"resource": ""
} |
q227164 | send_to_pipe_channel | train | def send_to_pipe_channel(channel_name,
label,
value):
'Send message through pipe to client component'
async_to_sync(async_send_to_pipe_channel)(channel_name=channel_name,
label=label,
... | python | {
"resource": ""
} |
q227165 | async_send_to_pipe_channel | train | async def async_send_to_pipe_channel(channel_name,
label,
value):
'Send message asynchronously through pipe to client component'
pcn = _form_pipe_channel_name(channel_name)
channel_layer = get_channel_layer()
await channel_layer.... | python | {
"resource": ""
} |
q227166 | MessageConsumer.pipe_value | train | def pipe_value(self, message):
'Send a new value into the ws pipe'
jmsg = json.dumps(message)
self.send(jmsg) | python | {
"resource": ""
} |
q227167 | MessageConsumer.update_pipe_channel | train | def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument
'''
Update this consumer to listen on channel_name for the js widget associated with uid
'''
pipe_group_name = _form_pipe_channel_name(channel_name)
if self.channel_layer:
curr... | python | {
"resource": ""
} |
q227168 | store_initial_arguments | train | def store_initial_arguments(request, initial_arguments=None):
'Store initial arguments, if any, and return a cache identifier'
if initial_arguments is None:
return None
# Generate a cache id
cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace('-', '')
# Store args in json form in... | python | {
"resource": ""
} |
q227169 | get_initial_arguments | train | def get_initial_arguments(request, cache_id=None):
'Extract initial arguments for the dash app'
if cache_id is None:
return None
if initial_argument_location():
return cache.get(cache_id)
return request.session[cache_id] | python | {
"resource": ""
} |
q227170 | dependencies | train | def dependencies(request, ident, stateless=False, **kwargs):
'Return the dependencies'
_, app = DashApp.locate_item(ident, stateless)
with app.app_context():
view_func = app.locate_endpoint_function('dash-dependencies')
resp = view_func()
return HttpResponse(resp.data,
... | python | {
"resource": ""
} |
q227171 | layout | train | def layout(request, ident, stateless=False, cache_id=None, **kwargs):
'Return the layout of the dash application'
_, app = DashApp.locate_item(ident, stateless)
view_func = app.locate_endpoint_function('dash-layout')
resp = view_func()
initial_arguments = get_initial_arguments(request, cache_id)
... | python | {
"resource": ""
} |
q227172 | update | train | def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_fun... | python | {
"resource": ""
} |
q227173 | main_view | train | def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
'Main view for a dash app'
_, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) | python | {
"resource": ""
} |
q227174 | app_assets | train | def app_assets(request, **kwargs):
'Return a local dash app asset, served up through the Django static framework'
get_params = request.GET.urlencode()
extra_part = ""
if get_params:
redone_url = "/static/dash/assets/%s?%s" %(extra_part, get_params)
else:
redone_url = "/static/dash/as... | python | {
"resource": ""
} |
q227175 | add_to_session | train | def add_to_session(request, template_name="index.html", **kwargs):
'Add some info to a session in a place that django-plotly-dash can pass to a callback'
django_plotly_dash = request.session.get("django_plotly_dash", dict())
session_add_count = django_plotly_dash.get('add_counter', 0)
django_plotly_da... | python | {
"resource": ""
} |
q227176 | asset_redirection | train | def asset_redirection(request, path, ident=None, stateless=False, **kwargs):
'Redirect static assets for a component'
X, app = DashApp.locate_item(ident, stateless)
# Redirect to a location based on the import path of the module containing the DjangoDash app
static_path = X.get_asset_static_url(path)
... | python | {
"resource": ""
} |
q227177 | dash_example_1_view | train | def dash_example_1_view(request, template_name="demo_six.html", **kwargs):
'Example view that inserts content into the dash context passed to the dash application'
context = {}
# create some context to send over to Dash:
dash_context = request.session.get("django_plotly_dash", dict())
dash_context... | python | {
"resource": ""
} |
q227178 | session_state_view | train | def session_state_view(request, template_name, **kwargs):
'Example view that exhibits the use of sessions to store state'
session = request.session
demo_count = session.get('django_plotly_dash', {})
ind_use = demo_count.get('ind_use', 0)
ind_use += 1
demo_count['ind_use'] = ind_use
conte... | python | {
"resource": ""
} |
q227179 | ContentCollector.adjust_response | train | def adjust_response(self, response):
'Locate placeholder magic strings and replace with content'
try:
c1 = self._replace(response.content,
self.header_placeholder,
self.embedded_holder.css)
response.content = self._r... | python | {
"resource": ""
} |
q227180 | callback_c | train | def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get(... | python | {
"resource": ""
} |
q227181 | callback_liveIn_button_press | train | def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_tim... | python | {
"resource": ""
} |
q227182 | generate_liveOut_layout | train | def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
htm... | python | {
"resource": ""
} |
q227183 | callback_liveOut_pipe_in | train | def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
'Handle something changing the value of the input pipe or the associated state uid'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
# Guard ag... | python | {
"resource": ""
} |
q227184 | callback_show_timeseries | train | def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red'... | python | {
"resource": ""
} |
q227185 | session_demo_danger_callback | train | def session_demo_danger_callback(da_children, session_state=None, **kwargs):
'Update output based just on state'
if not session_state:
return "Session state not yet available"
return "Session state contains: " + str(session_state.get('bootstrap_demo_state', "NOTHING")) + " and the page render count... | python | {
"resource": ""
} |
q227186 | session_demo_alert_callback | train | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
... | python | {
"resource": ""
} |
q227187 | add_usable_app | train | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name | python | {
"resource": ""
} |
q227188 | DjangoDash.get_base_pathname | train | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathnam... | python | {
"resource": ""
} |
q227189 | DjangoDash.do_form_dash_instance | train | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid,... | python | {
"resource": ""
} |
q227190 | DjangoDash.form_dash_instance | train | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks... | python | {
"resource": ""
} |
q227191 | DjangoDash.callback | train | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and stat... | python | {
"resource": ""
} |
q227192 | DjangoDash.expanded_callback | train | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
... | python | {
"resource": ""
} |
q227193 | WrappedDash.augment_initial_layout | train | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInByt... | python | {
"resource": ""
} |
q227194 | WrappedDash.walk_tree_and_extract | train | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None... | python | {
"resource": ""
} |
q227195 | WrappedDash.walk_tree_and_replace | train | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {... | python | {
"resource": ""
} |
q227196 | WrappedDash.locate_endpoint_function | train | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] | python | {
"resource": ""
} |
q227197 | WrappedDash.layout | train | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) | python | {
"resource": ""
} |
q227198 | WrappedDash._fix_component_id | train | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component... | python | {
"resource": ""
} |
q227199 | WrappedDash._fix_callback_item | train | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.