repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
ninuxorg/nodeshot | nodeshot/community/profiles/social_auth_extra/pipeline.py | create_user | def create_user(backend, details, response, uid, username, user=None, *args, **kwargs):
"""
Creates user. Depends on get_username pipeline.
"""
if user:
return {'user': user}
if not username:
return None
email = details.get('email')
original_email = None
# email is required
if not email:
message = _("""your social account needs to have a verified email address in order to proceed.""")
raise AuthFailed(backend, message)
# Avoid hitting field max length
if email and len(email) > 75:
original_email = email
email = ''
return {
'user': UserSocialAuth.create_user(username=username,
email=email,
sync_emailaddress=False),
'original_email': original_email,
'is_new': True
} | python | def create_user(backend, details, response, uid, username, user=None, *args, **kwargs):
"""
Creates user. Depends on get_username pipeline.
"""
if user:
return {'user': user}
if not username:
return None
email = details.get('email')
original_email = None
# email is required
if not email:
message = _("""your social account needs to have a verified email address in order to proceed.""")
raise AuthFailed(backend, message)
# Avoid hitting field max length
if email and len(email) > 75:
original_email = email
email = ''
return {
'user': UserSocialAuth.create_user(username=username,
email=email,
sync_emailaddress=False),
'original_email': original_email,
'is_new': True
} | [
"def",
"create_user",
"(",
"backend",
",",
"details",
",",
"response",
",",
"uid",
",",
"username",
",",
"user",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
":",
"return",
"{",
"'user'",
":",
"user",
"}",
"if",
"not",
"username",
":",
"return",
"None",
"email",
"=",
"details",
".",
"get",
"(",
"'email'",
")",
"original_email",
"=",
"None",
"# email is required",
"if",
"not",
"email",
":",
"message",
"=",
"_",
"(",
"\"\"\"your social account needs to have a verified email address in order to proceed.\"\"\"",
")",
"raise",
"AuthFailed",
"(",
"backend",
",",
"message",
")",
"# Avoid hitting field max length",
"if",
"email",
"and",
"len",
"(",
"email",
")",
">",
"75",
":",
"original_email",
"=",
"email",
"email",
"=",
"''",
"return",
"{",
"'user'",
":",
"UserSocialAuth",
".",
"create_user",
"(",
"username",
"=",
"username",
",",
"email",
"=",
"email",
",",
"sync_emailaddress",
"=",
"False",
")",
",",
"'original_email'",
":",
"original_email",
",",
"'is_new'",
":",
"True",
"}"
] | Creates user. Depends on get_username pipeline. | [
"Creates",
"user",
".",
"Depends",
"on",
"get_username",
"pipeline",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L13-L37 |
ninuxorg/nodeshot | nodeshot/community/profiles/social_auth_extra/pipeline.py | load_extra_data | def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs):
"""
Load extra data from provider and store it on current UserSocialAuth extra_data field.
"""
social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid)
# create verified email address
if kwargs['is_new'] and EMAIL_CONFIRMATION:
from ..models import EmailAddress
# check if email exist before creating it
# we might be associating an exisiting user
if EmailAddress.objects.filter(email=user.email).count() < 1:
EmailAddress.objects.create(user=user,
email=user.email,
verified=True,
primary=True)
if social_user:
extra_data = backend.extra_data(user, uid, response, details)
if kwargs.get('original_email') and 'email' not in extra_data:
extra_data['email'] = kwargs.get('original_email')
# update extra data if anything has changed
if extra_data and social_user.extra_data != extra_data:
if social_user.extra_data:
social_user.extra_data.update(extra_data)
else:
social_user.extra_data = extra_data
social_user.save()
# fetch additional data from facebook on creation
if backend.name == 'facebook' and kwargs['is_new']:
response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content)
try:
user.city, user.country = response.get('hometown').get('name').split(', ')
except (AttributeError, TypeError):
pass
try:
user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date()
except (AttributeError, TypeError):
pass
user.save()
return {'social_user': social_user} | python | def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs):
"""
Load extra data from provider and store it on current UserSocialAuth extra_data field.
"""
social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid)
# create verified email address
if kwargs['is_new'] and EMAIL_CONFIRMATION:
from ..models import EmailAddress
# check if email exist before creating it
# we might be associating an exisiting user
if EmailAddress.objects.filter(email=user.email).count() < 1:
EmailAddress.objects.create(user=user,
email=user.email,
verified=True,
primary=True)
if social_user:
extra_data = backend.extra_data(user, uid, response, details)
if kwargs.get('original_email') and 'email' not in extra_data:
extra_data['email'] = kwargs.get('original_email')
# update extra data if anything has changed
if extra_data and social_user.extra_data != extra_data:
if social_user.extra_data:
social_user.extra_data.update(extra_data)
else:
social_user.extra_data = extra_data
social_user.save()
# fetch additional data from facebook on creation
if backend.name == 'facebook' and kwargs['is_new']:
response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content)
try:
user.city, user.country = response.get('hometown').get('name').split(', ')
except (AttributeError, TypeError):
pass
try:
user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date()
except (AttributeError, TypeError):
pass
user.save()
return {'social_user': social_user} | [
"def",
"load_extra_data",
"(",
"backend",
",",
"details",
",",
"response",
",",
"uid",
",",
"user",
",",
"social_user",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"social_user",
"=",
"social_user",
"or",
"UserSocialAuth",
".",
"get_social_auth",
"(",
"backend",
".",
"name",
",",
"uid",
")",
"# create verified email address",
"if",
"kwargs",
"[",
"'is_new'",
"]",
"and",
"EMAIL_CONFIRMATION",
":",
"from",
".",
".",
"models",
"import",
"EmailAddress",
"# check if email exist before creating it",
"# we might be associating an exisiting user",
"if",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"user",
".",
"email",
")",
".",
"count",
"(",
")",
"<",
"1",
":",
"EmailAddress",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"user",
",",
"email",
"=",
"user",
".",
"email",
",",
"verified",
"=",
"True",
",",
"primary",
"=",
"True",
")",
"if",
"social_user",
":",
"extra_data",
"=",
"backend",
".",
"extra_data",
"(",
"user",
",",
"uid",
",",
"response",
",",
"details",
")",
"if",
"kwargs",
".",
"get",
"(",
"'original_email'",
")",
"and",
"'email'",
"not",
"in",
"extra_data",
":",
"extra_data",
"[",
"'email'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'original_email'",
")",
"# update extra data if anything has changed",
"if",
"extra_data",
"and",
"social_user",
".",
"extra_data",
"!=",
"extra_data",
":",
"if",
"social_user",
".",
"extra_data",
":",
"social_user",
".",
"extra_data",
".",
"update",
"(",
"extra_data",
")",
"else",
":",
"social_user",
".",
"extra_data",
"=",
"extra_data",
"social_user",
".",
"save",
"(",
")",
"# fetch additional data from facebook on creation",
"if",
"backend",
".",
"name",
"==",
"'facebook'",
"and",
"kwargs",
"[",
"'is_new'",
"]",
":",
"response",
"=",
"json",
".",
"loads",
"(",
"requests",
".",
"get",
"(",
"'https://graph.facebook.com/%s?access_token=%s'",
"%",
"(",
"extra_data",
"[",
"'id'",
"]",
",",
"extra_data",
"[",
"'access_token'",
"]",
")",
")",
".",
"content",
")",
"try",
":",
"user",
".",
"city",
",",
"user",
".",
"country",
"=",
"response",
".",
"get",
"(",
"'hometown'",
")",
".",
"get",
"(",
"'name'",
")",
".",
"split",
"(",
"', '",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"user",
".",
"birth_date",
"=",
"datetime",
".",
"strptime",
"(",
"response",
".",
"get",
"(",
"'birthday'",
")",
",",
"'%m/%d/%Y'",
")",
".",
"date",
"(",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"pass",
"user",
".",
"save",
"(",
")",
"return",
"{",
"'social_user'",
":",
"social_user",
"}"
] | Load extra data from provider and store it on current UserSocialAuth extra_data field. | [
"Load",
"extra",
"data",
"from",
"provider",
"and",
"store",
"it",
"on",
"current",
"UserSocialAuth",
"extra_data",
"field",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L40-L79 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/inward.py | Inward.clean | def clean(self, *args, **kwargs):
""" custom validation """
if not self.user and (not self.from_name or not self.from_email):
raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.'))
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email | python | def clean(self, *args, **kwargs):
""" custom validation """
if not self.user and (not self.from_name or not self.from_email):
raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.'))
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"user",
"and",
"(",
"not",
"self",
".",
"from_name",
"or",
"not",
"self",
".",
"from_email",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'If sender is not specified from_name and from_email must be filled in.'",
")",
")",
"# fill name and email",
"if",
"self",
".",
"user",
":",
"self",
".",
"from_name",
"=",
"self",
".",
"user",
".",
"get_full_name",
"(",
")",
"self",
".",
"from_email",
"=",
"self",
".",
"user",
".",
"email"
] | custom validation | [
"custom",
"validation"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L55-L62 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/inward.py | Inward.send | def send(self):
"""
Sends the email to the recipient
If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration
"""
if self.content_type.name == 'node':
to = [self.to.user.email]
elif self.content_type.name == 'layer':
to = [self.to.email]
# layer case is slightly special, mantainers need to be notified as well
# TODO: consider making the mantainers able to switch off notifications
for mantainer in self.to.mantainers.all().only('email'):
to += [mantainer.email]
else:
to = [self.to.email]
context = {
'sender_name': self.from_name,
'sender_email': self.from_email,
'message': self.message,
'site': settings.SITE_NAME,
'object_type': self.content_type.name,
'object_name': str(self.to)
}
message = render_to_string('mailing/inward_message.txt', context)
email = EmailMessage(
# subject
_('Contact request from %(sender_name)s - %(site)s') % context,
# message
message,
# from
settings.DEFAULT_FROM_EMAIL,
# to
to,
# reply-to header
headers={'Reply-To': self.from_email}
)
import socket
# try sending email
try:
email.send()
self.status = 1
# if error
except socket.error as e:
# log the error
import logging
log = logging.getLogger(__name__)
error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e
log.error(error_msg)
# set status of the instance as "error"
self.status = -1 | python | def send(self):
"""
Sends the email to the recipient
If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration
"""
if self.content_type.name == 'node':
to = [self.to.user.email]
elif self.content_type.name == 'layer':
to = [self.to.email]
# layer case is slightly special, mantainers need to be notified as well
# TODO: consider making the mantainers able to switch off notifications
for mantainer in self.to.mantainers.all().only('email'):
to += [mantainer.email]
else:
to = [self.to.email]
context = {
'sender_name': self.from_name,
'sender_email': self.from_email,
'message': self.message,
'site': settings.SITE_NAME,
'object_type': self.content_type.name,
'object_name': str(self.to)
}
message = render_to_string('mailing/inward_message.txt', context)
email = EmailMessage(
# subject
_('Contact request from %(sender_name)s - %(site)s') % context,
# message
message,
# from
settings.DEFAULT_FROM_EMAIL,
# to
to,
# reply-to header
headers={'Reply-To': self.from_email}
)
import socket
# try sending email
try:
email.send()
self.status = 1
# if error
except socket.error as e:
# log the error
import logging
log = logging.getLogger(__name__)
error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e
log.error(error_msg)
# set status of the instance as "error"
self.status = -1 | [
"def",
"send",
"(",
"self",
")",
":",
"if",
"self",
".",
"content_type",
".",
"name",
"==",
"'node'",
":",
"to",
"=",
"[",
"self",
".",
"to",
".",
"user",
".",
"email",
"]",
"elif",
"self",
".",
"content_type",
".",
"name",
"==",
"'layer'",
":",
"to",
"=",
"[",
"self",
".",
"to",
".",
"email",
"]",
"# layer case is slightly special, mantainers need to be notified as well",
"# TODO: consider making the mantainers able to switch off notifications",
"for",
"mantainer",
"in",
"self",
".",
"to",
".",
"mantainers",
".",
"all",
"(",
")",
".",
"only",
"(",
"'email'",
")",
":",
"to",
"+=",
"[",
"mantainer",
".",
"email",
"]",
"else",
":",
"to",
"=",
"[",
"self",
".",
"to",
".",
"email",
"]",
"context",
"=",
"{",
"'sender_name'",
":",
"self",
".",
"from_name",
",",
"'sender_email'",
":",
"self",
".",
"from_email",
",",
"'message'",
":",
"self",
".",
"message",
",",
"'site'",
":",
"settings",
".",
"SITE_NAME",
",",
"'object_type'",
":",
"self",
".",
"content_type",
".",
"name",
",",
"'object_name'",
":",
"str",
"(",
"self",
".",
"to",
")",
"}",
"message",
"=",
"render_to_string",
"(",
"'mailing/inward_message.txt'",
",",
"context",
")",
"email",
"=",
"EmailMessage",
"(",
"# subject",
"_",
"(",
"'Contact request from %(sender_name)s - %(site)s'",
")",
"%",
"context",
",",
"# message",
"message",
",",
"# from",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"# to",
"to",
",",
"# reply-to header",
"headers",
"=",
"{",
"'Reply-To'",
":",
"self",
".",
"from_email",
"}",
")",
"import",
"socket",
"# try sending email",
"try",
":",
"email",
".",
"send",
"(",
")",
"self",
".",
"status",
"=",
"1",
"# if error",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"# log the error",
"import",
"logging",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"error_msg",
"=",
"'nodeshot.community.mailing.models.inward.send(): %s'",
"%",
"e",
"log",
".",
"error",
"(",
"error_msg",
")",
"# set status of the instance as \"error\"",
"self",
".",
"status",
"=",
"-",
"1"
] | Sends the email to the recipient
If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration | [
"Sends",
"the",
"email",
"to",
"the",
"recipient",
"If",
"the",
"sending",
"fails",
"will",
"set",
"the",
"status",
"of",
"the",
"instance",
"to",
"error",
"and",
"will",
"log",
"the",
"error",
"according",
"to",
"your",
"project",
"s",
"django",
"-",
"logging",
"configuration"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L64-L116 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/inward.py | Inward.save | def save(self, *args, **kwargs):
"""
Custom save method
"""
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email
# if not sent yet
if int(self.status) < 1:
# tries sending email (will modify self.status!)
self.send()
# save in the database unless logging is explicitly turned off in the settings file
if INWARD_LOG:
super(Inward, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Custom save method
"""
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email
# if not sent yet
if int(self.status) < 1:
# tries sending email (will modify self.status!)
self.send()
# save in the database unless logging is explicitly turned off in the settings file
if INWARD_LOG:
super(Inward, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# fill name and email",
"if",
"self",
".",
"user",
":",
"self",
".",
"from_name",
"=",
"self",
".",
"user",
".",
"get_full_name",
"(",
")",
"self",
".",
"from_email",
"=",
"self",
".",
"user",
".",
"email",
"# if not sent yet",
"if",
"int",
"(",
"self",
".",
"status",
")",
"<",
"1",
":",
"# tries sending email (will modify self.status!)",
"self",
".",
"send",
"(",
")",
"# save in the database unless logging is explicitly turned off in the settings file",
"if",
"INWARD_LOG",
":",
"super",
"(",
"Inward",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Custom save method | [
"Custom",
"save",
"method"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L118-L134 |
ninuxorg/nodeshot | nodeshot/core/base/managers.py | BaseUtilityMixin.slice | def slice(self, order_by='pk', n=None):
""" return n objects according to specified ordering """
if n is not None and n < 0:
raise ValueError('slice parameter cannot be negative')
queryset = self.order_by(order_by)
if n is None:
return queryset[0]
else:
return queryset[0:n] | python | def slice(self, order_by='pk', n=None):
""" return n objects according to specified ordering """
if n is not None and n < 0:
raise ValueError('slice parameter cannot be negative')
queryset = self.order_by(order_by)
if n is None:
return queryset[0]
else:
return queryset[0:n] | [
"def",
"slice",
"(",
"self",
",",
"order_by",
"=",
"'pk'",
",",
"n",
"=",
"None",
")",
":",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'slice parameter cannot be negative'",
")",
"queryset",
"=",
"self",
".",
"order_by",
"(",
"order_by",
")",
"if",
"n",
"is",
"None",
":",
"return",
"queryset",
"[",
"0",
"]",
"else",
":",
"return",
"queryset",
"[",
"0",
":",
"n",
"]"
] | return n objects according to specified ordering | [
"return",
"n",
"objects",
"according",
"to",
"specified",
"ordering"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L18-L28 |
ninuxorg/nodeshot | nodeshot/core/base/managers.py | ACLMixin.access_level_up_to | def access_level_up_to(self, access_level):
""" returns all items that have an access level equal or lower than the one specified """
# if access_level is number
if isinstance(access_level, int):
value = access_level
# else if is string get the numeric value
else:
value = ACCESS_LEVELS.get(access_level)
# return queryset
return self.filter(access_level__lte=value) | python | def access_level_up_to(self, access_level):
""" returns all items that have an access level equal or lower than the one specified """
# if access_level is number
if isinstance(access_level, int):
value = access_level
# else if is string get the numeric value
else:
value = ACCESS_LEVELS.get(access_level)
# return queryset
return self.filter(access_level__lte=value) | [
"def",
"access_level_up_to",
"(",
"self",
",",
"access_level",
")",
":",
"# if access_level is number",
"if",
"isinstance",
"(",
"access_level",
",",
"int",
")",
":",
"value",
"=",
"access_level",
"# else if is string get the numeric value",
"else",
":",
"value",
"=",
"ACCESS_LEVELS",
".",
"get",
"(",
"access_level",
")",
"# return queryset",
"return",
"self",
".",
"filter",
"(",
"access_level__lte",
"=",
"value",
")"
] | returns all items that have an access level equal or lower than the one specified | [
"returns",
"all",
"items",
"that",
"have",
"an",
"access",
"level",
"equal",
"or",
"lower",
"than",
"the",
"one",
"specified"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L45-L54 |
ninuxorg/nodeshot | nodeshot/core/base/managers.py | ACLMixin.accessible_to | def accessible_to(self, user):
"""
returns all the items that are accessible to the specified user
if user is not authenticated will return public items
:param user: an user instance
"""
if user.is_superuser:
try:
queryset = self.get_queryset()
except AttributeError:
queryset = self
elif user.is_authenticated():
# get user group (higher id)
group = user.groups.all().order_by('-id')[0]
queryset = self.filter(access_level__lte=ACCESS_LEVELS.get(group.name))
else:
queryset = self.filter(access_level__lte=ACCESS_LEVELS.get('public'))
return queryset | python | def accessible_to(self, user):
"""
returns all the items that are accessible to the specified user
if user is not authenticated will return public items
:param user: an user instance
"""
if user.is_superuser:
try:
queryset = self.get_queryset()
except AttributeError:
queryset = self
elif user.is_authenticated():
# get user group (higher id)
group = user.groups.all().order_by('-id')[0]
queryset = self.filter(access_level__lte=ACCESS_LEVELS.get(group.name))
else:
queryset = self.filter(access_level__lte=ACCESS_LEVELS.get('public'))
return queryset | [
"def",
"accessible_to",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
".",
"is_superuser",
":",
"try",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"except",
"AttributeError",
":",
"queryset",
"=",
"self",
"elif",
"user",
".",
"is_authenticated",
"(",
")",
":",
"# get user group (higher id)",
"group",
"=",
"user",
".",
"groups",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"'-id'",
")",
"[",
"0",
"]",
"queryset",
"=",
"self",
".",
"filter",
"(",
"access_level__lte",
"=",
"ACCESS_LEVELS",
".",
"get",
"(",
"group",
".",
"name",
")",
")",
"else",
":",
"queryset",
"=",
"self",
".",
"filter",
"(",
"access_level__lte",
"=",
"ACCESS_LEVELS",
".",
"get",
"(",
"'public'",
")",
")",
"return",
"queryset"
] | returns all the items that are accessible to the specified user
if user is not authenticated will return public items
:param user: an user instance | [
"returns",
"all",
"the",
"items",
"that",
"are",
"accessible",
"to",
"the",
"specified",
"user",
"if",
"user",
"is",
"not",
"authenticated",
"will",
"return",
"public",
"items",
":",
"param",
"user",
":",
"an",
"user",
"instance"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L56-L74 |
ninuxorg/nodeshot | nodeshot/core/nodes/models/status.py | Status.save | def save(self, *args, **kwargs):
""" intercepts changes to is_default """
ignore_default_check = kwargs.pop('ignore_default_check', False)
# if making this status the default one
if self.is_default != self._current_is_default and self.is_default is True:
# uncheck other default statuses first
for status in self.__class__.objects.filter(is_default=True):
status.is_default = False
status.save(ignore_default_check=True)
super(Status, self).save(*args, **kwargs)
# in case there are no default statuses, make this one as the default one
if self.__class__.objects.filter(is_default=True).count() == 0 and not ignore_default_check:
self.is_default = True
self.save()
# update __current_status
self._current_is_default = self.is_default | python | def save(self, *args, **kwargs):
""" intercepts changes to is_default """
ignore_default_check = kwargs.pop('ignore_default_check', False)
# if making this status the default one
if self.is_default != self._current_is_default and self.is_default is True:
# uncheck other default statuses first
for status in self.__class__.objects.filter(is_default=True):
status.is_default = False
status.save(ignore_default_check=True)
super(Status, self).save(*args, **kwargs)
# in case there are no default statuses, make this one as the default one
if self.__class__.objects.filter(is_default=True).count() == 0 and not ignore_default_check:
self.is_default = True
self.save()
# update __current_status
self._current_is_default = self.is_default | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ignore_default_check",
"=",
"kwargs",
".",
"pop",
"(",
"'ignore_default_check'",
",",
"False",
")",
"# if making this status the default one",
"if",
"self",
".",
"is_default",
"!=",
"self",
".",
"_current_is_default",
"and",
"self",
".",
"is_default",
"is",
"True",
":",
"# uncheck other default statuses first",
"for",
"status",
"in",
"self",
".",
"__class__",
".",
"objects",
".",
"filter",
"(",
"is_default",
"=",
"True",
")",
":",
"status",
".",
"is_default",
"=",
"False",
"status",
".",
"save",
"(",
"ignore_default_check",
"=",
"True",
")",
"super",
"(",
"Status",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# in case there are no default statuses, make this one as the default one",
"if",
"self",
".",
"__class__",
".",
"objects",
".",
"filter",
"(",
"is_default",
"=",
"True",
")",
".",
"count",
"(",
")",
"==",
"0",
"and",
"not",
"ignore_default_check",
":",
"self",
".",
"is_default",
"=",
"True",
"self",
".",
"save",
"(",
")",
"# update __current_status",
"self",
".",
"_current_is_default",
"=",
"self",
".",
"is_default"
] | intercepts changes to is_default | [
"intercepts",
"changes",
"to",
"is_default"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/status.py#L56-L73 |
ninuxorg/nodeshot | nodeshot/networking/links/views.py | NodeLinkList.initial | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only links of current node
"""
super(NodeLinkList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
except Node.DoesNotExist:
raise Http404(_('Node not found.'))
# check permissions on node (for link creation)
self.check_object_permissions(request, self.node)
# return only links of current node
self.queryset = Link.objects.select_related('node_a', 'node_b')\
.accessible_to(self.request.user)\
.filter(Q(node_a_id=self.node.id) |
Q(node_b_id=self.node.id)) | python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only links of current node
"""
super(NodeLinkList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
except Node.DoesNotExist:
raise Http404(_('Node not found.'))
# check permissions on node (for link creation)
self.check_object_permissions(request, self.node)
# return only links of current node
self.queryset = Link.objects.select_related('node_a', 'node_b')\
.accessible_to(self.request.user)\
.filter(Q(node_a_id=self.node.id) |
Q(node_b_id=self.node.id)) | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NodeLinkList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure node exists",
"try",
":",
"self",
".",
"node",
"=",
"Node",
".",
"objects",
".",
"published",
"(",
")",
".",
"accessible_to",
"(",
"request",
".",
"user",
")",
".",
"get",
"(",
"slug",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'slug'",
",",
"None",
")",
")",
"except",
"Node",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Node not found.'",
")",
")",
"# check permissions on node (for link creation)",
"self",
".",
"check_object_permissions",
"(",
"request",
",",
"self",
".",
"node",
")",
"# return only links of current node",
"self",
".",
"queryset",
"=",
"Link",
".",
"objects",
".",
"select_related",
"(",
"'node_a'",
",",
"'node_b'",
")",
".",
"accessible_to",
"(",
"self",
".",
"request",
".",
"user",
")",
".",
"filter",
"(",
"Q",
"(",
"node_a_id",
"=",
"self",
".",
"node",
".",
"id",
")",
"|",
"Q",
"(",
"node_b_id",
"=",
"self",
".",
"node",
".",
"id",
")",
")"
] | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only links of current node | [
"Custom",
"initial",
"method",
":",
"*",
"ensure",
"node",
"exists",
"and",
"store",
"it",
"in",
"an",
"instance",
"attribute",
"*",
"change",
"queryset",
"to",
"return",
"only",
"links",
"of",
"current",
"node"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/views.py#L73-L93 |
ninuxorg/nodeshot | nodeshot/interop/sync/apps.py | AppConfig.ready | def ready(self):
""" patch LayerNodesList view to support external layers """
from .models import LayerExternal
from nodeshot.core.layers.views import LayerNodeListMixin
def get_nodes(self, request, *args, **kwargs):
try:
external = self.layer.external
except LayerExternal.DoesNotExist:
external = False
# override view get_nodes method if we have a custom one
if external and self.layer.is_external and hasattr(external, 'get_nodes'):
return external.get_nodes(self.__class__.__name__, request.query_params)
# otherwise return the standard one
else:
return (self.list(request, *args, **kwargs)).data
LayerNodeListMixin.get_nodes = get_nodes | python | def ready(self):
""" patch LayerNodesList view to support external layers """
from .models import LayerExternal
from nodeshot.core.layers.views import LayerNodeListMixin
def get_nodes(self, request, *args, **kwargs):
try:
external = self.layer.external
except LayerExternal.DoesNotExist:
external = False
# override view get_nodes method if we have a custom one
if external and self.layer.is_external and hasattr(external, 'get_nodes'):
return external.get_nodes(self.__class__.__name__, request.query_params)
# otherwise return the standard one
else:
return (self.list(request, *args, **kwargs)).data
LayerNodeListMixin.get_nodes = get_nodes | [
"def",
"ready",
"(",
"self",
")",
":",
"from",
".",
"models",
"import",
"LayerExternal",
"from",
"nodeshot",
".",
"core",
".",
"layers",
".",
"views",
"import",
"LayerNodeListMixin",
"def",
"get_nodes",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"external",
"=",
"self",
".",
"layer",
".",
"external",
"except",
"LayerExternal",
".",
"DoesNotExist",
":",
"external",
"=",
"False",
"# override view get_nodes method if we have a custom one",
"if",
"external",
"and",
"self",
".",
"layer",
".",
"is_external",
"and",
"hasattr",
"(",
"external",
",",
"'get_nodes'",
")",
":",
"return",
"external",
".",
"get_nodes",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"request",
".",
"query_params",
")",
"# otherwise return the standard one",
"else",
":",
"return",
"(",
"self",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
".",
"data",
"LayerNodeListMixin",
".",
"get_nodes",
"=",
"get_nodes"
] | patch LayerNodesList view to support external layers | [
"patch",
"LayerNodesList",
"view",
"to",
"support",
"external",
"layers"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/apps.py#L7-L24 |
ninuxorg/nodeshot | nodeshot/conf/celery.py | init_celery | def init_celery(project_name):
""" init celery app without the need of redundant code """
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name)
app = Celery(project_name)
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks')
return app | python | def init_celery(project_name):
""" init celery app without the need of redundant code """
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name)
app = Celery(project_name)
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks')
return app | [
"def",
"init_celery",
"(",
"project_name",
")",
":",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'DJANGO_SETTINGS_MODULE'",
",",
"'%s.settings'",
"%",
"project_name",
")",
"app",
"=",
"Celery",
"(",
"project_name",
")",
"app",
".",
"config_from_object",
"(",
"'django.conf:settings'",
")",
"app",
".",
"autodiscover_tasks",
"(",
"settings",
".",
"INSTALLED_APPS",
",",
"related_name",
"=",
"'tasks'",
")",
"return",
"app"
] | init celery app without the need of redundant code | [
"init",
"celery",
"app",
"without",
"the",
"need",
"of",
"redundant",
"code"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/conf/celery.py#L26-L32 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/outward.py | Outward.get_recipients | def get_recipients(self):
"""
Determine recipients depending on selected filtering which can be either:
* group based
* layer based
* user based
Choosing "group" and "layer" filtering together has the effect of sending the message
only to users for which the following conditions are both true:
* have a node assigned to one of the selected layers
* are part of any of the specified groups (eg: registered, community, trusted)
The user based filtering has instead the effect of translating in an **OR** query. Here's a practical example:
if selecting "group" and "user" filtering the message will be sent to all the users for which ANY of the following conditions is true:
* are part of any of the specified groups (eg: registered, community, trusted)
* selected users
"""
# user model
User = get_user_model()
# prepare email list
emails = []
# the following code is a bit ugly. Considering the titanic amount of work required to build all
# the cools functionalities that I have in my mind, I can't be bothered to waste time on making it nicer right now.
# if you have ideas on how to improve it to make it cleaner and less cluttered, please join in
# this method has unit tests written for it, therefore if you try to change it be sure to check unit tests do not fail after your changes
# python manage.py test mailing
# send to all case
if not self.is_filtered:
# retrieve only email DB column of all active users
users = User.objects.filter(is_active=True).only('email')
# loop over users list
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
else:
# selected users
if FILTERS.get('users') in self.filters:
# retrieve selected users
users = self.users.all().only('email')
# loop over selected users
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
# Q is a django object for "complex" filtering queries (not that complex in this case)
# init empty Q object that will be needed in case of group filtering
q = Q()
q2 = Q()
# if group filtering is checked
if FILTERS.get('groups') in self.filters:
# loop over each group
for group in self.groups:
# if not superusers
if group != '0':
# add the group to the Q object
# this means that the query will look for users of that specific group
q = q | Q(groups=int(group))
q2 = q2 | Q(user__groups=int(group))
else:
# this must be done manually because superusers is not a group but an attribute of the User model
q = q | Q(is_superuser=True)
q2 = q2 | Q(user__is_superuser=True)
# plus users must be active
q = q & Q(is_active=True)
# if layer filtering is checked
if FILTERS.get('layers') in self.filters:
# retrieve non-external layers
layers = self.layers.all().only('id')
# init empty q3
q3 = Q()
# loop over layers to form q3 object
for layer in layers:
q3 = q3 | Q(layer=layer)
# q2: user group if present
# q3: layers
# retrieve nodes
nodes = Node.objects.filter(q2 & q3)
# loop over nodes of a layer and get their email
for node in nodes:
# add email to the recipient list if not already there
if node.user.email not in emails:
emails += [node.user.email]
# else if group filterins is checked but not layers
elif FILTERS.get('groups') in self.filters and not FILTERS.get('layers') in self.filters:
# retrieve only email DB column of all active users
users = User.objects.filter(q).only('email')
# loop over users list
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
return emails | python | def get_recipients(self):
"""
Determine recipients depending on selected filtering which can be either:
* group based
* layer based
* user based
Choosing "group" and "layer" filtering together has the effect of sending the message
only to users for which the following conditions are both true:
* have a node assigned to one of the selected layers
* are part of any of the specified groups (eg: registered, community, trusted)
The user based filtering has instead the effect of translating in an **OR** query. Here's a practical example:
if selecting "group" and "user" filtering the message will be sent to all the users for which ANY of the following conditions is true:
* are part of any of the specified groups (eg: registered, community, trusted)
* selected users
"""
# user model
User = get_user_model()
# prepare email list
emails = []
# the following code is a bit ugly. Considering the titanic amount of work required to build all
# the cools functionalities that I have in my mind, I can't be bothered to waste time on making it nicer right now.
# if you have ideas on how to improve it to make it cleaner and less cluttered, please join in
# this method has unit tests written for it, therefore if you try to change it be sure to check unit tests do not fail after your changes
# python manage.py test mailing
# send to all case
if not self.is_filtered:
# retrieve only email DB column of all active users
users = User.objects.filter(is_active=True).only('email')
# loop over users list
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
else:
# selected users
if FILTERS.get('users') in self.filters:
# retrieve selected users
users = self.users.all().only('email')
# loop over selected users
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
# Q is a django object for "complex" filtering queries (not that complex in this case)
# init empty Q object that will be needed in case of group filtering
q = Q()
q2 = Q()
# if group filtering is checked
if FILTERS.get('groups') in self.filters:
# loop over each group
for group in self.groups:
# if not superusers
if group != '0':
# add the group to the Q object
# this means that the query will look for users of that specific group
q = q | Q(groups=int(group))
q2 = q2 | Q(user__groups=int(group))
else:
# this must be done manually because superusers is not a group but an attribute of the User model
q = q | Q(is_superuser=True)
q2 = q2 | Q(user__is_superuser=True)
# plus users must be active
q = q & Q(is_active=True)
# if layer filtering is checked
if FILTERS.get('layers') in self.filters:
# retrieve non-external layers
layers = self.layers.all().only('id')
# init empty q3
q3 = Q()
# loop over layers to form q3 object
for layer in layers:
q3 = q3 | Q(layer=layer)
# q2: user group if present
# q3: layers
# retrieve nodes
nodes = Node.objects.filter(q2 & q3)
# loop over nodes of a layer and get their email
for node in nodes:
# add email to the recipient list if not already there
if node.user.email not in emails:
emails += [node.user.email]
# else if group filterins is checked but not layers
elif FILTERS.get('groups') in self.filters and not FILTERS.get('layers') in self.filters:
# retrieve only email DB column of all active users
users = User.objects.filter(q).only('email')
# loop over users list
for user in users:
# add email to the recipient list if not already there
if user.email not in emails:
emails += [user.email]
return emails | [
"def",
"get_recipients",
"(",
"self",
")",
":",
"# user model",
"User",
"=",
"get_user_model",
"(",
")",
"# prepare email list",
"emails",
"=",
"[",
"]",
"# the following code is a bit ugly. Considering the titanic amount of work required to build all",
"# the cools functionalities that I have in my mind, I can't be bothered to waste time on making it nicer right now.",
"# if you have ideas on how to improve it to make it cleaner and less cluttered, please join in",
"# this method has unit tests written for it, therefore if you try to change it be sure to check unit tests do not fail after your changes",
"# python manage.py test mailing",
"# send to all case",
"if",
"not",
"self",
".",
"is_filtered",
":",
"# retrieve only email DB column of all active users",
"users",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"is_active",
"=",
"True",
")",
".",
"only",
"(",
"'email'",
")",
"# loop over users list",
"for",
"user",
"in",
"users",
":",
"# add email to the recipient list if not already there",
"if",
"user",
".",
"email",
"not",
"in",
"emails",
":",
"emails",
"+=",
"[",
"user",
".",
"email",
"]",
"else",
":",
"# selected users",
"if",
"FILTERS",
".",
"get",
"(",
"'users'",
")",
"in",
"self",
".",
"filters",
":",
"# retrieve selected users",
"users",
"=",
"self",
".",
"users",
".",
"all",
"(",
")",
".",
"only",
"(",
"'email'",
")",
"# loop over selected users",
"for",
"user",
"in",
"users",
":",
"# add email to the recipient list if not already there",
"if",
"user",
".",
"email",
"not",
"in",
"emails",
":",
"emails",
"+=",
"[",
"user",
".",
"email",
"]",
"# Q is a django object for \"complex\" filtering queries (not that complex in this case)",
"# init empty Q object that will be needed in case of group filtering",
"q",
"=",
"Q",
"(",
")",
"q2",
"=",
"Q",
"(",
")",
"# if group filtering is checked",
"if",
"FILTERS",
".",
"get",
"(",
"'groups'",
")",
"in",
"self",
".",
"filters",
":",
"# loop over each group",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"# if not superusers",
"if",
"group",
"!=",
"'0'",
":",
"# add the group to the Q object",
"# this means that the query will look for users of that specific group",
"q",
"=",
"q",
"|",
"Q",
"(",
"groups",
"=",
"int",
"(",
"group",
")",
")",
"q2",
"=",
"q2",
"|",
"Q",
"(",
"user__groups",
"=",
"int",
"(",
"group",
")",
")",
"else",
":",
"# this must be done manually because superusers is not a group but an attribute of the User model",
"q",
"=",
"q",
"|",
"Q",
"(",
"is_superuser",
"=",
"True",
")",
"q2",
"=",
"q2",
"|",
"Q",
"(",
"user__is_superuser",
"=",
"True",
")",
"# plus users must be active",
"q",
"=",
"q",
"&",
"Q",
"(",
"is_active",
"=",
"True",
")",
"# if layer filtering is checked",
"if",
"FILTERS",
".",
"get",
"(",
"'layers'",
")",
"in",
"self",
".",
"filters",
":",
"# retrieve non-external layers",
"layers",
"=",
"self",
".",
"layers",
".",
"all",
"(",
")",
".",
"only",
"(",
"'id'",
")",
"# init empty q3",
"q3",
"=",
"Q",
"(",
")",
"# loop over layers to form q3 object",
"for",
"layer",
"in",
"layers",
":",
"q3",
"=",
"q3",
"|",
"Q",
"(",
"layer",
"=",
"layer",
")",
"# q2: user group if present",
"# q3: layers",
"# retrieve nodes",
"nodes",
"=",
"Node",
".",
"objects",
".",
"filter",
"(",
"q2",
"&",
"q3",
")",
"# loop over nodes of a layer and get their email",
"for",
"node",
"in",
"nodes",
":",
"# add email to the recipient list if not already there",
"if",
"node",
".",
"user",
".",
"email",
"not",
"in",
"emails",
":",
"emails",
"+=",
"[",
"node",
".",
"user",
".",
"email",
"]",
"# else if group filterins is checked but not layers",
"elif",
"FILTERS",
".",
"get",
"(",
"'groups'",
")",
"in",
"self",
".",
"filters",
"and",
"not",
"FILTERS",
".",
"get",
"(",
"'layers'",
")",
"in",
"self",
".",
"filters",
":",
"# retrieve only email DB column of all active users",
"users",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"q",
")",
".",
"only",
"(",
"'email'",
")",
"# loop over users list",
"for",
"user",
"in",
"users",
":",
"# add email to the recipient list if not already there",
"if",
"user",
".",
"email",
"not",
"in",
"emails",
":",
"emails",
"+=",
"[",
"user",
".",
"email",
"]",
"return",
"emails"
] | Determine recipients depending on selected filtering which can be either:
* group based
* layer based
* user based
Choosing "group" and "layer" filtering together has the effect of sending the message
only to users for which the following conditions are both true:
* have a node assigned to one of the selected layers
* are part of any of the specified groups (eg: registered, community, trusted)
The user based filtering has instead the effect of translating in an **OR** query. Here's a practical example:
if selecting "group" and "user" filtering the message will be sent to all the users for which ANY of the following conditions is true:
* are part of any of the specified groups (eg: registered, community, trusted)
* selected users | [
"Determine",
"recipients",
"depending",
"on",
"selected",
"filtering",
"which",
"can",
"be",
"either",
":",
"*",
"group",
"based",
"*",
"layer",
"based",
"*",
"user",
"based"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L67-L166 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/outward.py | Outward.send | def send(self):
"""
Sends the email to the recipients
"""
# if it has already been sent don't send again
if self.status is OUTWARD_STATUS.get('sent'):
return False
# determine recipients
recipients = self.get_recipients()
# init empty list that will contain django's email objects
emails = []
# prepare text plain if necessary
if OUTWARD_HTML:
# store plain text in var
html_content = self.message
# set EmailClass to EmailMultiAlternatives
EmailClass = EmailMultiAlternatives
else:
EmailClass = EmailMessage
# default message is plain text
message = strip_tags(self.message)
# loop over recipients and fill "emails" list
for recipient in recipients:
msg = EmailClass(
# subject
self.subject,
# message
message,
# from
settings.DEFAULT_FROM_EMAIL,
# to
[recipient],
)
if OUTWARD_HTML:
msg.attach_alternative(html_content, "text/html")
# prepare email object
emails.append(msg)
# try sending email
try:
# counter will count how many emails have been sent
counter = 0
for email in emails:
# if step reached
if counter == OUTWARD_STEP:
# reset counter
counter = 0
# sleep
time.sleep(OUTWARD_DELAY)
# send email
email.send()
# increase counter
counter += 1
# if error (connection refused, SMTP down)
except socket.error as e:
# log the error
from logging import error
error('nodeshot.core.mailing.models.outward.send(): %s' % e)
# set status of the instance as "error"
self.status = OUTWARD_STATUS.get('error')
# change status
self.status = OUTWARD_STATUS.get('sent')
# save
self.save() | python | def send(self):
"""
Sends the email to the recipients
"""
# if it has already been sent don't send again
if self.status is OUTWARD_STATUS.get('sent'):
return False
# determine recipients
recipients = self.get_recipients()
# init empty list that will contain django's email objects
emails = []
# prepare text plain if necessary
if OUTWARD_HTML:
# store plain text in var
html_content = self.message
# set EmailClass to EmailMultiAlternatives
EmailClass = EmailMultiAlternatives
else:
EmailClass = EmailMessage
# default message is plain text
message = strip_tags(self.message)
# loop over recipients and fill "emails" list
for recipient in recipients:
msg = EmailClass(
# subject
self.subject,
# message
message,
# from
settings.DEFAULT_FROM_EMAIL,
# to
[recipient],
)
if OUTWARD_HTML:
msg.attach_alternative(html_content, "text/html")
# prepare email object
emails.append(msg)
# try sending email
try:
# counter will count how many emails have been sent
counter = 0
for email in emails:
# if step reached
if counter == OUTWARD_STEP:
# reset counter
counter = 0
# sleep
time.sleep(OUTWARD_DELAY)
# send email
email.send()
# increase counter
counter += 1
# if error (connection refused, SMTP down)
except socket.error as e:
# log the error
from logging import error
error('nodeshot.core.mailing.models.outward.send(): %s' % e)
# set status of the instance as "error"
self.status = OUTWARD_STATUS.get('error')
# change status
self.status = OUTWARD_STATUS.get('sent')
# save
self.save() | [
"def",
"send",
"(",
"self",
")",
":",
"# if it has already been sent don't send again",
"if",
"self",
".",
"status",
"is",
"OUTWARD_STATUS",
".",
"get",
"(",
"'sent'",
")",
":",
"return",
"False",
"# determine recipients",
"recipients",
"=",
"self",
".",
"get_recipients",
"(",
")",
"# init empty list that will contain django's email objects",
"emails",
"=",
"[",
"]",
"# prepare text plain if necessary",
"if",
"OUTWARD_HTML",
":",
"# store plain text in var",
"html_content",
"=",
"self",
".",
"message",
"# set EmailClass to EmailMultiAlternatives",
"EmailClass",
"=",
"EmailMultiAlternatives",
"else",
":",
"EmailClass",
"=",
"EmailMessage",
"# default message is plain text",
"message",
"=",
"strip_tags",
"(",
"self",
".",
"message",
")",
"# loop over recipients and fill \"emails\" list",
"for",
"recipient",
"in",
"recipients",
":",
"msg",
"=",
"EmailClass",
"(",
"# subject",
"self",
".",
"subject",
",",
"# message",
"message",
",",
"# from",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"# to",
"[",
"recipient",
"]",
",",
")",
"if",
"OUTWARD_HTML",
":",
"msg",
".",
"attach_alternative",
"(",
"html_content",
",",
"\"text/html\"",
")",
"# prepare email object",
"emails",
".",
"append",
"(",
"msg",
")",
"# try sending email",
"try",
":",
"# counter will count how many emails have been sent",
"counter",
"=",
"0",
"for",
"email",
"in",
"emails",
":",
"# if step reached",
"if",
"counter",
"==",
"OUTWARD_STEP",
":",
"# reset counter",
"counter",
"=",
"0",
"# sleep",
"time",
".",
"sleep",
"(",
"OUTWARD_DELAY",
")",
"# send email",
"email",
".",
"send",
"(",
")",
"# increase counter",
"counter",
"+=",
"1",
"# if error (connection refused, SMTP down)",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"# log the error",
"from",
"logging",
"import",
"error",
"error",
"(",
"'nodeshot.core.mailing.models.outward.send(): %s'",
"%",
"e",
")",
"# set status of the instance as \"error\"",
"self",
".",
"status",
"=",
"OUTWARD_STATUS",
".",
"get",
"(",
"'error'",
")",
"# change status",
"self",
".",
"status",
"=",
"OUTWARD_STATUS",
".",
"get",
"(",
"'sent'",
")",
"# save",
"self",
".",
"save",
"(",
")"
] | Sends the email to the recipients | [
"Sends",
"the",
"email",
"to",
"the",
"recipients"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L168-L234 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/outward.py | Outward.save | def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.save()
super(Outward, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.save()
super(Outward, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# change status to scheduled if necessary",
"if",
"self",
".",
"is_scheduled",
"and",
"self",
".",
"status",
"is",
"not",
"OUTWARD_STATUS",
".",
"get",
"(",
"'scheduled'",
")",
":",
"self",
".",
"status",
"=",
"OUTWARD_STATUS",
".",
"get",
"(",
"'scheduled'",
")",
"# call super.save()",
"super",
"(",
"Outward",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Custom save method | [
"Custom",
"save",
"method"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L236-L245 |
ninuxorg/nodeshot | nodeshot/community/mailing/models/outward.py | Outward.clean | def clean(self, *args, **kwargs):
"""
Custom validation
"""
if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None
or self.scheduled_time == '' or self.scheduled_time is None):
raise ValidationError(_('If message is scheduled both fields "scheduled date" and "scheduled time" must be specified'))
if self.is_scheduled is 1 and self.scheduled_date < now().date():
raise ValidationError(_('The scheduled date is set to a past date'))
if self.is_filtered is 1 and (len(self.filters) < 1 or self.filters == [''] or
self.filters == [u''] or self.filters == '' or self.filters is None):
raise ValidationError(_('If "recipient filtering" is active one of the filtering options should be selected'))
if self.is_filtered is 1 and FILTERS.get('groups') in self.filters and\
(len(self.groups) < 1 or self.groups == [''] or self.groups == [u''] or self.groups == '' or self.groups is None):
raise ValidationError(_('If group filtering is active at least one group of users should be selected')) | python | def clean(self, *args, **kwargs):
"""
Custom validation
"""
if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None
or self.scheduled_time == '' or self.scheduled_time is None):
raise ValidationError(_('If message is scheduled both fields "scheduled date" and "scheduled time" must be specified'))
if self.is_scheduled is 1 and self.scheduled_date < now().date():
raise ValidationError(_('The scheduled date is set to a past date'))
if self.is_filtered is 1 and (len(self.filters) < 1 or self.filters == [''] or
self.filters == [u''] or self.filters == '' or self.filters is None):
raise ValidationError(_('If "recipient filtering" is active one of the filtering options should be selected'))
if self.is_filtered is 1 and FILTERS.get('groups') in self.filters and\
(len(self.groups) < 1 or self.groups == [''] or self.groups == [u''] or self.groups == '' or self.groups is None):
raise ValidationError(_('If group filtering is active at least one group of users should be selected')) | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_scheduled",
"is",
"1",
"and",
"(",
"self",
".",
"scheduled_date",
"==",
"''",
"or",
"self",
".",
"scheduled_date",
"is",
"None",
"or",
"self",
".",
"scheduled_time",
"==",
"''",
"or",
"self",
".",
"scheduled_time",
"is",
"None",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'If message is scheduled both fields \"scheduled date\" and \"scheduled time\" must be specified'",
")",
")",
"if",
"self",
".",
"is_scheduled",
"is",
"1",
"and",
"self",
".",
"scheduled_date",
"<",
"now",
"(",
")",
".",
"date",
"(",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'The scheduled date is set to a past date'",
")",
")",
"if",
"self",
".",
"is_filtered",
"is",
"1",
"and",
"(",
"len",
"(",
"self",
".",
"filters",
")",
"<",
"1",
"or",
"self",
".",
"filters",
"==",
"[",
"''",
"]",
"or",
"self",
".",
"filters",
"==",
"[",
"u''",
"]",
"or",
"self",
".",
"filters",
"==",
"''",
"or",
"self",
".",
"filters",
"is",
"None",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'If \"recipient filtering\" is active one of the filtering options should be selected'",
")",
")",
"if",
"self",
".",
"is_filtered",
"is",
"1",
"and",
"FILTERS",
".",
"get",
"(",
"'groups'",
")",
"in",
"self",
".",
"filters",
"and",
"(",
"len",
"(",
"self",
".",
"groups",
")",
"<",
"1",
"or",
"self",
".",
"groups",
"==",
"[",
"''",
"]",
"or",
"self",
".",
"groups",
"==",
"[",
"u''",
"]",
"or",
"self",
".",
"groups",
"==",
"''",
"or",
"self",
".",
"groups",
"is",
"None",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'If group filtering is active at least one group of users should be selected'",
")",
")"
] | Custom validation | [
"Custom",
"validation"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L247-L264 |
ninuxorg/nodeshot | nodeshot/core/nodes/models/node.py | Node.save | def save(self, *args, **kwargs):
"""
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status
"""
# geometry collection check
if isinstance(self.geometry, GeometryCollection) and 0 < len(self.geometry) < 2:
self.geometry = self.geometry[0]
# if no status specified
if not self.status and not self.status_id:
try:
self.status = Status.objects.filter(is_default=True)[0]
except IndexError:
pass
super(Node, self).save(*args, **kwargs)
# if status of a node changes
if (self.status and self._current_status and self.status.id != self._current_status) or\
(self.status_id and self._current_status and self.status_id != self._current_status):
# send django signal
node_status_changed.send(
sender=self.__class__,
instance=self,
old_status=Status.objects.get(pk=self._current_status),
new_status=self.status
)
# update _current_status
self._current_status = self.status_id | python | def save(self, *args, **kwargs):
"""
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status
"""
# geometry collection check
if isinstance(self.geometry, GeometryCollection) and 0 < len(self.geometry) < 2:
self.geometry = self.geometry[0]
# if no status specified
if not self.status and not self.status_id:
try:
self.status = Status.objects.filter(is_default=True)[0]
except IndexError:
pass
super(Node, self).save(*args, **kwargs)
# if status of a node changes
if (self.status and self._current_status and self.status.id != self._current_status) or\
(self.status_id and self._current_status and self.status_id != self._current_status):
# send django signal
node_status_changed.send(
sender=self.__class__,
instance=self,
old_status=Status.objects.get(pk=self._current_status),
new_status=self.status
)
# update _current_status
self._current_status = self.status_id | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# geometry collection check",
"if",
"isinstance",
"(",
"self",
".",
"geometry",
",",
"GeometryCollection",
")",
"and",
"0",
"<",
"len",
"(",
"self",
".",
"geometry",
")",
"<",
"2",
":",
"self",
".",
"geometry",
"=",
"self",
".",
"geometry",
"[",
"0",
"]",
"# if no status specified",
"if",
"not",
"self",
".",
"status",
"and",
"not",
"self",
".",
"status_id",
":",
"try",
":",
"self",
".",
"status",
"=",
"Status",
".",
"objects",
".",
"filter",
"(",
"is_default",
"=",
"True",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"pass",
"super",
"(",
"Node",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# if status of a node changes",
"if",
"(",
"self",
".",
"status",
"and",
"self",
".",
"_current_status",
"and",
"self",
".",
"status",
".",
"id",
"!=",
"self",
".",
"_current_status",
")",
"or",
"(",
"self",
".",
"status_id",
"and",
"self",
".",
"_current_status",
"and",
"self",
".",
"status_id",
"!=",
"self",
".",
"_current_status",
")",
":",
"# send django signal",
"node_status_changed",
".",
"send",
"(",
"sender",
"=",
"self",
".",
"__class__",
",",
"instance",
"=",
"self",
",",
"old_status",
"=",
"Status",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"_current_status",
")",
",",
"new_status",
"=",
"self",
".",
"status",
")",
"# update _current_status",
"self",
".",
"_current_status",
"=",
"self",
".",
"status_id"
] | Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status | [
"Custom",
"save",
"method",
"does",
"the",
"following",
"things",
":",
"*",
"converts",
"geometry",
"collections",
"of",
"just",
"1",
"item",
"to",
"that",
"item",
"(",
"eg",
":",
"a",
"collection",
"of",
"1",
"Point",
"becomes",
"a",
"Point",
")",
"*",
"intercepts",
"changes",
"to",
"status",
"and",
"fires",
"node_status_changed",
"signal",
"*",
"set",
"default",
"status"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L88-L116 |
ninuxorg/nodeshot | nodeshot/core/nodes/models/node.py | Node.add_validation_method | def add_validation_method(cls, method):
"""
Extend validation of Node by adding a function to the _additional_validation list.
The additional validation function will be called by the clean method
:method function: function to be added to _additional_validation
"""
method_name = method.func_name
# add method name to additional validation method list
cls._additional_validation.append(method_name)
# add method to this class
setattr(cls, method_name, method) | python | def add_validation_method(cls, method):
"""
Extend validation of Node by adding a function to the _additional_validation list.
The additional validation function will be called by the clean method
:method function: function to be added to _additional_validation
"""
method_name = method.func_name
# add method name to additional validation method list
cls._additional_validation.append(method_name)
# add method to this class
setattr(cls, method_name, method) | [
"def",
"add_validation_method",
"(",
"cls",
",",
"method",
")",
":",
"method_name",
"=",
"method",
".",
"func_name",
"# add method name to additional validation method list",
"cls",
".",
"_additional_validation",
".",
"append",
"(",
"method_name",
")",
"# add method to this class",
"setattr",
"(",
"cls",
",",
"method_name",
",",
"method",
")"
] | Extend validation of Node by adding a function to the _additional_validation list.
The additional validation function will be called by the clean method
:method function: function to be added to _additional_validation | [
"Extend",
"validation",
"of",
"Node",
"by",
"adding",
"a",
"function",
"to",
"the",
"_additional_validation",
"list",
".",
"The",
"additional",
"validation",
"function",
"will",
"be",
"called",
"by",
"the",
"clean",
"method"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L129-L142 |
ninuxorg/nodeshot | nodeshot/core/nodes/models/node.py | Node.point | def point(self):
""" returns location of node. If node geometry is not a point a center point will be returned """
if not self.geometry:
raise ValueError('geometry attribute must be set before trying to get point property')
if self.geometry.geom_type == 'Point':
return self.geometry
else:
try:
# point_on_surface guarantees that the point is within the geometry
return self.geometry.point_on_surface
except GEOSException:
# fall back on centroid which may not be within the geometry
# for example, a horseshoe shaped polygon
return self.geometry.centroid | python | def point(self):
""" returns location of node. If node geometry is not a point a center point will be returned """
if not self.geometry:
raise ValueError('geometry attribute must be set before trying to get point property')
if self.geometry.geom_type == 'Point':
return self.geometry
else:
try:
# point_on_surface guarantees that the point is within the geometry
return self.geometry.point_on_surface
except GEOSException:
# fall back on centroid which may not be within the geometry
# for example, a horseshoe shaped polygon
return self.geometry.centroid | [
"def",
"point",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"geometry",
":",
"raise",
"ValueError",
"(",
"'geometry attribute must be set before trying to get point property'",
")",
"if",
"self",
".",
"geometry",
".",
"geom_type",
"==",
"'Point'",
":",
"return",
"self",
".",
"geometry",
"else",
":",
"try",
":",
"# point_on_surface guarantees that the point is within the geometry",
"return",
"self",
".",
"geometry",
".",
"point_on_surface",
"except",
"GEOSException",
":",
"# fall back on centroid which may not be within the geometry",
"# for example, a horseshoe shaped polygon",
"return",
"self",
".",
"geometry",
".",
"centroid"
] | returns location of node. If node geometry is not a point a center point will be returned | [
"returns",
"location",
"of",
"node",
".",
"If",
"node",
"geometry",
"is",
"not",
"a",
"point",
"a",
"center",
"point",
"will",
"be",
"returned"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L149-L162 |
ninuxorg/nodeshot | nodeshot/core/nodes/views.py | elevation_profile | def elevation_profile(request, format=None):
"""
Proxy to google elevation API but returns GeoJSON
(unless "original" parameter is passed, in which case the original response is returned).
For input parameters read:
https://developers.google.com/maps/documentation/elevation/
"""
if format is None:
format = 'json'
path = request.query_params.get('path')
if not path:
return Response({'detail': _('missing required path argument')}, status=400)
return Response(elevation(path,
api_key=ELEVATION_API_KEY,
sampling=ELEVATION_DEFAULT_SAMPLING)) | python | def elevation_profile(request, format=None):
"""
Proxy to google elevation API but returns GeoJSON
(unless "original" parameter is passed, in which case the original response is returned).
For input parameters read:
https://developers.google.com/maps/documentation/elevation/
"""
if format is None:
format = 'json'
path = request.query_params.get('path')
if not path:
return Response({'detail': _('missing required path argument')}, status=400)
return Response(elevation(path,
api_key=ELEVATION_API_KEY,
sampling=ELEVATION_DEFAULT_SAMPLING)) | [
"def",
"elevation_profile",
"(",
"request",
",",
"format",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":",
"format",
"=",
"'json'",
"path",
"=",
"request",
".",
"query_params",
".",
"get",
"(",
"'path'",
")",
"if",
"not",
"path",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"_",
"(",
"'missing required path argument'",
")",
"}",
",",
"status",
"=",
"400",
")",
"return",
"Response",
"(",
"elevation",
"(",
"path",
",",
"api_key",
"=",
"ELEVATION_API_KEY",
",",
"sampling",
"=",
"ELEVATION_DEFAULT_SAMPLING",
")",
")"
] | Proxy to google elevation API but returns GeoJSON
(unless "original" parameter is passed, in which case the original response is returned).
For input parameters read:
https://developers.google.com/maps/documentation/elevation/ | [
"Proxy",
"to",
"google",
"elevation",
"API",
"but",
"returns",
"GeoJSON",
"(",
"unless",
"original",
"parameter",
"is",
"passed",
"in",
"which",
"case",
"the",
"original",
"response",
"is",
"returned",
")",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L246-L263 |
ninuxorg/nodeshot | nodeshot/core/nodes/views.py | NodeList.perform_create | def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) | python | def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) | [
"def",
"perform_create",
"(",
"self",
",",
"serializer",
")",
":",
"if",
"serializer",
".",
"instance",
"is",
"None",
":",
"serializer",
".",
"save",
"(",
"user",
"=",
"self",
".",
"request",
".",
"user",
")"
] | determine user when node is added | [
"determine",
"user",
"when",
"node",
"is",
"added"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L51-L54 |
ninuxorg/nodeshot | nodeshot/core/nodes/views.py | NodeList.get_queryset | def get_queryset(self):
"""
Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL.
"""
# retrieve all nodes which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(NodeList, self).get_queryset().select_related('status', 'user', 'layer')
# query string params
search = self.request.query_params.get('search', None)
layers = self.request.query_params.get('layers', None)
if search is not None:
search_query = (
Q(name__icontains=search) |
Q(slug__icontains=search) |
Q(description__icontains=search) |
Q(address__icontains=search)
)
# add instructions for search to queryset
queryset = queryset.filter(search_query)
if layers is not None:
# look for nodes that are assigned to the specified layers
queryset = queryset.filter(Q(layer__slug__in=layers.split(',')))
return queryset | python | def get_queryset(self):
"""
Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL.
"""
# retrieve all nodes which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(NodeList, self).get_queryset().select_related('status', 'user', 'layer')
# query string params
search = self.request.query_params.get('search', None)
layers = self.request.query_params.get('layers', None)
if search is not None:
search_query = (
Q(name__icontains=search) |
Q(slug__icontains=search) |
Q(description__icontains=search) |
Q(address__icontains=search)
)
# add instructions for search to queryset
queryset = queryset.filter(search_query)
if layers is not None:
# look for nodes that are assigned to the specified layers
queryset = queryset.filter(Q(layer__slug__in=layers.split(',')))
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# retrieve all nodes which are published and accessible to current user",
"# and use joins to retrieve related fields",
"queryset",
"=",
"super",
"(",
"NodeList",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
".",
"select_related",
"(",
"'status'",
",",
"'user'",
",",
"'layer'",
")",
"# query string params",
"search",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"'search'",
",",
"None",
")",
"layers",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"'layers'",
",",
"None",
")",
"if",
"search",
"is",
"not",
"None",
":",
"search_query",
"=",
"(",
"Q",
"(",
"name__icontains",
"=",
"search",
")",
"|",
"Q",
"(",
"slug__icontains",
"=",
"search",
")",
"|",
"Q",
"(",
"description__icontains",
"=",
"search",
")",
"|",
"Q",
"(",
"address__icontains",
"=",
"search",
")",
")",
"# add instructions for search to queryset",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"search_query",
")",
"if",
"layers",
"is",
"not",
"None",
":",
"# look for nodes that are assigned to the specified layers",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"Q",
"(",
"layer__slug__in",
"=",
"layers",
".",
"split",
"(",
"','",
")",
")",
")",
"return",
"queryset"
] | Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL. | [
"Optionally",
"restricts",
"the",
"returned",
"nodes",
"by",
"filtering",
"against",
"a",
"search",
"query",
"parameter",
"in",
"the",
"URL",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L56-L79 |
ninuxorg/nodeshot | nodeshot/core/nodes/views.py | NodeImageList.initial | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node
"""
super(NodeImageList, self).initial(request, *args, **kwargs)
# ensure node exists
self.node = get_queryset_or_404(
Node.objects.published().accessible_to(request.user),
{'slug': self.kwargs['slug']}
)
# check permissions on node (for image creation)
self.check_object_permissions(request, self.node) | python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node
"""
super(NodeImageList, self).initial(request, *args, **kwargs)
# ensure node exists
self.node = get_queryset_or_404(
Node.objects.published().accessible_to(request.user),
{'slug': self.kwargs['slug']}
)
# check permissions on node (for image creation)
self.check_object_permissions(request, self.node) | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NodeImageList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure node exists",
"self",
".",
"node",
"=",
"get_queryset_or_404",
"(",
"Node",
".",
"objects",
".",
"published",
"(",
")",
".",
"accessible_to",
"(",
"request",
".",
"user",
")",
",",
"{",
"'slug'",
":",
"self",
".",
"kwargs",
"[",
"'slug'",
"]",
"}",
")",
"# check permissions on node (for image creation)",
"self",
".",
"check_object_permissions",
"(",
"request",
",",
"self",
".",
"node",
")"
] | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node | [
"Custom",
"initial",
"method",
":",
"*",
"ensure",
"node",
"exists",
"and",
"store",
"it",
"in",
"an",
"instance",
"attribute",
"*",
"change",
"queryset",
"to",
"return",
"only",
"images",
"of",
"current",
"node"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L163-L176 |
ninuxorg/nodeshot | nodeshot/community/notifications/tasks.py | create_notifications | def create_notifications(users, notification_model, notification_type, related_object):
"""
create notifications in a background job to avoid slowing down users
"""
# shortcuts for readability
Notification = notification_model
# text
additional = related_object.__dict__ if related_object else ''
notification_text = TEXTS[notification_type] % additional
# loop users, notification settings check is done in Notification model
for user in users:
n = Notification(
to_user=user,
type=notification_type,
text=notification_text
)
# attach related object if present
if related_object:
n.related_object = related_object
# create notification and send according to user settings
n.save() | python | def create_notifications(users, notification_model, notification_type, related_object):
"""
create notifications in a background job to avoid slowing down users
"""
# shortcuts for readability
Notification = notification_model
# text
additional = related_object.__dict__ if related_object else ''
notification_text = TEXTS[notification_type] % additional
# loop users, notification settings check is done in Notification model
for user in users:
n = Notification(
to_user=user,
type=notification_type,
text=notification_text
)
# attach related object if present
if related_object:
n.related_object = related_object
# create notification and send according to user settings
n.save() | [
"def",
"create_notifications",
"(",
"users",
",",
"notification_model",
",",
"notification_type",
",",
"related_object",
")",
":",
"# shortcuts for readability",
"Notification",
"=",
"notification_model",
"# text",
"additional",
"=",
"related_object",
".",
"__dict__",
"if",
"related_object",
"else",
"''",
"notification_text",
"=",
"TEXTS",
"[",
"notification_type",
"]",
"%",
"additional",
"# loop users, notification settings check is done in Notification model",
"for",
"user",
"in",
"users",
":",
"n",
"=",
"Notification",
"(",
"to_user",
"=",
"user",
",",
"type",
"=",
"notification_type",
",",
"text",
"=",
"notification_text",
")",
"# attach related object if present",
"if",
"related_object",
":",
"n",
".",
"related_object",
"=",
"related_object",
"# create notification and send according to user settings",
"n",
".",
"save",
"(",
")"
] | create notifications in a background job to avoid slowing down users | [
"create",
"notifications",
"in",
"a",
"background",
"job",
"to",
"avoid",
"slowing",
"down",
"users"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/tasks.py#L19-L42 |
ninuxorg/nodeshot | nodeshot/networking/net/models/interfaces/ethernet.py | Ethernet.save | def save(self, *args, **kwargs):
""" automatically set Interface.type to ethernet """
self.type = INTERFACE_TYPES.get('ethernet')
super(Ethernet, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
""" automatically set Interface.type to ethernet """
self.type = INTERFACE_TYPES.get('ethernet')
super(Ethernet, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"type",
"=",
"INTERFACE_TYPES",
".",
"get",
"(",
"'ethernet'",
")",
"super",
"(",
"Ethernet",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | automatically set Interface.type to ethernet | [
"automatically",
"set",
"Interface",
".",
"type",
"to",
"ethernet"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interfaces/ethernet.py#L21-L24 |
ninuxorg/nodeshot | nodeshot/core/api/views.py | root_endpoint | def root_endpoint(request, format=None):
"""
List of all the available resources of this RESTful API.
"""
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
if hasattr(urlmodule, 'urlconf_module'):
is_urlconf_module = True
else:
is_urlconf_module = False
# if url is really a urlmodule
if is_urlconf_module:
# loop over urls of that module
for url in urlmodule.urlconf_module.urlpatterns:
# TODO: configurable skip url in settings
# skip api-docs url
if url.name in ['django.swagger.resources.view']:
continue
# try adding url to list of urls to show
try:
endpoints.append({
'name': url.name.replace('api_', ''),
'url': reverse(url.name, request=request, format=format)
})
# urls of object details will fail silently (eg: /nodes/<slug>/)
except NoReverseMatch:
pass
return Response(endpoints) | python | def root_endpoint(request, format=None):
"""
List of all the available resources of this RESTful API.
"""
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
if hasattr(urlmodule, 'urlconf_module'):
is_urlconf_module = True
else:
is_urlconf_module = False
# if url is really a urlmodule
if is_urlconf_module:
# loop over urls of that module
for url in urlmodule.urlconf_module.urlpatterns:
# TODO: configurable skip url in settings
# skip api-docs url
if url.name in ['django.swagger.resources.view']:
continue
# try adding url to list of urls to show
try:
endpoints.append({
'name': url.name.replace('api_', ''),
'url': reverse(url.name, request=request, format=format)
})
# urls of object details will fail silently (eg: /nodes/<slug>/)
except NoReverseMatch:
pass
return Response(endpoints) | [
"def",
"root_endpoint",
"(",
"request",
",",
"format",
"=",
"None",
")",
":",
"endpoints",
"=",
"[",
"]",
"# loop over url modules",
"for",
"urlmodule",
"in",
"urlpatterns",
":",
"# is it a urlconf module?",
"if",
"hasattr",
"(",
"urlmodule",
",",
"'urlconf_module'",
")",
":",
"is_urlconf_module",
"=",
"True",
"else",
":",
"is_urlconf_module",
"=",
"False",
"# if url is really a urlmodule",
"if",
"is_urlconf_module",
":",
"# loop over urls of that module",
"for",
"url",
"in",
"urlmodule",
".",
"urlconf_module",
".",
"urlpatterns",
":",
"# TODO: configurable skip url in settings",
"# skip api-docs url",
"if",
"url",
".",
"name",
"in",
"[",
"'django.swagger.resources.view'",
"]",
":",
"continue",
"# try adding url to list of urls to show",
"try",
":",
"endpoints",
".",
"append",
"(",
"{",
"'name'",
":",
"url",
".",
"name",
".",
"replace",
"(",
"'api_'",
",",
"''",
")",
",",
"'url'",
":",
"reverse",
"(",
"url",
".",
"name",
",",
"request",
"=",
"request",
",",
"format",
"=",
"format",
")",
"}",
")",
"# urls of object details will fail silently (eg: /nodes/<slug>/)",
"except",
"NoReverseMatch",
":",
"pass",
"return",
"Response",
"(",
"endpoints",
")"
] | List of all the available resources of this RESTful API. | [
"List",
"of",
"all",
"the",
"available",
"resources",
"of",
"this",
"RESTful",
"API",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/api/views.py#L11-L40 |
ninuxorg/nodeshot | nodeshot/networking/net/models/interface.py | Interface.save | def save(self, *args, **kwargs):
"""
Custom save method does the following:
* save shortcuts if HSTORE is enabled
"""
if 'node' not in self.shortcuts:
self.shortcuts['node'] = self.device.node
if 'user' not in self.shortcuts and self.device.node.user:
self.shortcuts['user'] = self.device.node.user
if 'layer' not in self.shortcuts and 'nodeshot.core.layers' in settings.INSTALLED_APPS:
self.shortcuts['layer'] = self.device.node.layer
super(Interface, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Custom save method does the following:
* save shortcuts if HSTORE is enabled
"""
if 'node' not in self.shortcuts:
self.shortcuts['node'] = self.device.node
if 'user' not in self.shortcuts and self.device.node.user:
self.shortcuts['user'] = self.device.node.user
if 'layer' not in self.shortcuts and 'nodeshot.core.layers' in settings.INSTALLED_APPS:
self.shortcuts['layer'] = self.device.node.layer
super(Interface, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'node'",
"not",
"in",
"self",
".",
"shortcuts",
":",
"self",
".",
"shortcuts",
"[",
"'node'",
"]",
"=",
"self",
".",
"device",
".",
"node",
"if",
"'user'",
"not",
"in",
"self",
".",
"shortcuts",
"and",
"self",
".",
"device",
".",
"node",
".",
"user",
":",
"self",
".",
"shortcuts",
"[",
"'user'",
"]",
"=",
"self",
".",
"device",
".",
"node",
".",
"user",
"if",
"'layer'",
"not",
"in",
"self",
".",
"shortcuts",
"and",
"'nodeshot.core.layers'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"self",
".",
"shortcuts",
"[",
"'layer'",
"]",
"=",
"self",
".",
"device",
".",
"node",
".",
"layer",
"super",
"(",
"Interface",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Custom save method does the following:
* save shortcuts if HSTORE is enabled | [
"Custom",
"save",
"method",
"does",
"the",
"following",
":",
"*",
"save",
"shortcuts",
"if",
"HSTORE",
"is",
"enabled"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interface.py#L38-L52 |
ninuxorg/nodeshot | nodeshot/networking/net/models/interface.py | Interface.ip_addresses | def ip_addresses(self, value):
""" :param value: a list of ip addresses """
if not isinstance(value, list):
raise ValueError('ip_addresses value must be a list')
# in soem cases self.data might be none, so let's instantiate an empty dict
if self.data is None:
self.data = {}
# update field
self.data['ip_addresses'] = ', '.join(value) | python | def ip_addresses(self, value):
""" :param value: a list of ip addresses """
if not isinstance(value, list):
raise ValueError('ip_addresses value must be a list')
# in soem cases self.data might be none, so let's instantiate an empty dict
if self.data is None:
self.data = {}
# update field
self.data['ip_addresses'] = ', '.join(value) | [
"def",
"ip_addresses",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'ip_addresses value must be a list'",
")",
"# in soem cases self.data might be none, so let's instantiate an empty dict",
"if",
"self",
".",
"data",
"is",
"None",
":",
"self",
".",
"data",
"=",
"{",
"}",
"# update field",
"self",
".",
"data",
"[",
"'ip_addresses'",
"]",
"=",
"', '",
".",
"join",
"(",
"value",
")"
] | :param value: a list of ip addresses | [
":",
"param",
"value",
":",
"a",
"list",
"of",
"ip",
"addresses"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interface.py#L94-L102 |
ninuxorg/nodeshot | nodeshot/community/participation/models/comment.py | Comment.update_count | def update_count(self):
""" updates comment count """
node_rating_count = self.node.rating_count
node_rating_count.comment_count = self.node.comment_set.count()
node_rating_count.save() | python | def update_count(self):
""" updates comment count """
node_rating_count = self.node.rating_count
node_rating_count.comment_count = self.node.comment_set.count()
node_rating_count.save() | [
"def",
"update_count",
"(",
"self",
")",
":",
"node_rating_count",
"=",
"self",
".",
"node",
".",
"rating_count",
"node_rating_count",
".",
"comment_count",
"=",
"self",
".",
"node",
".",
"comment_set",
".",
"count",
"(",
")",
"node_rating_count",
".",
"save",
"(",
")"
] | updates comment count | [
"updates",
"comment",
"count"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L26-L30 |
ninuxorg/nodeshot | nodeshot/community/participation/models/comment.py | Comment.clean | def clean(self, *args, **kwargs):
"""
Check if comments can be inserted for parent node or parent layer
"""
# check done only for new nodes!
if not self.pk:
node = self.node
# ensure comments for this node are allowed
if node.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this node")
# ensure comments for this layer are allowed
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
layer = node.layer
if layer.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this layer") | python | def clean(self, *args, **kwargs):
"""
Check if comments can be inserted for parent node or parent layer
"""
# check done only for new nodes!
if not self.pk:
node = self.node
# ensure comments for this node are allowed
if node.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this node")
# ensure comments for this layer are allowed
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
layer = node.layer
if layer.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this layer") | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# check done only for new nodes!",
"if",
"not",
"self",
".",
"pk",
":",
"node",
"=",
"self",
".",
"node",
"# ensure comments for this node are allowed",
"if",
"node",
".",
"participation_settings",
".",
"comments_allowed",
"is",
"False",
":",
"raise",
"ValidationError",
"(",
"\"Comments not allowed for this node\"",
")",
"# ensure comments for this layer are allowed",
"if",
"'nodeshot.core.layers'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"layer",
"=",
"node",
".",
"layer",
"if",
"layer",
".",
"participation_settings",
".",
"comments_allowed",
"is",
"False",
":",
"raise",
"ValidationError",
"(",
"\"Comments not allowed for this layer\"",
")"
] | Check if comments can be inserted for parent node or parent layer | [
"Check",
"if",
"comments",
"can",
"be",
"inserted",
"for",
"parent",
"node",
"or",
"parent",
"layer"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L32-L46 |
ninuxorg/nodeshot | nodeshot/interop/sync/management/commands/sync.py | Command.retrieve_layers | def retrieve_layers(self, *args, **options):
"""
Retrieve specified layers or all external layers if no layer specified.
"""
# init empty Q object
queryset = Q()
# if no layer specified
if len(args) < 1:
# cache queryset
all_layers = Layer.objects.published().external()
# check if there is any layer to exclude
if options['exclude']:
# convert comma separated string in python list, ignore spaces
exclude_list = options['exclude'].replace(' ', '').split(',')
# retrieve all layers except the ones specified in exclude list
return all_layers.exclude(slug__in=exclude_list)
else:
# nothing to exclude, retrieve all layers
self.verbose('no layer specified, will retrieve all layers!')
return all_layers
# otherwise loop over args and retrieve each specified layer
for layer_slug in args:
queryset = queryset | Q(slug=layer_slug)
# verify existence
try:
# retrieve layer
layer = Layer.objects.get(slug=layer_slug)
# raise exception if layer is not external
if not layer.is_external:
raise CommandError('Layer "%s" is not an external layer\n\r' % layer_slug)
# raise exception if layer is not published
if not layer.is_published:
raise CommandError('Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug)
# raise exception if one of the layer looked for doesn't exist
except Layer.DoesNotExist:
raise CommandError('Layer "%s" does not exist\n\r' % layer_slug)
# return published external layers
return Layer.objects.published().external().select_related().filter(queryset) | python | def retrieve_layers(self, *args, **options):
"""
Retrieve specified layers or all external layers if no layer specified.
"""
# init empty Q object
queryset = Q()
# if no layer specified
if len(args) < 1:
# cache queryset
all_layers = Layer.objects.published().external()
# check if there is any layer to exclude
if options['exclude']:
# convert comma separated string in python list, ignore spaces
exclude_list = options['exclude'].replace(' ', '').split(',')
# retrieve all layers except the ones specified in exclude list
return all_layers.exclude(slug__in=exclude_list)
else:
# nothing to exclude, retrieve all layers
self.verbose('no layer specified, will retrieve all layers!')
return all_layers
# otherwise loop over args and retrieve each specified layer
for layer_slug in args:
queryset = queryset | Q(slug=layer_slug)
# verify existence
try:
# retrieve layer
layer = Layer.objects.get(slug=layer_slug)
# raise exception if layer is not external
if not layer.is_external:
raise CommandError('Layer "%s" is not an external layer\n\r' % layer_slug)
# raise exception if layer is not published
if not layer.is_published:
raise CommandError('Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug)
# raise exception if one of the layer looked for doesn't exist
except Layer.DoesNotExist:
raise CommandError('Layer "%s" does not exist\n\r' % layer_slug)
# return published external layers
return Layer.objects.published().external().select_related().filter(queryset) | [
"def",
"retrieve_layers",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# init empty Q object",
"queryset",
"=",
"Q",
"(",
")",
"# if no layer specified",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"# cache queryset",
"all_layers",
"=",
"Layer",
".",
"objects",
".",
"published",
"(",
")",
".",
"external",
"(",
")",
"# check if there is any layer to exclude",
"if",
"options",
"[",
"'exclude'",
"]",
":",
"# convert comma separated string in python list, ignore spaces",
"exclude_list",
"=",
"options",
"[",
"'exclude'",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"# retrieve all layers except the ones specified in exclude list",
"return",
"all_layers",
".",
"exclude",
"(",
"slug__in",
"=",
"exclude_list",
")",
"else",
":",
"# nothing to exclude, retrieve all layers",
"self",
".",
"verbose",
"(",
"'no layer specified, will retrieve all layers!'",
")",
"return",
"all_layers",
"# otherwise loop over args and retrieve each specified layer",
"for",
"layer_slug",
"in",
"args",
":",
"queryset",
"=",
"queryset",
"|",
"Q",
"(",
"slug",
"=",
"layer_slug",
")",
"# verify existence",
"try",
":",
"# retrieve layer",
"layer",
"=",
"Layer",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"layer_slug",
")",
"# raise exception if layer is not external",
"if",
"not",
"layer",
".",
"is_external",
":",
"raise",
"CommandError",
"(",
"'Layer \"%s\" is not an external layer\\n\\r'",
"%",
"layer_slug",
")",
"# raise exception if layer is not published",
"if",
"not",
"layer",
".",
"is_published",
":",
"raise",
"CommandError",
"(",
"'Layer \"%s\" is not published. Why are you trying to work on an unpublished layer?\\n\\r'",
"%",
"layer_slug",
")",
"# raise exception if one of the layer looked for doesn't exist",
"except",
"Layer",
".",
"DoesNotExist",
":",
"raise",
"CommandError",
"(",
"'Layer \"%s\" does not exist\\n\\r'",
"%",
"layer_slug",
")",
"# return published external layers",
"return",
"Layer",
".",
"objects",
".",
"published",
"(",
")",
".",
"external",
"(",
")",
".",
"select_related",
"(",
")",
".",
"filter",
"(",
"queryset",
")"
] | Retrieve specified layers or all external layers if no layer specified. | [
"Retrieve",
"specified",
"layers",
"or",
"all",
"external",
"layers",
"if",
"no",
"layer",
"specified",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L30-L70 |
ninuxorg/nodeshot | nodeshot/interop/sync/management/commands/sync.py | Command.handle | def handle(self, *args, **options):
""" execute sync command """
# store verbosity level in instance attribute for later use
self.verbosity = int(options.get('verbosity'))
# blank line
self.stdout.write('\r\n')
# retrieve layers
layers = self.retrieve_layers(*args, **options)
if len(layers) < 1:
self.stdout.write('no layers to process\n\r')
return
else:
self.verbose('going to process %d layers...' % len(layers))
# loop over
for layer in layers:
# retrieve interop class if available
try:
synchronizer_path = layer.external.synchronizer_path
except (ObjectDoesNotExist, AttributeError):
self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name)
continue
# if no synchronizer_path jump to next layer
if synchronizer_path == 'None':
self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name)
continue
if layer.external.config is None:
self.stdout.write('Layer %s does not have a config yet\n\r' % layer.name)
continue
# retrieve class
synchronizer = import_by_path(synchronizer_path)
self.stdout.write('imported module %s\r\n' % synchronizer.__name__)
# try running
try:
instance = synchronizer(layer, verbosity=self.verbosity)
self.stdout.write('Processing layer "%s"\r\n' % layer.slug)
messages = instance.sync()
except ImproperlyConfigured as e:
self.stdout.write('Validation error: %s\r\n' % e)
continue
except Exception as e:
self.stdout.write('Got Exception: %s\r\n' % e)
exception(e)
continue
for message in messages:
self.stdout.write('%s\n\r' % message)
self.stdout.write('\r\n') | python | def handle(self, *args, **options):
""" execute sync command """
# store verbosity level in instance attribute for later use
self.verbosity = int(options.get('verbosity'))
# blank line
self.stdout.write('\r\n')
# retrieve layers
layers = self.retrieve_layers(*args, **options)
if len(layers) < 1:
self.stdout.write('no layers to process\n\r')
return
else:
self.verbose('going to process %d layers...' % len(layers))
# loop over
for layer in layers:
# retrieve interop class if available
try:
synchronizer_path = layer.external.synchronizer_path
except (ObjectDoesNotExist, AttributeError):
self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name)
continue
# if no synchronizer_path jump to next layer
if synchronizer_path == 'None':
self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name)
continue
if layer.external.config is None:
self.stdout.write('Layer %s does not have a config yet\n\r' % layer.name)
continue
# retrieve class
synchronizer = import_by_path(synchronizer_path)
self.stdout.write('imported module %s\r\n' % synchronizer.__name__)
# try running
try:
instance = synchronizer(layer, verbosity=self.verbosity)
self.stdout.write('Processing layer "%s"\r\n' % layer.slug)
messages = instance.sync()
except ImproperlyConfigured as e:
self.stdout.write('Validation error: %s\r\n' % e)
continue
except Exception as e:
self.stdout.write('Got Exception: %s\r\n' % e)
exception(e)
continue
for message in messages:
self.stdout.write('%s\n\r' % message)
self.stdout.write('\r\n') | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# store verbosity level in instance attribute for later use",
"self",
".",
"verbosity",
"=",
"int",
"(",
"options",
".",
"get",
"(",
"'verbosity'",
")",
")",
"# blank line",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\r\\n'",
")",
"# retrieve layers",
"layers",
"=",
"self",
".",
"retrieve_layers",
"(",
"*",
"args",
",",
"*",
"*",
"options",
")",
"if",
"len",
"(",
"layers",
")",
"<",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'no layers to process\\n\\r'",
")",
"return",
"else",
":",
"self",
".",
"verbose",
"(",
"'going to process %d layers...'",
"%",
"len",
"(",
"layers",
")",
")",
"# loop over",
"for",
"layer",
"in",
"layers",
":",
"# retrieve interop class if available",
"try",
":",
"synchronizer_path",
"=",
"layer",
".",
"external",
".",
"synchronizer_path",
"except",
"(",
"ObjectDoesNotExist",
",",
"AttributeError",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'External Layer %s does not have a synchronizer class specified\\n\\r'",
"%",
"layer",
".",
"name",
")",
"continue",
"# if no synchronizer_path jump to next layer",
"if",
"synchronizer_path",
"==",
"'None'",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'External Layer %s does not have a synchronizer class specified\\n\\r'",
"%",
"layer",
".",
"name",
")",
"continue",
"if",
"layer",
".",
"external",
".",
"config",
"is",
"None",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'Layer %s does not have a config yet\\n\\r'",
"%",
"layer",
".",
"name",
")",
"continue",
"# retrieve class",
"synchronizer",
"=",
"import_by_path",
"(",
"synchronizer_path",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'imported module %s\\r\\n'",
"%",
"synchronizer",
".",
"__name__",
")",
"# try running",
"try",
":",
"instance",
"=",
"synchronizer",
"(",
"layer",
",",
"verbosity",
"=",
"self",
".",
"verbosity",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'Processing layer \"%s\"\\r\\n'",
"%",
"layer",
".",
"slug",
")",
"messages",
"=",
"instance",
".",
"sync",
"(",
")",
"except",
"ImproperlyConfigured",
"as",
"e",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'Validation error: %s\\r\\n'",
"%",
"e",
")",
"continue",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'Got Exception: %s\\r\\n'",
"%",
"e",
")",
"exception",
"(",
"e",
")",
"continue",
"for",
"message",
"in",
"messages",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'%s\\n\\r'",
"%",
"message",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\r\\n'",
")"
] | execute sync command | [
"execute",
"sync",
"command"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L76-L129 |
ninuxorg/nodeshot | nodeshot/interop/sync/models/node_external.py | save_external_nodes | def save_external_nodes(sender, **kwargs):
""" sync by creating nodes in external layers when needed """
node = kwargs['instance']
operation = 'add' if kwargs['created'] is True else 'change'
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
push_changes_to_external_layers.delay(node=node, external_layer=node.layer.external, operation=operation) | python | def save_external_nodes(sender, **kwargs):
""" sync by creating nodes in external layers when needed """
node = kwargs['instance']
operation = 'add' if kwargs['created'] is True else 'change'
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
push_changes_to_external_layers.delay(node=node, external_layer=node.layer.external, operation=operation) | [
"def",
"save_external_nodes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"kwargs",
"[",
"'instance'",
"]",
"operation",
"=",
"'add'",
"if",
"kwargs",
"[",
"'created'",
"]",
"is",
"True",
"else",
"'change'",
"if",
"node",
".",
"layer",
".",
"is_external",
"is",
"False",
"or",
"not",
"hasattr",
"(",
"node",
".",
"layer",
",",
"'external'",
")",
"or",
"node",
".",
"layer",
".",
"external",
".",
"synchronizer_path",
"is",
"None",
":",
"return",
"False",
"push_changes_to_external_layers",
".",
"delay",
"(",
"node",
"=",
"node",
",",
"external_layer",
"=",
"node",
".",
"layer",
".",
"external",
",",
"operation",
"=",
"operation",
")"
] | sync by creating nodes in external layers when needed | [
"sync",
"by",
"creating",
"nodes",
"in",
"external",
"layers",
"when",
"needed"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L36-L44 |
ninuxorg/nodeshot | nodeshot/interop/sync/models/node_external.py | delete_external_nodes | def delete_external_nodes(sender, **kwargs):
""" sync by deleting nodes from external layers when needed """
node = kwargs['instance']
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
if hasattr(node, 'external') and node.external.external_id:
push_changes_to_external_layers.delay(
node=node.external.external_id,
external_layer=node.layer.external,
operation='delete'
) | python | def delete_external_nodes(sender, **kwargs):
""" sync by deleting nodes from external layers when needed """
node = kwargs['instance']
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
if hasattr(node, 'external') and node.external.external_id:
push_changes_to_external_layers.delay(
node=node.external.external_id,
external_layer=node.layer.external,
operation='delete'
) | [
"def",
"delete_external_nodes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"node",
".",
"layer",
".",
"is_external",
"is",
"False",
"or",
"not",
"hasattr",
"(",
"node",
".",
"layer",
",",
"'external'",
")",
"or",
"node",
".",
"layer",
".",
"external",
".",
"synchronizer_path",
"is",
"None",
":",
"return",
"False",
"if",
"hasattr",
"(",
"node",
",",
"'external'",
")",
"and",
"node",
".",
"external",
".",
"external_id",
":",
"push_changes_to_external_layers",
".",
"delay",
"(",
"node",
"=",
"node",
".",
"external",
".",
"external_id",
",",
"external_layer",
"=",
"node",
".",
"layer",
".",
"external",
",",
"operation",
"=",
"'delete'",
")"
] | sync by deleting nodes from external layers when needed | [
"sync",
"by",
"deleting",
"nodes",
"from",
"external",
"layers",
"when",
"needed"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L48-L60 |
ninuxorg/nodeshot | nodeshot/community/participation/models/vote.py | Vote.save | def save(self, *args, **kwargs):
"""
ensure users cannot vote the same node multiple times
but let users change their votes
"""
if not self.pk:
old_votes = Vote.objects.filter(user=self.user, node=self.node)
for old_vote in old_votes:
old_vote.delete()
super(Vote, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
ensure users cannot vote the same node multiple times
but let users change their votes
"""
if not self.pk:
old_votes = Vote.objects.filter(user=self.user, node=self.node)
for old_vote in old_votes:
old_vote.delete()
super(Vote, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"old_votes",
"=",
"Vote",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"self",
".",
"user",
",",
"node",
"=",
"self",
".",
"node",
")",
"for",
"old_vote",
"in",
"old_votes",
":",
"old_vote",
".",
"delete",
"(",
")",
"super",
"(",
"Vote",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | ensure users cannot vote the same node multiple times
but let users change their votes | [
"ensure",
"users",
"cannot",
"vote",
"the",
"same",
"node",
"multiple",
"times",
"but",
"let",
"users",
"change",
"their",
"votes"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L36-L45 |
ninuxorg/nodeshot | nodeshot/community/participation/models/vote.py | Vote.update_count | def update_count(self):
""" updates likes and dislikes count """
node_rating_count = self.node.rating_count
node_rating_count.likes = self.node.vote_set.filter(vote=1).count()
node_rating_count.dislikes = self.node.vote_set.filter(vote=-1).count()
node_rating_count.save() | python | def update_count(self):
""" updates likes and dislikes count """
node_rating_count = self.node.rating_count
node_rating_count.likes = self.node.vote_set.filter(vote=1).count()
node_rating_count.dislikes = self.node.vote_set.filter(vote=-1).count()
node_rating_count.save() | [
"def",
"update_count",
"(",
"self",
")",
":",
"node_rating_count",
"=",
"self",
".",
"node",
".",
"rating_count",
"node_rating_count",
".",
"likes",
"=",
"self",
".",
"node",
".",
"vote_set",
".",
"filter",
"(",
"vote",
"=",
"1",
")",
".",
"count",
"(",
")",
"node_rating_count",
".",
"dislikes",
"=",
"self",
".",
"node",
".",
"vote_set",
".",
"filter",
"(",
"vote",
"=",
"-",
"1",
")",
".",
"count",
"(",
")",
"node_rating_count",
".",
"save",
"(",
")"
] | updates likes and dislikes count | [
"updates",
"likes",
"and",
"dislikes",
"count"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L47-L52 |
ninuxorg/nodeshot | nodeshot/community/participation/models/vote.py | Vote.clean | def clean(self, *args, **kwargs):
"""
Check if votes can be inserted for parent node or parent layer
"""
if not self.pk:
# ensure voting for this node is allowed
if self.node.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this node")
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
layer = self.node.layer
# ensure voting for this layer is allowed
if layer.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this layer") | python | def clean(self, *args, **kwargs):
"""
Check if votes can be inserted for parent node or parent layer
"""
if not self.pk:
# ensure voting for this node is allowed
if self.node.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this node")
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
layer = self.node.layer
# ensure voting for this layer is allowed
if layer.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this layer") | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"# ensure voting for this node is allowed",
"if",
"self",
".",
"node",
".",
"participation_settings",
".",
"voting_allowed",
"is",
"not",
"True",
":",
"raise",
"ValidationError",
"(",
"\"Voting not allowed for this node\"",
")",
"if",
"'nodeshot.core.layers'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"layer",
"=",
"self",
".",
"node",
".",
"layer",
"# ensure voting for this layer is allowed",
"if",
"layer",
".",
"participation_settings",
".",
"voting_allowed",
"is",
"not",
"True",
":",
"raise",
"ValidationError",
"(",
"\"Voting not allowed for this layer\"",
")"
] | Check if votes can be inserted for parent node or parent layer | [
"Check",
"if",
"votes",
"can",
"be",
"inserted",
"for",
"parent",
"node",
"or",
"parent",
"layer"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L54-L68 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | whois_list | def whois_list(request, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
results = []
# layer3 results
for ip in Ip.objects.select_related().all():
interface = ip.interface
user = interface.device.node.user
device = interface.device
results.append({
'address': str(ip.address),
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
})
# layer2 results
for interface in Interface.objects.select_related().all():
if interface.mac is None:
continue
user = interface.device.node.user
device = interface.device
results.append({
'address': str(interface.mac).replace('-', ':'),
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
})
return Response(results) | python | def whois_list(request, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
results = []
# layer3 results
for ip in Ip.objects.select_related().all():
interface = ip.interface
user = interface.device.node.user
device = interface.device
results.append({
'address': str(ip.address),
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
})
# layer2 results
for interface in Interface.objects.select_related().all():
if interface.mac is None:
continue
user = interface.device.node.user
device = interface.device
results.append({
'address': str(interface.mac).replace('-', ':'),
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
})
return Response(results) | [
"def",
"whois_list",
"(",
"request",
",",
"format",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"# layer3 results",
"for",
"ip",
"in",
"Ip",
".",
"objects",
".",
"select_related",
"(",
")",
".",
"all",
"(",
")",
":",
"interface",
"=",
"ip",
".",
"interface",
"user",
"=",
"interface",
".",
"device",
".",
"node",
".",
"user",
"device",
"=",
"interface",
".",
"device",
"results",
".",
"append",
"(",
"{",
"'address'",
":",
"str",
"(",
"ip",
".",
"address",
")",
",",
"'user'",
":",
"user",
".",
"username",
",",
"'name'",
":",
"user",
".",
"get_full_name",
"(",
")",
",",
"'device'",
":",
"device",
".",
"name",
",",
"'node'",
":",
"device",
".",
"node",
".",
"name",
"}",
")",
"# layer2 results",
"for",
"interface",
"in",
"Interface",
".",
"objects",
".",
"select_related",
"(",
")",
".",
"all",
"(",
")",
":",
"if",
"interface",
".",
"mac",
"is",
"None",
":",
"continue",
"user",
"=",
"interface",
".",
"device",
".",
"node",
".",
"user",
"device",
"=",
"interface",
".",
"device",
"results",
".",
"append",
"(",
"{",
"'address'",
":",
"str",
"(",
"interface",
".",
"mac",
")",
".",
"replace",
"(",
"'-'",
",",
"':'",
")",
",",
"'user'",
":",
"user",
".",
"username",
",",
"'name'",
":",
"user",
".",
"get_full_name",
"(",
")",
",",
"'device'",
":",
"device",
".",
"name",
",",
"'node'",
":",
"device",
".",
"node",
".",
"name",
"}",
")",
"return",
"Response",
"(",
"results",
")"
] | Retrieve basic whois information related to a layer2 or layer3 network address. | [
"Retrieve",
"basic",
"whois",
"information",
"related",
"to",
"a",
"layer2",
"or",
"layer3",
"network",
"address",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L335-L365 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | whois_detail | def whois_detail(request, address, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
address_obj = None
try:
address_obj = IPAddress(address)
except AddrFormatError:
try:
address_obj = EUI(address)
except AddrFormatError:
pass
if not address_obj:
return Response({'detail': 'invalid address'}, status=400)
elif isinstance(address_obj, IPAddress):
try:
ip = Ip.objects.get(address=address)
except Ip.DoesNotExist:
return Response({'detail': 'address not found'}, status=404)
else:
interface = ip.interface
else:
try:
interface = Interface.objects.get(mac=address)
except Interface.DoesNotExist:
return Response({'detail': 'address not found'}, status=404)
# prepare response
user = interface.device.node.user
device = interface.device
data = {
'address': address,
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
}
return Response(data) | python | def whois_detail(request, address, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
address_obj = None
try:
address_obj = IPAddress(address)
except AddrFormatError:
try:
address_obj = EUI(address)
except AddrFormatError:
pass
if not address_obj:
return Response({'detail': 'invalid address'}, status=400)
elif isinstance(address_obj, IPAddress):
try:
ip = Ip.objects.get(address=address)
except Ip.DoesNotExist:
return Response({'detail': 'address not found'}, status=404)
else:
interface = ip.interface
else:
try:
interface = Interface.objects.get(mac=address)
except Interface.DoesNotExist:
return Response({'detail': 'address not found'}, status=404)
# prepare response
user = interface.device.node.user
device = interface.device
data = {
'address': address,
'user': user.username,
'name': user.get_full_name(),
'device': device.name,
'node': device.node.name
}
return Response(data) | [
"def",
"whois_detail",
"(",
"request",
",",
"address",
",",
"format",
"=",
"None",
")",
":",
"address_obj",
"=",
"None",
"try",
":",
"address_obj",
"=",
"IPAddress",
"(",
"address",
")",
"except",
"AddrFormatError",
":",
"try",
":",
"address_obj",
"=",
"EUI",
"(",
"address",
")",
"except",
"AddrFormatError",
":",
"pass",
"if",
"not",
"address_obj",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"'invalid address'",
"}",
",",
"status",
"=",
"400",
")",
"elif",
"isinstance",
"(",
"address_obj",
",",
"IPAddress",
")",
":",
"try",
":",
"ip",
"=",
"Ip",
".",
"objects",
".",
"get",
"(",
"address",
"=",
"address",
")",
"except",
"Ip",
".",
"DoesNotExist",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"'address not found'",
"}",
",",
"status",
"=",
"404",
")",
"else",
":",
"interface",
"=",
"ip",
".",
"interface",
"else",
":",
"try",
":",
"interface",
"=",
"Interface",
".",
"objects",
".",
"get",
"(",
"mac",
"=",
"address",
")",
"except",
"Interface",
".",
"DoesNotExist",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"'address not found'",
"}",
",",
"status",
"=",
"404",
")",
"# prepare response",
"user",
"=",
"interface",
".",
"device",
".",
"node",
".",
"user",
"device",
"=",
"interface",
".",
"device",
"data",
"=",
"{",
"'address'",
":",
"address",
",",
"'user'",
":",
"user",
".",
"username",
",",
"'name'",
":",
"user",
".",
"get_full_name",
"(",
")",
",",
"'device'",
":",
"device",
".",
"name",
",",
"'node'",
":",
"device",
".",
"node",
".",
"name",
"}",
"return",
"Response",
"(",
"data",
")"
] | Retrieve basic whois information related to a layer2 or layer3 network address. | [
"Retrieve",
"basic",
"whois",
"information",
"related",
"to",
"a",
"layer2",
"or",
"layer3",
"network",
"address",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L369-L405 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | DeviceList.get_queryset | def get_queryset(self):
"""
Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL.
"""
# retrieve all devices which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(DeviceList, self).get_queryset()#.select_related('layer', 'status', 'user')
# retrieve value of querystring parameter "search"
search = self.request.query_params.get('search', None)
if search is not None:
search_query = (
Q(name__icontains=search) |
Q(description__icontains=search)
)
# add instructions for search to queryset
queryset = queryset.filter(search_query)
return queryset | python | def get_queryset(self):
"""
Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL.
"""
# retrieve all devices which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(DeviceList, self).get_queryset()#.select_related('layer', 'status', 'user')
# retrieve value of querystring parameter "search"
search = self.request.query_params.get('search', None)
if search is not None:
search_query = (
Q(name__icontains=search) |
Q(description__icontains=search)
)
# add instructions for search to queryset
queryset = queryset.filter(search_query)
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# retrieve all devices which are published and accessible to current user",
"# and use joins to retrieve related fields",
"queryset",
"=",
"super",
"(",
"DeviceList",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"#.select_related('layer', 'status', 'user')",
"# retrieve value of querystring parameter \"search\"",
"search",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"'search'",
",",
"None",
")",
"if",
"search",
"is",
"not",
"None",
":",
"search_query",
"=",
"(",
"Q",
"(",
"name__icontains",
"=",
"search",
")",
"|",
"Q",
"(",
"description__icontains",
"=",
"search",
")",
")",
"# add instructions for search to queryset",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"search_query",
")",
"return",
"queryset"
] | Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL. | [
"Optionally",
"restricts",
"the",
"returned",
"devices",
"by",
"filtering",
"against",
"a",
"search",
"query",
"parameter",
"in",
"the",
"URL",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L35-L55 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | NodeDeviceList.initial | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(NodeDeviceList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
except Node.DoesNotExist:
raise Http404(_('Node not found.'))
# check permissions on node (for device creation)
self.check_object_permissions(request, self.node)
# return only devices of current node
self.queryset = Device.objects.filter(node_id=self.node.id)\
.accessible_to(self.request.user)\
.select_related('node') | python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(NodeDeviceList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
except Node.DoesNotExist:
raise Http404(_('Node not found.'))
# check permissions on node (for device creation)
self.check_object_permissions(request, self.node)
# return only devices of current node
self.queryset = Device.objects.filter(node_id=self.node.id)\
.accessible_to(self.request.user)\
.select_related('node') | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NodeDeviceList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure node exists",
"try",
":",
"self",
".",
"node",
"=",
"Node",
".",
"objects",
".",
"published",
"(",
")",
".",
"accessible_to",
"(",
"request",
".",
"user",
")",
".",
"get",
"(",
"slug",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'slug'",
",",
"None",
")",
")",
"except",
"Node",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Node not found.'",
")",
")",
"# check permissions on node (for device creation)",
"self",
".",
"check_object_permissions",
"(",
"request",
",",
"self",
".",
"node",
")",
"# return only devices of current node",
"self",
".",
"queryset",
"=",
"Device",
".",
"objects",
".",
"filter",
"(",
"node_id",
"=",
"self",
".",
"node",
".",
"id",
")",
".",
"accessible_to",
"(",
"self",
".",
"request",
".",
"user",
")",
".",
"select_related",
"(",
"'node'",
")"
] | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node | [
"Custom",
"initial",
"method",
":",
"*",
"ensure",
"node",
"exists",
"and",
"store",
"it",
"in",
"an",
"instance",
"attribute",
"*",
"change",
"queryset",
"to",
"return",
"only",
"devices",
"of",
"current",
"node"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L101-L123 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | BaseInterfaceList.initial | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(BaseInterfaceList, self).initial(request, *args, **kwargs)
# ensure device exists
try:
self.device = Device.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Device.DoesNotExist:
raise Http404(_('Device not found.'))
# check permissions on device (for interface creation)
self.check_object_permissions(request, self.device)
# return only interfaces of current device
self.queryset = self.model.objects.filter(device_id=self.device.id)\
.accessible_to(self.request.user) | python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(BaseInterfaceList, self).initial(request, *args, **kwargs)
# ensure device exists
try:
self.device = Device.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Device.DoesNotExist:
raise Http404(_('Device not found.'))
# check permissions on device (for interface creation)
self.check_object_permissions(request, self.device)
# return only interfaces of current device
self.queryset = self.model.objects.filter(device_id=self.device.id)\
.accessible_to(self.request.user) | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"BaseInterfaceList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure device exists",
"try",
":",
"self",
".",
"device",
"=",
"Device",
".",
"objects",
".",
"accessible_to",
"(",
"request",
".",
"user",
")",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'pk'",
",",
"None",
")",
")",
"except",
"Device",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Device not found.'",
")",
")",
"# check permissions on device (for interface creation)",
"self",
".",
"check_object_permissions",
"(",
"request",
",",
"self",
".",
"device",
")",
"# return only interfaces of current device",
"self",
".",
"queryset",
"=",
"self",
".",
"model",
".",
"objects",
".",
"filter",
"(",
"device_id",
"=",
"self",
".",
"device",
".",
"id",
")",
".",
"accessible_to",
"(",
"self",
".",
"request",
".",
"user",
")"
] | Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node | [
"Custom",
"initial",
"method",
":",
"*",
"ensure",
"device",
"exists",
"and",
"store",
"it",
"in",
"an",
"instance",
"attribute",
"*",
"change",
"queryset",
"to",
"return",
"only",
"devices",
"of",
"current",
"node"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L145-L165 |
ninuxorg/nodeshot | nodeshot/networking/net/views.py | InterfaceIpList.initial | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure interface exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(InterfaceIpList, self).initial(request, *args, **kwargs)
# ensure interface exists
try:
self.interface = Interface.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Interface.DoesNotExist:
raise Http404(_('Interface not found.'))
# check permissions on interface (for interface creation)
self.check_object_permissions(request, self.interface)
# return only interfaces of current interface
self.queryset = self.model.objects.filter(interface_id=self.interface.id)\
.accessible_to(self.request.user) | python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure interface exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(InterfaceIpList, self).initial(request, *args, **kwargs)
# ensure interface exists
try:
self.interface = Interface.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Interface.DoesNotExist:
raise Http404(_('Interface not found.'))
# check permissions on interface (for interface creation)
self.check_object_permissions(request, self.interface)
# return only interfaces of current interface
self.queryset = self.model.objects.filter(interface_id=self.interface.id)\
.accessible_to(self.request.user) | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"InterfaceIpList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure interface exists",
"try",
":",
"self",
".",
"interface",
"=",
"Interface",
".",
"objects",
".",
"accessible_to",
"(",
"request",
".",
"user",
")",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'pk'",
",",
"None",
")",
")",
"except",
"Interface",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Interface not found.'",
")",
")",
"# check permissions on interface (for interface creation)",
"self",
".",
"check_object_permissions",
"(",
"request",
",",
"self",
".",
"interface",
")",
"# return only interfaces of current interface",
"self",
".",
"queryset",
"=",
"self",
".",
"model",
".",
"objects",
".",
"filter",
"(",
"interface_id",
"=",
"self",
".",
"interface",
".",
"id",
")",
".",
"accessible_to",
"(",
"self",
".",
"request",
".",
"user",
")"
] | Custom initial method:
* ensure interface exists and store it in an instance attribute
* change queryset to return only devices of current node | [
"Custom",
"initial",
"method",
":",
"*",
"ensure",
"interface",
"exists",
"and",
"store",
"it",
"in",
"an",
"instance",
"attribute",
"*",
"change",
"queryset",
"to",
"return",
"only",
"devices",
"of",
"current",
"node"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L279-L299 |
ninuxorg/nodeshot | nodeshot/community/profiles/html_views.py | group_and_bridge | def group_and_bridge(kwargs):
"""
Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database.
"""
bridge = kwargs.pop("bridge", None)
if bridge:
try:
group = bridge.get_group(**kwargs)
except ObjectDoesNotExist:
raise Http404
else:
group = None
return group, bridge | python | def group_and_bridge(kwargs):
"""
Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database.
"""
bridge = kwargs.pop("bridge", None)
if bridge:
try:
group = bridge.get_group(**kwargs)
except ObjectDoesNotExist:
raise Http404
else:
group = None
return group, bridge | [
"def",
"group_and_bridge",
"(",
"kwargs",
")",
":",
"bridge",
"=",
"kwargs",
".",
"pop",
"(",
"\"bridge\"",
",",
"None",
")",
"if",
"bridge",
":",
"try",
":",
"group",
"=",
"bridge",
".",
"get_group",
"(",
"*",
"*",
"kwargs",
")",
"except",
"ObjectDoesNotExist",
":",
"raise",
"Http404",
"else",
":",
"group",
"=",
"None",
"return",
"group",
",",
"bridge"
] | Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database. | [
"Given",
"kwargs",
"from",
"the",
"view",
"(",
"with",
"view",
"specific",
"keys",
"popped",
")",
"pull",
"out",
"the",
"bridge",
"and",
"fetch",
"group",
"from",
"database",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/html_views.py#L17-L33 |
ninuxorg/nodeshot | nodeshot/core/base/models.py | BaseDate.save | def save(self, *args, **kwargs):
"""
automatically update updated date field
"""
# auto fill updated field with current time unless explicitly disabled
auto_update = kwargs.get('auto_update', True)
if auto_update:
self.updated = now()
# remove eventual auto_update
if 'auto_update' in kwargs:
kwargs.pop('auto_update')
super(BaseDate, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
automatically update updated date field
"""
# auto fill updated field with current time unless explicitly disabled
auto_update = kwargs.get('auto_update', True)
if auto_update:
self.updated = now()
# remove eventual auto_update
if 'auto_update' in kwargs:
kwargs.pop('auto_update')
super(BaseDate, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# auto fill updated field with current time unless explicitly disabled",
"auto_update",
"=",
"kwargs",
".",
"get",
"(",
"'auto_update'",
",",
"True",
")",
"if",
"auto_update",
":",
"self",
".",
"updated",
"=",
"now",
"(",
")",
"# remove eventual auto_update",
"if",
"'auto_update'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'auto_update'",
")",
"super",
"(",
"BaseDate",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | automatically update updated date field | [
"automatically",
"update",
"updated",
"date",
"field"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L64-L77 |
ninuxorg/nodeshot | nodeshot/core/base/models.py | BaseOrdered.save | def save(self, *args, **kwargs):
""" if order left blank """
if self.order == '' or self.order is None:
try:
self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1
except IndexError:
self.order = 0
super(BaseOrdered, self).save() | python | def save(self, *args, **kwargs):
""" if order left blank """
if self.order == '' or self.order is None:
try:
self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1
except IndexError:
self.order = 0
super(BaseOrdered, self).save() | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"order",
"==",
"''",
"or",
"self",
".",
"order",
"is",
"None",
":",
"try",
":",
"self",
".",
"order",
"=",
"self",
".",
"get_auto_order_queryset",
"(",
")",
".",
"order_by",
"(",
"\"-order\"",
")",
"[",
"0",
"]",
".",
"order",
"+",
"1",
"except",
"IndexError",
":",
"self",
".",
"order",
"=",
"0",
"super",
"(",
"BaseOrdered",
",",
"self",
")",
".",
"save",
"(",
")"
] | if order left blank | [
"if",
"order",
"left",
"blank"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L161-L168 |
ninuxorg/nodeshot | nodeshot/core/base/utils.py | check_dependencies | def check_dependencies(dependencies, module):
"""
Ensure dependencies of a module are listed in settings.INSTALLED_APPS
:dependencies string | list: list of dependencies to check
:module string: string representing the path to the current app
"""
if type(dependencies) == str:
dependencies = [dependencies]
elif type(dependencies) != list:
raise TypeError('dependencies argument must be of type list or string')
for dependency in dependencies:
if dependency not in settings.INSTALLED_APPS:
raise DependencyError('%s depends on %s, which should be in settings.INSTALLED_APPS' % (module, dependency)) | python | def check_dependencies(dependencies, module):
"""
Ensure dependencies of a module are listed in settings.INSTALLED_APPS
:dependencies string | list: list of dependencies to check
:module string: string representing the path to the current app
"""
if type(dependencies) == str:
dependencies = [dependencies]
elif type(dependencies) != list:
raise TypeError('dependencies argument must be of type list or string')
for dependency in dependencies:
if dependency not in settings.INSTALLED_APPS:
raise DependencyError('%s depends on %s, which should be in settings.INSTALLED_APPS' % (module, dependency)) | [
"def",
"check_dependencies",
"(",
"dependencies",
",",
"module",
")",
":",
"if",
"type",
"(",
"dependencies",
")",
"==",
"str",
":",
"dependencies",
"=",
"[",
"dependencies",
"]",
"elif",
"type",
"(",
"dependencies",
")",
"!=",
"list",
":",
"raise",
"TypeError",
"(",
"'dependencies argument must be of type list or string'",
")",
"for",
"dependency",
"in",
"dependencies",
":",
"if",
"dependency",
"not",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"raise",
"DependencyError",
"(",
"'%s depends on %s, which should be in settings.INSTALLED_APPS'",
"%",
"(",
"module",
",",
"dependency",
")",
")"
] | Ensure dependencies of a module are listed in settings.INSTALLED_APPS
:dependencies string | list: list of dependencies to check
:module string: string representing the path to the current app | [
"Ensure",
"dependencies",
"of",
"a",
"module",
"are",
"listed",
"in",
"settings",
".",
"INSTALLED_APPS"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L38-L52 |
ninuxorg/nodeshot | nodeshot/core/base/utils.py | choicify | def choicify(dictionary):
"""
Converts a readable python dictionary into a django model/form
choice structure (list of tuples) ordered based on the values of each key
:param dictionary: the dictionary to convert
"""
# get order of the fields
ordered_fields = sorted(dictionary, key=dictionary.get)
choices = []
# loop over each field
for field in ordered_fields:
# build tuple (value, i18n_key)
row = (dictionary[field], _(field.replace('_', ' ')))
# append tuple to choices
choices.append(row)
# return django sorted choices
return choices | python | def choicify(dictionary):
"""
Converts a readable python dictionary into a django model/form
choice structure (list of tuples) ordered based on the values of each key
:param dictionary: the dictionary to convert
"""
# get order of the fields
ordered_fields = sorted(dictionary, key=dictionary.get)
choices = []
# loop over each field
for field in ordered_fields:
# build tuple (value, i18n_key)
row = (dictionary[field], _(field.replace('_', ' ')))
# append tuple to choices
choices.append(row)
# return django sorted choices
return choices | [
"def",
"choicify",
"(",
"dictionary",
")",
":",
"# get order of the fields",
"ordered_fields",
"=",
"sorted",
"(",
"dictionary",
",",
"key",
"=",
"dictionary",
".",
"get",
")",
"choices",
"=",
"[",
"]",
"# loop over each field",
"for",
"field",
"in",
"ordered_fields",
":",
"# build tuple (value, i18n_key)",
"row",
"=",
"(",
"dictionary",
"[",
"field",
"]",
",",
"_",
"(",
"field",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
")",
")",
"# append tuple to choices",
"choices",
".",
"append",
"(",
"row",
")",
"# return django sorted choices",
"return",
"choices"
] | Converts a readable python dictionary into a django model/form
choice structure (list of tuples) ordered based on the values of each key
:param dictionary: the dictionary to convert | [
"Converts",
"a",
"readable",
"python",
"dictionary",
"into",
"a",
"django",
"model",
"/",
"form",
"choice",
"structure",
"(",
"list",
"of",
"tuples",
")",
"ordered",
"based",
"on",
"the",
"values",
"of",
"each",
"key"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L55-L72 |
ninuxorg/nodeshot | nodeshot/core/base/utils.py | get_key_by_value | def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
"""
for key, value in dictionary.iteritems():
if value == search_value:
return ugettext(key) | python | def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
"""
for key, value in dictionary.iteritems():
if value == search_value:
return ugettext(key) | [
"def",
"get_key_by_value",
"(",
"dictionary",
",",
"search_value",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"iteritems",
"(",
")",
":",
"if",
"value",
"==",
"search_value",
":",
"return",
"ugettext",
"(",
"key",
")"
] | searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for | [
"searchs",
"a",
"value",
"in",
"a",
"dicionary",
"and",
"returns",
"the",
"key",
"of",
"the",
"first",
"occurrence"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L75-L84 |
ninuxorg/nodeshot | nodeshot/core/layers/views.py | LayerNodeListMixin.get_layer | def get_layer(self):
""" retrieve layer from DB """
if self.layer:
return
try:
self.layer = Layer.objects.get(slug=self.kwargs['slug'])
except Layer.DoesNotExist:
raise Http404(_('Layer not found')) | python | def get_layer(self):
""" retrieve layer from DB """
if self.layer:
return
try:
self.layer = Layer.objects.get(slug=self.kwargs['slug'])
except Layer.DoesNotExist:
raise Http404(_('Layer not found')) | [
"def",
"get_layer",
"(",
"self",
")",
":",
"if",
"self",
".",
"layer",
":",
"return",
"try",
":",
"self",
".",
"layer",
"=",
"Layer",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"'slug'",
"]",
")",
"except",
"Layer",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'Layer not found'",
")",
")"
] | retrieve layer from DB | [
"retrieve",
"layer",
"from",
"DB"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L56-L63 |
ninuxorg/nodeshot | nodeshot/core/layers/views.py | LayerNodeListMixin.get_queryset | def get_queryset(self):
""" extend parent class queryset by filtering nodes of the specified layer """
self.get_layer()
return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id) | python | def get_queryset(self):
""" extend parent class queryset by filtering nodes of the specified layer """
self.get_layer()
return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"self",
".",
"get_layer",
"(",
")",
"return",
"super",
"(",
"LayerNodeListMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
".",
"filter",
"(",
"layer_id",
"=",
"self",
".",
"layer",
".",
"id",
")"
] | extend parent class queryset by filtering nodes of the specified layer | [
"extend",
"parent",
"class",
"queryset",
"by",
"filtering",
"nodes",
"of",
"the",
"specified",
"layer"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L65-L68 |
ninuxorg/nodeshot | nodeshot/core/layers/views.py | LayerNodeListMixin.get_nodes | def get_nodes(self, request, *args, **kwargs):
""" this method might be overridden by other modules (eg: nodeshot.interop.sync) """
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *args, **kwargs)).data | python | def get_nodes(self, request, *args, **kwargs):
""" this method might be overridden by other modules (eg: nodeshot.interop.sync) """
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *args, **kwargs)).data | [
"def",
"get_nodes",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# ListSerializerMixin.list returns a serializer object",
"return",
"(",
"self",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
".",
"data"
] | this method might be overridden by other modules (eg: nodeshot.interop.sync) | [
"this",
"method",
"might",
"be",
"overridden",
"by",
"other",
"modules",
"(",
"eg",
":",
"nodeshot",
".",
"interop",
".",
"sync",
")"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L70-L73 |
ninuxorg/nodeshot | nodeshot/core/layers/views.py | LayerNodeListMixin.get | def get(self, request, *args, **kwargs):
""" Retrieve list of nodes of the specified layer """
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) | python | def get(self, request, *args, **kwargs):
""" Retrieve list of nodes of the specified layer """
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"get_layer",
"(",
")",
"# get nodes of layer",
"nodes",
"=",
"self",
".",
"get_nodes",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"Response",
"(",
"nodes",
")"
] | Retrieve list of nodes of the specified layer | [
"Retrieve",
"list",
"of",
"nodes",
"of",
"the",
"specified",
"layer"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L75-L80 |
ninuxorg/nodeshot | nodeshot/networking/net/models/ip.py | Ip.save | def save(self, *args, **kwargs):
"""
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
"""
self.protocol = 'ipv%d' % self.address.version
# save
super(Ip, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
"""
self.protocol = 'ipv%d' % self.address.version
# save
super(Ip, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"protocol",
"=",
"'ipv%d'",
"%",
"self",
".",
"address",
".",
"version",
"# save",
"super",
"(",
"Ip",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience. | [
"Determines",
"ip",
"protocol",
"version",
"automatically",
".",
"Stores",
"address",
"in",
"interface",
"shortcuts",
"for",
"convenience",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/ip.py#L36-L43 |
ninuxorg/nodeshot | nodeshot/interop/oldimporter/db.py | DefaultRouter.allow_relation | def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed between nodeshot2 objects only
"""
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
return True
return None | python | def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed between nodeshot2 objects only
"""
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
return True
return None | [
"def",
"allow_relation",
"(",
"self",
",",
"obj1",
",",
"obj2",
",",
"*",
"*",
"hints",
")",
":",
"if",
"obj1",
".",
"_meta",
".",
"app_label",
"!=",
"'oldimporter'",
"and",
"obj2",
".",
"_meta",
".",
"app_label",
"!=",
"'oldimporter'",
":",
"return",
"True",
"return",
"None"
] | Relations between objects are allowed between nodeshot2 objects only | [
"Relations",
"between",
"objects",
"are",
"allowed",
"between",
"nodeshot2",
"objects",
"only"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L24-L30 |
ninuxorg/nodeshot | nodeshot/interop/oldimporter/db.py | OldNodeshotRouter.allow_migrate | def allow_migrate(self, db, model):
"""
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
"""
if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter':
return False
return True | python | def allow_migrate(self, db, model):
"""
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
"""
if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter':
return False
return True | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"db",
"!=",
"'old_nodeshot'",
"or",
"model",
".",
"_meta",
".",
"app_label",
"!=",
"'oldimporter'",
":",
"return",
"False",
"return",
"True"
] | Make sure the old_nodeshot app only appears in the 'old_nodeshot' database | [
"Make",
"sure",
"the",
"old_nodeshot",
"app",
"only",
"appears",
"in",
"the",
"old_nodeshot",
"database"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L66-L72 |
ninuxorg/nodeshot | nodeshot/community/profiles/forms.py | ResetPasswordForm.clean_email | def clean_email(self):
""" ensure email is in the database """
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True
).count() == 0
else:
condition = User.objects.get(
email__iexact=self.cleaned_data["email"],
is_active=True
).count() == 0
if condition is True:
raise forms.ValidationError(
_("Email address not verified for any user account")
)
return self.cleaned_data["email"] | python | def clean_email(self):
""" ensure email is in the database """
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True
).count() == 0
else:
condition = User.objects.get(
email__iexact=self.cleaned_data["email"],
is_active=True
).count() == 0
if condition is True:
raise forms.ValidationError(
_("Email address not verified for any user account")
)
return self.cleaned_data["email"] | [
"def",
"clean_email",
"(",
"self",
")",
":",
"if",
"EMAIL_CONFIRMATION",
":",
"from",
".",
"models",
"import",
"EmailAddress",
"condition",
"=",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"email__iexact",
"=",
"self",
".",
"cleaned_data",
"[",
"\"email\"",
"]",
",",
"verified",
"=",
"True",
")",
".",
"count",
"(",
")",
"==",
"0",
"else",
":",
"condition",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"email__iexact",
"=",
"self",
".",
"cleaned_data",
"[",
"\"email\"",
"]",
",",
"is_active",
"=",
"True",
")",
".",
"count",
"(",
")",
"==",
"0",
"if",
"condition",
"is",
"True",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"_",
"(",
"\"Email address not verified for any user account\"",
")",
")",
"return",
"self",
".",
"cleaned_data",
"[",
"\"email\"",
"]"
] | ensure email is in the database | [
"ensure",
"email",
"is",
"in",
"the",
"database"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/forms.py#L23-L41 |
ninuxorg/nodeshot | nodeshot/core/metrics/views.py | metric_details | def metric_details(request, pk, format=None):
"""
Get or write metric values
"""
metric = get_object_or_404(Metric, pk=pk)
# get
if request.method == 'GET':
try:
results = metric.select(q=request.query_params.get('q', metric.query))
except InfluxDBClientError as e:
return Response({'detail': e.content}, status=e.code)
return Response(list(results.get_points(metric.name)))
# post
else:
if not request.data:
return Response({'detail': 'expected values in POST data or JSON payload'},
status=400)
data = request.data.copy()
# try converting strings to floats when sending form-data
if request.content_type != 'application/json':
for key, value in data.items():
try:
data[key] = float(value) if '.' in value else int(value)
except ValueError:
pass
# write
metric.write(data)
return Response({'detail': 'ok'}) | python | def metric_details(request, pk, format=None):
"""
Get or write metric values
"""
metric = get_object_or_404(Metric, pk=pk)
# get
if request.method == 'GET':
try:
results = metric.select(q=request.query_params.get('q', metric.query))
except InfluxDBClientError as e:
return Response({'detail': e.content}, status=e.code)
return Response(list(results.get_points(metric.name)))
# post
else:
if not request.data:
return Response({'detail': 'expected values in POST data or JSON payload'},
status=400)
data = request.data.copy()
# try converting strings to floats when sending form-data
if request.content_type != 'application/json':
for key, value in data.items():
try:
data[key] = float(value) if '.' in value else int(value)
except ValueError:
pass
# write
metric.write(data)
return Response({'detail': 'ok'}) | [
"def",
"metric_details",
"(",
"request",
",",
"pk",
",",
"format",
"=",
"None",
")",
":",
"metric",
"=",
"get_object_or_404",
"(",
"Metric",
",",
"pk",
"=",
"pk",
")",
"# get",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"try",
":",
"results",
"=",
"metric",
".",
"select",
"(",
"q",
"=",
"request",
".",
"query_params",
".",
"get",
"(",
"'q'",
",",
"metric",
".",
"query",
")",
")",
"except",
"InfluxDBClientError",
"as",
"e",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"e",
".",
"content",
"}",
",",
"status",
"=",
"e",
".",
"code",
")",
"return",
"Response",
"(",
"list",
"(",
"results",
".",
"get_points",
"(",
"metric",
".",
"name",
")",
")",
")",
"# post",
"else",
":",
"if",
"not",
"request",
".",
"data",
":",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"'expected values in POST data or JSON payload'",
"}",
",",
"status",
"=",
"400",
")",
"data",
"=",
"request",
".",
"data",
".",
"copy",
"(",
")",
"# try converting strings to floats when sending form-data",
"if",
"request",
".",
"content_type",
"!=",
"'application/json'",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"try",
":",
"data",
"[",
"key",
"]",
"=",
"float",
"(",
"value",
")",
"if",
"'.'",
"in",
"value",
"else",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"pass",
"# write",
"metric",
".",
"write",
"(",
"data",
")",
"return",
"Response",
"(",
"{",
"'detail'",
":",
"'ok'",
"}",
")"
] | Get or write metric values | [
"Get",
"or",
"write",
"metric",
"values"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/views.py#L12-L39 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.add_client | def add_client(self, user_id=None):
"""
Adds current instance to public or private channel.
If user_id is specified it will be added to the private channel,
If user_id is not specified it will be added to the public one instead.
"""
if user_id is None:
# generate a random uuid if it's an unauthenticated client
self.channel = 'public'
user_id = uuid.uuid1().hex
else:
self.channel = 'private'
self.id = user_id
self.channels[self.channel][self.id] = self
print 'Client connected to the %s channel.' % self.channel | python | def add_client(self, user_id=None):
"""
Adds current instance to public or private channel.
If user_id is specified it will be added to the private channel,
If user_id is not specified it will be added to the public one instead.
"""
if user_id is None:
# generate a random uuid if it's an unauthenticated client
self.channel = 'public'
user_id = uuid.uuid1().hex
else:
self.channel = 'private'
self.id = user_id
self.channels[self.channel][self.id] = self
print 'Client connected to the %s channel.' % self.channel | [
"def",
"add_client",
"(",
"self",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"user_id",
"is",
"None",
":",
"# generate a random uuid if it's an unauthenticated client",
"self",
".",
"channel",
"=",
"'public'",
"user_id",
"=",
"uuid",
".",
"uuid1",
"(",
")",
".",
"hex",
"else",
":",
"self",
".",
"channel",
"=",
"'private'",
"self",
".",
"id",
"=",
"user_id",
"self",
".",
"channels",
"[",
"self",
".",
"channel",
"]",
"[",
"self",
".",
"id",
"]",
"=",
"self",
"print",
"'Client connected to the %s channel.'",
"%",
"self",
".",
"channel"
] | Adds current instance to public or private channel.
If user_id is specified it will be added to the private channel,
If user_id is not specified it will be added to the public one instead. | [
"Adds",
"current",
"instance",
"to",
"public",
"or",
"private",
"channel",
".",
"If",
"user_id",
"is",
"specified",
"it",
"will",
"be",
"added",
"to",
"the",
"private",
"channel",
"If",
"user_id",
"is",
"not",
"specified",
"it",
"will",
"be",
"added",
"to",
"the",
"public",
"one",
"instead",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L21-L36 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.broadcast | def broadcast(cls, message):
""" broadcast message to all connected clients """
clients = cls.get_clients()
# loop over every client and send message
for id, client in clients.iteritems():
client.send_message(message) | python | def broadcast(cls, message):
""" broadcast message to all connected clients """
clients = cls.get_clients()
# loop over every client and send message
for id, client in clients.iteritems():
client.send_message(message) | [
"def",
"broadcast",
"(",
"cls",
",",
"message",
")",
":",
"clients",
"=",
"cls",
".",
"get_clients",
"(",
")",
"# loop over every client and send message",
"for",
"id",
",",
"client",
"in",
"clients",
".",
"iteritems",
"(",
")",
":",
"client",
".",
"send_message",
"(",
"message",
")"
] | broadcast message to all connected clients | [
"broadcast",
"message",
"to",
"all",
"connected",
"clients"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L43-L48 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.send_private_message | def send_private_message(self, user_id, message):
"""
Send a message to a specific client.
Returns True if successful, False otherwise
"""
try:
client = self.channels['private'][str(user_id)]
except KeyError:
print '====debug===='
print self.channels['private']
print 'client with id %s not found' % user_id
return False
client.send_message(message)
print 'message sent to client #%s' % user_id
return True | python | def send_private_message(self, user_id, message):
"""
Send a message to a specific client.
Returns True if successful, False otherwise
"""
try:
client = self.channels['private'][str(user_id)]
except KeyError:
print '====debug===='
print self.channels['private']
print 'client with id %s not found' % user_id
return False
client.send_message(message)
print 'message sent to client #%s' % user_id
return True | [
"def",
"send_private_message",
"(",
"self",
",",
"user_id",
",",
"message",
")",
":",
"try",
":",
"client",
"=",
"self",
".",
"channels",
"[",
"'private'",
"]",
"[",
"str",
"(",
"user_id",
")",
"]",
"except",
"KeyError",
":",
"print",
"'====debug===='",
"print",
"self",
".",
"channels",
"[",
"'private'",
"]",
"print",
"'client with id %s not found'",
"%",
"user_id",
"return",
"False",
"client",
".",
"send_message",
"(",
"message",
")",
"print",
"'message sent to client #%s'",
"%",
"user_id",
"return",
"True"
] | Send a message to a specific client.
Returns True if successful, False otherwise | [
"Send",
"a",
"message",
"to",
"a",
"specific",
"client",
".",
"Returns",
"True",
"if",
"successful",
"False",
"otherwise"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L51-L66 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.get_clients | def get_clients(self):
""" return a merge of public and private clients """
public = self.channels['public']
private = self.channels['private']
return dict(public.items() + private.items()) | python | def get_clients(self):
""" return a merge of public and private clients """
public = self.channels['public']
private = self.channels['private']
return dict(public.items() + private.items()) | [
"def",
"get_clients",
"(",
"self",
")",
":",
"public",
"=",
"self",
".",
"channels",
"[",
"'public'",
"]",
"private",
"=",
"self",
".",
"channels",
"[",
"'private'",
"]",
"return",
"dict",
"(",
"public",
".",
"items",
"(",
")",
"+",
"private",
".",
"items",
"(",
")",
")"
] | return a merge of public and private clients | [
"return",
"a",
"merge",
"of",
"public",
"and",
"private",
"clients"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L69-L73 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.open | def open(self):
""" method which is called every time a new client connects """
print 'Connection opened.'
# retrieve user_id if specified
user_id = self.get_argument("user_id", None)
# add client to list of connected clients
self.add_client(user_id)
# welcome message
self.send_message("Welcome to nodeshot websocket server.")
# new client connected message
client_count = len(self.get_clients().keys())
new_client_message = 'New client connected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients')
# broadcast new client connected message to all connected clients
self.broadcast(new_client_message)
print self.channels['private'] | python | def open(self):
""" method which is called every time a new client connects """
print 'Connection opened.'
# retrieve user_id if specified
user_id = self.get_argument("user_id", None)
# add client to list of connected clients
self.add_client(user_id)
# welcome message
self.send_message("Welcome to nodeshot websocket server.")
# new client connected message
client_count = len(self.get_clients().keys())
new_client_message = 'New client connected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients')
# broadcast new client connected message to all connected clients
self.broadcast(new_client_message)
print self.channels['private'] | [
"def",
"open",
"(",
"self",
")",
":",
"print",
"'Connection opened.'",
"# retrieve user_id if specified",
"user_id",
"=",
"self",
".",
"get_argument",
"(",
"\"user_id\"",
",",
"None",
")",
"# add client to list of connected clients",
"self",
".",
"add_client",
"(",
"user_id",
")",
"# welcome message",
"self",
".",
"send_message",
"(",
"\"Welcome to nodeshot websocket server.\"",
")",
"# new client connected message",
"client_count",
"=",
"len",
"(",
"self",
".",
"get_clients",
"(",
")",
".",
"keys",
"(",
")",
")",
"new_client_message",
"=",
"'New client connected, now we have %d %s!'",
"%",
"(",
"client_count",
",",
"'client'",
"if",
"client_count",
"<=",
"1",
"else",
"'clients'",
")",
"# broadcast new client connected message to all connected clients",
"self",
".",
"broadcast",
"(",
"new_client_message",
")",
"print",
"self",
".",
"channels",
"[",
"'private'",
"]"
] | method which is called every time a new client connects | [
"method",
"which",
"is",
"called",
"every",
"time",
"a",
"new",
"client",
"connects"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L75-L91 |
ninuxorg/nodeshot | nodeshot/core/websockets/handlers.py | WebSocketHandler.on_close | def on_close(self):
""" method which is called every time a client disconnects """
print 'Connection closed.'
self.remove_client()
client_count = len(self.get_clients().keys())
new_client_message = '1 client disconnected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients')
self.broadcast(new_client_message) | python | def on_close(self):
""" method which is called every time a client disconnects """
print 'Connection closed.'
self.remove_client()
client_count = len(self.get_clients().keys())
new_client_message = '1 client disconnected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients')
self.broadcast(new_client_message) | [
"def",
"on_close",
"(",
"self",
")",
":",
"print",
"'Connection closed.'",
"self",
".",
"remove_client",
"(",
")",
"client_count",
"=",
"len",
"(",
"self",
".",
"get_clients",
"(",
")",
".",
"keys",
"(",
")",
")",
"new_client_message",
"=",
"'1 client disconnected, now we have %d %s!'",
"%",
"(",
"client_count",
",",
"'client'",
"if",
"client_count",
"<=",
"1",
"else",
"'clients'",
")",
"self",
".",
"broadcast",
"(",
"new_client_message",
")"
] | method which is called every time a client disconnects | [
"method",
"which",
"is",
"called",
"every",
"time",
"a",
"client",
"disconnects"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L99-L106 |
ninuxorg/nodeshot | nodeshot/core/metrics/utils.py | get_db | def get_db():
"""Returns an ``InfluxDBClient`` instance."""
return client.InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
) | python | def get_db():
"""Returns an ``InfluxDBClient`` instance."""
return client.InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
) | [
"def",
"get_db",
"(",
")",
":",
"return",
"client",
".",
"InfluxDBClient",
"(",
"settings",
".",
"INFLUXDB_HOST",
",",
"settings",
".",
"INFLUXDB_PORT",
",",
"settings",
".",
"INFLUXDB_USER",
",",
"settings",
".",
"INFLUXDB_PASSWORD",
",",
"settings",
".",
"INFLUXDB_DATABASE",
",",
")"
] | Returns an ``InfluxDBClient`` instance. | [
"Returns",
"an",
"InfluxDBClient",
"instance",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L8-L16 |
ninuxorg/nodeshot | nodeshot/core/metrics/utils.py | query | def query(query, params={}, epoch=None,
expected_response_code=200, database=None):
"""Wrapper around ``InfluxDBClient.query()``."""
db = get_db()
database = database or settings.INFLUXDB_DATABASE
return db.query(query, params, epoch, expected_response_code, database=database) | python | def query(query, params={}, epoch=None,
expected_response_code=200, database=None):
"""Wrapper around ``InfluxDBClient.query()``."""
db = get_db()
database = database or settings.INFLUXDB_DATABASE
return db.query(query, params, epoch, expected_response_code, database=database) | [
"def",
"query",
"(",
"query",
",",
"params",
"=",
"{",
"}",
",",
"epoch",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"database",
"=",
"None",
")",
":",
"db",
"=",
"get_db",
"(",
")",
"database",
"=",
"database",
"or",
"settings",
".",
"INFLUXDB_DATABASE",
"return",
"db",
".",
"query",
"(",
"query",
",",
"params",
",",
"epoch",
",",
"expected_response_code",
",",
"database",
"=",
"database",
")"
] | Wrapper around ``InfluxDBClient.query()``. | [
"Wrapper",
"around",
"InfluxDBClient",
".",
"query",
"()",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L19-L24 |
ninuxorg/nodeshot | nodeshot/core/metrics/utils.py | write_async | def write_async(name, values, tags={}, timestamp=None, database=None):
""" write metrics """
thread = Thread(target=write,
args=(name, values, tags, timestamp, database))
thread.start() | python | def write_async(name, values, tags={}, timestamp=None, database=None):
""" write metrics """
thread = Thread(target=write,
args=(name, values, tags, timestamp, database))
thread.start() | [
"def",
"write_async",
"(",
"name",
",",
"values",
",",
"tags",
"=",
"{",
"}",
",",
"timestamp",
"=",
"None",
",",
"database",
"=",
"None",
")",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"write",
",",
"args",
"=",
"(",
"name",
",",
"values",
",",
"tags",
",",
"timestamp",
",",
"database",
")",
")",
"thread",
".",
"start",
"(",
")"
] | write metrics | [
"write",
"metrics"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L27-L31 |
ninuxorg/nodeshot | nodeshot/core/metrics/utils.py | write | def write(name, values, tags={}, timestamp=None, database=None):
""" Method to be called via threading module. """
point = {
'measurement': name,
'tags': tags,
'fields': values
}
if isinstance(timestamp, datetime):
timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
if timestamp:
point['time'] = timestamp
try:
get_db().write({'points': [point]},
{'db': database or settings.INFLUXDB_DATABASE})
except Exception, e:
if settings.INFLUXDB_FAIL_SILENTLY:
pass
else:
raise e | python | def write(name, values, tags={}, timestamp=None, database=None):
""" Method to be called via threading module. """
point = {
'measurement': name,
'tags': tags,
'fields': values
}
if isinstance(timestamp, datetime):
timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
if timestamp:
point['time'] = timestamp
try:
get_db().write({'points': [point]},
{'db': database or settings.INFLUXDB_DATABASE})
except Exception, e:
if settings.INFLUXDB_FAIL_SILENTLY:
pass
else:
raise e | [
"def",
"write",
"(",
"name",
",",
"values",
",",
"tags",
"=",
"{",
"}",
",",
"timestamp",
"=",
"None",
",",
"database",
"=",
"None",
")",
":",
"point",
"=",
"{",
"'measurement'",
":",
"name",
",",
"'tags'",
":",
"tags",
",",
"'fields'",
":",
"values",
"}",
"if",
"isinstance",
"(",
"timestamp",
",",
"datetime",
")",
":",
"timestamp",
"=",
"timestamp",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"if",
"timestamp",
":",
"point",
"[",
"'time'",
"]",
"=",
"timestamp",
"try",
":",
"get_db",
"(",
")",
".",
"write",
"(",
"{",
"'points'",
":",
"[",
"point",
"]",
"}",
",",
"{",
"'db'",
":",
"database",
"or",
"settings",
".",
"INFLUXDB_DATABASE",
"}",
")",
"except",
"Exception",
",",
"e",
":",
"if",
"settings",
".",
"INFLUXDB_FAIL_SILENTLY",
":",
"pass",
"else",
":",
"raise",
"e"
] | Method to be called via threading module. | [
"Method",
"to",
"be",
"called",
"via",
"threading",
"module",
"."
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L34-L52 |
ninuxorg/nodeshot | nodeshot/core/metrics/utils.py | create_database | def create_database():
""" creates database if necessary """
db = get_db()
response = db.query('SHOW DATABASES')
items = list(response.get_points('databases'))
databases = [database['name'] for database in items]
# if database does not exists, create it
if settings.INFLUXDB_DATABASE not in databases:
db.create_database(settings.INFLUXDB_DATABASE)
print('Created inlfuxdb database {0}'.format(settings.INFLUXDB_DATABASE)) | python | def create_database():
""" creates database if necessary """
db = get_db()
response = db.query('SHOW DATABASES')
items = list(response.get_points('databases'))
databases = [database['name'] for database in items]
# if database does not exists, create it
if settings.INFLUXDB_DATABASE not in databases:
db.create_database(settings.INFLUXDB_DATABASE)
print('Created inlfuxdb database {0}'.format(settings.INFLUXDB_DATABASE)) | [
"def",
"create_database",
"(",
")",
":",
"db",
"=",
"get_db",
"(",
")",
"response",
"=",
"db",
".",
"query",
"(",
"'SHOW DATABASES'",
")",
"items",
"=",
"list",
"(",
"response",
".",
"get_points",
"(",
"'databases'",
")",
")",
"databases",
"=",
"[",
"database",
"[",
"'name'",
"]",
"for",
"database",
"in",
"items",
"]",
"# if database does not exists, create it",
"if",
"settings",
".",
"INFLUXDB_DATABASE",
"not",
"in",
"databases",
":",
"db",
".",
"create_database",
"(",
"settings",
".",
"INFLUXDB_DATABASE",
")",
"print",
"(",
"'Created inlfuxdb database {0}'",
".",
"format",
"(",
"settings",
".",
"INFLUXDB_DATABASE",
")",
")"
] | creates database if necessary | [
"creates",
"database",
"if",
"necessary"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L55-L64 |
ninuxorg/nodeshot | nodeshot/community/participation/models/rating.py | Rating.save | def save(self, *args, **kwargs):
"""
ensure users cannot rate the same node multiple times
but let users change their rating
"""
if not self.pk:
old_ratings = Rating.objects.filter(user=self.user, node=self.node)
for old_rating in old_ratings:
old_rating.delete()
super(Rating, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
ensure users cannot rate the same node multiple times
but let users change their rating
"""
if not self.pk:
old_ratings = Rating.objects.filter(user=self.user, node=self.node)
for old_rating in old_ratings:
old_rating.delete()
super(Rating, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"old_ratings",
"=",
"Rating",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"self",
".",
"user",
",",
"node",
"=",
"self",
".",
"node",
")",
"for",
"old_rating",
"in",
"old_ratings",
":",
"old_rating",
".",
"delete",
"(",
")",
"super",
"(",
"Rating",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | ensure users cannot rate the same node multiple times
but let users change their rating | [
"ensure",
"users",
"cannot",
"rate",
"the",
"same",
"node",
"multiple",
"times",
"but",
"let",
"users",
"change",
"their",
"rating"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L34-L43 |
ninuxorg/nodeshot | nodeshot/community/participation/models/rating.py | Rating.update_count | def update_count(self):
""" updates rating count and rating average """
node_rating_count = self.node.rating_count
node_rating_count.rating_count = self.node.rating_set.count()
node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate']
# if all ratings are deleted the value will be None!
if node_rating_count.rating_avg is None:
# set to 0 otherwise we'll get an exception
node_rating_count.rating_avg = 0
node_rating_count.save() | python | def update_count(self):
""" updates rating count and rating average """
node_rating_count = self.node.rating_count
node_rating_count.rating_count = self.node.rating_set.count()
node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate']
# if all ratings are deleted the value will be None!
if node_rating_count.rating_avg is None:
# set to 0 otherwise we'll get an exception
node_rating_count.rating_avg = 0
node_rating_count.save() | [
"def",
"update_count",
"(",
"self",
")",
":",
"node_rating_count",
"=",
"self",
".",
"node",
".",
"rating_count",
"node_rating_count",
".",
"rating_count",
"=",
"self",
".",
"node",
".",
"rating_set",
".",
"count",
"(",
")",
"node_rating_count",
".",
"rating_avg",
"=",
"self",
".",
"node",
".",
"rating_set",
".",
"aggregate",
"(",
"rate",
"=",
"Avg",
"(",
"'value'",
")",
")",
"[",
"'rate'",
"]",
"# if all ratings are deleted the value will be None!",
"if",
"node_rating_count",
".",
"rating_avg",
"is",
"None",
":",
"# set to 0 otherwise we'll get an exception",
"node_rating_count",
".",
"rating_avg",
"=",
"0",
"node_rating_count",
".",
"save",
"(",
")"
] | updates rating count and rating average | [
"updates",
"rating",
"count",
"and",
"rating",
"average"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L45-L56 |
ninuxorg/nodeshot | nodeshot/community/participation/models/rating.py | Rating.clean | def clean(self, *args, **kwargs):
"""
Check if rating can be inserted for parent node or parent layer
"""
if not self.pk:
node = self.node
layer = Layer.objects.get(pk=node.layer_id)
if layer.participation_settings.rating_allowed is not True:
raise ValidationError("Rating not allowed for this layer")
if node.participation_settings.rating_allowed is not True:
raise ValidationError("Rating not allowed for this node") | python | def clean(self, *args, **kwargs):
"""
Check if rating can be inserted for parent node or parent layer
"""
if not self.pk:
node = self.node
layer = Layer.objects.get(pk=node.layer_id)
if layer.participation_settings.rating_allowed is not True:
raise ValidationError("Rating not allowed for this layer")
if node.participation_settings.rating_allowed is not True:
raise ValidationError("Rating not allowed for this node") | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"node",
"=",
"self",
".",
"node",
"layer",
"=",
"Layer",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"node",
".",
"layer_id",
")",
"if",
"layer",
".",
"participation_settings",
".",
"rating_allowed",
"is",
"not",
"True",
":",
"raise",
"ValidationError",
"(",
"\"Rating not allowed for this layer\"",
")",
"if",
"node",
".",
"participation_settings",
".",
"rating_allowed",
"is",
"not",
"True",
":",
"raise",
"ValidationError",
"(",
"\"Rating not allowed for this node\"",
")"
] | Check if rating can be inserted for parent node or parent layer | [
"Check",
"if",
"rating",
"can",
"be",
"inserted",
"for",
"parent",
"node",
"or",
"parent",
"layer"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L58-L68 |
ninuxorg/nodeshot | nodeshot/community/participation/models/base.py | UpdateCountsMixin.save | def save(self, *args, **kwargs):
""" custom save method to update counts """
# the following lines determines if the comment is being created or not
# in case the comment exists the pk attribute is an int
created = type(self.pk) is not int
super(UpdateCountsMixin, self).save(*args, **kwargs)
# this operation must be performed after the parent save
if created:
self.update_count() | python | def save(self, *args, **kwargs):
""" custom save method to update counts """
# the following lines determines if the comment is being created or not
# in case the comment exists the pk attribute is an int
created = type(self.pk) is not int
super(UpdateCountsMixin, self).save(*args, **kwargs)
# this operation must be performed after the parent save
if created:
self.update_count() | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# the following lines determines if the comment is being created or not",
"# in case the comment exists the pk attribute is an int",
"created",
"=",
"type",
"(",
"self",
".",
"pk",
")",
"is",
"not",
"int",
"super",
"(",
"UpdateCountsMixin",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# this operation must be performed after the parent save",
"if",
"created",
":",
"self",
".",
"update_count",
"(",
")"
] | custom save method to update counts | [
"custom",
"save",
"method",
"to",
"update",
"counts"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L17-L27 |
ninuxorg/nodeshot | nodeshot/community/participation/models/base.py | UpdateCountsMixin.delete | def delete(self, *args, **kwargs):
""" custom delete method to update counts """
super(UpdateCountsMixin, self).delete(*args, **kwargs)
self.update_count() | python | def delete(self, *args, **kwargs):
""" custom delete method to update counts """
super(UpdateCountsMixin, self).delete(*args, **kwargs)
self.update_count() | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"UpdateCountsMixin",
",",
"self",
")",
".",
"delete",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"update_count",
"(",
")"
] | custom delete method to update counts | [
"custom",
"delete",
"method",
"to",
"update",
"counts"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L29-L32 |
ninuxorg/nodeshot | nodeshot/networking/links/utils.py | update_topology | def update_topology():
"""
updates all the topology
sends logs to the "nodeshot.networking" logger
"""
for topology in Topology.objects.all():
try:
topology.update()
except Exception as e:
msg = 'Failed to update {}'.format(topology.__repr__())
logger.exception(msg)
print('{0}: {1}\n'
'see networking.log for more information\n'.format(msg, e.__class__)) | python | def update_topology():
"""
updates all the topology
sends logs to the "nodeshot.networking" logger
"""
for topology in Topology.objects.all():
try:
topology.update()
except Exception as e:
msg = 'Failed to update {}'.format(topology.__repr__())
logger.exception(msg)
print('{0}: {1}\n'
'see networking.log for more information\n'.format(msg, e.__class__)) | [
"def",
"update_topology",
"(",
")",
":",
"for",
"topology",
"in",
"Topology",
".",
"objects",
".",
"all",
"(",
")",
":",
"try",
":",
"topology",
".",
"update",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Failed to update {}'",
".",
"format",
"(",
"topology",
".",
"__repr__",
"(",
")",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"print",
"(",
"'{0}: {1}\\n'",
"'see networking.log for more information\\n'",
".",
"format",
"(",
"msg",
",",
"e",
".",
"__class__",
")",
")"
] | updates all the topology
sends logs to the "nodeshot.networking" logger | [
"updates",
"all",
"the",
"topology",
"sends",
"logs",
"to",
"the",
"nodeshot",
".",
"networking",
"logger"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/utils.py#L20-L32 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector.save | def save(self, *args, **kwargs):
"""
Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True
"""
self.host = self.host.strip()
if not self.id:
self.device = self.__create_device()
if self.store is True:
super(DeviceConnector, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True
"""
self.host = self.host.strip()
if not self.id:
self.device = self.__create_device()
if self.store is True:
super(DeviceConnector, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"host",
"=",
"self",
".",
"host",
".",
"strip",
"(",
")",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
"device",
"=",
"self",
".",
"__create_device",
"(",
")",
"if",
"self",
".",
"store",
"is",
"True",
":",
"super",
"(",
"DeviceConnector",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True | [
"Custom",
"save",
"does",
"the",
"following",
":",
"*",
"strip",
"trailing",
"whitespace",
"from",
"host",
"attribute",
"*",
"create",
"device",
"and",
"all",
"other",
"related",
"objects",
"*",
"store",
"connection",
"config",
"in",
"DB",
"if",
"store",
"attribute",
"is",
"True"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L63-L76 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector.clean | def clean(self, *args, **kwargs):
""" validation """
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | python | def clean(self, *args, **kwargs):
""" validation """
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_validate_backend",
"(",
")",
"self",
".",
"_validate_config",
"(",
")",
"self",
".",
"_validate_netengine",
"(",
")",
"self",
".",
"_validate_duplicates",
"(",
")"
] | validation | [
"validation"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L78-L83 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector.backend_class | def backend_class(self):
"""
returns python netengine backend class, importing it if needed
"""
if not self.backend:
return None
if not self.__backend_class:
self.__backend_class = self._get_netengine_backend()
return self.__backend_class | python | def backend_class(self):
"""
returns python netengine backend class, importing it if needed
"""
if not self.backend:
return None
if not self.__backend_class:
self.__backend_class = self._get_netengine_backend()
return self.__backend_class | [
"def",
"backend_class",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"backend",
":",
"return",
"None",
"if",
"not",
"self",
".",
"__backend_class",
":",
"self",
".",
"__backend_class",
"=",
"self",
".",
"_get_netengine_backend",
"(",
")",
"return",
"self",
".",
"__backend_class"
] | returns python netengine backend class, importing it if needed | [
"returns",
"python",
"netengine",
"backend",
"class",
"importing",
"it",
"if",
"needed"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L94-L104 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector.netengine | def netengine(self):
""" access netengine instance """
# return None if no backend chosen yet
if not self.backend:
return None
# init instance of the netengine backend if not already done
if not self.__netengine:
NetengineBackend = self.backend_class
arguments = self._build_netengine_arguments()
self.__netengine = NetengineBackend(**arguments)
# return netengine instance
return self.__netengine | python | def netengine(self):
""" access netengine instance """
# return None if no backend chosen yet
if not self.backend:
return None
# init instance of the netengine backend if not already done
if not self.__netengine:
NetengineBackend = self.backend_class
arguments = self._build_netengine_arguments()
self.__netengine = NetengineBackend(**arguments)
# return netengine instance
return self.__netengine | [
"def",
"netengine",
"(",
"self",
")",
":",
"# return None if no backend chosen yet",
"if",
"not",
"self",
".",
"backend",
":",
"return",
"None",
"# init instance of the netengine backend if not already done",
"if",
"not",
"self",
".",
"__netengine",
":",
"NetengineBackend",
"=",
"self",
".",
"backend_class",
"arguments",
"=",
"self",
".",
"_build_netengine_arguments",
"(",
")",
"self",
".",
"__netengine",
"=",
"NetengineBackend",
"(",
"*",
"*",
"arguments",
")",
"# return netengine instance",
"return",
"self",
".",
"__netengine"
] | access netengine instance | [
"access",
"netengine",
"instance"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L107-L121 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._validate_backend | def _validate_backend(self):
""" ensure backend string representation is correct """
try:
self.backend_class
# if we get an import error the specified path is wrong
except (ImportError, AttributeError) as e:
raise ValidationError(_('No valid backend found, got the following python exception: "%s"') % e) | python | def _validate_backend(self):
""" ensure backend string representation is correct """
try:
self.backend_class
# if we get an import error the specified path is wrong
except (ImportError, AttributeError) as e:
raise ValidationError(_('No valid backend found, got the following python exception: "%s"') % e) | [
"def",
"_validate_backend",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"backend_class",
"# if we get an import error the specified path is wrong",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
"as",
"e",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'No valid backend found, got the following python exception: \"%s\"'",
")",
"%",
"e",
")"
] | ensure backend string representation is correct | [
"ensure",
"backend",
"string",
"representation",
"is",
"correct"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L123-L129 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._validate_config | def _validate_config(self):
""" ensure REQUIRED_CONFIG_KEYS are filled """
# exit if no backend specified
if not self.backend:
return
# exit if no required config keys
if len(self.REQUIRED_CONFIG_KEYS) < 1:
return
self.config = self.config or {} # default to empty dict of no config
required_keys_set = set(self.REQUIRED_CONFIG_KEYS)
config_keys_set = set(self.config.keys())
missing_required_keys = required_keys_set - config_keys_set
unrecognized_keys = config_keys_set - required_keys_set
# if any missing required key raise ValidationError
if len(missing_required_keys) > 0:
# converts list in comma separated string
missing_keys_string = ', '.join(missing_required_keys)
# django error
raise ValidationError(_('Missing required config keys: "%s"') % missing_keys_string)
elif len(unrecognized_keys) > 0:
# converts list in comma separated string
unrecognized_keys_string = ', '.join(unrecognized_keys)
# django error
raise ValidationError(_('Unrecognized config keys: "%s"') % unrecognized_keys_string) | python | def _validate_config(self):
""" ensure REQUIRED_CONFIG_KEYS are filled """
# exit if no backend specified
if not self.backend:
return
# exit if no required config keys
if len(self.REQUIRED_CONFIG_KEYS) < 1:
return
self.config = self.config or {} # default to empty dict of no config
required_keys_set = set(self.REQUIRED_CONFIG_KEYS)
config_keys_set = set(self.config.keys())
missing_required_keys = required_keys_set - config_keys_set
unrecognized_keys = config_keys_set - required_keys_set
# if any missing required key raise ValidationError
if len(missing_required_keys) > 0:
# converts list in comma separated string
missing_keys_string = ', '.join(missing_required_keys)
# django error
raise ValidationError(_('Missing required config keys: "%s"') % missing_keys_string)
elif len(unrecognized_keys) > 0:
# converts list in comma separated string
unrecognized_keys_string = ', '.join(unrecognized_keys)
# django error
raise ValidationError(_('Unrecognized config keys: "%s"') % unrecognized_keys_string) | [
"def",
"_validate_config",
"(",
"self",
")",
":",
"# exit if no backend specified",
"if",
"not",
"self",
".",
"backend",
":",
"return",
"# exit if no required config keys",
"if",
"len",
"(",
"self",
".",
"REQUIRED_CONFIG_KEYS",
")",
"<",
"1",
":",
"return",
"self",
".",
"config",
"=",
"self",
".",
"config",
"or",
"{",
"}",
"# default to empty dict of no config",
"required_keys_set",
"=",
"set",
"(",
"self",
".",
"REQUIRED_CONFIG_KEYS",
")",
"config_keys_set",
"=",
"set",
"(",
"self",
".",
"config",
".",
"keys",
"(",
")",
")",
"missing_required_keys",
"=",
"required_keys_set",
"-",
"config_keys_set",
"unrecognized_keys",
"=",
"config_keys_set",
"-",
"required_keys_set",
"# if any missing required key raise ValidationError",
"if",
"len",
"(",
"missing_required_keys",
")",
">",
"0",
":",
"# converts list in comma separated string",
"missing_keys_string",
"=",
"', '",
".",
"join",
"(",
"missing_required_keys",
")",
"# django error",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Missing required config keys: \"%s\"'",
")",
"%",
"missing_keys_string",
")",
"elif",
"len",
"(",
"unrecognized_keys",
")",
">",
"0",
":",
"# converts list in comma separated string",
"unrecognized_keys_string",
"=",
"', '",
".",
"join",
"(",
"unrecognized_keys",
")",
"# django error",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Unrecognized config keys: \"%s\"'",
")",
"%",
"unrecognized_keys_string",
")"
] | ensure REQUIRED_CONFIG_KEYS are filled | [
"ensure",
"REQUIRED_CONFIG_KEYS",
"are",
"filled"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L131-L156 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._validate_netengine | def _validate_netengine(self):
"""
call netengine validate() method
verifies connection parameters are correct
"""
if self.backend:
try:
self.netengine.validate()
except NetEngineError as e:
raise ValidationError(e) | python | def _validate_netengine(self):
"""
call netengine validate() method
verifies connection parameters are correct
"""
if self.backend:
try:
self.netengine.validate()
except NetEngineError as e:
raise ValidationError(e) | [
"def",
"_validate_netengine",
"(",
"self",
")",
":",
"if",
"self",
".",
"backend",
":",
"try",
":",
"self",
".",
"netengine",
".",
"validate",
"(",
")",
"except",
"NetEngineError",
"as",
"e",
":",
"raise",
"ValidationError",
"(",
"e",
")"
] | call netengine validate() method
verifies connection parameters are correct | [
"call",
"netengine",
"validate",
"()",
"method",
"verifies",
"connection",
"parameters",
"are",
"correct"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L158-L167 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._validate_duplicates | def _validate_duplicates(self):
"""
Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated
"""
# if connector is being created right now
if not self.id:
duplicates = []
self.netengine_dict = self.netengine.to_dict()
# loop over interfaces and check mac address
for interface in self.netengine_dict['interfaces']:
# avoid checking twice for the same interface (often ifconfig returns duplicates)
if interface['mac_address'] in duplicates:
continue
# check in DB
if Interface.objects.filter(mac__iexact=interface['mac_address']).count() > 0:
duplicates.append(interface['mac_address'])
# if we have duplicates raise validation error
if len(duplicates) > 0:
mac_address_string = ', '.join(duplicates)
raise ValidationError(_('interfaces with the following mac addresses already exist: %s') % mac_address_string) | python | def _validate_duplicates(self):
"""
Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated
"""
# if connector is being created right now
if not self.id:
duplicates = []
self.netengine_dict = self.netengine.to_dict()
# loop over interfaces and check mac address
for interface in self.netengine_dict['interfaces']:
# avoid checking twice for the same interface (often ifconfig returns duplicates)
if interface['mac_address'] in duplicates:
continue
# check in DB
if Interface.objects.filter(mac__iexact=interface['mac_address']).count() > 0:
duplicates.append(interface['mac_address'])
# if we have duplicates raise validation error
if len(duplicates) > 0:
mac_address_string = ', '.join(duplicates)
raise ValidationError(_('interfaces with the following mac addresses already exist: %s') % mac_address_string) | [
"def",
"_validate_duplicates",
"(",
"self",
")",
":",
"# if connector is being created right now",
"if",
"not",
"self",
".",
"id",
":",
"duplicates",
"=",
"[",
"]",
"self",
".",
"netengine_dict",
"=",
"self",
".",
"netengine",
".",
"to_dict",
"(",
")",
"# loop over interfaces and check mac address",
"for",
"interface",
"in",
"self",
".",
"netengine_dict",
"[",
"'interfaces'",
"]",
":",
"# avoid checking twice for the same interface (often ifconfig returns duplicates)",
"if",
"interface",
"[",
"'mac_address'",
"]",
"in",
"duplicates",
":",
"continue",
"# check in DB",
"if",
"Interface",
".",
"objects",
".",
"filter",
"(",
"mac__iexact",
"=",
"interface",
"[",
"'mac_address'",
"]",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"duplicates",
".",
"append",
"(",
"interface",
"[",
"'mac_address'",
"]",
")",
"# if we have duplicates raise validation error",
"if",
"len",
"(",
"duplicates",
")",
">",
"0",
":",
"mac_address_string",
"=",
"', '",
".",
"join",
"(",
"duplicates",
")",
"raise",
"ValidationError",
"(",
"_",
"(",
"'interfaces with the following mac addresses already exist: %s'",
")",
"%",
"mac_address_string",
")"
] | Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated | [
"Ensure",
"we",
"re",
"not",
"creating",
"a",
"device",
"that",
"already",
"exists",
"Runs",
"only",
"when",
"the",
"DeviceConnector",
"object",
"is",
"created",
"not",
"when",
"is",
"updated"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L169-L190 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._get_netengine_arguments | def _get_netengine_arguments(self, required=False):
"""
returns list of available config params
returns list of required config params if required is True
for internal use only
"""
# inspect netengine class
backend_class = self._get_netengine_backend()
argspec = inspect.getargspec(backend_class.__init__)
# store args
args = argspec.args
# remove known arguments
for argument_name in ['self', 'host', 'port']:
args.remove(argument_name)
if required:
# list of default values
default_values = list(argspec.defaults)
# always remove last default value, which is port number
default_values = default_values[0:-1]
# remove an amount of arguments equals to number of default values, starting from right
args = args[0:len(args)-len(default_values)]
return args | python | def _get_netengine_arguments(self, required=False):
"""
returns list of available config params
returns list of required config params if required is True
for internal use only
"""
# inspect netengine class
backend_class = self._get_netengine_backend()
argspec = inspect.getargspec(backend_class.__init__)
# store args
args = argspec.args
# remove known arguments
for argument_name in ['self', 'host', 'port']:
args.remove(argument_name)
if required:
# list of default values
default_values = list(argspec.defaults)
# always remove last default value, which is port number
default_values = default_values[0:-1]
# remove an amount of arguments equals to number of default values, starting from right
args = args[0:len(args)-len(default_values)]
return args | [
"def",
"_get_netengine_arguments",
"(",
"self",
",",
"required",
"=",
"False",
")",
":",
"# inspect netengine class",
"backend_class",
"=",
"self",
".",
"_get_netengine_backend",
"(",
")",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"backend_class",
".",
"__init__",
")",
"# store args",
"args",
"=",
"argspec",
".",
"args",
"# remove known arguments",
"for",
"argument_name",
"in",
"[",
"'self'",
",",
"'host'",
",",
"'port'",
"]",
":",
"args",
".",
"remove",
"(",
"argument_name",
")",
"if",
"required",
":",
"# list of default values",
"default_values",
"=",
"list",
"(",
"argspec",
".",
"defaults",
")",
"# always remove last default value, which is port number",
"default_values",
"=",
"default_values",
"[",
"0",
":",
"-",
"1",
"]",
"# remove an amount of arguments equals to number of default values, starting from right",
"args",
"=",
"args",
"[",
"0",
":",
"len",
"(",
"args",
")",
"-",
"len",
"(",
"default_values",
")",
"]",
"return",
"args"
] | returns list of available config params
returns list of required config params if required is True
for internal use only | [
"returns",
"list",
"of",
"available",
"config",
"params",
"returns",
"list",
"of",
"required",
"config",
"params",
"if",
"required",
"is",
"True",
"for",
"internal",
"use",
"only"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L192-L216 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._get_netengine_backend | def _get_netengine_backend(self):
"""
returns the netengine backend specified in self.backend
for internal use only
"""
# extract backend class name, eg: AirOS or OpenWRT
backend_class_name = self.backend.split('.')[-1]
# convert to lowercase to get the path
backend_path = self.backend.lower()
# import module by its path
module = import_module(backend_path)
# get netengine backend class
BackendClass = getattr(module, backend_class_name)
return BackendClass | python | def _get_netengine_backend(self):
"""
returns the netengine backend specified in self.backend
for internal use only
"""
# extract backend class name, eg: AirOS or OpenWRT
backend_class_name = self.backend.split('.')[-1]
# convert to lowercase to get the path
backend_path = self.backend.lower()
# import module by its path
module = import_module(backend_path)
# get netengine backend class
BackendClass = getattr(module, backend_class_name)
return BackendClass | [
"def",
"_get_netengine_backend",
"(",
"self",
")",
":",
"# extract backend class name, eg: AirOS or OpenWRT",
"backend_class_name",
"=",
"self",
".",
"backend",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"# convert to lowercase to get the path",
"backend_path",
"=",
"self",
".",
"backend",
".",
"lower",
"(",
")",
"# import module by its path",
"module",
"=",
"import_module",
"(",
"backend_path",
")",
"# get netengine backend class",
"BackendClass",
"=",
"getattr",
"(",
"module",
",",
"backend_class_name",
")",
"return",
"BackendClass"
] | returns the netengine backend specified in self.backend
for internal use only | [
"returns",
"the",
"netengine",
"backend",
"specified",
"in",
"self",
".",
"backend",
"for",
"internal",
"use",
"only"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L218-L232 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector._build_netengine_arguments | def _build_netengine_arguments(self):
"""
returns a python dictionary representing arguments
that will be passed to a netengine backend
for internal use only
"""
arguments = {
"host": self.host
}
if self.config is not None:
for key, value in self.config.iteritems():
arguments[key] = value
if self.port:
arguments["port"] = self.port
return arguments | python | def _build_netengine_arguments(self):
"""
returns a python dictionary representing arguments
that will be passed to a netengine backend
for internal use only
"""
arguments = {
"host": self.host
}
if self.config is not None:
for key, value in self.config.iteritems():
arguments[key] = value
if self.port:
arguments["port"] = self.port
return arguments | [
"def",
"_build_netengine_arguments",
"(",
"self",
")",
":",
"arguments",
"=",
"{",
"\"host\"",
":",
"self",
".",
"host",
"}",
"if",
"self",
".",
"config",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"config",
".",
"iteritems",
"(",
")",
":",
"arguments",
"[",
"key",
"]",
"=",
"value",
"if",
"self",
".",
"port",
":",
"arguments",
"[",
"\"port\"",
"]",
"=",
"self",
".",
"port",
"return",
"arguments"
] | returns a python dictionary representing arguments
that will be passed to a netengine backend
for internal use only | [
"returns",
"a",
"python",
"dictionary",
"representing",
"arguments",
"that",
"will",
"be",
"passed",
"to",
"a",
"netengine",
"backend",
"for",
"internal",
"use",
"only"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L234-L251 |
ninuxorg/nodeshot | nodeshot/networking/connectors/models/device_connector.py | DeviceConnector.__create_device | def __create_device(self):
"""
creates device, internal use only
"""
# retrieve netengine dictionary from memory or from network
device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict())
device = Device()
device.node_id = self.node_id
device.name = device_dict['name']
device.type = device_dict['type']
device.status = DEVICE_STATUS.get('reachable')
device.os = device_dict['os']
device.os_version = device_dict['os_version']
# this is the first time the device is seen by the system because we are just adding it
device.first_seen = now()
# and is also the latest
device.last_seen = now()
device.full_clean()
device.save()
# add routing protocols
for routing_protocol in device_dict['routing_protocols']:
# retrieve routing protocol from DB
try:
rp = RoutingProtocol.objects.filter(
name__iexact=routing_protocol['name'],
version__iexact=routing_protocol['version']
)[0]
# create if doesn't exist yet
except IndexError:
rp = RoutingProtocol(
name=routing_protocol['name'],
version=routing_protocol['version']
)
rp.full_clean()
rp.save()
# add to device
device.routing_protocols.add(rp)
for interface in device_dict['interfaces']:
interface_object = False
vap_object = False
# create interface depending on type
if interface['type'] == 'ethernet':
interface_object = Ethernet(**{
'device': device,
'name': interface['name'],
'mac': interface['mac_address'],
'mtu': interface['mtu'],
'standard': interface['standard'],
'duplex': interface['duplex'],
'tx_rate': interface['tx_rate'],
'rx_rate': interface['rx_rate']
})
elif interface['type'] == 'wireless':
interface_object = Wireless(**{
'device': device,
'name': interface['name'],
'mac': interface['mac_address'],
'mtu': interface['mtu'],
'mode': interface['mode'],
'standard': interface['standard'],
'channel': interface['channel'],
'channel_width': interface['channel_width'],
'output_power': interface['output_power'],
'dbm': interface['dbm'],
'noise': interface['noise'],
'tx_rate': interface['tx_rate'],
'rx_rate': interface['rx_rate']
})
for vap in interface['vap']:
vap_object = Vap(
essid=vap['essid'],
bssid=vap['bssid'],
encryption=vap['encryption']
)
if interface_object:
interface_object.full_clean()
interface_object.save()
if vap_object:
vap_object.interface = interface_object
vap_object.full_clean()
vap_object.save()
for ip in interface['ip']:
ip_object = Ip(**{
'interface': interface_object,
'address': ip['address'],
})
ip_object.full_clean()
ip_object.save()
if HARDWARE_INSTALLED:
# try getting device model from db
try:
device_model = DeviceModel.objects.filter(name__iexact=device_dict['model'])[0]
# if it does not exist create it
except IndexError as e:
# try getting manufacturer from DB
try:
manufacturer = Manufacturer.objects.filter(name__iexact=device_dict['manufacturer'])[0]
# or create
except IndexError as e:
manufacturer = Manufacturer(name=device_dict['manufacturer'])
manufacturer.full_clean()
manufacturer.save()
device_model = DeviceModel(
manufacturer=manufacturer,
name=device_dict['model']
)
device_model.ram = device_dict['RAM_total']
device_model.full_clean()
device_model.save()
# create relation between device model and device
rel = DeviceToModelRel(device=device, model=device_model)
rel.full_clean()
rel.save()
return device | python | def __create_device(self):
"""
creates device, internal use only
"""
# retrieve netengine dictionary from memory or from network
device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict())
device = Device()
device.node_id = self.node_id
device.name = device_dict['name']
device.type = device_dict['type']
device.status = DEVICE_STATUS.get('reachable')
device.os = device_dict['os']
device.os_version = device_dict['os_version']
# this is the first time the device is seen by the system because we are just adding it
device.first_seen = now()
# and is also the latest
device.last_seen = now()
device.full_clean()
device.save()
# add routing protocols
for routing_protocol in device_dict['routing_protocols']:
# retrieve routing protocol from DB
try:
rp = RoutingProtocol.objects.filter(
name__iexact=routing_protocol['name'],
version__iexact=routing_protocol['version']
)[0]
# create if doesn't exist yet
except IndexError:
rp = RoutingProtocol(
name=routing_protocol['name'],
version=routing_protocol['version']
)
rp.full_clean()
rp.save()
# add to device
device.routing_protocols.add(rp)
for interface in device_dict['interfaces']:
interface_object = False
vap_object = False
# create interface depending on type
if interface['type'] == 'ethernet':
interface_object = Ethernet(**{
'device': device,
'name': interface['name'],
'mac': interface['mac_address'],
'mtu': interface['mtu'],
'standard': interface['standard'],
'duplex': interface['duplex'],
'tx_rate': interface['tx_rate'],
'rx_rate': interface['rx_rate']
})
elif interface['type'] == 'wireless':
interface_object = Wireless(**{
'device': device,
'name': interface['name'],
'mac': interface['mac_address'],
'mtu': interface['mtu'],
'mode': interface['mode'],
'standard': interface['standard'],
'channel': interface['channel'],
'channel_width': interface['channel_width'],
'output_power': interface['output_power'],
'dbm': interface['dbm'],
'noise': interface['noise'],
'tx_rate': interface['tx_rate'],
'rx_rate': interface['rx_rate']
})
for vap in interface['vap']:
vap_object = Vap(
essid=vap['essid'],
bssid=vap['bssid'],
encryption=vap['encryption']
)
if interface_object:
interface_object.full_clean()
interface_object.save()
if vap_object:
vap_object.interface = interface_object
vap_object.full_clean()
vap_object.save()
for ip in interface['ip']:
ip_object = Ip(**{
'interface': interface_object,
'address': ip['address'],
})
ip_object.full_clean()
ip_object.save()
if HARDWARE_INSTALLED:
# try getting device model from db
try:
device_model = DeviceModel.objects.filter(name__iexact=device_dict['model'])[0]
# if it does not exist create it
except IndexError as e:
# try getting manufacturer from DB
try:
manufacturer = Manufacturer.objects.filter(name__iexact=device_dict['manufacturer'])[0]
# or create
except IndexError as e:
manufacturer = Manufacturer(name=device_dict['manufacturer'])
manufacturer.full_clean()
manufacturer.save()
device_model = DeviceModel(
manufacturer=manufacturer,
name=device_dict['model']
)
device_model.ram = device_dict['RAM_total']
device_model.full_clean()
device_model.save()
# create relation between device model and device
rel = DeviceToModelRel(device=device, model=device_model)
rel.full_clean()
rel.save()
return device | [
"def",
"__create_device",
"(",
"self",
")",
":",
"# retrieve netengine dictionary from memory or from network",
"device_dict",
"=",
"getattr",
"(",
"self",
",",
"'netengine_dict'",
",",
"self",
".",
"netengine",
".",
"to_dict",
"(",
")",
")",
"device",
"=",
"Device",
"(",
")",
"device",
".",
"node_id",
"=",
"self",
".",
"node_id",
"device",
".",
"name",
"=",
"device_dict",
"[",
"'name'",
"]",
"device",
".",
"type",
"=",
"device_dict",
"[",
"'type'",
"]",
"device",
".",
"status",
"=",
"DEVICE_STATUS",
".",
"get",
"(",
"'reachable'",
")",
"device",
".",
"os",
"=",
"device_dict",
"[",
"'os'",
"]",
"device",
".",
"os_version",
"=",
"device_dict",
"[",
"'os_version'",
"]",
"# this is the first time the device is seen by the system because we are just adding it",
"device",
".",
"first_seen",
"=",
"now",
"(",
")",
"# and is also the latest",
"device",
".",
"last_seen",
"=",
"now",
"(",
")",
"device",
".",
"full_clean",
"(",
")",
"device",
".",
"save",
"(",
")",
"# add routing protocols",
"for",
"routing_protocol",
"in",
"device_dict",
"[",
"'routing_protocols'",
"]",
":",
"# retrieve routing protocol from DB",
"try",
":",
"rp",
"=",
"RoutingProtocol",
".",
"objects",
".",
"filter",
"(",
"name__iexact",
"=",
"routing_protocol",
"[",
"'name'",
"]",
",",
"version__iexact",
"=",
"routing_protocol",
"[",
"'version'",
"]",
")",
"[",
"0",
"]",
"# create if doesn't exist yet",
"except",
"IndexError",
":",
"rp",
"=",
"RoutingProtocol",
"(",
"name",
"=",
"routing_protocol",
"[",
"'name'",
"]",
",",
"version",
"=",
"routing_protocol",
"[",
"'version'",
"]",
")",
"rp",
".",
"full_clean",
"(",
")",
"rp",
".",
"save",
"(",
")",
"# add to device",
"device",
".",
"routing_protocols",
".",
"add",
"(",
"rp",
")",
"for",
"interface",
"in",
"device_dict",
"[",
"'interfaces'",
"]",
":",
"interface_object",
"=",
"False",
"vap_object",
"=",
"False",
"# create interface depending on type",
"if",
"interface",
"[",
"'type'",
"]",
"==",
"'ethernet'",
":",
"interface_object",
"=",
"Ethernet",
"(",
"*",
"*",
"{",
"'device'",
":",
"device",
",",
"'name'",
":",
"interface",
"[",
"'name'",
"]",
",",
"'mac'",
":",
"interface",
"[",
"'mac_address'",
"]",
",",
"'mtu'",
":",
"interface",
"[",
"'mtu'",
"]",
",",
"'standard'",
":",
"interface",
"[",
"'standard'",
"]",
",",
"'duplex'",
":",
"interface",
"[",
"'duplex'",
"]",
",",
"'tx_rate'",
":",
"interface",
"[",
"'tx_rate'",
"]",
",",
"'rx_rate'",
":",
"interface",
"[",
"'rx_rate'",
"]",
"}",
")",
"elif",
"interface",
"[",
"'type'",
"]",
"==",
"'wireless'",
":",
"interface_object",
"=",
"Wireless",
"(",
"*",
"*",
"{",
"'device'",
":",
"device",
",",
"'name'",
":",
"interface",
"[",
"'name'",
"]",
",",
"'mac'",
":",
"interface",
"[",
"'mac_address'",
"]",
",",
"'mtu'",
":",
"interface",
"[",
"'mtu'",
"]",
",",
"'mode'",
":",
"interface",
"[",
"'mode'",
"]",
",",
"'standard'",
":",
"interface",
"[",
"'standard'",
"]",
",",
"'channel'",
":",
"interface",
"[",
"'channel'",
"]",
",",
"'channel_width'",
":",
"interface",
"[",
"'channel_width'",
"]",
",",
"'output_power'",
":",
"interface",
"[",
"'output_power'",
"]",
",",
"'dbm'",
":",
"interface",
"[",
"'dbm'",
"]",
",",
"'noise'",
":",
"interface",
"[",
"'noise'",
"]",
",",
"'tx_rate'",
":",
"interface",
"[",
"'tx_rate'",
"]",
",",
"'rx_rate'",
":",
"interface",
"[",
"'rx_rate'",
"]",
"}",
")",
"for",
"vap",
"in",
"interface",
"[",
"'vap'",
"]",
":",
"vap_object",
"=",
"Vap",
"(",
"essid",
"=",
"vap",
"[",
"'essid'",
"]",
",",
"bssid",
"=",
"vap",
"[",
"'bssid'",
"]",
",",
"encryption",
"=",
"vap",
"[",
"'encryption'",
"]",
")",
"if",
"interface_object",
":",
"interface_object",
".",
"full_clean",
"(",
")",
"interface_object",
".",
"save",
"(",
")",
"if",
"vap_object",
":",
"vap_object",
".",
"interface",
"=",
"interface_object",
"vap_object",
".",
"full_clean",
"(",
")",
"vap_object",
".",
"save",
"(",
")",
"for",
"ip",
"in",
"interface",
"[",
"'ip'",
"]",
":",
"ip_object",
"=",
"Ip",
"(",
"*",
"*",
"{",
"'interface'",
":",
"interface_object",
",",
"'address'",
":",
"ip",
"[",
"'address'",
"]",
",",
"}",
")",
"ip_object",
".",
"full_clean",
"(",
")",
"ip_object",
".",
"save",
"(",
")",
"if",
"HARDWARE_INSTALLED",
":",
"# try getting device model from db",
"try",
":",
"device_model",
"=",
"DeviceModel",
".",
"objects",
".",
"filter",
"(",
"name__iexact",
"=",
"device_dict",
"[",
"'model'",
"]",
")",
"[",
"0",
"]",
"# if it does not exist create it",
"except",
"IndexError",
"as",
"e",
":",
"# try getting manufacturer from DB",
"try",
":",
"manufacturer",
"=",
"Manufacturer",
".",
"objects",
".",
"filter",
"(",
"name__iexact",
"=",
"device_dict",
"[",
"'manufacturer'",
"]",
")",
"[",
"0",
"]",
"# or create",
"except",
"IndexError",
"as",
"e",
":",
"manufacturer",
"=",
"Manufacturer",
"(",
"name",
"=",
"device_dict",
"[",
"'manufacturer'",
"]",
")",
"manufacturer",
".",
"full_clean",
"(",
")",
"manufacturer",
".",
"save",
"(",
")",
"device_model",
"=",
"DeviceModel",
"(",
"manufacturer",
"=",
"manufacturer",
",",
"name",
"=",
"device_dict",
"[",
"'model'",
"]",
")",
"device_model",
".",
"ram",
"=",
"device_dict",
"[",
"'RAM_total'",
"]",
"device_model",
".",
"full_clean",
"(",
")",
"device_model",
".",
"save",
"(",
")",
"# create relation between device model and device",
"rel",
"=",
"DeviceToModelRel",
"(",
"device",
"=",
"device",
",",
"model",
"=",
"device_model",
")",
"rel",
".",
"full_clean",
"(",
")",
"rel",
".",
"save",
"(",
")",
"return",
"device"
] | creates device, internal use only | [
"creates",
"device",
"internal",
"use",
"only"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L259-L383 |
ninuxorg/nodeshot | nodeshot/core/base/cache.py | cache_by_group | def cache_by_group(view_instance, view_method, request, args, kwargs):
"""
Cache view response by media type and user group.
The cache_key is constructed this way: "{view_name:path.group.media_type}"
EG: "MenuList:/api/v1/menu/.public.application/json"
Possible groups are:
* public
* superuser
* the rest are retrieved from DB (registered, community, trusted are the default ones)
"""
if request.user.is_anonymous():
group = 'public'
elif request.user.is_superuser:
group = 'superuser'
else:
try:
group = request.user.groups.all().order_by('-id').first().name
except IndexError:
group = 'public'
key = '%s:%s.%s.%s' % (
view_instance.__class__.__name__,
request.META['PATH_INFO'],
group,
request.accepted_media_type
)
return key | python | def cache_by_group(view_instance, view_method, request, args, kwargs):
"""
Cache view response by media type and user group.
The cache_key is constructed this way: "{view_name:path.group.media_type}"
EG: "MenuList:/api/v1/menu/.public.application/json"
Possible groups are:
* public
* superuser
* the rest are retrieved from DB (registered, community, trusted are the default ones)
"""
if request.user.is_anonymous():
group = 'public'
elif request.user.is_superuser:
group = 'superuser'
else:
try:
group = request.user.groups.all().order_by('-id').first().name
except IndexError:
group = 'public'
key = '%s:%s.%s.%s' % (
view_instance.__class__.__name__,
request.META['PATH_INFO'],
group,
request.accepted_media_type
)
return key | [
"def",
"cache_by_group",
"(",
"view_instance",
",",
"view_method",
",",
"request",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"request",
".",
"user",
".",
"is_anonymous",
"(",
")",
":",
"group",
"=",
"'public'",
"elif",
"request",
".",
"user",
".",
"is_superuser",
":",
"group",
"=",
"'superuser'",
"else",
":",
"try",
":",
"group",
"=",
"request",
".",
"user",
".",
"groups",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"'-id'",
")",
".",
"first",
"(",
")",
".",
"name",
"except",
"IndexError",
":",
"group",
"=",
"'public'",
"key",
"=",
"'%s:%s.%s.%s'",
"%",
"(",
"view_instance",
".",
"__class__",
".",
"__name__",
",",
"request",
".",
"META",
"[",
"'PATH_INFO'",
"]",
",",
"group",
",",
"request",
".",
"accepted_media_type",
")",
"return",
"key"
] | Cache view response by media type and user group.
The cache_key is constructed this way: "{view_name:path.group.media_type}"
EG: "MenuList:/api/v1/menu/.public.application/json"
Possible groups are:
* public
* superuser
* the rest are retrieved from DB (registered, community, trusted are the default ones) | [
"Cache",
"view",
"response",
"by",
"media",
"type",
"and",
"user",
"group",
".",
"The",
"cache_key",
"is",
"constructed",
"this",
"way",
":",
"{",
"view_name",
":",
"path",
".",
"group",
".",
"media_type",
"}",
"EG",
":",
"MenuList",
":",
"/",
"api",
"/",
"v1",
"/",
"menu",
"/",
".",
"public",
".",
"application",
"/",
"json",
"Possible",
"groups",
"are",
":",
"*",
"public",
"*",
"superuser",
"*",
"the",
"rest",
"are",
"retrieved",
"from",
"DB",
"(",
"registered",
"community",
"trusted",
"are",
"the",
"default",
"ones",
")"
] | train | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/cache.py#L16-L43 |
bcwaldon/warlock | warlock/core.py | model_factory | def model_factory(schema, resolver=None, base_class=model.Model, name=None):
"""Generate a model class based on the provided JSON Schema
:param schema: dict representing valid JSON schema
:param name: A name to give the class, if `name` is not in `schema`
"""
schema = copy.deepcopy(schema)
resolver = resolver
class Model(base_class):
def __init__(self, *args, **kwargs):
self.__dict__['schema'] = schema
self.__dict__['resolver'] = resolver
base_class.__init__(self, *args, **kwargs)
if resolver is not None:
Model.resolver = resolver
if name is not None:
Model.__name__ = name
elif 'name' in schema:
Model.__name__ = str(schema['name'])
return Model | python | def model_factory(schema, resolver=None, base_class=model.Model, name=None):
"""Generate a model class based on the provided JSON Schema
:param schema: dict representing valid JSON schema
:param name: A name to give the class, if `name` is not in `schema`
"""
schema = copy.deepcopy(schema)
resolver = resolver
class Model(base_class):
def __init__(self, *args, **kwargs):
self.__dict__['schema'] = schema
self.__dict__['resolver'] = resolver
base_class.__init__(self, *args, **kwargs)
if resolver is not None:
Model.resolver = resolver
if name is not None:
Model.__name__ = name
elif 'name' in schema:
Model.__name__ = str(schema['name'])
return Model | [
"def",
"model_factory",
"(",
"schema",
",",
"resolver",
"=",
"None",
",",
"base_class",
"=",
"model",
".",
"Model",
",",
"name",
"=",
"None",
")",
":",
"schema",
"=",
"copy",
".",
"deepcopy",
"(",
"schema",
")",
"resolver",
"=",
"resolver",
"class",
"Model",
"(",
"base_class",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__dict__",
"[",
"'schema'",
"]",
"=",
"schema",
"self",
".",
"__dict__",
"[",
"'resolver'",
"]",
"=",
"resolver",
"base_class",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resolver",
"is",
"not",
"None",
":",
"Model",
".",
"resolver",
"=",
"resolver",
"if",
"name",
"is",
"not",
"None",
":",
"Model",
".",
"__name__",
"=",
"name",
"elif",
"'name'",
"in",
"schema",
":",
"Model",
".",
"__name__",
"=",
"str",
"(",
"schema",
"[",
"'name'",
"]",
")",
"return",
"Model"
] | Generate a model class based on the provided JSON Schema
:param schema: dict representing valid JSON schema
:param name: A name to give the class, if `name` is not in `schema` | [
"Generate",
"a",
"model",
"class",
"based",
"on",
"the",
"provided",
"JSON",
"Schema"
] | train | https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/core.py#L22-L44 |
bcwaldon/warlock | warlock/model.py | Model.patch | def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() | python | def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() | [
"def",
"patch",
"(",
"self",
")",
":",
"original",
"=",
"self",
".",
"__dict__",
"[",
"'__original__'",
"]",
"return",
"jsonpatch",
".",
"make_patch",
"(",
"original",
",",
"dict",
"(",
"self",
")",
")",
".",
"to_string",
"(",
")"
] | Return a jsonpatch object representing the delta | [
"Return",
"a",
"jsonpatch",
"object",
"representing",
"the",
"delta"
] | train | https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L125-L128 |
bcwaldon/warlock | warlock/model.py | Model.changes | def changes(self):
"""Dumber version of 'patch' method"""
deprecation_msg = 'Model.changes will be removed in warlock v2'
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
return copy.deepcopy(self.__dict__['changes']) | python | def changes(self):
"""Dumber version of 'patch' method"""
deprecation_msg = 'Model.changes will be removed in warlock v2'
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
return copy.deepcopy(self.__dict__['changes']) | [
"def",
"changes",
"(",
"self",
")",
":",
"deprecation_msg",
"=",
"'Model.changes will be removed in warlock v2'",
"warnings",
".",
"warn",
"(",
"deprecation_msg",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"__dict__",
"[",
"'changes'",
"]",
")"
] | Dumber version of 'patch' method | [
"Dumber",
"version",
"of",
"patch",
"method"
] | train | https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L131-L135 |
bcwaldon/warlock | warlock/model.py | Model.validate | def validate(self, obj):
"""Apply a JSON schema to an object"""
try:
if self.resolver is not None:
jsonschema.validate(obj, self.schema, resolver=self.resolver)
else:
jsonschema.validate(obj, self.schema)
except jsonschema.ValidationError as exc:
raise exceptions.ValidationError(str(exc)) | python | def validate(self, obj):
"""Apply a JSON schema to an object"""
try:
if self.resolver is not None:
jsonschema.validate(obj, self.schema, resolver=self.resolver)
else:
jsonschema.validate(obj, self.schema)
except jsonschema.ValidationError as exc:
raise exceptions.ValidationError(str(exc)) | [
"def",
"validate",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"if",
"self",
".",
"resolver",
"is",
"not",
"None",
":",
"jsonschema",
".",
"validate",
"(",
"obj",
",",
"self",
".",
"schema",
",",
"resolver",
"=",
"self",
".",
"resolver",
")",
"else",
":",
"jsonschema",
".",
"validate",
"(",
"obj",
",",
"self",
".",
"schema",
")",
"except",
"jsonschema",
".",
"ValidationError",
"as",
"exc",
":",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"str",
"(",
"exc",
")",
")"
] | Apply a JSON schema to an object | [
"Apply",
"a",
"JSON",
"schema",
"to",
"an",
"object"
] | train | https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L137-L145 |
sashs/filebytes | filebytes/mach_o.py | MachO.isSupportedContent | def isSupportedContent(cls, fileContent):
"""Returns if the files are valid for this filetype"""
magic = bytearray(fileContent)[:4]
return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p('<I', 0xfeedfacf) | python | def isSupportedContent(cls, fileContent):
"""Returns if the files are valid for this filetype"""
magic = bytearray(fileContent)[:4]
return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p('<I', 0xfeedfacf) | [
"def",
"isSupportedContent",
"(",
"cls",
",",
"fileContent",
")",
":",
"magic",
"=",
"bytearray",
"(",
"fileContent",
")",
"[",
":",
"4",
"]",
"return",
"magic",
"==",
"p",
"(",
"'>I'",
",",
"0xfeedface",
")",
"or",
"magic",
"==",
"p",
"(",
"'>I'",
",",
"0xfeedfacf",
")",
"or",
"magic",
"==",
"p",
"(",
"'<I'",
",",
"0xfeedface",
")",
"or",
"magic",
"==",
"p",
"(",
"'<I'",
",",
"0xfeedfacf",
")"
] | Returns if the files are valid for this filetype | [
"Returns",
"if",
"the",
"files",
"are",
"valid",
"for",
"this",
"filetype"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/mach_o.py#L476-L479 |
sashs/filebytes | filebytes/oat.py | OAT._parseOatHeader | def _parseOatHeader(self, data):
"""Returns the OatHeader"""
header = OatHeader.from_buffer(data)
if header.magic != b'oat\n':
raise BinaryError('No valid OAT file')
key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(OatHeader))
key_value_store = self.__parseKeyValueStore(key_value_store_bytes)
return OatHeaderData(header=header, keyValueStoreRaw=key_value_store_bytes, keyValueStore=key_value_store) | python | def _parseOatHeader(self, data):
"""Returns the OatHeader"""
header = OatHeader.from_buffer(data)
if header.magic != b'oat\n':
raise BinaryError('No valid OAT file')
key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(OatHeader))
key_value_store = self.__parseKeyValueStore(key_value_store_bytes)
return OatHeaderData(header=header, keyValueStoreRaw=key_value_store_bytes, keyValueStore=key_value_store) | [
"def",
"_parseOatHeader",
"(",
"self",
",",
"data",
")",
":",
"header",
"=",
"OatHeader",
".",
"from_buffer",
"(",
"data",
")",
"if",
"header",
".",
"magic",
"!=",
"b'oat\\n'",
":",
"raise",
"BinaryError",
"(",
"'No valid OAT file'",
")",
"key_value_store_bytes",
"=",
"(",
"c_ubyte",
"*",
"header",
".",
"keyValueStoreSize",
")",
".",
"from_buffer",
"(",
"data",
",",
"sizeof",
"(",
"OatHeader",
")",
")",
"key_value_store",
"=",
"self",
".",
"__parseKeyValueStore",
"(",
"key_value_store_bytes",
")",
"return",
"OatHeaderData",
"(",
"header",
"=",
"header",
",",
"keyValueStoreRaw",
"=",
"key_value_store_bytes",
",",
"keyValueStore",
"=",
"key_value_store",
")"
] | Returns the OatHeader | [
"Returns",
"the",
"OatHeader"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/oat.py#L169-L178 |
sashs/filebytes | filebytes/oat.py | OAT.__parseKeyValueStore | def __parseKeyValueStore(self, data):
"""Returns a dictionary filled with the keys and values of the key value store"""
offset = 0
key_value_store = {}
while offset != len(data):
key = get_str(data, offset)
offset += len(key)+1
value = get_str(data, offset)
offset += len(value)+1
key_value_store[key] = value
return key_value_store | python | def __parseKeyValueStore(self, data):
"""Returns a dictionary filled with the keys and values of the key value store"""
offset = 0
key_value_store = {}
while offset != len(data):
key = get_str(data, offset)
offset += len(key)+1
value = get_str(data, offset)
offset += len(value)+1
key_value_store[key] = value
return key_value_store | [
"def",
"__parseKeyValueStore",
"(",
"self",
",",
"data",
")",
":",
"offset",
"=",
"0",
"key_value_store",
"=",
"{",
"}",
"while",
"offset",
"!=",
"len",
"(",
"data",
")",
":",
"key",
"=",
"get_str",
"(",
"data",
",",
"offset",
")",
"offset",
"+=",
"len",
"(",
"key",
")",
"+",
"1",
"value",
"=",
"get_str",
"(",
"data",
",",
"offset",
")",
"offset",
"+=",
"len",
"(",
"value",
")",
"+",
"1",
"key_value_store",
"[",
"key",
"]",
"=",
"value",
"return",
"key_value_store"
] | Returns a dictionary filled with the keys and values of the key value store | [
"Returns",
"a",
"dictionary",
"filled",
"with",
"the",
"keys",
"and",
"values",
"of",
"the",
"key",
"value",
"store"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/oat.py#L180-L193 |
sashs/filebytes | filebytes/pe.py | to_raw_address | def to_raw_address(addr, section):
"""Converts the addr from a rva to a pointer to raw data in the file"""
return addr - section.header.VirtualAddress + section.header.PointerToRawData | python | def to_raw_address(addr, section):
"""Converts the addr from a rva to a pointer to raw data in the file"""
return addr - section.header.VirtualAddress + section.header.PointerToRawData | [
"def",
"to_raw_address",
"(",
"addr",
",",
"section",
")",
":",
"return",
"addr",
"-",
"section",
".",
"header",
".",
"VirtualAddress",
"+",
"section",
".",
"header",
".",
"PointerToRawData"
] | Converts the addr from a rva to a pointer to raw data in the file | [
"Converts",
"the",
"addr",
"from",
"a",
"rva",
"to",
"a",
"pointer",
"to",
"raw",
"data",
"in",
"the",
"file"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L356-L358 |
sashs/filebytes | filebytes/pe.py | PE._getSuitableClasses | def _getSuitableClasses(self, data, imageDosHeader):
"""Returns the class which holds the suitable classes for the loaded file"""
classes = None
machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_lfanew+4).value]
if machine == IMAGE_FILE_MACHINE.I386:
classes = PE32
elif machine == IMAGE_FILE_MACHINE.AMD64:
classes = PE64
return classes | python | def _getSuitableClasses(self, data, imageDosHeader):
"""Returns the class which holds the suitable classes for the loaded file"""
classes = None
machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_lfanew+4).value]
if machine == IMAGE_FILE_MACHINE.I386:
classes = PE32
elif machine == IMAGE_FILE_MACHINE.AMD64:
classes = PE64
return classes | [
"def",
"_getSuitableClasses",
"(",
"self",
",",
"data",
",",
"imageDosHeader",
")",
":",
"classes",
"=",
"None",
"machine",
"=",
"IMAGE_FILE_MACHINE",
"[",
"c_ushort",
".",
"from_buffer",
"(",
"data",
",",
"imageDosHeader",
".",
"header",
".",
"e_lfanew",
"+",
"4",
")",
".",
"value",
"]",
"if",
"machine",
"==",
"IMAGE_FILE_MACHINE",
".",
"I386",
":",
"classes",
"=",
"PE32",
"elif",
"machine",
"==",
"IMAGE_FILE_MACHINE",
".",
"AMD64",
":",
"classes",
"=",
"PE64",
"return",
"classes"
] | Returns the class which holds the suitable classes for the loaded file | [
"Returns",
"the",
"class",
"which",
"holds",
"the",
"suitable",
"classes",
"for",
"the",
"loaded",
"file"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L486-L496 |
sashs/filebytes | filebytes/pe.py | PE._parseImageDosHeader | def _parseImageDosHeader(self, data):
"""Returns the ImageDosHeader"""
ioh = IMAGE_DOS_HEADER.from_buffer(data)
if ioh.e_magic != b'MZ':
raise BinaryError('No valid PE/COFF file')
return ImageDosHeaderData(header=ioh) | python | def _parseImageDosHeader(self, data):
"""Returns the ImageDosHeader"""
ioh = IMAGE_DOS_HEADER.from_buffer(data)
if ioh.e_magic != b'MZ':
raise BinaryError('No valid PE/COFF file')
return ImageDosHeaderData(header=ioh) | [
"def",
"_parseImageDosHeader",
"(",
"self",
",",
"data",
")",
":",
"ioh",
"=",
"IMAGE_DOS_HEADER",
".",
"from_buffer",
"(",
"data",
")",
"if",
"ioh",
".",
"e_magic",
"!=",
"b'MZ'",
":",
"raise",
"BinaryError",
"(",
"'No valid PE/COFF file'",
")",
"return",
"ImageDosHeaderData",
"(",
"header",
"=",
"ioh",
")"
] | Returns the ImageDosHeader | [
"Returns",
"the",
"ImageDosHeader"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L498-L504 |
sashs/filebytes | filebytes/pe.py | PE._parseImageNtHeaders | def _parseImageNtHeaders(self, data, imageDosHeader):
"""Returns the ImageNtHeaders"""
inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew)
if inth.Signature != b'PE':
raise BinaryError('No valid PE/COFF file')
return ImageNtHeaderData(header=inth) | python | def _parseImageNtHeaders(self, data, imageDosHeader):
"""Returns the ImageNtHeaders"""
inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew)
if inth.Signature != b'PE':
raise BinaryError('No valid PE/COFF file')
return ImageNtHeaderData(header=inth) | [
"def",
"_parseImageNtHeaders",
"(",
"self",
",",
"data",
",",
"imageDosHeader",
")",
":",
"inth",
"=",
"self",
".",
"_classes",
".",
"IMAGE_NT_HEADERS",
".",
"from_buffer",
"(",
"data",
",",
"imageDosHeader",
".",
"header",
".",
"e_lfanew",
")",
"if",
"inth",
".",
"Signature",
"!=",
"b'PE'",
":",
"raise",
"BinaryError",
"(",
"'No valid PE/COFF file'",
")",
"return",
"ImageNtHeaderData",
"(",
"header",
"=",
"inth",
")"
] | Returns the ImageNtHeaders | [
"Returns",
"the",
"ImageNtHeaders"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L506-L513 |
sashs/filebytes | filebytes/pe.py | PE._parseSections | def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False):
"""Parses the sections in the memory and returns a list of them"""
sections = []
optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER)
offset = optional_header_offset + imageNtHeaders.header.FileHeader.SizeOfOptionalHeader # start reading behind the dos- and ntheaders
image_section_header_size = sizeof(IMAGE_SECTION_HEADER)
for sectionNo in range(imageNtHeaders.header.FileHeader.NumberOfSections):
ishdr = IMAGE_SECTION_HEADER.from_buffer(data, offset)
if parse_header_only:
raw = None
bytes_ = bytearray()
else:
size = ishdr.SizeOfRawData
raw = (c_ubyte * size).from_buffer(data, ishdr.PointerToRawData)
bytes_ = bytearray(raw)
sections.append(SectionData(header=ishdr, name=ishdr.Name.decode('ASCII', errors='ignore'), bytes=bytes_, raw=raw))
offset += image_section_header_size
return sections | python | def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False):
"""Parses the sections in the memory and returns a list of them"""
sections = []
optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER)
offset = optional_header_offset + imageNtHeaders.header.FileHeader.SizeOfOptionalHeader # start reading behind the dos- and ntheaders
image_section_header_size = sizeof(IMAGE_SECTION_HEADER)
for sectionNo in range(imageNtHeaders.header.FileHeader.NumberOfSections):
ishdr = IMAGE_SECTION_HEADER.from_buffer(data, offset)
if parse_header_only:
raw = None
bytes_ = bytearray()
else:
size = ishdr.SizeOfRawData
raw = (c_ubyte * size).from_buffer(data, ishdr.PointerToRawData)
bytes_ = bytearray(raw)
sections.append(SectionData(header=ishdr, name=ishdr.Name.decode('ASCII', errors='ignore'), bytes=bytes_, raw=raw))
offset += image_section_header_size
return sections | [
"def",
"_parseSections",
"(",
"self",
",",
"data",
",",
"imageDosHeader",
",",
"imageNtHeaders",
",",
"parse_header_only",
"=",
"False",
")",
":",
"sections",
"=",
"[",
"]",
"optional_header_offset",
"=",
"imageDosHeader",
".",
"header",
".",
"e_lfanew",
"+",
"4",
"+",
"sizeof",
"(",
"IMAGE_FILE_HEADER",
")",
"offset",
"=",
"optional_header_offset",
"+",
"imageNtHeaders",
".",
"header",
".",
"FileHeader",
".",
"SizeOfOptionalHeader",
"# start reading behind the dos- and ntheaders",
"image_section_header_size",
"=",
"sizeof",
"(",
"IMAGE_SECTION_HEADER",
")",
"for",
"sectionNo",
"in",
"range",
"(",
"imageNtHeaders",
".",
"header",
".",
"FileHeader",
".",
"NumberOfSections",
")",
":",
"ishdr",
"=",
"IMAGE_SECTION_HEADER",
".",
"from_buffer",
"(",
"data",
",",
"offset",
")",
"if",
"parse_header_only",
":",
"raw",
"=",
"None",
"bytes_",
"=",
"bytearray",
"(",
")",
"else",
":",
"size",
"=",
"ishdr",
".",
"SizeOfRawData",
"raw",
"=",
"(",
"c_ubyte",
"*",
"size",
")",
".",
"from_buffer",
"(",
"data",
",",
"ishdr",
".",
"PointerToRawData",
")",
"bytes_",
"=",
"bytearray",
"(",
"raw",
")",
"sections",
".",
"append",
"(",
"SectionData",
"(",
"header",
"=",
"ishdr",
",",
"name",
"=",
"ishdr",
".",
"Name",
".",
"decode",
"(",
"'ASCII'",
",",
"errors",
"=",
"'ignore'",
")",
",",
"bytes",
"=",
"bytes_",
",",
"raw",
"=",
"raw",
")",
")",
"offset",
"+=",
"image_section_header_size",
"return",
"sections"
] | Parses the sections in the memory and returns a list of them | [
"Parses",
"the",
"sections",
"in",
"the",
"memory",
"and",
"returns",
"a",
"list",
"of",
"them"
] | train | https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L515-L539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.