_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15800 | load_fixtures | train | def load_fixtures():
"""Populate a database with data from fixtures."""
if local("pwd", capture=True) == PRODUCTION_DOCUMENT_ROOT:
abort("Refusing to automatically load fixtures into production database!")
if not confirm("Are you sure you want to load all fixtures? This could have unintended conse... | python | {
"resource": ""
} |
q15801 | deploy | train | def deploy():
"""Deploy to production."""
_require_root()
if not confirm("This will apply any available migrations to the database. Has the database been backed up?"):
abort("Aborted.")
if not confirm("Are you sure you want to deploy?"):
abort("Aborted.")
with lcd(PRODUCTION_DOCUME... | python | {
"resource": ""
} |
q15802 | forcemigrate | train | def forcemigrate(app=None):
"""Force migrations to apply for a given app."""
if app is None:
abort("No app name given.")
local("./manage.py migrate {} --fake".format(app))
local("./manage.py migrate {}".format(app)) | python | {
"resource": ""
} |
q15803 | UserManager.users_with_birthday | train | def users_with_birthday(self, month, day):
"""Return a list of user objects who have a birthday on a given date."""
users = User.objects.filter(properties___birthday__month=month, properties___birthday__day=day)
results = []
for user in users:
# TODO: permissions system
... | python | {
"resource": ""
} |
q15804 | UserManager.get_teachers_sorted | train | def get_teachers_sorted(self):
"""Get teachers sorted by last name.
This is used for the announcement request page.
"""
teachers = self.get_teachers()
teachers = [(u.last_name, u.first_name, u.id) for u in teachers]
for t in teachers:
if t is None or t[0] is... | python | {
"resource": ""
} |
q15805 | User.member_of | train | def member_of(self, group):
"""Returns whether a user is a member of a certain group.
Args:
group
The name of a group (string) or a group object
Returns:
Boolean
"""
if isinstance(group, Group):
group = group.name
ret... | python | {
"resource": ""
} |
q15806 | User.permissions | train | def permissions(self):
"""Dynamically generate dictionary of privacy options
"""
# TODO: optimize this, it's kind of a bad solution for listing a mostly
# static set of files.
# We could either add a permissions dict as an attribute or cache this
# in some way. Creating a... | python | {
"resource": ""
} |
q15807 | User._current_user_override | train | def _current_user_override(self):
"""Return whether the currently logged in user is a teacher, and can view all of a student's
information regardless of their privacy settings."""
try:
# threadlocals is a module, not an actual thread locals object
request = threadlocals.r... | python | {
"resource": ""
} |
q15808 | User.age | train | def age(self):
"""Returns a user's age, based on their birthday.
Returns:
integer
"""
date = datetime.today().date()
b = self.birthday
if b:
return int((date - b).days / 365)
return None | python | {
"resource": ""
} |
q15809 | User.is_eighth_sponsor | train | def is_eighth_sponsor(self):
"""Determine whether the given user is associated with an.
:class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity
sponsoring information.
"""
# FIXME: remove recursive dep
from ..eighth.models import EighthSp... | python | {
"resource": ""
} |
q15810 | User.frequent_signups | train | def frequent_signups(self):
"""Return a QuerySet of activity id's and counts for the activities that a given user
has signed up for more than `settings.SIMILAR_THRESHOLD` times"""
key = "{}:frequent_signups".format(self.username)
cached = cache.get(key)
if cached:
ret... | python | {
"resource": ""
} |
q15811 | User.absence_count | train | def absence_count(self):
"""Return the user's absence count.
If the user has no absences
or is not a signup user, returns 0.
"""
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True... | python | {
"resource": ""
} |
q15812 | User.absence_info | train | def absence_info(self):
"""Return information about the user's absences."""
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True) | python | {
"resource": ""
} |
q15813 | User.handle_delete | train | def handle_delete(self):
"""Handle a graduated user being deleted."""
from intranet.apps.eighth.models import EighthScheduledActivity
EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update(
archived_member_count=F('archived_member_count')+1) | python | {
"resource": ""
} |
q15814 | UserProperties.set_permission | train | def set_permission(self, permission, value, parent=False, admin=False):
""" Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful.
"""
try:
if not getattr(self, 'parent_{}'.format(permission)) ... | python | {
"resource": ""
} |
q15815 | UserProperties.attribute_is_visible | train | def attribute_is_visible(self, permission):
""" Checks privacy options to see if an attribute is visible to public
"""
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student)... | python | {
"resource": ""
} |
q15816 | admin_required | train | def admin_required(group):
"""Decorator that requires the user to be in a certain admin group.
For example, @admin_required("polls") would check whether a user is
in the "admin_polls" group or in the "admin_all" group.
"""
def in_admin_group(user):
return user.is_authenticated and user.ha... | python | {
"resource": ""
} |
q15817 | get_personal_info | train | def get_personal_info(user):
"""Get a user's personal info attributes to pass as an initial value to a
PersonalInformationForm."""
# change this to not use other_phones
num_phones = len(user.phones.all() or [])
num_emails = len(user.emails.all() or [])
num_websites = len(user.websites.all() or [... | python | {
"resource": ""
} |
q15818 | get_preferred_pic | train | def get_preferred_pic(user):
"""Get a user's preferred picture attributes to pass as an initial value to a
PreferredPictureForm."""
# FIXME: remove this hardcoded junk
preferred_pic = {"preferred_photo": "AUTO"}
if user.preferred_photo:
preferred_pic["preferred_photo"] = user.preferred_phot... | python | {
"resource": ""
} |
q15819 | get_privacy_options | train | def get_privacy_options(user):
"""Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm."""
privacy_options = {}
for ptype in user.permissions:
for field in user.permissions[ptype]:
if ptype == "self":
privacy_options["{}-{}".format(field, pty... | python | {
"resource": ""
} |
q15820 | get_notification_options | train | def get_notification_options(user):
"""Get a user's notification options to pass as an initial value to a
NotificationOptionsForm."""
notification_options = {}
notification_options["receive_news_emails"] = user.receive_news_emails
notification_options["receive_eighth_emails"] = user.receive_eighth_... | python | {
"resource": ""
} |
q15821 | preferences_view | train | def preferences_view(request):
"""View and process updates to the preferences page."""
user = request.user
if request.method == "POST":
logger.debug(dict(request.POST))
phone_formset, email_formset, website_formset, errors = save_personal_info(request, user)
if user.is_student:
... | python | {
"resource": ""
} |
q15822 | privacy_options_view | train | def privacy_options_view(request):
"""View and edit privacy options for a user."""
if "user" in request.GET:
user = User.objects.user_with_ion_id(request.GET.get("user"))
elif "student_id" in request.GET:
user = User.objects.user_with_student_id(request.GET.get("student_id"))
else:
... | python | {
"resource": ""
} |
q15823 | IntentIntegrator.scan | train | def scan(cls, formats=ALL_CODE_TYPES, camera=-1):
""" Shortcut only one at a time will work... """
app = AndroidApplication.instance()
r = app.create_future()
#: Initiate a scan
pkg = BarcodePackage.instance()
pkg.setBarcodeResultListener(pkg.getId())
pkg.onB... | python | {
"resource": ""
} |
q15824 | AndroidBarcodeView.on_activity_lifecycle_changed | train | def on_activity_lifecycle_changed(self, change):
""" If the app pauses without pausing the barcode scanner
the camera can't be reopened. So we must do it here.
"""
d = self.declaration
if d.active:
if change['value'] == 'paused':
self.widget.pause... | python | {
"resource": ""
} |
q15825 | AndroidBarcodeView.destroy | train | def destroy(self):
""" Cleanup the activty lifecycle listener """
if self.widget:
self.set_active(False)
super(AndroidBarcodeView, self).destroy() | python | {
"resource": ""
} |
q15826 | make_inaturalist_api_get_call | train | def make_inaturalist_api_get_call(endpoint: str, params: Dict, **kwargs) -> requests.Response:
"""Make an API call to iNaturalist.
endpoint is a string such as 'observations' !! do not put / in front
method: 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'
kwargs are passed to requests.request
Retur... | python | {
"resource": ""
} |
q15827 | get_observation | train | def get_observation(observation_id: int) -> Dict[str, Any]:
"""Get details about an observation.
:param observation_id:
:returns: a dict with details on the observation
:raises: ObservationNotFound
"""
r = get_observations(params={'id': observation_id})
if r['results']:
return r['r... | python | {
"resource": ""
} |
q15828 | get_access_token | train | def get_access_token(username: str, password: str, app_id: str, app_secret: str) -> str:
"""
Get an access token using the user's iNaturalist username and password.
(you still need an iNaturalist app to do this)
:param username:
:param password:
:param app_id:
:param app_secret:
:retur... | python | {
"resource": ""
} |
q15829 | add_photo_to_observation | train | def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str):
"""Upload a picture and assign it to an existing observation.
:param observation_id: the ID of the observation
:param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'r... | python | {
"resource": ""
} |
q15830 | delete_observation | train | def delete_observation(observation_id: int, access_token: str) -> List[Dict[str, Any]]:
"""
Delete an observation.
:param observation_id:
:param access_token:
:return:
"""
headers = _build_auth_header(access_token)
headers['Content-type'] = 'application/json'
response = requests.d... | python | {
"resource": ""
} |
q15831 | FieldPlaceholder.create_instance | train | def create_instance(self, parent):
"""Create an instance based off this placeholder with some parent"""
self.kwargs['instantiate'] = True
self.kwargs['parent'] = parent
instance = self.cls(*self.args, **self.kwargs)
instance._field_seqno = self._field_seqno
return instanc... | python | {
"resource": ""
} |
q15832 | BaseField._ph2f | train | def _ph2f(self, placeholder):
"""Lookup a field given a field placeholder"""
if issubclass(placeholder.cls, FieldAccessor):
return placeholder.cls.access(self._parent, placeholder)
return self._parent.lookup_field_by_placeholder(placeholder) | python | {
"resource": ""
} |
q15833 | CRCField.packed_checksum | train | def packed_checksum(self, data):
"""Given the data of the entire packet return the checksum bytes"""
self.field.setval(self.algo(data[self.start:self.end]))
sio = BytesIO()
self.field.pack(sio)
return sio.getvalue() | python | {
"resource": ""
} |
q15834 | FieldAccessor.access | train | def access(cls, parent, placeholder):
"""Resolve the deferred field attribute access.
:param cls: the FieldAccessor class
:param parent: owning structure of the field being accessed
:param placeholder: FieldPlaceholder object which holds our info
:returns: FieldAccessor instance... | python | {
"resource": ""
} |
q15835 | crc16_ccitt | train | def crc16_ccitt(data, crc=0):
"""Calculate the crc16 ccitt checksum of some data
A starting crc value may be specified if desired. The input data
is expected to be a sequence of bytes (string) and the output
is an integer in the range (0, 0xFFFF). No packing is done to the
resultant crc value. T... | python | {
"resource": ""
} |
q15836 | StreamProtocolHandler.feed | train | def feed(self, new_bytes):
"""Feed a new set of bytes into the protocol handler
These bytes will be immediately fed into the parsing state machine and
if new packets are found, the ``packet_callback`` will be executed
with the fully-formed message.
:param new_bytes: The new byt... | python | {
"resource": ""
} |
q15837 | URL.validate | train | def validate(self, instance, value):
"""Check if input is valid URL"""
value = super(URL, self).validate(instance, value)
parsed_url = urlparse(value)
if not parsed_url.scheme or not parsed_url.netloc:
self.error(instance, value, extra='URL needs scheme and netloc.')
... | python | {
"resource": ""
} |
q15838 | Singleton.serialize | train | def serialize(self, include_class=True, save_dynamic=False, **kwargs):
"""Serialize Singleton instance to a dictionary.
This behaves identically to HasProperties.serialize, except it also
saves the identifying name in the dictionary as well.
"""
json_dict = super(Singleton, self... | python | {
"resource": ""
} |
q15839 | Singleton.deserialize | train | def deserialize(cls, value, trusted=False, strict=False,
assert_valid=False, **kwargs):
"""Create a Singleton instance from a serialized dictionary.
This behaves identically to HasProperties.deserialize, except if
the singleton is already found in the singleton registry the ... | python | {
"resource": ""
} |
q15840 | add_properties_callbacks | train | def add_properties_callbacks(cls):
"""Class decorator to add change notifications to builtin containers"""
for name in cls._mutators: #pylint: disable=protected-access
if not hasattr(cls, name):
continue
setattr(cls, name, properties_mu... | python | {
"resource": ""
} |
q15841 | properties_mutator | train | def properties_mutator(cls, name, ioper=False):
"""Wraps a mutating container method to add HasProperties notifications
If the container is not part of a HasProperties instance, behavior
is unchanged. However, if it is part of a HasProperties instance
the new method calls set, triggering change notific... | python | {
"resource": ""
} |
q15842 | properties_operator | train | def properties_operator(cls, name):
"""Wraps a container operator to ensure container class is maintained"""
def wrapper(self, *args, **kwargs):
"""Perform operation and cast to container class"""
output = getattr(super(cls, self), name)(*args, **kwargs)
return cls(output)
wrapped ... | python | {
"resource": ""
} |
q15843 | observable_copy | train | def observable_copy(value, name, instance):
"""Return an observable container for HasProperties notifications
This method creates a new container class to allow HasProperties
instances to :code:`observe_mutations`. It returns a copy of the
input value as this new class.
The output class behaves id... | python | {
"resource": ""
} |
q15844 | validate_prop | train | def validate_prop(value):
"""Validate Property instance for container items"""
if (
isinstance(value, CLASS_TYPES) and
issubclass(value, HasProperties)
):
value = Instance('', value)
if not isinstance(value, basic.Property):
raise TypeError('Contained prop must be... | python | {
"resource": ""
} |
q15845 | Tuple.validate | train | def validate(self, instance, value):
"""Check the class of the container and validate each element
This returns a copy of the container to prevent unwanted sharing of
pointers.
"""
if not self.coerce and not isinstance(value, self._class_container):
self.error(instan... | python | {
"resource": ""
} |
q15846 | Tuple.assert_valid | train | def assert_valid(self, instance, value=None):
"""Check if tuple and contained properties are valid"""
valid = super(Tuple, self).assert_valid(instance, value)
if not valid:
return False
if value is None:
value = instance._get(self.name)
if value is Non... | python | {
"resource": ""
} |
q15847 | Tuple.serialize | train | def serialize(self, value, **kwargs):
"""Return a serialized copy of the tuple"""
kwargs.update({'include_class': kwargs.get('include_class', True)})
if self.serializer is not None:
return self.serializer(value, **kwargs)
if value is None:
return None
seri... | python | {
"resource": ""
} |
q15848 | Tuple.deserialize | train | def deserialize(self, value, **kwargs):
"""Return a deserialized copy of the tuple"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer is not None:
return self.deserializer(value, **kwargs)
if value is None:
return None
output_... | python | {
"resource": ""
} |
q15849 | Tuple.to_json | train | def to_json(value, **kwargs):
"""Return a copy of the tuple as a list
If the tuple contains HasProperties instances, they are serialized.
"""
serial_list = [
val.serialize(**kwargs) if isinstance(val, HasProperties)
else val for val in value
]
ret... | python | {
"resource": ""
} |
q15850 | Tuple.sphinx_class | train | def sphinx_class(self):
"""Redefine sphinx class to point to prop class"""
classdoc = self.prop.sphinx_class().replace(
':class:`', '{info} of :class:`'
)
return classdoc.format(info=self.class_info) | python | {
"resource": ""
} |
q15851 | Dictionary.assert_valid | train | def assert_valid(self, instance, value=None):
"""Check if dict and contained properties are valid"""
valid = super(Dictionary, self).assert_valid(instance, value)
if not valid:
return False
if value is None:
value = instance._get(self.name)
if value is Non... | python | {
"resource": ""
} |
q15852 | Dictionary.serialize | train | def serialize(self, value, **kwargs):
"""Return a serialized copy of the dict"""
kwargs.update({'include_class': kwargs.get('include_class', True)})
if self.serializer is not None:
return self.serializer(value, **kwargs)
if value is None:
return None
seria... | python | {
"resource": ""
} |
q15853 | Dictionary.deserialize | train | def deserialize(self, value, **kwargs):
"""Return a deserialized copy of the dict"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer is not None:
return self.deserializer(value, **kwargs)
if value is None:
return None
output_t... | python | {
"resource": ""
} |
q15854 | Dictionary.to_json | train | def to_json(value, **kwargs):
"""Return a copy of the dictionary
If the values are HasProperties instances, they are serialized
"""
serial_dict = {
key: (
val.serialize(**kwargs) if isinstance(val, HasProperties)
else val
)
... | python | {
"resource": ""
} |
q15855 | filter_props | train | def filter_props(has_props_cls, input_dict, include_immutable=True):
"""Split a dictionary based keys that correspond to Properties
Returns:
**(props_dict, others_dict)** - Tuple of two dictionaries. The first contains
key/value pairs from the input dictionary that correspond to the
Properties of t... | python | {
"resource": ""
} |
q15856 | Union.default | train | def default(self):
"""Default value of the property"""
prop_def = getattr(self, '_default', utils.undefined)
for prop in self.props:
if prop.default is utils.undefined:
continue
if prop_def is utils.undefined:
prop_def = prop.default
... | python | {
"resource": ""
} |
q15857 | Union._try_prop_method | train | def _try_prop_method(self, instance, value, method_name):
"""Helper method to perform a method on each of the union props
This method gathers all errors and returns them at the end
if the method on each of the props fails.
"""
error_messages = []
for prop in self.props:
... | python | {
"resource": ""
} |
q15858 | Union.assert_valid | train | def assert_valid(self, instance, value=None):
"""Check if the Union has a valid value"""
valid = super(Union, self).assert_valid(instance, value)
if not valid:
return False
if value is None:
value = instance._get(self.name)
if value is None:
... | python | {
"resource": ""
} |
q15859 | Union.serialize | train | def serialize(self, value, **kwargs):
"""Return a serialized value
If no serializer is provided, it uses the serialize method of the
prop corresponding to the value
"""
kwargs.update({'include_class': kwargs.get('include_class', True)})
if self.serializer is not None:
... | python | {
"resource": ""
} |
q15860 | Union.deserialize | train | def deserialize(self, value, **kwargs):
"""Return a deserialized value
If no deserializer is provided, it uses the deserialize method of the
prop corresponding to the value
"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer is not None:
... | python | {
"resource": ""
} |
q15861 | Union.to_json | train | def to_json(value, **kwargs):
"""Return value, serialized if value is a HasProperties instance"""
if isinstance(value, HasProperties):
return value.serialize(**kwargs)
return value | python | {
"resource": ""
} |
q15862 | accept_kwargs | train | def accept_kwargs(func):
"""Wrap a function that may not accept kwargs so they are accepted
The output function will always have call signature of
:code:`func(val, **kwargs)`, whereas the original function may have
call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`.
In the case of ... | python | {
"resource": ""
} |
q15863 | GettableProperty.terms | train | def terms(self):
"""Initialization terms and options for Property"""
terms = PropertyTerms(
self.name,
self.__class__,
self._args,
self._kwargs,
self.meta
)
return terms | python | {
"resource": ""
} |
q15864 | GettableProperty.tag | train | def tag(self, *tag, **kwtags):
"""Tag a Property instance with metadata dictionary"""
if not tag:
pass
elif len(tag) == 1 and isinstance(tag[0], dict):
self._meta.update(tag[0])
else:
raise TypeError('Tags must be provided as key-word arguments or '
... | python | {
"resource": ""
} |
q15865 | GettableProperty.equal | train | def equal(self, value_a, value_b): #pylint: disable=no-self-use
"""Check if two valid Property values are equal
.. note::
This method assumes that :code:`None` and
:code:`properties.undefined` are never passed in as values
"""
... | python | {
"resource": ""
} |
q15866 | GettableProperty.get_property | train | def get_property(self):
"""Establishes access of GettableProperty values"""
scope = self
def fget(self):
"""Call the HasProperties _get method"""
return self._get(scope.name)
return property(fget=fget, doc=scope.sphinx()) | python | {
"resource": ""
} |
q15867 | GettableProperty.deserialize | train | def deserialize(self, value, **kwargs): #pylint: disable=unused-argument
"""Deserialize input value to valid Property value
This method uses the Property :code:`deserializer` if available.
Otherwise, it uses :code:`from_json`. Any keyword arguments are
... | python | {
"resource": ""
} |
q15868 | GettableProperty.sphinx | train | def sphinx(self):
"""Generate Sphinx-formatted documentation for the Property"""
try:
assert __IPYTHON__
classdoc = ''
except (NameError, AssertionError):
scls = self.sphinx_class()
classdoc = ' ({})'.format(scls) if scls else ''
prop_doc ... | python | {
"resource": ""
} |
q15869 | GettableProperty.sphinx_class | train | def sphinx_class(self):
"""Property class name formatted for Sphinx doc linking"""
classdoc = ':class:`{cls} <{pref}.{cls}>`'
if self.__module__.split('.')[0] == 'properties':
pref = 'properties'
else:
pref = text_type(self.__module__)
return classdoc.form... | python | {
"resource": ""
} |
q15870 | DynamicProperty.setter | train | def setter(self, func):
"""Register a set function for the DynamicProperty
This function must take two arguments, self and the new value.
Input value to the function is validated with prop validation prior to
execution.
"""
if not callable(func):
raise TypeEr... | python | {
"resource": ""
} |
q15871 | DynamicProperty.deleter | train | def deleter(self, func):
"""Register a delete function for the DynamicProperty
This function may only take one argument, self.
"""
if not callable(func):
raise TypeError('deleter must be callable function')
if hasattr(func, '__code__') and func.__code__.co_argcount !... | python | {
"resource": ""
} |
q15872 | Property.sphinx | train | def sphinx(self):
"""Basic docstring formatted for Sphinx docs"""
if callable(self.default):
default_val = self.default()
default_str = 'new instance of {}'.format(
default_val.__class__.__name__
)
else:
default_val = self.default
... | python | {
"resource": ""
} |
q15873 | Boolean.validate | train | def validate(self, instance, value):
"""Checks if value is a boolean"""
if self.cast:
value = bool(value)
if not isinstance(value, BOOLEAN_TYPES):
self.error(instance, value)
return value | python | {
"resource": ""
} |
q15874 | Boolean.from_json | train | def from_json(value, **kwargs):
"""Coerces JSON string to boolean"""
if isinstance(value, string_types):
value = value.upper()
if value in ('TRUE', 'Y', 'YES', 'ON'):
return True
if value in ('FALSE', 'N', 'NO', 'OFF'):
return False
... | python | {
"resource": ""
} |
q15875 | Complex.validate | train | def validate(self, instance, value):
"""Checks that value is a complex number
Floats and Integers are coerced to complex numbers
"""
try:
compval = complex(value)
if not self.cast and (
abs(value.real - compval.real) > TOL or
... | python | {
"resource": ""
} |
q15876 | String.validate | train | def validate(self, instance, value):
"""Check if value is a string, and strips it and changes case"""
value_type = type(value)
if not isinstance(value, string_types):
self.error(instance, value)
if self.regex is not None and self.regex.search(value) is None: #pylint: d... | python | {
"resource": ""
} |
q15877 | StringChoice.info | train | def info(self):
"""Formatted string to display the available choices"""
if self.descriptions is None:
choice_list = ['"{}"'.format(choice) for choice in self.choices]
else:
choice_list = [
'"{}" ({})'.format(choice, self.descriptions[choice])
... | python | {
"resource": ""
} |
q15878 | StringChoice.validate | train | def validate(self, instance, value): #pylint: disable=inconsistent-return-statements
"""Check if input is a valid string based on the choices"""
if not isinstance(value, string_types):
self.error(instance, value)
for key, val in self.choices.item... | python | {
"resource": ""
} |
q15879 | Color.validate | train | def validate(self, instance, value):
"""Check if input is valid color and converts to RGB"""
if isinstance(value, string_types):
value = COLORS_NAMED.get(value, value)
if value.upper() == 'RANDOM':
value = random.choice(COLORS_20)
value = value.upper()... | python | {
"resource": ""
} |
q15880 | DateTime.validate | train | def validate(self, instance, value):
"""Check if value is a valid datetime object or JSON datetime string"""
if isinstance(value, datetime.datetime):
return value
if not isinstance(value, string_types):
self.error(
instance=instance,
value=... | python | {
"resource": ""
} |
q15881 | Uuid.validate | train | def validate(self, instance, value):
"""Check that value is a valid UUID instance"""
if not isinstance(value, uuid.UUID):
self.error(instance, value)
return value | python | {
"resource": ""
} |
q15882 | File.valid_modes | train | def valid_modes(self):
"""Valid modes of an open file"""
default_mode = (self.mode,) if self.mode is not None else None
return getattr(self, '_valid_mode', default_mode) | python | {
"resource": ""
} |
q15883 | File.validate | train | def validate(self, instance, value):
"""Checks that the value is a valid file open in the correct mode
If value is a string, it attempts to open it with the given mode.
"""
if isinstance(value, string_types) and self.mode is not None:
try:
value = open(value,... | python | {
"resource": ""
} |
q15884 | Renamed.display_warning | train | def display_warning(self):
"""Display a FutureWarning about using a Renamed Property"""
if self.warn:
warnings.warn(
"\nProperty '{}' is deprecated and may be removed in the "
"future. Please use '{}'.".format(self.name, self.new_name),
FutureW... | python | {
"resource": ""
} |
q15885 | Instance.validate | train | def validate(self, instance, value):
"""Check if value is valid type of instance_class
If value is an instance of instance_class, it is returned unmodified.
If value is either (1) a keyword dictionary with valid parameters
to construct an instance of instance_class or (2) a valid input
... | python | {
"resource": ""
} |
q15886 | Instance.assert_valid | train | def assert_valid(self, instance, value=None):
"""Checks if valid, including HasProperty instances pass validation"""
valid = super(Instance, self).assert_valid(instance, value)
if not valid:
return False
if value is None:
value = instance._get(self.name)
i... | python | {
"resource": ""
} |
q15887 | Instance.serialize | train | def serialize(self, value, **kwargs):
"""Serialize instance to JSON
If the value is a HasProperties instance, it is serialized with
the include_class argument passed along. Otherwise, to_json is
called.
"""
kwargs.update({'include_class': kwargs.get('include_class', True... | python | {
"resource": ""
} |
q15888 | Instance.to_json | train | def to_json(value, **kwargs):
"""Convert instance to JSON"""
if isinstance(value, HasProperties):
return value.serialize(**kwargs)
try:
return json.loads(json.dumps(value))
except TypeError:
raise TypeError(
"Cannot convert type {} to J... | python | {
"resource": ""
} |
q15889 | Instance.sphinx_class | train | def sphinx_class(self):
"""Redefine sphinx class so documentation links to instance_class"""
classdoc = ':class:`{cls} <{pref}.{cls}>`'.format(
cls=self.instance_class.__name__,
pref=self.instance_class.__module__,
)
return classdoc | python | {
"resource": ""
} |
q15890 | properties_observer | train | def properties_observer(instance, prop, callback, **kwargs):
"""Adds properties callback handler"""
change_only = kwargs.get('change_only', True)
observer(instance, prop, callback, change_only=change_only) | python | {
"resource": ""
} |
q15891 | directional_link._update | train | def _update(self, *_):
"""Set target value to source value"""
if getattr(self, '_unlinked', False):
return
if getattr(self, '_updating', False):
return
self._updating = True
try:
setattr(self.target[0], self.target[1], self.transform(
... | python | {
"resource": ""
} |
q15892 | Array.validate | train | def validate(self, instance, value):
"""Determine if array is valid based on shape and dtype"""
if not isinstance(value, (tuple, list, np.ndarray)):
self.error(instance, value)
if self.coerce:
value = self.wrapper(value)
valid_class = (
self.wrapper if... | python | {
"resource": ""
} |
q15893 | Array.error | train | def error(self, instance, value, error_class=None, extra=''):
"""Generates a ValueError on setting property to an invalid value"""
error_class = error_class or ValidationError
if not isinstance(value, (list, tuple, np.ndarray)):
super(Array, self).error(instance, value, error_class, ... | python | {
"resource": ""
} |
q15894 | Array.deserialize | train | def deserialize(self, value, **kwargs):
"""De-serialize the property value from JSON
If no deserializer has been registered, this converts the value
to the wrapper class with given dtype.
"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer i... | python | {
"resource": ""
} |
q15895 | Array.to_json | train | def to_json(value, **kwargs):
"""Convert array to JSON list
nan values are converted to string 'nan', inf values to 'inf'.
"""
def _recurse_list(val):
if val and isinstance(val[0], list):
return [_recurse_list(v) for v in val]
return [str(v) if np... | python | {
"resource": ""
} |
q15896 | BaseVector.validate | train | def validate(self, instance, value):
"""Check shape and dtype of vector and scales it to given length"""
value = super(BaseVector, self).validate(instance, value)
if self.length is not None:
try:
value.length = self._length_array(value)
except ZeroDivisi... | python | {
"resource": ""
} |
q15897 | LazyI18nString.localize | train | def localize(self, lng: str) -> str:
"""
Evaluate the given string with respect to the locale defined by ``lng``.
If no string is available in the currently active language, this will give you
the string in the system's default language. If this is unavailable as well, it
will g... | python | {
"resource": ""
} |
q15898 | _set_listener | train | def _set_listener(instance, obs):
"""Add listeners to a HasProperties instance"""
if obs.names is everything:
names = list(instance._props)
else:
names = obs.names
for name in names:
if name not in instance._listeners:
instance._listeners[name] = {typ: [] for typ in L... | python | {
"resource": ""
} |
q15899 | _get_listeners | train | def _get_listeners(instance, change):
"""Gets listeners of changed Property on a HasProperties instance"""
if (
change['mode'] not in listeners_disabled._quarantine and #pylint: disable=protected-access
change['name'] in instance._listeners
):
return instance._liste... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.