INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Deserialize ``value``. :param value: The value to be deserialized. :param str attr: The attribute/key in `data` to be deserialized. :param dict data: The raw input data passed to the `Schema.load`. :param dict kwargs': Field-specific keyword arguments. :raise ValidationError: If...
def deserialize(self, value, attr=None, data=None, **kwargs): """Deserialize ``value``. :param value: The value to be deserialized. :param str attr: The attribute/key in `data` to be deserialized. :param dict data: The raw input data passed to the `Schema.load`. :param dict kwar...
Update field with values from its parent schema. Called by :meth:`_bind_field<marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema schema: Parent schema.
def _bind_to_schema(self, field_name, schema): """Update field with values from its parent schema. Called by :meth:`_bind_field<marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema schema: Parent schema. """ self.parent = s...
Reference to the `Schema` that this field belongs to even if it is buried in a `List`. Return `None` for unbound fields.
def root(self): """Reference to the `Schema` that this field belongs to even if it is buried in a `List`. Return `None` for unbound fields. """ ret = self while hasattr(ret, 'parent') and ret.parent: ret = ret.parent return ret if isinstance(ret, SchemaABC) el...
The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema`
def schema(self): """The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema` """ if not self.__schema: # Inherit context from parent. context = getattr(self.parent, 'context', {}) if isinstance(self.nested...
Same as :meth:`Field._deserialize` with additional ``partial`` argument. :param bool|tuple partial: For nested schemas, the ``partial`` parameter passed to `Schema.load`. .. versionchanged:: 3.0.0 Add ``partial`` parameter
def _deserialize(self, value, attr, data, partial=None, **kwargs): """Same as :meth:`Field._deserialize` with additional ``partial`` argument. :param bool|tuple partial: For nested schemas, the ``partial`` parameter passed to `Schema.load`. .. versionchanged:: 3.0.0 Add...
Format the value or raise a :exc:`ValidationError` if an error occurs.
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None if isinstance(value, uuid.UUID): return value try: if isinstance(value, bytes) and len(value) == 16: ...
Return the number value for value, given this field's `num_type`.
def _format_num(self, value): """Return the number value for value, given this field's `num_type`.""" # (value is True or value is False) is ~5x faster than isinstance(value, bool) if value is True or value is False: raise TypeError('value must be a Number, not a boolean.') r...
Format the value or raise a :exc:`ValidationError` if an error occurs.
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None try: return self._format_num(value) except (TypeError, ValueError): self.fail('invalid', input=value) except...
Return a string if `self.as_string=True`, otherwise return this field's `num_type`.
def _serialize(self, value, attr, obj, **kwargs): """Return a string if `self.as_string=True`, otherwise return this field's `num_type`.""" ret = self._validated(value) return ( self._to_string(ret) if (self.as_string and ret not in (None, missing_)) else ret ...
Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.
def _deserialize(self, value, attr, data, **kwargs): """Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.""" if not value: # falsy values are invalid self.fail('invalid') try: return utils.from_iso_time(value) except (AttributeError, TypeE...
Return True if ``val`` is either a subclass or instance of ``class_``.
def is_instance_or_subclass(val, class_): """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset.
def local_rfcformat(dt): """Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset. """ weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()] month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'...
Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of :meth:`marshmallow.Schema.dump`.
def pprint(obj, *args, **kwargs): """Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of :meth:`marshmallow.Schema.dump`. """ if isinstance(obj, collections.OrderedDict): print(json.dumps(obj, *args, **kwargs)) else: ...
Return the RFC822-formatted representation of a datetime object. :param datetime dt: The datetime. :param bool localtime: If ``True``, return the date relative to the local timezone instead of UTC, displaying the proper offset, e.g. "Sun, 10 Nov 2013 08:23:45 -0600"
def rfcformat(dt, localtime=False): """Return the RFC822-formatted representation of a datetime object. :param datetime dt: The datetime. :param bool localtime: If ``True``, return the date relative to the local timezone instead of UTC, displaying the proper offset, e.g. "Sun, 10 Nov 2013 0...
Return the ISO8601-formatted UTC representation of a datetime object.
def isoformat(dt, localtime=False, *args, **kwargs): """Return the ISO8601-formatted UTC representation of a datetime object.""" if localtime and dt.tzinfo is not None: localized = dt else: if dt.tzinfo is None: localized = UTC.localize(dt) else: localized = d...
Parse a RFC822-formatted datetime string and return a datetime object. Use dateutil's parser if possible. https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime
def from_rfc(datestring, use_dateutil=True): """Parse a RFC822-formatted datetime string and return a datetime object. Use dateutil's parser if possible. https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime """ # Use dateutil's parser if possible ...
Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if possible and return a timezone-aware datetime.
def from_iso_datetime(datetimestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if possible and return a timezone-aware datetime. """ if not _iso8601_datetime_re.match(datetimestring): raise ValueError('Not a valid ISO8...
Parse an ISO8601-formatted datetime string and return a datetime.time object.
def from_iso_time(timestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime.time object. """ if not _iso8601_time_re.match(timestring): raise ValueError('Not a valid ISO8601-formatted time string') if dateutil_available and use_dateutil: retu...
Set a value in a dict. If `key` contains a '.', it is assumed be a path (i.e. dot-delimited string) to the value's location. :: >>> d = {} >>> set_value(d, 'foo.bar', 42) >>> d {'foo': {'bar': 42}}
def set_value(dct, key, value): """Set a value in a dict. If `key` contains a '.', it is assumed be a path (i.e. dot-delimited string) to the value's location. :: >>> d = {} >>> set_value(d, 'foo.bar', 42) >>> d {'foo': {'bar': 42}} """ if '.' in key: head, ...
Given a callable, return a tuple of argument names. Handles `functools.partial` objects and class-based callables. .. versionchanged:: 3.0.0a1 Do not return bound arguments, eg. ``self``.
def get_func_args(func): """Given a callable, return a tuple of argument names. Handles `functools.partial` objects and class-based callables. .. versionchanged:: 3.0.0a1 Do not return bound arguments, eg. ``self``. """ if isinstance(func, functools.partial): return _signature(func....
Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance.
def resolve_field_instance(cls_or_instance): """Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance. """ if isinstance(cls_or_instance, type): if not issubclass(cls_or_instance, FieldABC): raise FieldInst...
Convert naive time to local time
def localize(self, dt, is_dst=False): """Convert naive time to local time""" if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') return dt.replace(tzinfo=self)
Checks whether or not the email address is already verified beyond allauth scope, for example, by having accepted an invitation before signing up.
def is_email_verified(self, request, email): """ Checks whether or not the email address is already verified beyond allauth scope, for example, by having accepted an invitation before signing up. """ ret = False verified_email = request.session.get('account_verifi...
Check if a username/password combination is valid.
def check_auth(email, password): """Check if a username/password combination is valid. """ try: user = User.get(User.email == email) except User.DoesNotExist: return False return password == user.password
Returns the default URL to redirect to after logging in. Note that URLs passed explicitly (e.g. by passing along a `next` GET parameter) take precedence over the value returned here.
def get_login_redirect_url(self, request): """ Returns the default URL to redirect to after logging in. Note that URLs passed explicitly (e.g. by passing along a `next` GET parameter) take precedence over the value returned here. """ assert request.user.is_authenticated ...
Correct the timezone information on the given datetime
def normalize(self, dt, is_dst=False): """Correct the timezone information on the given datetime""" if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self)
Fetches email address from email API endpoint
def get_email(self, token): """Fetches email address from email API endpoint""" resp = requests.get(self.emails_url, params={'access_token': token.token}) emails = resp.json().get('values', []) email = '' try: email = emails[0].get('email')...
The URL to return to after successful e-mail confirmation.
def get_email_confirmation_redirect_url(self, request): """ The URL to return to after successful e-mail confirmation. """ if request.user.is_authenticated: if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL: return \ app_settin...
Saves a new `User` instance using information provided in the signup form.
def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from .utils import user_username, user_email, user_field data = form.cleaned_data first_name = data.get('first_name') ...
Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique).
def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ from .utils import user_username, user_email, user_field first_name = user_field(user, '...
Validates the username. You can hook into this if you want to (dynamically) restrict what usernames can be chosen.
def clean_username(self, username, shallow=False): """ Validates the username. You can hook into this if you want to (dynamically) restrict what usernames can be chosen. """ for validator in app_settings.USERNAME_VALIDATORS: validator(username) # TODO: Add re...
Validates a password. You can hook into this if you want to restric the allowed password choices.
def clean_password(self, password, user=None): """ Validates a password. You can hook into this if you want to restric the allowed password choices. """ min_length = app_settings.PASSWORD_MIN_LENGTH if min_length and len(password) < min_length: raise forms.Val...
Wrapper of `django.contrib.messages.add_message`, that reads the message text from a template.
def add_message(self, request, level, message_template, message_context=None, extra_tags=''): """ Wrapper of `django.contrib.messages.add_message`, that reads the message text from a template. """ if 'django.contrib.messages' in settings.INSTALLED_APPS: ...
Marks the email address as confirmed on the db
def confirm_email(self, request, email_address): """ Marks the email address as confirmed on the db """ email_address.verified = True email_address.set_as_primary(conditional=True) email_address.save()
Constructs the email confirmation (activation) url. Note that if you have architected your system such that email confirmations are sent outside of the request context `request` can be `None` here.
def get_email_confirmation_url(self, request, emailconfirmation): """Constructs the email confirmation (activation) url. Note that if you have architected your system such that email confirmations are sent outside of the request context `request` can be `None` here. """ ...
Only authenticates, does not actually login. See `login`
def authenticate(self, request, **credentials): """Only authenticates, does not actually login. See `login`""" from allauth.account.auth_backends import AuthenticationBackend self.pre_authenticate(request, **credentials) AuthenticationBackend.unstash_authenticated_user() user = ...
Extract fields from a metadata query.
def extract_common_fields(self, data): """Extract fields from a metadata query.""" return dict( dc=data.get('dc'), role=data.get('role'), account_name=data.get('accountname'), user_id=data.get('user_id'), login=data.get('login'), lo...
Convert XML structure to dict recursively, repeated keys entries are returned as in list containers.
def to_dict(self, xml): """ Convert XML structure to dict recursively, repeated keys entries are returned as in list containers. """ children = list(xml) if not children: return xml.text else: out = {} for node in list(xml): ...
{% provider_login_url "facebook" next=bla %} {% provider_login_url "openid" openid="http://me.yahoo.com" next=bla %}
def provider_login_url(parser, token): """ {% provider_login_url "facebook" next=bla %} {% provider_login_url "openid" openid="http://me.yahoo.com" next=bla %} """ bits = token.split_contents() provider_id = bits[1] params = token_kwargs(bits[2:], parser, support_legacy=False) return Pro...
{% get_social_accounts user as accounts %} Then: {{accounts.twitter}} -- a list of connected Twitter accounts {{accounts.twitter.0}} -- the first Twitter account {% if accounts %} -- if there is at least one social account
def get_social_accounts(user): """ {% get_social_accounts user as accounts %} Then: {{accounts.twitter}} -- a list of connected Twitter accounts {{accounts.twitter.0}} -- the first Twitter account {% if accounts %} -- if there is at least one social account """ accounts = {}...
Saves a newly signed up social login. In case of auto-signup, the signup form is not available.
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(reques...
Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User...
def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated repres...
Returns the default URL to redirect to after successfully connecting a social account.
def get_connect_redirect_url(self, request, socialaccount): """ Returns the default URL to redirect to after successfully connecting a social account. """ assert request.user.is_authenticated url = reverse('socialaccount_connections') return url
Validate whether or not the socialaccount account can be safely disconnected.
def validate_disconnect(self, account, accounts): """ Validate whether or not the socialaccount account can be safely disconnected. """ if len(accounts) == 1: # No usable password would render the local account unusable if not account.user.has_usable_passw...
Since Django 1.6 items added to the session are no longer pickled, but JSON encoded by default. We are storing partially complete models in the session (user, account, token, ...). We cannot use standard Django serialization, as these are models are not "complete" yet. Serialization will start complaini...
def serialize_instance(instance): """ Since Django 1.6 items added to the session are no longer pickled, but JSON encoded by default. We are storing partially complete models in the session (user, account, token, ...). We cannot use standard Django serialization, as these are models are not "complet...
This function is a verbatim copy of django.forms.Form.order_fields() to support field ordering below Django 1.9. field_order is a list of field names specifying the order. Append fields not included in the list in the default order for backward compatibility with subclasses not overriding field_order. ...
def set_form_field_order(form, field_order): """ This function is a verbatim copy of django.forms.Form.order_fields() to support field ordering below Django 1.9. field_order is a list of field names specifying the order. Append fields not included in the list in the default order for backward compa...
request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where request is None.
def build_absolute_uri(request, location, protocol=None): """request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where request is None. """ from .account import app_settings as account_settings if request is None: site = Site.objects.ge...
Currently, we inherit from the custom form, if any. This is all not very elegant, though it serves a purpose: - There are two signup forms: one for local accounts, and one for social accounts - Both share a common base (BaseSignupForm) - Given the above, how to put in a custom signup form? Which...
def _base_signup_form_class(): """ Currently, we inherit from the custom form, if any. This is all not very elegant, though it serves a purpose: - There are two signup forms: one for local accounts, and one for social accounts - Both share a common base (BaseSignupForm) - Given the above...
Provides the credentials required to authenticate the user for login.
def user_credentials(self): """ Provides the credentials required to authenticate the user for login. """ credentials = {} login = self.cleaned_data["login"] if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: credentials["email"] = lo...
Parses the FacebookLocales.xml file and builds a dict relating every available language ('en, 'es, 'zh', ...) with a list of available regions for that language ('en' -> 'US', 'EN') and an (arbitrary) default region.
def _build_locale_table(filename_or_file): """ Parses the FacebookLocales.xml file and builds a dict relating every available language ('en, 'es, 'zh', ...) with a list of available regions for that language ('en' -> 'US', 'EN') and an (arbitrary) default region. """ # Require the XML parser mod...
Wrapper function so that the default mapping is only built when needed
def get_default_locale_callable(): """ Wrapper function so that the default mapping is only built when needed """ exec_dir = os.path.dirname(os.path.realpath(__file__)) xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml') fb_locales = _build_locale_table(xml_path) def default_l...
The user is required to hand over an e-mail address when signing up
def EMAIL_REQUIRED(self): """ The user is required to hand over an e-mail address when signing up """ from allauth.account import app_settings as account_settings return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED)
See e-mail verification method
def EMAIL_VERIFICATION(self): """ See e-mail verification method """ from allauth.account import app_settings as account_settings return self._setting("EMAIL_VERIFICATION", account_settings.EMAIL_VERIFICATION)
Returns string representation of a social account. Includes the name of the user.
def to_str(self): ''' Returns string representation of a social account. Includes the name of the user. ''' dflt = super(DataportenAccount, self).to_str() return '%s (%s)' % ( self.account.extra_data.get('name', ''), dflt, )
This function extracts information from the /userinfo endpoint which will be consumed by allauth.socialaccount.adapter.populate_user(). Look there to find which key-value pairs that should be saved in the returned dict. Typical return dict: { "userid": "76a7a061-3c55...
def extract_common_fields(self, data): ''' This function extracts information from the /userinfo endpoint which will be consumed by allauth.socialaccount.adapter.populate_user(). Look there to find which key-value pairs that should be saved in the returned dict. Typical ...
Even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified users to proceed. This decorator ensures the user is authenticated and has a verified email address. If the former is not the case then the behavior is identical to ...
def verified_email_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified user...
Added because the Dropbox OAuth2 flow doesn't work when scope is passed in, which is empty.
def _strip_empty_keys(self, params): """Added because the Dropbox OAuth2 flow doesn't work when scope is passed in, which is empty. """ keys = [k for k, v in params.items() if v == ''] for key in keys: del params[key]
Django on py2 raises ValueError on large values.
def int_to_base36(i): """ Django on py2 raises ValueError on large values. """ if six.PY2: char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if not isinstance(i, six.integer_types): raise Type...
Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts)
def save(self, request, connect=False): """ Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) """ assert not self.is_existing user = self.user user.save() self.account.user = user se...
Lookup existing account, if any.
def lookup(self): """ Lookup existing account, if any. """ assert not self.is_existing try: a = SocialAccount.objects.get(provider=self.account.provider, uid=self.account.uid) # Update account a.extra_d...
Instantiates and populates a `SocialLogin` model based on the data retrieved in `response`. The method does NOT save the model to the DB. Data for `SocialLogin` will be extracted from `response` with the help of the `.extract_uid()`, `.extract_extra_data()`, `.extract_common_fie...
def sociallogin_from_response(self, request, response): """ Instantiates and populates a `SocialLogin` model based on the data retrieved in `response`. The method does NOT save the model to the DB. Data for `SocialLogin` will be extracted from `response` with the help of...
Extract fields from a basic user query.
def extract_common_fields(self, data): """Extract fields from a basic user query.""" email = None for curr_email in data.get("emails", []): email = email or curr_email.get("email") if curr_email.get("verified", False) and \ curr_email.get("primary", Fa...
Arguments: request - The get request to the callback URL /accounts/dataporten/login/callback. app - The corresponding SocialApp model instance token - A token object with access token given in token.token Returns: Should return a dict with ...
def complete_login(self, request, app, token, **kwargs): ''' Arguments: request - The get request to the callback URL /accounts/dataporten/login/callback. app - The corresponding SocialApp model instance token - A token object with access token...
View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider
def dispatch(self, request): """ View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider """ login_done_url = reverse(self.adapter.provider_id + "_callback") client = self._get_client(request, login_done_ur...
Simply logging in the user may become a security issue. If you do not take proper care (e.g. don't purge used email confirmations), a malicious person that got hold of the link will be able to login over and over again and the user is unable to do anything about it. Even restoring their ...
def login_on_confirm(self, confirmation): """ Simply logging in the user may become a security issue. If you do not take proper care (e.g. don't purge used email confirmations), a malicious person that got hold of the link will be able to login over and over again and the user is...
Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`.
def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError, TypeError): return...
{'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]}
def _extract_email(data): """ {'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]} """ ret = '' elements = data.get('elements', []) if len(elements) > 0: ret = elements[0].get('handle~', {}).get('emailAddres...
Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token
def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self.request_token is None: get_params = {} if self.parameters: get_params.update(self...
Obtain the access token to access private resources at the API endpoint.
def get_access_token(self): """ Obtain the access token to access private resources at the API endpoint. """ if self.access_token is None: request_token = self._get_rt_from_session() oauth = OAuth1( self.consumer_key, client...
Returns a ``HttpResponseRedirect`` object to redirect the user to the URL the OAuth provider handles authorization.
def get_redirect(self, authorization_url, extra_params): """ Returns a ``HttpResponseRedirect`` object to redirect the user to the URL the OAuth provider handles authorization. """ request_token = self._get_request_token() params = {'oauth_token': request_token['oauth_tok...
Get the saved access token for private resources from the session.
def _get_at_from_session(self): """ Get the saved access token for private resources from the session. """ try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.req...
Request a API endpoint at ``url`` with ``params`` being either the POST or GET data.
def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_at_from_session() oauth = OAuth1( self.consumer_key, client_sec...
Returns the next URL to redirect to, if it was explicitly passed via the request.
def get_next_redirect_url(request, redirect_field_name="next"): """ Returns the next URL to redirect to, if it was explicitly passed via the request. """ redirect_to = get_request_param(request, redirect_field_name) if not get_adapter(request).is_safe_url(redirect_to): redirect_to = None...
Gets or sets (optional) user model fields. No-op if fields do not exist.
def user_field(user, field, *args): """ Gets or sets (optional) user model fields. No-op if fields do not exist. """ if not field: return User = get_user_model() try: field_meta = User._meta.get_field(field) max_length = field_meta.max_length except FieldDoesNotExist:...
Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verification is optional and we are only logging in).
def perform_login(request, user, email_verification, redirect_url=None, signal_kwargs=None, signup=False): """ Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verifi...
Takes a list of EmailAddress instances and cleans it up, making sure only valid ones remain, without multiple primaries etc. Order is important: e.g. if multiple primary e-mail addresses exist, the first one encountered will be kept as primary.
def cleanup_email_addresses(request, addresses): """ Takes a list of EmailAddress instances and cleans it up, making sure only valid ones remain, without multiple primaries etc. Order is important: e.g. if multiple primary e-mail addresses exist, the first one encountered will be kept as primary. ...
Creates proper EmailAddress for the user that was just signed up. Only sets up, doesn't do any other handling such as sending out email confirmation mails etc.
def setup_user_email(request, user, addresses): """ Creates proper EmailAddress for the user that was just signed up. Only sets up, doesn't do any other handling such as sending out email confirmation mails etc. """ from .models import EmailAddress assert not EmailAddress.objects.filter(use...
Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users.
def sync_user_email_addresses(user): """ Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users. """ from .models import EmailAddress email = user_email...
Return list of users by email address Typically one, at most just a few in length. First we look through EmailAddress table, than customisable User model table. Add results together avoiding SQL joins and deduplicate.
def filter_users_by_email(email): """Return list of users by email address Typically one, at most just a few in length. First we look through EmailAddress table, than customisable User model table. Add results together avoiding SQL joins and deduplicate. """ from .models import EmailAddress ...
This should return a string.
def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if issubclass(type(User._meta.pk), models.UUIDField): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ret = user.pk if isinstance(ret, six.integ...
`allauth` needs tokens for OAuth based providers. So let's setup some dummy tokens
def setup_dummy_social_apps(sender, **kwargs): """ `allauth` needs tokens for OAuth based providers. So let's setup some dummy tokens """ from allauth.socialaccount.providers import registry from allauth.socialaccount.models import SocialApp from allauth.socialaccount.providers.oauth.provide...
Return value dumped to string.
def value_from_object(self, obj): """Return value dumped to string.""" val = super(JSONField, self).value_from_object(obj) return self.get_prep_value(val)
See e-mail verification method
def EMAIL_VERIFICATION(self): """ See e-mail verification method """ ret = self._setting("EMAIL_VERIFICATION", self.EmailVerificationMethod.OPTIONAL) # Deal with legacy (boolean based) setting if ret is True: ret = self.EmailVerific...
Minimum password Length
def PASSWORD_MIN_LENGTH(self): """ Minimum password Length """ from django.conf import settings ret = None if not settings.AUTH_PASSWORD_VALIDATORS: ret = self._setting("PASSWORD_MIN_LENGTH", 6) return ret
Small helper function to call a function (map_function) on a list of data chunks (chunk_list) and convert the results into a flattened list. This function is used to send chunks of data with a size larger than 1 to the workers in parallel and process these on the worker. :param chunk_list: A l...
def _function_with_partly_reduce(chunk_list, map_function, kwargs): """ Small helper function to call a function (map_function) on a list of data chunks (chunk_list) and convert the results into a flattened list. This function is used to send chunks of data with a size larger than 1 to the ...
This generator chunks a list of data into slices of length chunk_size. If the chunk_size is not a divider of the data length, the last slice will be shorter than chunk_size. :param data: The data to chunk. :type data: list :param chunk_size: Each chunks size. The last chunk may be small...
def partition(data, chunk_size): """ This generator chunks a list of data into slices of length chunk_size. If the chunk_size is not a divider of the data length, the last slice will be shorter than chunk_size. :param data: The data to chunk. :type data: list :param chun...
Calculates the best chunk size for a list of length data_length. The current implemented formula is more or less an empirical result for multiprocessing case on one machine. :param data_length: A length which defines how many calculations there need to be. :type data_length: int ...
def calculate_best_chunk_size(self, data_length): """ Calculates the best chunk size for a list of length data_length. The current implemented formula is more or less an empirical result for multiprocessing case on one machine. :param data_length: A length which defines how man...
This method contains the core functionality of the DistributorBaseClass class. It maps the map_function to each element of the data and reduces the results to return a flattened list. How the jobs are calculated, is determined by the classes :func:`tsfresh.utilities.distribution.Distr...
def map_reduce(self, map_function, data, function_kwargs=None, chunk_size=None, data_length=None): """ This method contains the core functionality of the DistributorBaseClass class. It maps the map_function to each element of the data and reduces the results to return a flattened list. ...
Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed by one worker. ...
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of ch...
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chun...
Uses the number of dask workers in the cluster (during execution time, meaning when you start the extraction) to find the optimal chunk_size. :param data_length: A length which defines how many calculations there need to be. :type data_length: int
def calculate_best_chunk_size(self, data_length): """ Uses the number of dask workers in the cluster (during execution time, meaning when you start the extraction) to find the optimal chunk_size. :param data_length: A length which defines how many calculations there need to be. ...
Calculates the features in a parallel fashion by distributing the map command to a thread pool :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed...
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a parallel fashion by distributing the map command to a thread pool :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - ...
Collects the result from the workers and closes the thread pool.
def close(self): """ Collects the result from the workers and closes the thread pool. """ self.pool.close() self.pool.terminate() self.pool.join()
Creates a mapping from kind names to fc_parameters objects (which are itself mappings from feature calculators to settings) to extract only the features contained in the columns. To do so, for every feature name in columns this method 1. split the column name into col, feature, params part 2. decid...
def from_columns(columns, columns_to_ignore=None): """ Creates a mapping from kind names to fc_parameters objects (which are itself mappings from feature calculators to settings) to extract only the features contained in the columns. To do so, for every feature name in columns this method 1. sp...
Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions. Elements that roll beyond the last position are re-introduced at the beginning. Similarly, element...
def _roll(a, shift): """ Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions. Elements that roll beyond the last position are re-introduced at ...
This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,True,True] >>> _get_length_sequences_where(x...
def _get_length_sequences_where(x): """ This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,...
Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) As described by Friedrich et al. (2000): Physics Letters A 271, p. 217-222 *Extracting model equations from experimental ...
def _estimate_friedrich_coefficients(x, m, r): """ Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) As described by Friedrich et al. (2000): Physics Letters A 271, p. 217...
Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_agg: The name of the aggregation function that should be an...
def _aggregate_on_chunks(x, f_agg, chunk_len): """ Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_...
This method returns a decorator that sets the property key of the function to value
def set_property(key, value): """ This method returns a decorator that sets the property key of the function to value """ def decorate_func(func): setattr(func, key, value) if func.__doc__ and key == "fctype": func.__doc__ = func.__doc__ + "\n\n *This function is of type: ...
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x being larger than 1 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool
def variance_larger_than_standard_deviation(x): """ Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x being larger than 1 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this featur...