INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a function F ( x y z ) that interpolates any values on the grid.
def _interpolationFunctionFactory(self, spline_order=None, cval=None): """Returns a function F(x,y,z) that interpolates any values on the grid. _interpolationFunctionFactory(self,spline_order=3,cval=None) --> F *cval* is set to :meth:`Grid.grid.min`. *cval* cannot be chosen too large o...
Populate the instance from the ccp4 file * filename *.
def read(self, filename): """Populate the instance from the ccp4 file *filename*.""" if filename is not None: self.filename = filename with open(self.filename, 'rb') as ccp4: h = self.header = self._read_header(ccp4) nentries = h['nc'] * h['nr'] * h['ns'] ...
Detect the byteorder of stream ccp4file and return format character.
def _detect_byteorder(ccp4file): """Detect the byteorder of stream `ccp4file` and return format character. Try all endinaness and alignment options until we find something that looks sensible ("MAPS " in the first 4 bytes). (The ``machst`` field could be used to obtain endianness, but ...
Read header bytes
def _read_header(self, ccp4file): """Read header bytes""" bsaflag = self._detect_byteorder(ccp4file) # Parse the top of the header (4-byte words, 1 to 25). nheader = struct.calcsize(self._headerfmt) names = [r.key for r in self._header_struct] bintopheader = ccp4file.re...
Get the data for a specific device for a specific end date
def get_data(self, **kwargs): """ Get the data for a specific device for a specific end date Keyword Arguments: limit - max 288 end_date - is Epoch in milliseconds :return: """ limit = int(kwargs.get('limit', 288)) end_date = kwargs.get('...
Get all devices
def get_devices(self): """ Get all devices :return: A list of AmbientWeatherStation instances. """ retn = [] api_devices = self.api_call('devices') self.log('DEVICES:') self.log(api_devices) for device in api_devices: ret...
Create URL with supplied path and opts parameters dict.
def create_url(self, path, params={}, opts={}): """ Create URL with supplied path and `opts` parameters dict. Parameters ---------- path : str opts : dict Dictionary specifying URL parameters. Non-imgix parameters are added to the URL unprocessed....
Set a url parameter.
def set_parameter(self, key, value): """ Set a url parameter. Parameters ---------- key : str If key ends with '64', the value provided will be automatically base64 encoded. """ if value is None or isinstance(value, (int, float, bool)): ...
Start subscription manager for real time data.
async def rt_connect(self, loop): """Start subscription manager for real time data.""" if self.sub_manager is not None: return self.sub_manager = SubscriptionManager( loop, "token={}".format(self._access_token), SUB_ENDPOINT ) self.sub_manager.start()
Execute gql.
async def execute(self, document, variable_values=None): """Execute gql.""" res = await self._execute(document, variable_values) if res is None: return None return res.get("data")
Execute gql.
async def _execute(self, document, variable_values=None, retry=2): """Execute gql.""" query_str = print_ast(document) payload = {"query": query_str, "variables": variable_values or {}} post_args = { "headers": {"Authorization": "Bearer " + self._access_token}, "d...
Update home info.
def sync_update_info(self, *_): """Update home info.""" loop = asyncio.get_event_loop() task = loop.create_task(self.update_info()) loop.run_until_complete(task)
Update home info async.
async def update_info(self, *_): """Update home info async.""" query = gql( """ { viewer { name homes { subscriptions { status } id } } } """ ) ...
Return list of Tibber homes.
def get_homes(self, only_active=True): """Return list of Tibber homes.""" return [self.get_home(home_id) for home_id in self.get_home_ids(only_active)]
Retun an instance of TibberHome for given home id.
def get_home(self, home_id): """Retun an instance of TibberHome for given home id.""" if home_id not in self._all_home_ids: _LOGGER.error("Could not find any Tibber home with id: %s", home_id) return None if home_id not in self._homes.keys(): self._homes[home_...
Send notification.
async def send_notification(self, title, message): """Send notification.""" query = gql( """ mutation{ sendPushNotification(input: { title: "%s", message: "%s", }){ successful pushedToNumberOfDevices } ...
Update current price info async.
async def update_info(self): """Update current price info async.""" query = gql( """ { viewer { home(id: "%s") { appNickname features { realTimeConsumptionEnabled } currentSubscription {...
Update current price info.
def sync_update_current_price_info(self): """Update current price info.""" loop = asyncio.get_event_loop() task = loop.create_task(self.update_current_price_info()) loop.run_until_complete(task)
Update current price info async.
async def update_current_price_info(self): """Update current price info async.""" query = gql( """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy ...
Update current price info.
def sync_update_price_info(self): """Update current price info.""" loop = asyncio.get_event_loop() task = loop.create_task(self.update_price_info()) loop.run_until_complete(task)
Update price info async.
async def update_price_info(self): """Update price info async.""" query = gql( """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy tax ...
Return the currency.
def currency(self): """Return the currency.""" try: current_subscription = self.info["viewer"]["home"]["currentSubscription"] return current_subscription["priceInfo"]["current"]["currency"] except (KeyError, TypeError, IndexError): _LOGGER.error("Could not fin...
Return the price unit.
def price_unit(self): """Return the price unit.""" currency = self.currency consumption_unit = self.consumption_unit if not currency or not consumption_unit: _LOGGER.error("Could not find price_unit.") return " " return currency + "/" + consumption_unit
Connect to Tibber and subscribe to Tibber rt subscription.
async def rt_subscribe(self, loop, async_callback): """Connect to Tibber and subscribe to Tibber rt subscription.""" if self._subscription_id is not None: _LOGGER.error("Already subscribed.") return await self._tibber_control.rt_connect(loop) document = gql( ...
Unsubscribe to Tibber rt subscription.
async def rt_unsubscribe(self): """Unsubscribe to Tibber rt subscription.""" if self._subscription_id is None: _LOGGER.error("Not subscribed.") return await self._tibber_control.sub_manager.unsubscribe(self._subscription_id)
Is real time subscription running.
def rt_subscription_running(self): """Is real time subscription running.""" return ( self._tibber_control.sub_manager is not None and self._tibber_control.sub_manager.is_running and self._subscription_id is not None )
Get historic data.
async def get_historic_data(self, n_data): """Get historic data.""" query = gql( """ { viewer { home(id: "%s") { consumption(resolution: HOURLY, last: %s) { nodes { f...
get_historic_data.
def sync_get_historic_data(self, n_data): """get_historic_data.""" loop = asyncio.get_event_loop() task = loop.create_task(self.get_historic_data(n_data)) loop.run_until_complete(task) return self._data
Removes the temporary value set for None attributes.
def cleanup_none(self): """ Removes the temporary value set for None attributes. """ for (prop, default) in self.defaults.items(): if getattr(self, prop) == '_None': setattr(self, prop, None)
Build the execution environment.
def build_environ(self, sock_file, conn): """ Build the execution environment. """ # Grab the request line request = self.read_request_line(sock_file) # Copy the Base Environment environ = self.base_environ.copy() # Grab the headers for k, v in self.read_headers...
Write the data to the output socket.
def write(self, data, sections=None): """ Write the data to the output socket. """ if self.error[0]: self.status = self.error[0] data = b(self.error[1]) if not self.headers_sent: self.send_headers(data, sections) if self.request_method != 'HEAD': ...
Store the HTTP status and headers to be sent when self. write is called.
def start_response(self, status, response_headers, exc_info=None): """ Store the HTTP status and headers to be sent when self.write is called. """ if exc_info: try: if self.headers_sent: # Re-raise original exception if headers sent ...
A Cherrypy wsgiserver - compatible wrapper.
def CherryPyWSGIServer(bind_addr, wsgi_app, numthreads = 10, server_name = None, max = -1, request_queue_size = 5, timeout = 10, shutdown_timeout = 5): """...
Initial run to figure out what VRF s are available Decided to get this one from Configured - section because bulk - getting all instance - data to do the same could get ridiculously heavy Assuming we re always interested in the DefaultVRF
def get_bgp_neighbors(self): def generate_vrf_query(vrf_name): """ Helper to provide XML-query for the VRF-type we're interested in. """ if vrf_name == "global": rpc_command = '<Get><Operational><BGP><InstanceTable><Instance><Naming>\ ...
Aggregate a list of prefixes.
def aggregate(l): """Aggregate a `list` of prefixes. Keyword arguments: l -- a python list of prefixes Example use: >>> aggregate(["10.0.0.0/8", "10.0.0.0/24"]) ['10.0.0.0/8'] """ tree = radix.Radix() for item in l: try: tree.add(item) except (ValueError...
Walk a py - radix tree and aggregate it.
def aggregate_tree(l_tree): """Walk a py-radix tree and aggregate it. Arguments l_tree -- radix.Radix() object """ def _aggregate_phase1(tree): # phase1 removes any supplied prefixes which are superfluous because # they are already included in another supplied prefix. For example, ...
Metric for ordinal data.
def _ordinal_metric(_v1, _v2, i1, i2, n_v): """Metric for ordinal data.""" if i1 > i2: i1, i2 = i2, i1 return (np.sum(n_v[i1:(i2 + 1)]) - (n_v[i1] + n_v[i2]) / 2) ** 2
Metric for ratio data.
def _ratio_metric(v1, v2, **_kwargs): """Metric for ratio data.""" return (((v1 - v2) / (v1 + v2)) ** 2) if v1 + v2 != 0 else 0
Coincidence matrix.
def _coincidences(value_counts, value_domain, dtype=np.float64): """Coincidence matrix. Parameters ---------- value_counts : ndarray, with shape (N, V) Number of coders that assigned a certain value to a determined unit, where N is the number of units and V is the value count. valu...
Random coincidence matrix.
def _random_coincidences(value_domain, n, n_v): """Random coincidence matrix. Parameters ---------- value_domain : array_like, with shape (V,) Possible values V the units can take. If the level of measurement is not nominal, it must be ordered. n : scalar Number of pairable...
Distances of the different possible values.
def _distances(value_domain, distance_metric, n_v): """Distances of the different possible values. Parameters ---------- value_domain : array_like, with shape (V,) Possible values V the units can take. If the level of measurement is not nominal, it must be ordered. distance_metric ...
Return the value counts given the reliability data.
def _reliability_data_to_value_counts(reliability_data, value_domain): """Return the value counts given the reliability data. Parameters ---------- reliability_data : ndarray, with shape (M, N) Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of r...
Compute Krippendorff s alpha.
def alpha(reliability_data=None, value_counts=None, value_domain=None, level_of_measurement='interval', dtype=np.float64): """Compute Krippendorff's alpha. See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information. Parameters ---------- reliability_data : array_like, ...
Maps to fortran CDF_Inquire.
def inquire(self): """Maps to fortran CDF_Inquire. Assigns parameters returned by CDF_Inquire to pysatCDF instance. Not intended for regular direct use by user. """ name = copy.deepcopy(self.fname) stats = fortran_cdf.inquire(name) # break out fortran ...
Gets all CDF z - variable information not data though.
def _read_all_z_variable_info(self): """Gets all CDF z-variable information, not data though. Maps to calls using var_inquire. Gets information on data type, number of elements, number of dimensions, etc. """ self.z_variable_info = {} self.z_variable_names_by_num = {} ...
Loads all variables from CDF. Note this routine is called automatically upon instantiation.
def load_all_variables(self): """Loads all variables from CDF. Note this routine is called automatically upon instantiation. """ self.data = {} # need to add r variable names file_var_names = self.z_variable_info.keys() # collect variabl...
Calls fortran functions to load CDF variable data
def _call_multi_fortran_z(self, names, data_types, rec_nums, dim_sizes, input_type_code, func, epoch=False, data_offset=None, epoch16=False): """Calls fortran functions to load CDF variable data Parameters ---------- names : li...
process and attach data from fortran_cdf. get_multi_ *
def _process_return_multi_z(self, data, names, dim_sizes): """process and attach data from fortran_cdf.get_multi_*""" # process data d1 = 0 d2 = 0 for name, dim_size in zip(names, dim_sizes): d2 = d1 + dim_size if dim_size == 1: self.data[n...
Read all attribute properties g r and z attributes
def _read_all_attribute_info(self): """Read all attribute properties, g, r, and z attributes""" num = copy.deepcopy(self._num_attrs) fname = copy.deepcopy(self.fname) out = fortran_cdf.inquire_all_attr(fname, num, len(fname)) status = out[0] names = out[1].astype('U') ...
Read all CDF z - attribute data
def _read_all_z_attribute_data(self): """Read all CDF z-attribute data""" self.meta = {} # collect attribute info needed to get more info from # fortran routines max_entries = [] attr_nums = [] names = [] attr_names = [] names = self.var_attrs_inf...
Calls Fortran function that reads attribute data. data_offset translates unsigned into signed. If number read in is negative offset added.
def _call_multi_fortran_z_attr(self, names, data_types, num_elems, entry_nums, attr_nums, var_names, input_type_code, func, data_offset=None): """Calls Fortran function that reads attribute data. data_offset translates unsign...
process and attach data from fortran_cdf. get_multi_ *
def _process_return_multi_z_attr(self, data, attr_names, var_names, sub_num_elems): '''process and attach data from fortran_cdf.get_multi_*''' # process data for i, (attr_name, var_name, num_e) in enumerate(zip(attr_names, var_names, sub_num_elems)): if var_name not in self.meta.key...
Exports loaded CDF data into data meta for pysat module Notes ----- The * _labels should be set to the values in the file if present. Note that once the meta object returned from this function is attached to a pysat. Instrument object then the * _labels on the Instrument are assigned to the newly attached Meta object. ...
def to_pysat(self, flatten_twod=True, units_label='UNITS', name_label='long_name', fill_label='FILLVAL', plot_label='FieldNam', min_label='ValidMin', max_label='ValidMax', notes_label='Var_Notes', desc_label='CatDesc', axi...
Returns uptime in seconds or None on Linux.
def _uptime_linux(): """Returns uptime in seconds or None, on Linux.""" # With procfs try: f = open('/proc/uptime', 'r') up = float(f.readline().split()[0]) f.close() return up except (IOError, ValueError): pass # Without procfs (really?) try: lib...
A way to figure out the boot time directly on Linux.
def _boottime_linux(): """A way to figure out the boot time directly on Linux.""" global __boottime try: f = open('/proc/stat', 'r') for line in f: if line.startswith('btime'): __boottime = int(line.split()[1]) if datetime is None: raise NotIm...
Returns uptime in seconds or None on AmigaOS.
def _uptime_amiga(): """Returns uptime in seconds or None, on AmigaOS.""" global __boottime try: __boottime = os.stat('RAM:').st_ctime return time.time() - __boottime except (NameError, OSError): return None
Returns uptime in seconds on None on BeOS/ Haiku.
def _uptime_beos(): """Returns uptime in seconds on None, on BeOS/Haiku.""" try: libroot = ctypes.CDLL('libroot.so') except (AttributeError, OSError): return None if not hasattr(libroot, 'system_time'): return None libroot.system_time.restype = ctypes.c_int64 return lib...
Returns uptime in seconds or None on BSD ( including OS X ).
def _uptime_bsd(): """Returns uptime in seconds or None, on BSD (including OS X).""" global __boottime try: libc = ctypes.CDLL('libc.so') except AttributeError: return None except OSError: # OS X; can't use ctypes.util.find_library because that creates # a new process...
Returns uptime in seconds or None on MINIX.
def _uptime_minix(): """Returns uptime in seconds or None, on MINIX.""" try: f = open('/proc/uptime', 'r') up = float(f.read()) f.close() return up except (IOError, ValueError): return None
Returns uptime in seconds or None on Plan 9.
def _uptime_plan9(): """Returns uptime in seconds or None, on Plan 9.""" # Apparently Plan 9 only has Python 2.2, which I'm not prepared to # support. Maybe some Linuxes implement /dev/time, though, someone was # talking about it somewhere. try: # The time file holds one 32-bit number repres...
Returns uptime in seconds or None on Solaris.
def _uptime_solaris(): """Returns uptime in seconds or None, on Solaris.""" global __boottime try: kstat = ctypes.CDLL('libkstat.so') except (AttributeError, OSError): return None # kstat doesn't have uptime, but it does have boot time. # Unfortunately, getting at it isn't perfe...
Returns uptime in seconds or None on Syllable.
def _uptime_syllable(): """Returns uptime in seconds or None, on Syllable.""" global __boottime try: __boottime = os.stat('/dev/pty/mst/pty0').st_mtime return time.time() - __boottime except (NameError, OSError): return None
Returns uptime in seconds or None on Windows. Warning: may return incorrect answers after 49. 7 days on versions older than Vista.
def _uptime_windows(): """ Returns uptime in seconds or None, on Windows. Warning: may return incorrect answers after 49.7 days on versions older than Vista. """ if hasattr(ctypes, 'windll') and hasattr(ctypes.windll, 'kernel32'): lib = ctypes.windll.kernel32 else: try: ...
Returns uptime in seconds if even remotely possible or None if not.
def uptime(): """Returns uptime in seconds if even remotely possible, or None if not.""" if __boottime is not None: return time.time() - __boottime return {'amiga': _uptime_amiga, 'aros12': _uptime_amiga, 'beos5': _uptime_beos, 'cygwin': _uptime_linux, ...
Returns boot time if remotely possible or None if not.
def boottime(): """Returns boot time if remotely possible, or None if not.""" global __boottime if __boottime is None: up = uptime() if up is None: return None if __boottime is None: _boottime_linux() if datetime is None: raise RuntimeError('datetime mod...
Initialize an empty JSON file.
def _initfile(path, data="dict"): """Initialize an empty JSON file.""" data = {} if data.lower() == "dict" else [] # The file will need to be created if it doesn't exist if not os.path.exists(path): # The file doesn't exist # Raise exception if the directory that should contain the file doesn't...
A simpler version of data to avoid infinite recursion in some cases.
def _data(self): """A simpler version of data to avoid infinite recursion in some cases. Don't use this. """ if self.is_caching: return self.cache with open(self.path, "r") as f: return json.load(f)
Overwrite the file with new data. You probably shouldn t do this yourself it s easy to screw up your whole file with this.
def data(self, data): """Overwrite the file with new data. You probably shouldn't do this yourself, it's easy to screw up your whole file with this.""" if self.is_caching: self.cache = data else: fcontents = self.file_contents with open(self.path, "w")...
Make sure that the class behaves like the data structure that it is so that we don t get a ListFile trying to represent a dict.
def _updateType(self): """Make sure that the class behaves like the data structure that it is, so that we don't get a ListFile trying to represent a dict.""" data = self._data() # Change type if needed if isinstance(data, dict) and isinstance(self, ListFile): self.__c...
Initialize a new file that starts out with some data. Pass data as a list dict or JSON string.
def with_data(path, data): """Initialize a new file that starts out with some data. Pass data as a list, dict, or JSON string. """ # De-jsonize data if necessary if isinstance(data, str): data = json.loads(data) # Make sure this is really a new file i...
Check if plugin is configured.
def is_configured(self, project, **kwargs): """ Check if plugin is configured. """ params = self.get_option return bool(params('server_host', project) and params('server_port', project))
Process error.
def post_process(self, group, event, is_new, is_sample, **kwargs): """ Process error. """ if not self.is_configured(group.project): return host = self.get_option('server_host', group.project) port = int(self.get_option('server_port', group.project)) p...
ping statistics.
def as_dict(self): """ ping statistics. Returns: |dict|: Examples: >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_dict() { "destination": "...
ping statistics.
def as_tuple(self): """ ping statistics. Returns: |namedtuple|: Examples: >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_tuple() PingResult(destination='go...
Sending ICMP packets.
def ping(self): """ Sending ICMP packets. :return: ``ping`` command execution result. :rtype: :py:class:`.PingResult` :raises ValueError: If parameters not valid. """ self.__validate_ping_param() ping_proc = subprocrunner.SubprocessRunner(self.__get_pin...
Parse ping command output.
def parse(self, ping_message): """ Parse ping command output. Args: ping_message (str or :py:class:`~pingparsing.PingResult`): ``ping`` command output. Returns: :py:class:`~pingparsing.PingStats`: Parsed result. """ try: ...
Send a verification email for the email address.
def send_confirmation(self): """ Send a verification email for the email address. """ confirmation = EmailConfirmation.objects.create(email=self) confirmation.send()
Send a notification about a duplicate signup.
def send_duplicate_notification(self): """ Send a notification about a duplicate signup. """ email_utils.send_email( from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[self.email], subject=_("Registration Attempt"), template_name="rest...
Set this email address as the user s primary email.
def set_primary(self): """ Set this email address as the user's primary email. """ query = EmailAddress.objects.filter(is_primary=True, user=self.user) query = query.exclude(pk=self.pk) # The transaction is atomic so there is never a gap where a user # has no pri...
Mark the instance s email as verified.
def confirm(self): """ Mark the instance's email as verified. """ self.email.is_verified = True self.email.save() signals.email_verified.send(email=self.email, sender=self.__class__) logger.info("Verified email address: %s", self.email.email)
Determine if the confirmation has expired.
def is_expired(self): """ Determine if the confirmation has expired. Returns: bool: ``True`` if the confirmation has expired and ``False`` otherwise. """ expiration_time = self.created_at + datetime.timedelta(days=1) return ti...
Send a verification email to the user.
def send(self): """ Send a verification email to the user. """ context = { "verification_url": app_settings.EMAIL_VERIFICATION_URL.format( key=self.key ) } email_utils.send_email( context=context, from_email...
Create a new user instance.
def _create(cls, model_class, *args, **kwargs): """ Create a new user instance. Args: model_class: The type of model to create an instance of. args: Positional arguments to create the instance with. kwargs: Keyw...
Create a new email and send a confirmation to it.
def create(self, validated_data): """ Create a new email and send a confirmation to it. Returns: The newly creating ``EmailAddress`` instance. """ email_query = models.EmailAddress.objects.filter( email=self.validated_data["email"] ) if e...
Update the instance the serializer is bound to.
def update(self, instance, validated_data): """ Update the instance the serializer is bound to. Args: instance: The instance the serializer is bound to. validated_data: The data to update the serializer with. Returns: ...
Validate the provided email address.
def validate_email(self, email): """ Validate the provided email address. The email address is first modified to match the RFC spec. Namely, the domain portion of the email is lowercased. Returns: The validated email address. Raises: serializers...
Validate the provided is_primary parameter.
def validate_is_primary(self, is_primary): """ Validate the provided 'is_primary' parameter. Returns: The validated 'is_primary' value. Raises: serializers.ValidationError: If the user attempted to mark an unverified email as thei...
Validate the provided data.
def validate(self, data): """ Validate the provided data. Returns: dict: The validated data. Raises: serializers.ValidationError: If the provided password is invalid. """ user = self._confirmation.email.user ...
Validate the provided confirmation key.
def validate_key(self, key): """ Validate the provided confirmation key. Returns: str: The validated confirmation key. Raises: serializers.ValidationError: If there is no email confirmation with the given key or th...
Send out a password reset if the provided data is valid.
def save(self): """ Send out a password reset if the provided data is valid. If the provided email address exists and is verified, a reset email is sent to the address. Returns: The password reset token if it was returned and ``None`` otherwise. ...
Reset the user s password if the provided information is valid.
def save(self): """ Reset the user's password if the provided information is valid. """ token = models.PasswordResetToken.objects.get( key=self.validated_data["key"] ) token.email.user.set_password(self.validated_data["password"]) token.email.user.sav...
Validate the provided reset key.
def validate_key(self, key): """ Validate the provided reset key. Returns: The validated key. Raises: serializers.ValidationError: If the provided key does not exist. """ if not models.PasswordResetToken.valid_tokens.filter(key=ke...
Create a new user from the data passed to the serializer.
def create(self, validated_data): """ Create a new user from the data passed to the serializer. If the provided email has not been verified yet, the user is created and a verification email is sent to the address. Otherwise we send a notification to the email address that ...
Validate the provided email address.
def validate_email(self, email): """ Validate the provided email address. Args: email: The email address to validate. Returns: The provided email address, transformed to match the RFC spec. Namely, the domain portion of the email must...
Resend a verification email to the provided address.
def save(self): """ Resend a verification email to the provided address. If the provided email is already verified no action is taken. """ try: email = models.EmailAddress.objects.get( email=self.validated_data["email"], is_verified=False ...
Create a new email address.
def create(self, *args, **kwargs): """ Create a new email address. """ is_primary = kwargs.pop("is_primary", False) with transaction.atomic(): email = super(EmailAddressManager, self).create(*args, **kwargs) if is_primary: email.set_prima...
Return all unexpired password reset tokens.
def get_queryset(self): """ Return all unexpired password reset tokens. """ oldest = timezone.now() - app_settings.PASSWORD_RESET_EXPIRATION queryset = super(ValidPasswordResetTokenManager, self).get_queryset() return queryset.filter(created_at__gt=oldest)
Handle execution of the command.
def handle(self, *args, **kwargs): """ Handle execution of the command. """ cutoff = timezone.now() cutoff -= app_settings.CONFIRMATION_EXPIRATION cutoff -= app_settings.CONFIRMATION_SAVE_PERIOD queryset = models.EmailConfirmation.objects.filter( crea...
Get a user by their ID.
def get_user(self, user_id): """ Get a user by their ID. Args: user_id: The ID of the user to fetch. Returns: The user with the specified ID if they exist and ``None`` otherwise. """ try: return get_user_mo...
Attempt to authenticate a set of credentials.
def authenticate(self, request, email=None, password=None, username=None): """ Attempt to authenticate a set of credentials. Args: request: The request associated with the authentication attempt. email: The user's email address. ...