_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q240900 | Unchained.shell_context_processor | train | def shell_context_processor(self, fn):
"""
Registers a shell context processor function.
"""
self._defer(lambda app: app.shell_context_processor(fn))
return fn | python | {
"resource": ""
} |
q240901 | Unchained.url_defaults | train | def url_defaults(self, fn):
"""
Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place.
"""
self._defer(lambda app: app.url_defaults(fn))
return fn | python | {
"resource": ""
} |
q240902 | Unchained.errorhandler | train | def errorhandler(self, code_or_exception):
"""
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an
error code. Example::
@app.errorhandler(404)
def page_not_found(error):
retu... | python | {
"resource": ""
} |
q240903 | Unchained.template_filter | train | def template_filter(self,
arg: Optional[Callable] = None,
*,
name: Optional[str] = None,
pass_context: bool = False,
inject: Optional[Union[bool, Iterable[str]]] = None,
safe: ... | python | {
"resource": ""
} |
q240904 | Unchained._reset | train | def _reset(self):
"""
This method is for use by tests only!
"""
self.bundles = AttrDict()
self._bundles = _DeferredBundleFunctionsStore()
self.babel_bundle = None
self.env = None
self.extensions = AttrDict()
self.services = AttrDict()
self... | python | {
"resource": ""
} |
q240905 | model_fields | train | def model_fields(model, db_session=None, only=None, exclude=None,
field_args=None, converter=None, exclude_pk=False,
exclude_fk=False):
"""
Generate a dictionary of fields for a given SQLAlchemy model.
See `model_form` docstring for description of parameters.
"""
m... | python | {
"resource": ""
} |
q240906 | url | train | def url(url: str, method: str):
"""Show details for a specific URL."""
try:
url_rule, params = (current_app.url_map.bind('localhost')
.match(url, method=method, return_rule=True))
except (NotFound, MethodNotAllowed)\
as e:
click.secho(str(e), fg='white... | python | {
"resource": ""
} |
q240907 | urls | train | def urls(order_by: Optional[str] = None):
"""List all URLs registered with the app."""
url_rules: List[Rule] = current_app.url_map._rules
# sort the rules. by default they're sorted by priority,
# ie in the order they were registered with the app
if order_by == 'view':
url_rules = sorted(ur... | python | {
"resource": ""
} |
q240908 | Api.register_converter | train | def register_converter(self, converter, conv_type, conv_format=None, *, name=None):
"""
Register custom path parameter converter.
:param BaseConverter converter: Converter
Subclass of werkzeug's BaseConverter
:param str conv_type: Parameter type
:param str conv_forma... | python | {
"resource": ""
} |
q240909 | AppFactoryHook.run_hook | train | def run_hook(self, app: FlaskUnchained, bundles: List[Bundle]):
"""
Hook entry point. Override to disable standard behavior of iterating
over bundles to discover objects and processing them.
"""
self.process_objects(app, self.collect_from_bundles(bundles)) | python | {
"resource": ""
} |
q240910 | singularize | train | def singularize(word, pos=NOUN, custom=None):
""" Returns the singular of a given word.
"""
if custom and word in custom:
return custom[word]
# Recurse compound words (e.g. mothers-in-law).
if "-" in word:
w = word.split("-")
if len(w) > 1 and w[1] in plural_prepositions:
... | python | {
"resource": ""
} |
q240911 | AppFactory.create_basic_app | train | def create_basic_app(cls, bundles=None, _config_overrides=None):
"""
Creates a "fake" app for use while developing
"""
bundles = bundles or []
name = bundles[-1].module_name if bundles else 'basic_app'
app = FlaskUnchained(name, template_folder=os.path.join(
o... | python | {
"resource": ""
} |
q240912 | list_roles | train | def list_roles():
"""
List roles.
"""
roles = role_manager.all()
if roles:
print_table(['ID', 'Name'], [(role.id, role.name) for role in roles])
else:
click.echo('No roles found.') | python | {
"resource": ""
} |
q240913 | create_role | train | def create_role(name):
"""
Create a new role.
"""
role = role_manager.create(name=name)
if click.confirm(f'Are you sure you want to create {role!r}?'):
role_manager.save(role, commit=True)
click.echo(f'Successfully created {role!r}')
else:
click.echo('Cancelled.') | python | {
"resource": ""
} |
q240914 | delete_role | train | def delete_role(query):
"""
Delete a role.
"""
role = _query_to_role(query)
if click.confirm(f'Are you sure you want to delete {role!r}?'):
role_manager.delete(role, commit=True)
click.echo(f'Successfully deleted {role!r}')
else:
click.echo('Cancelled.') | python | {
"resource": ""
} |
q240915 | slugify | train | def slugify(field_name, slug_field_name=None, mutable=False):
"""Class decorator to specify a field to slugify. Slugs are immutable by
default unless mutable=True is passed.
Usage::
@slugify('title')
def Post(Model):
title = Column(String(100))
slug = Column(String(... | python | {
"resource": ""
} |
q240916 | get_message_plain_text | train | def get_message_plain_text(msg: Message):
"""
Converts an HTML message to plain text.
:param msg: A :class:`~flask_mail.Message`
:return: The plain text message.
"""
if msg.body:
return msg.body
if BeautifulSoup is None or not msg.html:
return msg.html
plain_text = '\n... | python | {
"resource": ""
} |
q240917 | _send_mail | train | def _send_mail(subject_or_message: Optional[Union[str, Message]] = None,
to: Optional[Union[str, List[str]]] = None,
template: Optional[str] = None,
**kwargs):
"""
The default function used for sending emails.
:param subject_or_message: A subject string, or for ... | python | {
"resource": ""
} |
q240918 | extract | train | def extract(domain):
"""
Extract newly added translations keys from source code.
"""
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
babel_cfg = _get_babel_cfg()
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'extract -F {babel_cfg... | python | {
"resource": ""
} |
q240919 | init | train | def init(lang, domain):
"""
Initialize translations for a language code.
"""
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain... | python | {
"resource": ""
} |
q240920 | update | train | def update(domain):
"""
Update language-specific translations files with new keys discovered by
``flask babel extract``.
"""
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'update -i ... | python | {
"resource": ""
} |
q240921 | RelationshipsMetaOption.get_value | train | def get_value(self, meta, base_model_meta, mcs_args: McsArgs):
"""overridden to merge with inherited value"""
if mcs_args.Meta.abstract:
return None
value = getattr(base_model_meta, self.name, {}) or {}
value.update(getattr(meta, self.name, {}))
return value | python | {
"resource": ""
} |
q240922 | Controller.flash | train | def flash(self, msg: str, category: Optional[str] = None):
"""
Convenience method for flashing messages.
:param msg: The message to flash.
:param category: The category of the message.
"""
if not request.is_json and app.config.FLASH_MESSAGES:
flash(msg, categ... | python | {
"resource": ""
} |
q240923 | Controller.render | train | def render(self, template_name: str, **ctx):
"""
Convenience method for rendering a template.
:param template_name: The template's name. Can either be a full path,
or a filename in the controller's template folder.
:param ctx: Context variables to pass into... | python | {
"resource": ""
} |
q240924 | Controller.redirect | train | def redirect(self,
where: Optional[str] = None,
default: Optional[str] = None,
override: Optional[str] = None,
**url_kwargs):
"""
Convenience method for returning redirect responses.
:param where: A URL, endpoint, or config key... | python | {
"resource": ""
} |
q240925 | Controller.jsonify | train | def jsonify(self,
data: Any,
code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK,
headers: Optional[Dict[str, str]] = None,
):
"""
Convenience method to return json responses.
:param data: The python data to jsonify.
:pa... | python | {
"resource": ""
} |
q240926 | Controller.errors | train | def errors(self,
errors: List[str],
code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST,
key: str = 'errors',
headers: Optional[Dict[str, str]] = None,
):
"""
Convenience method to return errors as json.
:par... | python | {
"resource": ""
} |
q240927 | set_password | train | def set_password(query, password, send_email):
"""
Set a user's password.
"""
user = _query_to_user(query)
if click.confirm(f'Are you sure you want to change {user!r}\'s password?'):
security_service.change_password(user, password, send_email=send_email)
user_manager.save(user, commi... | python | {
"resource": ""
} |
q240928 | confirm_user | train | def confirm_user(query):
"""
Confirm a user account.
"""
user = _query_to_user(query)
if click.confirm(f'Are you sure you want to confirm {user!r}?'):
if security_service.confirm_user(user):
click.echo(f'Successfully confirmed {user!r} at '
f'{user.confirme... | python | {
"resource": ""
} |
q240929 | add_role_to_user | train | def add_role_to_user(user, role):
"""
Add a role to a user.
"""
user = _query_to_user(user)
role = _query_to_role(role)
if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'):
user.roles.append(role)
user_manager.save(user, commit=True)
click.echo(f'Succe... | python | {
"resource": ""
} |
q240930 | remove_role_from_user | train | def remove_role_from_user(user, role):
"""
Remove a role from a user.
"""
user = _query_to_user(user)
role = _query_to_role(role)
if click.confirm(f'Are you sure you want to remove {role!r} from {user!r}?'):
user.roles.remove(role)
user_manager.save(user, commit=True)
cli... | python | {
"resource": ""
} |
q240931 | anonymous_user_required | train | def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
"""
Decorator requiring that there is no user currently logged in.
Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
"""
def wrapper(fn):
@wraps(fn)
def decorated(*args, **... | python | {
"resource": ""
} |
q240932 | SecurityService.login_user | train | def login_user(self,
user: User,
remember: Optional[bool] = None,
duration: Optional[timedelta] = None,
force: bool = False,
fresh: bool = True,
) -> bool:
"""
Logs a user in. You should pas... | python | {
"resource": ""
} |
q240933 | SecurityService.register_user | train | def register_user(self, user, allow_login=None, send_email=None,
_force_login_without_confirmation=False):
"""
Service method to register a user.
Sends signal `user_registered`.
Returns True if the user has been logged in, False otherwise.
"""
shou... | python | {
"resource": ""
} |
q240934 | SecurityService.change_password | train | def change_password(self, user, password, send_email=None):
"""
Service method to change a user's password.
Sends signal `password_changed`.
:param user: The :class:`User`'s password to change.
:param password: The new password.
:param send_email: Whether or not to over... | python | {
"resource": ""
} |
q240935 | SecurityService.confirm_user | train | def confirm_user(self, user):
"""
Confirms the specified user. Returns False if the user has already been
confirmed, True otherwise.
:param user: The user to confirm.
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = self.security... | python | {
"resource": ""
} |
q240936 | SecurityService.send_mail | train | def send_mail(self, subject, to, template, **template_ctx):
"""
Utility method to send mail with the `mail` template context.
"""
if not self.mail:
from warnings import warn
warn('Attempting to send mail without the mail bundle installed! '
'Pleas... | python | {
"resource": ""
} |
q240937 | _ModelSerializerMetaclass.get_declared_fields | train | def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
"""
Updates declared fields with fields converted from the SQLAlchemy model
passed as the `model` class Meta option.
"""
opts = klass.opts
converter = opts.model_converter(schema_cls=klass)
... | python | {
"resource": ""
} |
q240938 | JupyterWidget.reset | train | def reset(self, clear=False):
"""
Overridden to customize the order that the banners are printed
"""
if self._executing:
self._executing = False
self._request_info['execute'] = {}
self._reading = False
self._highlighter.highlighting_on = False
... | python | {
"resource": ""
} |
q240939 | IPythonKernelApp.log_connection_info | train | def log_connection_info(self):
"""
Overridden to customize the start-up message printed to the terminal
"""
_ctrl_c_lines = [
'NOTE: Ctrl-C does not work to exit from the command line.',
'To exit, just close the window, type "exit" or "quit" at the '
'... | python | {
"resource": ""
} |
q240940 | url_for | train | def url_for(endpoint_or_url_or_config_key: str,
_anchor: Optional[str] = None,
_cls: Optional[Union[object, type]] = None,
_external: Optional[bool] = False,
_external_host: Optional[str] = None,
_method: Optional[str] = None,
_scheme: Optional[str... | python | {
"resource": ""
} |
q240941 | redirect | train | def redirect(where: Optional[str] = None,
default: Optional[str] = None,
override: Optional[str] = None,
_anchor: Optional[str] = None,
_cls: Optional[Union[object, type]] = None,
_external: Optional[bool] = False,
_external_host: Optional[st... | python | {
"resource": ""
} |
q240942 | _url_for | train | def _url_for(endpoint: str, **values) -> Union[str, None]:
"""
The same as flask's url_for, except this also supports building external
urls for hosts that are different from app.config.SERVER_NAME. One case
where this is especially useful is for single page apps, where the frontend
is not hosted by... | python | {
"resource": ""
} |
q240943 | roles_required | train | def roles_required(*roles):
"""
Decorator which specifies that a user must have all the specified roles.
Aborts with HTTP 403: Forbidden if the user doesn't have the required roles.
Example::
@app.route('/dashboard')
@roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
def dashboard()... | python | {
"resource": ""
} |
q240944 | SecurityUtilsService.verify_hash | train | def verify_hash(self, hashed_data, compare_data):
"""
Verify a hash in the security token hashing context.
"""
return self.security.hashing_context.verify(
encode_string(compare_data), hashed_data) | python | {
"resource": ""
} |
q240945 | auth_required | train | def auth_required(decorated_fn=None, **role_rules):
"""
Decorator for requiring an authenticated user, optionally with roles.
Roles are passed as keyword arguments, like so::
@auth_required(role='REQUIRE_THIS_ONE_ROLE')
@auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES'])
... | python | {
"resource": ""
} |
q240946 | _auth_required | train | def _auth_required():
"""
Decorator that protects endpoints through token and session auth mechanisms
"""
login_mechanisms = (
('token', lambda: _check_token()),
('session', lambda: current_user.is_authenticated),
)
def wrapper(fn):
@wraps(fn)
def decorated_view... | python | {
"resource": ""
} |
q240947 | async_mail_task | train | def async_mail_task(subject_or_message, to=None, template=None, **kwargs):
"""
Celery task to send emails asynchronously using the mail bundle.
"""
to = to or kwargs.pop('recipients', [])
msg = make_message(subject_or_message, to, template, **kwargs)
with mail.connect() as connection:
co... | python | {
"resource": ""
} |
q240948 | ApiBundle.after_init_app | train | def after_init_app(self, app: FlaskUnchained):
"""
Configure the JSON encoder for Flask to be able to serialize Enums,
LocalProxy objects, and SQLAlchemy models.
"""
self.set_json_encoder(app)
app.before_first_request(self.register_model_resources) | python | {
"resource": ""
} |
q240949 | Route.endpoint | train | def endpoint(self):
"""
The endpoint for this route.
"""
if self._endpoint:
return self._endpoint
elif self._controller_cls:
endpoint = f'{snake_case(self._controller_cls.__name__)}.{self.method_name}'
return endpoint if not self.bp_name else f... | python | {
"resource": ""
} |
q240950 | Route.method_name | train | def method_name(self):
"""
The string name of this route's view function.
"""
if isinstance(self.view_func, str):
return self.view_func
return self.view_func.__name__ | python | {
"resource": ""
} |
q240951 | Route.module_name | train | def module_name(self):
"""
The module where this route's view function was defined.
"""
if not self.view_func:
return None
elif self._controller_cls:
rv = inspect.getmodule(self._controller_cls).__name__
return rv
return inspect.getmodu... | python | {
"resource": ""
} |
q240952 | Route.full_rule | train | def full_rule(self):
"""
The full url rule for this route, including any blueprint prefix.
"""
return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/')) | python | {
"resource": ""
} |
q240953 | Route.full_name | train | def full_name(self):
"""
The full name of this route's view function, including the module path
and controller name, if any.
"""
if not self.view_func:
return None
prefix = self.view_func.__module__
if self._controller_cls:
prefix = f'{pre... | python | {
"resource": ""
} |
q240954 | project | train | def project(dest, app_bundle, force, dev,
admin, api, celery, graphene, mail, oauth,
security, session, sqlalchemy, webpack):
"""
Create a new Flask Unchained project.
"""
if os.path.exists(dest) and os.listdir(dest) and not force:
if not click.confirm(f'WARNING: Project ... | python | {
"resource": ""
} |
q240955 | PluginManager.produce | train | def produce(self, *args, **kwargs):
"""Produce a new set of plugins, treating the current set as plugin
factories.
"""
new_plugins = []
for p in self._plugins:
r = p(*args, **kwargs)
new_plugins.append(r)
return PluginManager(new_plugins) | python | {
"resource": ""
} |
q240956 | PluginManager.call | train | def call(self, methodname, *args, **kwargs):
"""Call a common method on all the plugins, if it exists."""
for plugin in self._plugins:
method = getattr(plugin, methodname, None)
if method is None:
continue
yield method(*args, **kwargs) | python | {
"resource": ""
} |
q240957 | PluginManager.pipe | train | def pipe(self, methodname, first_arg, *args, **kwargs):
"""Call a common method on all the plugins, if it exists. The return
value of each call becomes the replaces the first argument in the given
argument list to pass to the next.
Useful to utilize plugins as sets of filters.
"... | python | {
"resource": ""
} |
q240958 | unified_load | train | def unified_load(namespace, subclasses=None, recurse=False):
"""Provides a unified interface to both the module and class loaders,
finding modules by default or classes if given a ``subclasses`` parameter.
"""
if subclasses is not None:
return ClassLoader(recurse=recurse).load(namespace, subcla... | python | {
"resource": ""
} |
q240959 | ModuleLoader._fill_cache | train | def _fill_cache(self, namespace):
"""Load all modules found in a namespace"""
modules = self._findPluginModules(namespace)
self._cache = list(modules) | python | {
"resource": ""
} |
q240960 | XmlModel.build_tree | train | def build_tree(self):
"""Bulids the tree with all the fields converted to Elements
"""
if self.built:
return
self.doc_root = self.root.element()
for key in self.sorted_fields():
if key not in self._fields:
continue
field = self.... | python | {
"resource": ""
} |
q240961 | _preserve_settings | train | def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter."""
@functools.wraps(method)
def _wrapper(
old: "ObservableProperty", handler: T.Callable
) -> "Obse... | python | {
"resource": ""
} |
q240962 | ObservableProperty._trigger_event | train | def _trigger_event(
self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any
) -> None:
"""Triggers an event on the associated Observable object.
The Holder is the object this property is a member of, alt_name
is used as the event name when self.event is not set, actio... | python | {
"resource": ""
} |
q240963 | ObservableProperty.create_with | train | def create_with(
cls, event: str = None, observable: T.Union[str, Observable] = None
) -> T.Callable[..., "ObservableProperty"]:
"""Creates a partial application of ObservableProperty with
event and observable preset."""
return functools.partial(cls, event=event, observable=obse... | python | {
"resource": ""
} |
q240964 | Observable.get_all_handlers | train | def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]:
"""Returns a dict with event names as keys and lists of
registered handlers as values."""
events = {}
for event, handlers in self._events.items():
events[event] = list(handlers)
return events | python | {
"resource": ""
} |
q240965 | Observable.get_handlers | train | def get_handlers(self, event: str) -> T.List[T.Callable]:
"""Returns a list of handlers registered for the given event."""
return list(self._events.get(event, [])) | python | {
"resource": ""
} |
q240966 | Observable.is_registered | train | def is_registered(self, event: str, handler: T.Callable) -> bool:
"""Returns whether the given handler is registered for the
given event."""
return handler in self._events.get(event, []) | python | {
"resource": ""
} |
q240967 | Observable.on | train | def on( # pylint: disable=invalid-name
self, event: str, *handlers: T.Callable
) -> T.Callable:
"""Registers one or more handlers to a specified event.
This method may as well be used as a decorator for the handler."""
def _on_wrapper(*handlers: T.Callable) -> T.Callable:
... | python | {
"resource": ""
} |
q240968 | Observable.once | train | def once(self, event: str, *handlers: T.Callable) -> T.Callable:
"""Registers one or more handlers to a specified event, but
removes them when the event is first triggered.
This method may as well be used as a decorator for the handler."""
def _once_wrapper(*handlers: T.Callable) -> T.C... | python | {
"resource": ""
} |
q240969 | Observable.trigger | train | def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool:
"""Triggers all handlers which are subscribed to an event.
Returns True when there were callbacks to execute, False otherwise."""
callbacks = list(self._events.get(event, []))
if not callbacks:
return False
... | python | {
"resource": ""
} |
q240970 | connection | train | def connection(profile_name='default', api_key=None):
"""Connect to DataPoint with the given API key profile name."""
if api_key is None:
profile_fname = datapoint.profile.API_profile_fname(profile_name)
if not os.path.exists(profile_fname):
raise ValueError('Profile not found in {}.... | python | {
"resource": ""
} |
q240971 | Timestep.elements | train | def elements(self):
"""Return a list of the elements which are not None"""
elements = []
for el in ct:
if isinstance(el[1], datapoint.Element.Element):
elements.append(el[1])
return elements | python | {
"resource": ""
} |
q240972 | Manager.__retry_session | train | def __retry_session(self, retries=10, backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
"""
Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint
"""
# requests.Session ... | python | {
"resource": ""
} |
q240973 | Manager.__call_api | train | def __call_api(self, path, params=None, api_url=FORECAST_URL):
"""
Call the datapoint api using the requests module
"""
if not params:
params = dict()
payload = {'key': self.api_key}
payload.update(params)
url = "%s/%s" % (api_url, path)
# Ad... | python | {
"resource": ""
} |
q240974 | Manager._get_wx_units | train | def _get_wx_units(self, params, name):
"""
Give the Wx array returned from datapoint and an element
name and return the units for that element.
"""
units = ""
for param in params:
if str(name) == str(param['name']):
units = param['units']
... | python | {
"resource": ""
} |
q240975 | Manager._visibility_to_text | train | def _visibility_to_text(self, distance):
"""
Convert observed visibility in metres to text used in forecast
"""
if not isinstance(distance, (int, long)):
raise ValueError("Distance must be an integer not", type(distance))
if distance < 0:
raise ValueError... | python | {
"resource": ""
} |
q240976 | Manager.get_forecast_sites | train | def get_forecast_sites(self):
"""
This function returns a list of Site object.
"""
time_now = time()
if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None:
data = self.__call_api("sitelist/")
... | python | {
"resource": ""
} |
q240977 | Manager.get_nearest_site | train | def get_nearest_site(self, latitude=None, longitude=None):
"""
Deprecated. This function returns nearest Site object to the specified
coordinates.
"""
warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'
warn(warning_message, Deprecati... | python | {
"resource": ""
} |
q240978 | Manager.get_nearest_forecast_site | train | def get_nearest_forecast_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site object to the specified
coordinates.
"""
if longitude is None:
print('ERROR: No latitude given.')
return False
if latitude is None:
... | python | {
"resource": ""
} |
q240979 | Manager.get_observation_sites | train | def get_observation_sites(self):
"""
This function returns a list of Site objects for which observations are available.
"""
if (time() - self.observation_sites_last_update) > self.observation_sites_update_time:
self.observation_sites_last_update = time()
data = se... | python | {
"resource": ""
} |
q240980 | Manager.get_nearest_observation_site | train | def get_nearest_observation_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site to the specified
coordinates that supports observations
"""
if longitude is None:
print('ERROR: No longitude given.')
return False
if... | python | {
"resource": ""
} |
q240981 | RegionManager.call_api | train | def call_api(self, path, **kwargs):
'''
Call datapoint api
'''
if 'key' not in kwargs:
kwargs['key'] = self.api_key
req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)
if req.status_code != requests.codes.ok:
req.raise_for_stat... | python | {
"resource": ""
} |
q240982 | RegionManager.get_all_regions | train | def get_all_regions(self):
'''
Request a list of regions from Datapoint. Returns each Region
as a Site object. Regions rarely change, so we cache the response
for one hour to minimise requests to API.
'''
if (time() - self.regions_last_update) < self.regions_update_time:
... | python | {
"resource": ""
} |
q240983 | Forecast.now | train | def now(self):
"""
Function to return just the current timestep from this forecast
"""
# From the comments in issue 19: forecast.days[0] is dated for the
# previous day shortly after midnight
now = None
# Set the time now to be in the same time zone as the first... | python | {
"resource": ""
} |
q240984 | Forecast.future | train | def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
"""
Function to return a future timestep
"""
future = None
# Initialize variables to 0
dd, hh, mm, ss = [0 for i in range(4)]
if (in_days != None):
dd = dd + in_days
... | python | {
"resource": ""
} |
q240985 | install_API_key | train | def install_API_key(api_key, profile_name='default'):
"""Put the given API key into the given profile name."""
fname = API_profile_fname(profile_name)
if not os.path.isdir(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
with open(fname, 'w') as fh:
fh.write(api_key) | python | {
"resource": ""
} |
q240986 | is_namedtuple | train | def is_namedtuple(type_: Type[Any]) -> bool:
'''
Generated with typing.NamedTuple
'''
return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields') | python | {
"resource": ""
} |
q240987 | uniontypes | train | def uniontypes(type_: Type[Any]) -> Set[Type[Any]]:
'''
Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version.
'''
if not is_union(type_):
raise ValueError('Not a Union: ' + str(type_))
if... | python | {
"resource": ""
} |
q240988 | Dumper.index | train | def index(self, value: Any) -> int:
"""
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
"""
for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)):
try:
match = co... | python | {
"resource": ""
} |
q240989 | Dumper.dump | train | def dump(self, value: Any) -> Any:
"""
Dump the typed data structure into its
untyped equivalent.
"""
index = self.index(value)
func = self.handlers[index][1]
return func(self, value) | python | {
"resource": ""
} |
q240990 | _forwardrefload | train | def _forwardrefload(l: Loader, value: Any, type_: type) -> Any:
"""
This resolves a ForwardRef.
It just looks up the type in the dictionary of known types
and loads the value using that.
"""
if l.frefs is None:
raise TypedloadException('ForwardRef resolving is disabled for the loader', ... | python | {
"resource": ""
} |
q240991 | _basicload | train | def _basicload(l: Loader, value: Any, type_: type) -> Any:
"""
This converts a value into a basic type.
In theory it does nothing, but it performs type checking
and raises if conditions fail.
It also attempts casting, if enabled.
"""
if type(value) != type_:
if l.basiccast:
... | python | {
"resource": ""
} |
q240992 | _unionload | train | def _unionload(l: Loader, value, type_) -> Any:
"""
Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised.
"""
try:
args = uniontypes(type_)
... | python | {
"resource": ""
} |
q240993 | _enumload | train | def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course... | python | {
"resource": ""
} |
q240994 | _noneload | train | def _noneload(l: Loader, value, type_) -> None:
"""
Loads a value that can only be None,
so it fails if it isn't
"""
if value is None:
return None
raise TypedloadValueError('Not None', value=value, type_=type_) | python | {
"resource": ""
} |
q240995 | Loader.index | train | def index(self, type_: Type[T]) -> int:
"""
Returns the index in the handlers list
that matches the given type.
If no condition matches, ValueError is raised.
"""
for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)):
try:
match =... | python | {
"resource": ""
} |
q240996 | Loader.load | train | def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T:
"""
Loads value into the typed data structure.
TypeError is raised if there is no known way to treat type_,
otherwise all errors raise a ValueError.
"""
try:
index = ... | python | {
"resource": ""
} |
q240997 | get_data | train | def get_data(city: Optional[str]) -> Dict[str, Any]:
"""
Use the Yahoo weather API to get weather information
"""
req = urllib.request.Request(get_url(city))
with urllib.request.urlopen(req) as f:
response = f.read()
answer = response.decode('ascii')
data = json.loads(answer)
r =... | python | {
"resource": ""
} |
q240998 | load | train | def load(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data into a type.
It is useful to avoid creating the Loader object,
in case only the default parameters are used.
"""
from . import dataloader
loader = dataloader.Loader(**kwargs)
return loader.load(val... | python | {
"resource": ""
} |
q240999 | dump | train | def dump(value: Any, **kwargs) -> Any:
"""
Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used.
"""
from . import datadumper
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.