code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
active = int(data.request.get('%s.active' % widget.name, '0'))
if not active:
return 0
expires = data.extracted
if expires:
return time.mktime(expires.utctimetuple())
return UNSET | def expiration_extractor(widget, data) | Extract expiration information.
- If active flag not set, Account is disabled (value 0).
- If active flag set and value is UNSET, account never expires.
- If active flag set and datetime choosen, account expires at given
datetime.
- Timestamp in seconds since epoch is returned. | 6.861214 | 6.085258 | 1.127514 |
_next(self)
cfg = ugm_general(self.model)
if cfg.attrs['users_account_expiration'] != 'True':
return
mode = 'edit'
if not self.request.has_permission(
'manage_expiration', self.model.parent):
mode = 'display'
if self.action... | def prepare(_next, self) | Hook after prepare and set expiration widget to
``self.form``. | 7.578238 | 7.136557 | 1.06189 |
response = Response()
cfg = ugm_general(model)
response.body = model.attrs[cfg.attrs['users_portrait_attr']]
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Cache-Control'] = 'max-age=0'
return response | def portrait_image(model, request) | XXX: needs polishing. Return configured default portrait if not set
on user. | 6.811791 | 6.385629 | 1.066738 |
_next(self)
if not self.portrait_support:
return
model = self.model
request = self.request
if request.has_permission('edit_user', model.parent):
mode = 'edit'
else:
mode = 'display'
cfg = ugm_general(model)
imag... | def prepare(_next, self) | Hook after prepare and set 'portrait' as image widget to
``self.form``. | 4.28776 | 4.133512 | 1.037316 |
if not self.local_management_enabled:
return False
request = get_current_request()
if authenticated_userid(request) == security.ADMIN_USER:
return False
roles = security.authenticated_user(request).roles
if 'admin' in roles or 'manager' in roles:
... | def local_manager_consider_for_user(self) | Flag whether local manager ACL should be considered for current
authenticated user. | 4.664754 | 4.242509 | 1.099527 |
config = self.root['settings']['ugm_localmanager'].attrs
user = security.authenticated_user(get_current_request())
if not user:
return None
gids = user.group_ids
adm_gids = list()
for gid in gids:
rule = config.get(gid)
if rule... | def local_manager_gid(self) | Group id of local manager group of current authenticated member.
Currently a user can be assigned only to one local manager group. If
more than one local manager group is configured, an error is raised. | 4.671305 | 4.292544 | 1.088237 |
adm_gid = self.local_manager_gid
if not adm_gid:
return None
config = self.root['settings']['ugm_localmanager'].attrs
return config[adm_gid] | def local_manager_rule(self) | Return rule for local manager. | 12.246211 | 10.665019 | 1.14826 |
groups = self.root['groups'].backend
managed_uids = set()
for gid in self.local_manager_target_gids:
group = groups.get(gid)
if group:
managed_uids.update(group.member_ids)
return list(managed_uids) | def local_manager_target_uids(self) | Target uid's for local manager. | 4.46262 | 4.288991 | 1.040482 |
config = self.root['settings']['ugm_localmanager'].attrs
rule = config[adm_gid]
if gid not in rule['target']:
raise Exception(u"group '%s' not managed by '%s'" % (gid, adm_gid))
return gid in rule['default'] | def local_manager_is_default(self, adm_gid, gid) | Check whether gid is default group for local manager group. | 7.77599 | 7.896833 | 0.984697 |
schema = copy.deepcopy(form_field_definitions.user)
uid, login = self._get_auth_attrs()
if uid != login:
field = schema.get(login, schema['default'])
if field['chain'].find('*optional_login') == -1:
field['chain'] = '%s:%s' % (
... | def form_field_definitions(self) | Hook optional_login extractor if necessary for form defaults. | 7.321303 | 6.426126 | 1.139303 |
params = request.params
uid = params.get('id')
if not uid:
return {
'success': False,
'message': u"No user ID given.",
}
users = model.backend
if uid in users:
return {
'success': False,
'message': u"User with given ID al... | def remote_add_user(model, request) | Add user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
New user id.
password
User password to be set ... | 2.729614 | 2.710109 | 1.007197 |
params = request.params
uid = params.get('id')
if not uid:
return {
'success': False,
'message': u"No user ID given.",
}
users = model.backend
if uid not in users:
return {
'success': False,
'message': u"User with given I... | def remote_delete_user(model, request) | Remove user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
Id of user to delete. | 2.816376 | 3.38711 | 0.831498 |
if obj is not None:
try:
# this is enough to load the new schema
obj.external
except LayerExternal.DoesNotExist:
pass
return super(LayerExternalInline, self).get_formset(request, obj=None, **kwargs) | def get_formset(self, request, obj=None, **kwargs) | Load Synchronizer schema to display specific fields in admin | 7.671225 | 6.931522 | 1.106716 |
while __websocket_server_running__:
pipein = open(PUBLIC_PIPE, 'r')
line = pipein.readline().replace('\n', '').replace('\r', '')
if line != '':
WebSocketHandler.broadcast(line)
print line
remaining_lines = pipein.read()
pipein... | def public_broadcaster() | Thread which runs in parallel and constantly checks for new messages
in the public pipe and broadcasts them publicly to all connected clients. | 3.815082 | 3.526299 | 1.081894 |
while __websocket_server_running__:
pipein = open(PRIVATE_PIPE, 'r')
line = pipein.readline().replace('\n', '').replace('\r', '')
if line != '':
message = json.loads(line)
WebSocketHandler.send_private_message(user_id=message['user_id'],
... | def private_messenger() | Thread which runs in parallel and constantly checks for new messages
in the private pipe and sends them to the specific client.
If client is not connected the message is discarded. | 3.729586 | 3.475378 | 1.073145 |
func = write_async if async else write
return func(name=self.name,
values=values,
tags=self.tags,
timestamp=timestamp,
database=database) | def write(self, values, timestamp=None, database=None, async=True) | write metric point | 3.770655 | 3.769261 | 1.00037 |
if not self.pk and self.model.polarization:
self.polarization = self.model.polarization
super(Antenna, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | 1. set polarization according to AntennaModel (self.model.polarization) when creating a new antenna
2. inherit latitude and longitude from node | 4.221358 | 2.796927 | 1.509284 |
# init django rest framework specific stuff
serializer_class = self.get_serializer_class()
context = self.get_serializer_context()
# init empty list
services = []
# loop over each service
for service_type in SERVICES.keys():
# initialize ser... | def get(self, request, *args, **kwargs) | return list of open 311 services | 5.332884 | 4.967339 | 1.07359 |
serializers = {
'node': NodeRequestListSerializer,
'vote': VoteRequestListSerializer,
'comment': CommentRequestListSerializer,
'rate': RatingRequestListSerializer,
}
context = self.get_serializer_context()
service_code = context['r... | def get_serializer(self, instance=None, data=None,
many=False, partial=False) | Return the serializer instance that should be used for validating and
deserializing input, and for serializing output. | 2.738972 | 2.72373 | 1.005596 |
if 'service_code' not in request.GET.keys():
return Response({ 'detail': _('A service code must be inserted') }, status=404)
service_code = request.GET['service_code']
if service_code not in SERVICES.keys():
return Response({ 'detail': _('Service not found') },... | def get(self, request, *args, **kwargs) | Retrieve list of service requests | 1.973653 | 1.947223 | 1.013573 |
service_code = request.data['service_code']
if service_code not in SERVICES.keys():
return Response({ 'detail': _('Service not found') }, status=404)
serializers = {
'node': NodeRequestSerializer,
'vote': VoteRequestSerializer,
'comment'... | def post(self, request, *args, **kwargs) | Post a service request (requires authentication) | 3.563036 | 3.472856 | 1.025967 |
from nodeshot.core.nodes.base import ExtensibleNodeSerializer
from .models import Vote
from .serializers import (CommentRelationSerializer,
ParticipationSerializer)
ExtensibleNodeSerializer.add_relationship(
'comments',
... | def ready(self) | Add user info to ExtensibleNodeSerializer | 2.615263 | 2.431658 | 1.075506 |
if kwargs['created']:
obj = kwargs['instance']
queryset = exclude_owner_of_node(obj)
create_notifications.delay(**{
"users": queryset,
"notification_model": Notification,
"notification_type": "node_created",
"related_object": obj
}... | def node_created_handler(sender, **kwargs) | send notification when a new node is created according to users's settings | 5.80981 | 5.216669 | 1.113701 |
obj = kwargs['instance']
obj.old_status = kwargs['old_status'].name
obj.new_status = kwargs['new_status'].name
queryset = exclude_owner_of_node(obj)
create_notifications.delay(**{
"users": queryset,
"notification_model": Notification,
"notification_type": "node_status_ch... | def node_status_changed_handler(**kwargs) | send notification when the status of a node changes according to users's settings | 3.873728 | 3.666298 | 1.056578 |
latest = self.latest
current = NetJsonParser(self.json())
return diff(current, latest) | def diff(self) | shortcut to netdiff.diff | 24.192467 | 15.0122 | 1.61152 |
nodes = []
links = []
for link in self.link_set.all():
if self.is_layer2:
source = link.interface_a.mac
destination = link.interface_b.mac
else:
source = str(link.interface_a.ip_set.first().address)
... | def json(self) | returns a dict that represents a NetJSON NetworkGraph object | 2.804452 | 2.591408 | 1.082211 |
from .link import Link # avoid circular dependency
diff = self.diff()
status = {
'added': 'active',
'removed': 'disconnected',
'changed': 'active'
}
for section in ['added', 'removed', 'changed']:
# section might be empt... | def update(self) | Updates topology
Links are not deleted straightaway but set as "disconnected" | 4.18456 | 3.974529 | 1.052844 |
if self.synchronizer_path != 'None' and self.config:
# call synchronizer custom clean
try:
self.synchronizer.load_config(self.config)
self.synchronizer.clean()
except ImproperlyConfigured as e:
raise ValidationError(e.m... | def clean(self, *args, **kwargs) | Call self.synchronizer.clean method | 6.676126 | 4.803182 | 1.389938 |
after_save = kwargs.pop('after_save', True)
super(LayerExternal, self).save(*args, **kwargs)
# call after_external_layer_saved method of synchronizer
if after_save:
try:
synchronizer = self.synchronizer
except ImproperlyConfigured:
... | def save(self, *args, **kwargs) | call synchronizer "after_external_layer_saved" method
for any additional operation that must be executed after save | 4.47012 | 3.05858 | 1.461502 |
if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:
return False
# ensure data is up to date
if (self._synchronizer is not None and self._synchronizer_class.__name__ not in self.synchronizer_path):
self._synchronizer = None
... | def synchronizer(self) | access synchronizer | 3.975838 | 3.956744 | 1.004826 |
if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:
return False
# ensure data is up to date
if (self._synchronizer_class is not None and self._synchronizer_class.__name__ not in self.synchronizer_path):
self._synchronizer = None
... | def synchronizer_class(self) | returns synchronizer class | 3.274958 | 3.176138 | 1.031113 |
view = self.context.get('view')
request = copy(self.context.get('request'))
request._method = 'PUT'
try:
view.check_object_permissions(request, obj)
except (PermissionDenied, NotAuthenticated):
return False
else:
return True | def get_can_edit(self, obj) | returns true if user has permission to edit, false otherwise | 3.164624 | 2.865166 | 1.104517 |
args = {
'slug': obj.node.slug,
'pk': obj.pk
}
return reverse('api_node_image_detail',
kwargs=args,
request=self.context.get('request', None)) | def get_details(self, obj) | returns uri of API image resource | 4.722611 | 3.405471 | 1.386772 |
super(GeoRss, self).parse()
# support RSS and ATOM
tag_name = 'item' if '<item>' in self.data else 'entry'
self.parsed_data = self.parsed_data.getElementsByTagName(tag_name) | def parse(self) | parse data | 7.756332 | 7.267337 | 1.067287 |
if request.method == 'POST':
user = Profile.objects.only('id', 'username').get(username=view.kwargs['username'])
return request.user.id == user.id
return True | def has_permission(self, request, view) | applies to social-link-list | 4.22 | 3.847905 | 1.096701 |
try:
os.remove(self.file.file.name)
# image does not exist
except (OSError, IOError):
pass
super(Image, self).delete(*args, **kwargs) | def delete(self, *args, **kwargs) | delete image when an image record is deleted | 4.379036 | 3.669418 | 1.193387 |
if type == 'etx':
if 0 < self.etx < 1.5:
quality = 1
elif self.etx < 3:
quality = 2
else:
quality = 3
elif type == 'dbm':
if -83 < self.dbm < 0:
quality = 1
elif self.dbm > ... | def get_quality(self, type='etx') | used to determine color of links | 2.626518 | 2.720241 | 0.965546 |
if not self.pk and self.layer and not self.layer.new_nodes_allowed:
raise ValidationError(_('New nodes are not allowed for this layer')) | def new_nodes_allowed_for_layer(self) | ensure new nodes are allowed for this layer | 5.413847 | 4.119628 | 1.314159 |
if self.layer and self.layer.nodes_minimum_distance:
minimum_distance = self.layer.nodes_minimum_distance
# TODO - lower priority: do this check only when coordinates are changing
near_nodes = Node.objects.exclude(pk=self.id).filter(geometry__distance_lte=(self.geometry, D(m=minimum_dis... | def nodes_minimum_distance_validation(self) | if minimum distance is specified, ensure node is not too close to other nodes; | 4.883543 | 4.26947 | 1.143829 |
# if area is a polygon ensure it contains the node
if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):
raise ValidationError(_('Node must be inside layer area')) | def node_contained_in_layer_area_validation(self) | if layer defines an area, ensure node coordinates are contained in the area | 5.693274 | 4.766503 | 1.194434 |
super(Layer, self).save(*args, **kwargs)
# if is_published of an existing layer changes
if self.pk and self.is_published != self._current_is_published:
# send django signal
layer_is_published_changed.send(
sender=self.__class__,
i... | def save(self, *args, **kwargs) | intercepts changes to is_published and fires layer_is_published_changed signal | 3.292231 | 2.560718 | 1.285667 |
if self.pk:
self.node_set.all().update(is_published=self.is_published) | def update_nodes_published(self) | publish or unpublish nodes of current layer | 4.645613 | 4.082062 | 1.138055 |
action = request.query_params.get('action', 'unread')
# action can be only "unread" (default), "count" and "all"
action = action if action == 'count' or action == 'all' else 'unread'
# mark as read parameter, defaults to true
mark_as_read = request.query_params.get('read... | def get(self, request, format=None) | get HTTP method | 3.773627 | 3.71653 | 1.015363 |
notifications = notifications.filter(is_read=False)
serializer = UnreadNotificationSerializer(list(notifications), # evaluate queryset
many=True,
context=self.get_serializer_context())
#... | def get_unread(self, request, notifications, mark_as_read) | return unread notifications and mark as read
(unless read=false param is passed) | 4.249146 | 4.134642 | 1.027694 |
return Response({'count': notifications.filter(is_read=False).count()}) | def get_count(self, request, notifications, mark_as_read=False) | return count of unread notification | 4.85912 | 3.342675 | 1.453662 |
return self.list(request, notifications) | def get_all(self, request, notifications, mark_as_read=False) | return all notifications with pagination | 13.049249 | 7.437454 | 1.754532 |
try:
obj = self.get_queryset()
except self.model.DoesNotExist:
raise Http404()
self.check_object_permissions(self.request, obj)
return obj | def get_object(self, queryset=None) | get privacy settings of current user | 2.614607 | 2.473794 | 1.056922 |
if self.status != LINK_STATUS.get('planned'):
if self.interface_a is None or self.interface_b is None:
raise ValidationError(_('fields "from interface" and "to interface" are mandatory in this case'))
if (self.interface_a_id == self.interface_b_id) or (self.inte... | def clean(self, *args, **kwargs) | Custom validation
1. interface_a and interface_b mandatory except for planned links
2. planned links should have at least node_a and node_b filled in
3. dbm and noise fields can be filled only for radio links
4. interface_a and interface_b must differ
5. inter... | 3.404106 | 2.504342 | 1.359281 |
if not self.type:
if self.interface_a.type == INTERFACE_TYPES.get('wireless'):
self.type = LINK_TYPES.get('radio')
elif self.interface_a.type == INTERFACE_TYPES.get('ethernet'):
self.type = LINK_TYPES.get('ethernet')
else:
... | def save(self, *args, **kwargs) | Custom save does the following:
* determine link type if not specified
* automatically fill 'node_a' and 'node_b' fields if necessary
* draw line between two nodes
* fill shortcut properties node_a_name and node_b_name | 1.743655 | 1.62138 | 1.075414 |
a = source
b = target
# ensure parameters are coherent
if not (valid_ipv4(a) and valid_ipv4(b)) and not (valid_ipv6(a) and valid_ipv6(b)) and not (valid_mac(a) and valid_mac(b)):
raise ValueError('Expecting valid ipv4, ipv6 or mac address')
# get interfaces
... | def get_link(cls, source, target, topology=None) | Find link between source and target, (or vice versa, order is irrelevant).
:param source: ip or mac addresses
:param target: ip or mac addresses
:param topology: optional topology relation
:returns: Link object
:raises: LinkNotFound | 2.803828 | 2.73768 | 1.024162 |
try:
return cls.get_link(source, target, topology)
except LinkNotFound as e:
pass
# create link
link = Link(interface_a=e.interface_a,
interface_b=e.interface_b,
status=LINK_STATUS['active'],
met... | def get_or_create(cls, source, target, cost, topology=None) | Tries to find a link with get_link, creates a new link if link not found. | 3.816398 | 3.430045 | 1.112638 |
changed = False
status_id = LINK_STATUS[status]
if self.status != status_id:
self.status = status_id
changed = True
if self.metric_value != cost:
self.metric_value = cost
changed = True
if changed:
self.save() | def ensure(self, status, cost) | ensure link properties correspond to the specified ones
perform save operation only if necessary | 2.996686 | 2.611342 | 1.147565 |
send_outward_mails.delay(queryset)
# show message in the admin
messages.info(request, _('Message sent successfully'), fail_silently=True) | def send(self, request, queryset) | Send action available in change outward list | 8.121337 | 7.216025 | 1.125458 |
try:
self.get_object(**kwargs)
except Http404:
return Response({'detail': _('Not Found')}, status=404)
if not self.is_contactable():
return Response({'detail': _('This resource cannot be contacted')}, status=400)
content_type = ContentType.o... | def post(self, request, *args, **kwargs) | Contact node owner. | 2.638916 | 2.638901 | 1.000006 |
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(request.user, context=self.get_serializer_context()).data)
else:
return Response({'detail': _('Authentication credentials were not provided')}, status=401) | def get(self, request, *args, **kwargs) | return profile of current user if authenticated otherwise 401 | 3.544528 | 2.878239 | 1.231492 |
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
login(request, serializer.instance)
if request.data.get('remember'):
# TODO: remember configurable
request.session.set_expiry(60 * 60 * 24 * 7 * 3)
... | def post(self, request, format=None) | authenticate | 2.763402 | 2.845538 | 0.971135 |
serializer_class = self.get_serializer_class()
serializer = serializer_class(data=request.data, instance=request.user)
if serializer.is_valid():
serializer.save()
return Response({'detail': _(u'Password successfully changed')})
return Response(serialize... | def post(self, request, format=None) | validate password change operation and return result | 2.773334 | 2.430878 | 1.140878 |
self.before_start()
self.retrieve_data()
self.parse()
# TRICK: disable new_nodes_allowed_for_layer validation
try:
Node._additional_validation.remove('new_nodes_allowed_for_layer')
except ValueError as e:
print "WARNING! got exception: %s... | def sync(self) | This is the method that does everything automatically (at least attempts to).
Steps:
0. Call "before_start" method (which might be implemented by children classes)
1. Retrieve data from external source
2. Parse the data
3. Save the data locally
4. Cal... | 6.041564 | 5.116502 | 1.1808 |
# shortcuts for readability
url = self.config.get('url')
timeout = float(self.config.get('timeout', 10))
# perform HTTP request and store content
self.data = requests.get(url, verify=self.verify_ssl, timeout=timeout).content | def retrieve_data(self) | retrieve data from an HTTP URL | 5.185883 | 4.517322 | 1.148 |
try:
xmlnode = item.getElementsByTagName(tag)[0].firstChild
except IndexError as e:
if default is not False:
return default
else:
raise IndexError(e)
if xmlnode is not None:
return unicode(xmlnode.nodeValue... | def get_text(item, tag, default=False) | returns text content of an xml tag | 3.363315 | 3.136545 | 1.072299 |
item = self.parse_item(item)
# name is required
if not item['name']:
raise Exception('Expected property %s not found in item %s.' % (self.keys['name'], item))
elif len(item['name']) > 75:
item['name'] = item['name'][:75]
if not item['status']:
... | def _convert_item(self, item) | take a parsed item as input and returns a python dictionary
the keys will be saved into the Node model
either in their respective fields or in the hstore "data" field
:param item: object representing parsed item | 2.295838 | 2.270992 | 1.010941 |
return self.queryset.all().accessible_to(user=self.request.user) | def get_queryset(self) | Returns only objects which are accessible to the current user.
If user is not authenticated all public objects will be returned.
Model must implement AccessLevelManager! | 11.226642 | 5.743473 | 1.954678 |
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
return self.update(request, *args, **kwargs) | def put(self, request, *args, **kwargs) | custom put method to support django-reversion | 3.787922 | 3.008924 | 1.258896 |
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
kwargs['partial'] = True
return self.update(request, *args, **kwargs) | def patch(self, request, *args, **kwargs) | custom patch method to support django-reversion | 3.66673 | 3.015549 | 1.215941 |
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('created through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
return self.create(request, *args, **kwargs) | def post(self, request, *args, **kwargs) | custom put method to support django-reversion | 3.631349 | 2.920377 | 1.243452 |
adding_new = False
if not self.pk or (not self.cpu and not self.ram):
# if self.model.cpu is not empty
if self.model.cpu:
self.cpu = self.model.cpu
# if self.model.ram is not empty
if self.model.ram:
self.ram = self... | def save(self, *args, **kwargs) | when creating a new record fill CPU and RAM info if available | 3.480722 | 3.213094 | 1.083293 |
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handler, sender=Node) | def disconnect() | disconnect signals | 3.699999 | 3.110945 | 1.189349 |
post_save.connect(node_created_handler, sender=Node)
node_status_changed.connect(node_status_changed_handler)
pre_delete.connect(node_deleted_handler, sender=Node) | def reconnect() | reconnect signals | 3.589251 | 3.161768 | 1.135204 |
if self.from_user and self.from_user_id == self.to_user_id:
raise ValidationError(_('A user cannot send a notification to herself/himself')) | def clean(self, *args, **kwargs) | from_user and to_user must differ | 6.733836 | 4.403004 | 1.529373 |
created = self.pk is None
# save notification to database only if user settings allow it
if self.check_user_settings(medium='web'):
super(Notification, self).save(*args, **kwargs)
if created:
# send notifications through other mediums according to user ... | def save(self, *args, **kwargs) | custom save method to send email and push notification | 8.064592 | 7.896849 | 1.021242 |
# send only if user notification setting is set to true
if self.check_user_settings():
send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email])
return True
else:
# return false otherwise
return False | def send_email(self) | send email notification according to user settings | 5.876471 | 4.988903 | 1.177908 |
# custom notifications are always sent
if self.type == 'custom':
return True
try:
user_settings = getattr(self.to_user, '%s_notification_settings' % medium)
except ObjectDoesNotExist:
# user has no settings specified
# TODO: it wo... | def check_user_settings(self, medium='email') | Ensure user is ok with receiving this notification through the specified medium.
Available mediums are 'web' and 'email', while 'mobile' notifications will
hopefully be implemented in the future. | 4.252933 | 4.201696 | 1.012194 |
url = settings.SITE_URL
hello_text = __("Hi %s," % self.to_user.get_full_name())
action_text = __("\n\nMore details here: %s") % url
explain_text = __(
"This is an automatic notification sent from from %s.\n"
"If you want to stop receiving this notificati... | def email_message(self) | compose complete email message text | 5.657026 | 5.403419 | 1.046935 |
super(OpenWisp, self).parse()
self.parsed_data = self.parsed_data.getElementsByTagName('item') | def parse(self) | parse data | 13.898635 | 11.755483 | 1.182311 |
salt = sha1(str(random())).hexdigest()[:5]
return sha1(salt + email).hexdigest() | def generate_key(self, email) | Generate a new email confirmation key and return it. | 4.260803 | 3.82213 | 1.114772 |
"Create an email confirmation obj from the given email address obj"
confirmation_key = self.generate_key(email_address.email)
confirmation = self.create(
email_address=email_address,
created_at=now(),
key=confirmation_key,
)
return confirmation | def create_emailconfirmation(self, email_address) | Create an email confirmation obj from the given email address obj | 4.415329 | 3.265217 | 1.352232 |
values = {
'value': 1,
'path': kwargs['request'].path,
'user_id': str(kwargs['user'].pk),
'username': kwargs['user'].username,
}
write('user_logins', values=values) | def user_loggedin(sender, **kwargs) | collect metrics about user logins | 4.505438 | 3.656257 | 1.232254 |
if kwargs.get('created'):
write('user_variations', {'variation': 1}, tags={'action': 'created'})
write('user_count', {'total': User.objects.count()}) | def user_deleted(sender, **kwargs) | collect metrics about new users signing up | 10.283036 | 7.071754 | 1.4541 |
try:
return self.noderatingcount
except ObjectDoesNotExist:
node_rating_count = NodeRatingCount(node=self)
node_rating_count.save()
return node_rating_count | def _node_rating_count(self) | Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count | 3.326467 | 2.867571 | 1.16003 |
try:
return self.node_participation_settings
except ObjectDoesNotExist:
node_participation_settings = NodeParticipationSettings(node=self)
node_participation_settings.save()
return node_participation_settings | def _node_participation_settings(self) | Return node_participation_settings record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.participation_settings | 2.295359 | 2.119748 | 1.082845 |
if getattr(self.layer.participation_settings, '{0}_allowed'.format(action)) is False:
return False
else:
return getattr(self.participation_settings, '{0}_allowed'.format(action)) | def _action_allowed(self, action) | participation actions can be disabled on layer level, or disabled on a per node basis | 5.456424 | 3.444287 | 1.584195 |
created = kwargs['created']
node = kwargs['instance']
if created:
# create node_rating_count and settings
# task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True
# if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be exe... | def create_node_rating_counts_settings(sender, **kwargs) | create node rating count and settings | 4.800289 | 4.262976 | 1.126042 |
created = kwargs['created']
layer = kwargs['instance']
if created:
# create layer participation settings
# task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True
# if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be exec... | def create_layer_rating_settings(sender, **kwargs) | create layer rating settings | 6.631445 | 6.567928 | 1.009671 |
created = self.pk is None
sync_emailaddress = kwargs.pop('sync_emailaddress', True)
# ensure usable password
if created and self.has_usable_password() is False:
self.set_password(self.password)
# save
super(Profile, self).save(*args, **kwargs)
... | def save(self, *args, **kwargs) | performs actions on create:
* ensure instance has usable password
* set default group
* keep in sync with email address model | 3.993376 | 3.38289 | 1.180463 |
if EMAIL_CONFIRMATION:
self.is_active = False
self.save()
return True
else:
return False | def needs_confirmation(self) | set is_active to False if needs email confirmation | 5.092744 | 3.21519 | 1.583963 |
self.set_password(new_password)
self.save()
password_changed.send(sender=self.__class__, user=self) | def change_password(self, new_password) | Changes password and sends a signal | 2.760664 | 2.385922 | 1.157064 |
super(NodeRelationViewMixin, self).initial(request, *args, **kwargs)
self.node = get_object_or_404(Node, **{'slug': self.kwargs['slug']})
self.queryset = self.model.objects.filter(node_id=self.node.id) | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only comments of current node | 3.003253 | 2.598622 | 1.15571 |
for key, value in TEXTS.items():
# custom notifications cannot be disabled
if 'custom' in [key, value]:
continue
field_type = USER_SETTING[key]['type']
if field_type == 'boolean':
field = models.BooleanField(_(key), default=DEFAULT_BOOLEAN)
elif... | def add_notifications(myclass) | Decorator which adds fields dynamically to User Notification Settings models.
Each of the keys in the TEXTS dictionary
are added as a field and DB column. | 5.222024 | 4.671827 | 1.117769 |
user = authenticate(**self.user_credentials(attrs))
if user:
if user.is_active:
self.instance = user
else:
raise serializers.ValidationError(_("This account is currently inactive."))
else:
error = _("Invalid login cred... | def validate(self, attrs) | checks if login credentials are correct | 3.737739 | 3.456662 | 1.081315 |
return reverse('api_user_social_links_detail',
args=[obj.user.username, obj.pk],
request=self.context.get('request'),
format=self.context.get('format')) | def get_details(self, obj) | return detail url | 4.264334 | 3.53983 | 1.204672 |
if not obj.city and not obj.country:
return None
elif obj.city and obj.country:
return '%s, %s' % (obj.city, obj.country)
elif obj.city or obj.country:
return obj.city or obj.country | def get_location(self, obj) | return user's location | 2.089177 | 1.922089 | 1.086931 |
if value != self.initial_data['password']:
raise serializers.ValidationError(_('Password confirmation mismatch'))
return value | def validate_password_confirmation(self, value) | password_confirmation check | 4.185635 | 3.932207 | 1.064449 |
if self.instance and self.instance.has_usable_password() and not self.instance.check_password(value):
raise serializers.ValidationError(_('Current password is not correct'))
return value | def validate_current_password(self, value) | current password check | 2.628077 | 2.570525 | 1.022389 |
if value != self.initial_data['password1']:
raise serializers.ValidationError(_('Password confirmation mismatch'))
return value | def validate_password2(self, value) | password_confirmation check | 4.796213 | 4.645052 | 1.032542 |
if EMAIL_CONFIRMATION:
queryset = EmailAddress.objects.filter(email__iexact=value, verified=True)
else:
queryset = User.objects.get(email__iexact=value, is_active=True).count() == 0
if queryset.count() < 1:
raise serializers.ValidationError(_("Email a... | def validate_email(self, value) | ensure email is in the database | 3.477846 | 3.29381 | 1.055873 |
instance.user.set_password(validated_data["password1"])
instance.user.full_clean()
instance.user.save()
# mark password reset object as reset
instance.reset = True
instance.full_clean()
instance.save()
return instance | def update(self, instance, validated_data) | change password | 4.017739 | 3.675597 | 1.093085 |
custom_checks = kwargs.pop('custom_checks', True)
super(Device, self).save(*args, **kwargs)
if custom_checks is False:
return
changed = False
if not self.location:
self.location = self.node.point
changed = True
if not self... | def save(self, *args, **kwargs) | Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled | 2.883962 | 2.722967 | 1.059125 |
# support passing email address too
if type(user) is unicode:
from .profile import Profile as User
user = User.objects.get(email=user)
temp_key = token_generator.make_token(user)
# save it to the password reset model
password_reset = PasswordRes... | def create_for_user(self, user) | create password reset for specified user | 2.885092 | 2.752272 | 1.048259 |
self.options = options
delete = False
try:
# blank line
self.stdout.write('\r\n')
# store verbosity level in instance attribute for later use
self.verbosity = int(self.options.get('verbosity'))
self.verbose('disabling signals... | def handle(self, *args, **options) | execute synchronize command | 5.533738 | 5.574328 | 0.992718 |
valid = {
"default": "default",
"def": "default",
"discard": "discard",
"dis": "discard",
}
question = % (node.name, len(layers))
available_layers = ""
for layer in layers:
available_layers += "%d (%s)\n" % (l... | def prompt_layer_selection(self, node, layers) | Ask user what to do when an old node is contained in more than one layer.
Possible answers are:
* use default layer (default answer if pressing enter)
* choose layer
* discard node | 3.343536 | 3.195393 | 1.046361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.