output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def validate(self, attrs):
""" checks if login credentials are correct """
user = authenticate(**self.user_credentials(attrs))
if user:
if user.is_active:
self.instance = user
else:
raise serializers.ValidationError(_("This account is curr... | Write a Python 3 function for
checking if login credentials are correct | As a python code expert, you are capable of creating scripts from specifications. |
Get details url for a user | How would you explain what the following Python 3 function does
def get_details(self, obj):
return reverse('api_user_social_links_detail',
args=[obj.user.username, obj.pk],
request=self.context.get('request'),
format=self.context.get('format')... | As a Python code translator, you convert algorithms and pseudocode into Python. |
get user s location | Can you tell what is the following Python 3 function doing
def get_location(self, obj):
if not obj.city and not obj.country:
return None
elif obj.city and obj.country:
return '%s, %s' % (obj.city, obj.country)
elif obj.city or obj.country:
return obj.city or o... | As a Python code composer, you craft elegant and concise scripts. |
ensure email is in the database | Explain what the following Python 3 code does
def validate_email(self, value):
if EMAIL_CONFIRMATION:
queryset = EmailAddress.objects.filter(email__iexact=value, verified=True)
else:
queryset = User.objects.get(email__iexact=value, is_active=True).count() == 0
if queryset... | You are a Python code architect, reviewing and designing scalable and efficient code |
update user with new password | Given the following Python 3 function, write the documentation
def update(self, instance, validated_data):
instance.user.set_password(validated_data["password1"])
instance.user.full_clean()
instance.user.save()
# mark password reset object as reset
instance.reset = True
i... | As a Python code composer, you craft elegant and concise scripts. |
Custom save method that automatically inherit node coordinates and elevation and shortcuts if HSTORE is enabled. | Can you tell what is the following Python 3 function doing
def save(self, *args, **kwargs):
custom_checks = kwargs.pop('custom_checks', True)
super(Device, self).save(*args, **kwargs)
if custom_checks is False:
return
changed = False
if not self.location:
... | As a Python code composer, you craft elegant and concise scripts. |
create password reset for specified user | Explain what the following Python 3 code does
def create_for_user(self, user):
# support passing email address too
if type(user) is unicode:
from .profile import Profile as User
user = User.objects.get(email=user)
temp_key = token_generator.make_token(user)
# sa... | As a Python code analyst, you investigate and solve complex coding mysteries |
def prompt_layer_selection(self, node, layers):
"""Ask user what to do when an old node is contained in more than one layer.
Possible answers are:
* use default layer (default answer if pressing enter)
* choose layer
* discard node
"""
valid = {
... | Implement a function in Python 3 to
prompt user what to do when an old node is contained in more than one layer. | As a python code expert, you are capable of creating scripts from specifications. |
def check_status_mapping(self):
""" ensure status map does not contain status values which are not present in DB """
self.verbose('checking status mapping...')
if not self.status_mapping:
self.message('no status mapping found')
return
for old_val, new_val in sel... | Implement a function in Python 3 to
ensure status map does not contain status values which are not present in DB | You are a Python code architect, reviewing and designing scalable and efficient code |
retrieve nodes from old mysql DB | Can you tell what is the following Python 3 function doing
def retrieve_nodes(self):
self.verbose('retrieving nodes from old mysql DB...')
self.old_nodes = list(OldNode.objects.all())
self.message('retrieved %d nodes' % len(self.old_nodes)) | You are a Python code analyst, evaluating scripts for potential improvements. |
extract user info from retrieved nodes | Make a summary of the following Python 3 code
def extract_users(self):
email_set = set()
users_dict = {}
self.verbose('going to extract user information from retrieved nodes...')
for node in self.old_nodes:
email_set.add(node.email)
if node.email not in users_d... | As a python code expert, you are capable of creating scripts from specifications. |
def import_admins(self):
""" save admins to local DB """
self.message('saving admins into local DB')
saved_admins = []
for olduser in OldUser.objects.all():
try:
user = User.objects.get(Q(username=olduser.username) | Q(email=olduser.email))
excep... | Write a Python 3 function for
saving admins into local DB | You are a Python code generator, capable of creating scripts from specifications. |
def import_users(self):
""" save users to local DB """
self.message('saving users into local DB')
saved_users = self.saved_admins
# loop over all extracted unique email addresses
for email in self.email_set:
owner = self.users_dict[email].get('owner')
#... | Create a Python 3 function to
import users into DB | As a Python code translator, you convert algorithms and pseudocode into Python. |
import nodes into local DB | Can you generate a brief explanation for the following Python 3 code
def import_nodes(self):
self.message('saving nodes into local DB...')
saved_nodes = []
# loop over all old node and create new nodes
for old_node in self.old_nodes:
# if this old node is unconfirmed skip t... | You are a Python code generator, capable of creating scripts from specifications. |
delete imported nodes that are not present in the old database | Can you tell what is the following Python 3 function doing
def check_deleted_nodes(self):
imported_nodes = Node.objects.filter(data__contains=['imported'])
deleted_nodes = []
for node in imported_nodes:
if OldNode.objects.filter(pk=node.pk).count() == 0:
user = node.... | You are a Python code architect, reviewing and designing scalable and efficient code |
create user notification settings on user creation | Given the following Python 3 function, write the documentation
def create_settings(sender, **kwargs):
created = kwargs['created']
user = kwargs['instance']
if created:
UserWebNotificationSettings.objects.create(user=user)
UserEmailNotificationSettings.objects.create(user=user) | As a Python code analyst, you investigate and solve complex coding mysteries |
Add user info to ExtensibleNodeSerializer | Here you have a function in Python 3, explain what it does
def ready(self):
from nodeshot.core.nodes.base import ExtensibleNodeSerializer
from .serializers import ProfileRelationSerializer
ExtensibleNodeSerializer.add_relationship(
name='user',
serializer=ProfileRelation... | As a python code expert, you are capable of creating scripts from specifications. |
def parse(self):
""" parse geojson and ensure is collection """
try:
self.parsed_data = json.loads(self.data)
except UnicodeError as e:
self.parsed_data = json.loads(self.data.decode('latin1'))
except Exception as e:
raise Exception('Error while conver... | Implement a Python 3 function for
parsing geojson and ensure is collection | As a python code expert, you are capable of creating scripts from specifications. |
Adds a relationship to the given serializer. | Given the following Python 3 function, write the documentation
def add_relationship(_class, name,
view_name=None, lookup_field=None,
serializer=None, many=False, queryset=None,
function=None):
""" adds a relationship to serializer
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieve old notifications from the database. | Can you generate a brief explanation for the following Python 3 code
def retrieve_old_notifications(self):
date = ago(days=DELETE_OLD)
return Notification.objects.filter(added__lte=date) | As a Python code translator, you convert algorithms and pseudocode into Python. |
writes message to the pipe | Can you generate the documentation for the following Python 3 function
def send_message(message, pipe='public'):
if pipe not in ['public', 'private']:
raise ValueError('pipe argument can be only "public" or "private"')
else:
pipe = pipe.upper()
pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' el... | As a python code expert, you are capable of creating scripts from specifications. |
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 requir... | Create a Python 3 function for
creating user in the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load extra data from provider and store it on current UserSocialAuth extra_data field. | Here you have a function in Python 3, explain what it does
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:... | You are a Python code analyst, evaluating scripts for potential improvements. |
custom validation for the from_name and from_email attributes | Here you have a function in Python 3, explain what it does
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 s... | As a Python code composer, you craft elegant and concise scripts. |
Sends the email to the recipient | Here you have a function in Python 3, explain what it does
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 w... | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Can you create a Python 3 function that
returns n objects according to specified ordering | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
... | Create a Python 3 function for
returning all items that have an access level lower than or lower than the specified value | As a Python code composer, you craft elegant and concise scripts. |
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_q... | How would you implement a function in Python 3 that
returns all the items that are accessible to the specified user | As a Python code analyst, you investigate and solve complex coding mysteries |
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 defau... | Can you implement a function in Python 3 that
intercepts changes to is_default | As a python code expert, you are capable of creating scripts from specifications. |
patch LayerNodesList view to support external layers | Can you tell what is the following Python 3 function doing
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
exce... | As a Python code composer, you craft elegant and concise scripts. |
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 wh... | Can you implement a function in Python 3 that
returns a list of recipients for the current node and the current level of the user. | As a Python code composer, you craft elegant and concise scripts. |
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... | Can you create a Python 3 function that
sends the email to the recipients and returns True if the email was successfully sent False otherwise. | You are a Python code generator, capable of creating scripts from specifications. |
Custom save method for the node object. | Can you generate a brief explanation for the following Python 3 code
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 ... | As a Python code composer, you craft elegant and concise scripts. |
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
"""
metho... | Implement a Python 3 function for
extending validation of a Node by adding a function to the _additional_validation list. | You are a Python code generator, capable of creating scripts from specifications. |
returns location of node in the geometry | How would you explain what the following Python 3 function does
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:... | As a Python code composer, you craft elegant and concise scripts. |
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 i... | Implement a function in Python 3 to
return a Google Elevation profile for the specified resource. | You are a Python code architect, reviewing and designing scalable and efficient code |
def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) | Write a Python 3 script to
determine user when node is added | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a queryset of all nodes which are published and accessible to current user. | Can you generate the documentation for the following Python 3 function
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', 'laye... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 el... | Can you write a function in Python 3 where it
creates notifications in a background job to avoid slowing down users | As a Python code analyst, you investigate and solve complex coding mysteries |
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
... | Implement a function in Python 3 to
return a list of all the available resources of this RESTful API. | You are a Python code architect, reviewing and designing scalable and efficient code |
Custom save method does the following : | Make a summary of the following Python 3 code
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'... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Implement a function in Python 3 to
set the ip_addresses field | As a Python code composer, you craft elegant and concise scripts. |
Check if comments can be inserted for this node or layer | Make a summary of the following Python 3 code
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:
rais... | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve specified layers or all external layers if no layer specified. | Can you generate a brief explanation for the following Python 3 code
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()
... | You are a Python code analyst, evaluating scripts for potential improvements. |
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_v... | Implement a function in Python 3 to
ensure users cannot vote the same node multiple times and let users change their votes | As a Python code composer, you craft elegant and concise scripts. |
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() | Implement a Python 3 function for
updating likes and dislikes count | As a Python code translator, you convert algorithms and pseudocode into 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(... | Can you create a Python 3 function that
checks if votes can be inserted for this node or parent layer | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve basic whois information related to a layer2 or layer3 network address. | Make a summary of the following Python 3 code
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({
'ad... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 Add... | Implement a function in Python 3 to
retrieve basic whois information related to a network address. | As a python code expert, you are capable of creating scripts from specifications. |
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 = su... | Implement a Python 3 function for
returning a queryset of all devices which are published and accessible to current user. | You are a Python code generator, capable of creating scripts from specifications. |
Custom initial method for base class base interfaces. | Can you generate a brief explanation for the following Python 3 code
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)\
... | You are a Python code generator, capable of creating scripts from specifications. |
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:
... | Can you write a function in Python 3 where it
gives a dict of kwargs pull out the group and bridge from the database and return the group and bridge. | As a Python code composer, you craft elegant and concise scripts. |
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 eventua... | Write a Python 3 function that can
save the object to the database. | You are a Python code architect, reviewing and designing scalable and efficient code |
if order left blank | Can you generate the documentation for the following Python 3 function
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.orde... | You are a Python code generator, capable of creating scripts from specifications. |
Checks that the dependencies of a module are listed in settings. INSTALLED_APPS | Here you have a function in Python 3, explain what it does
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 dep... | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a readable python dictionary into a django model / form
choice structure ordered based on the values of each key in the dictionary | Given the following Python 3 function, write the documentation
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 = (dictionar... | As a Python code analyst, you investigate and solve complex coding mysteries |
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:
... | Write a Python 3 function that can
search a value in a dicionary and returns the key of the first occurrence in the dicionary and returns the key of the first occurrence in the dicionary | As a Python code composer, you craft elegant and concise scripts. |
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')) | Can you implement a function in Python 3 that
retrieves layer from DB | As a Python code translator, you convert algorithms and pseudocode into 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) | Create a Python 3 function for
extending parent class queryset by filtering nodes of the specified layer | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve list of nodes of the specified layer | Can you tell what is the following Python 3 function doing
def get(self, request, *args, **kwargs):
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) | As a Python code analyst, you investigate and solve complex coding mysteries |
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) | Write a Python 3 script to
save the IP record in the cache. | As a python code expert, you are capable of creating scripts from specifications. |
Allow relation between objects between nodeshot2 objects only | Can you generate a brief explanation for the following Python 3 code
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
return True
return None | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Implement a function in Python 3 to
allow migrations of old_nodeshot models to old_nodeshot models | You are a Python code architect, reviewing and designing scalable and efficient code |
ensure email is in the database | Explain what the following Python 3 code does
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
... | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
... | Write a Python 3 function for
getting or write metric values | As a python code expert, you are capable of creating scripts from specifications. |
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:
# gener... | Can you create a Python 3 function that
adds current instance to public or private channel. | You are a Python code generator, capable of creating scripts from specifications. |
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) | Write a Python 3 script to
broadcast a message to all connected clients | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | How would you implement a function in Python 3 that
sends a message to a specific client. Returns True if successful False otherwise. | You are a Python code generator, capable of creating scripts from specifications. |
return a merge of public and private clients | Can you generate the documentation for the following Python 3 function
def get_clients(self):
public = self.channels['public']
private = self.channels['private']
return dict(public.items() + private.items()) | As a Python code composer, you craft elegant and concise scripts. |
Returns an InfluxDBClient instance. | Can you generate the documentation for the following Python 3 function
def get_db():
return client.InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
) | As a Python code analyst, you investigate and solve complex coding mysteries |
Wrapper around InfluxDBClient. query | Given the following Python 3 function, write the documentation
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, epo... | You are a Python code generator, capable of creating scripts from specifications. |
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 d... | Create a Python 3 function for
creating database if necessary | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
... | Create a Python 3 function for
ensuring users cannot rate the same node multiple times and let users change their rating | As a Python code composer, you craft elegant and concise scripts. |
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 rati... | Can you create a Python 3 function that
updates the count of the node and the rating average | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if rating can be inserted for this node or parent layer | Can you generate the documentation for the following Python 3 function
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 ValidationEr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
custom save method to update counts | Can you tell what is the following Python 3 function doing
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).s... | You are a Python code analyst, evaluating scripts for potential improvements. |
Updates all the topology and sends logs to the nodeshot. networking logger | Make a summary of the following Python 3 code
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'
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Custom save method for device connector. | Explain what the following Python 3 code does
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) | As a Python code analyst, you investigate and solve complex coding mysteries |
def clean(self, *args, **kwargs):
""" validation """
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | How would you code a function in Python 3 to
clean up the cache | As a python code expert, you are capable of creating scripts from specifications. |
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 | Write a Python 3 function that can
return python netengine backend class importing it if needed | As a python code expert, you are capable of creating scripts from specifications. |
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... | Implement a Python 3 function for
ensuring backend string representation is correct | You are a Python code architect, reviewing and designing scalable and efficient code |
validate that the config is well formed | Explain what the following Python 3 code does
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
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) | How would you code a function in Python 3 to
call netengine validate method | As a Python code translator, you convert algorithms and pseudocode into 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.... | Can you create a Python 3 function that
checks that we don t create a device that already exists and that we don t have any duplicate interfaces. | You are a Python code analyst, evaluating scripts for potential improvements. |
returns list of available config params | Make a summary of the following Python 3 code
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 a... | As a python code expert, you are capable of creating scripts from specifications. |
returns the netengine backend specified in self. backend
for internal use only
| Make a summary of the following Python 3 code
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 pa... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Can you implement a function in Python 3 that
builds a python dictionary representing the arguments that will be passed to netengine backend for internal use only | As a Python code translator, you convert algorithms and pseudocode into 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.... | Write a Python 3 script to
create a new device object based on the current state of the node. | As a Python code analyst, you investigate and solve complex coding mysteries |
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
*... | Write a Python 3 script to
cache view response by group. | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
reso... | Write a Python 3 function that can
generate a model class based on the provided JSON schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() | Write a Python 3 script to
return a jsonpatch object representing the delta | You are a Python code generator, capable of creating scripts from specifications. |
A list of changes in this object. | Make a summary of the following Python 3 code
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']) | You are a Python code architect, reviewing and designing scalable and efficient code |
Apply a JSON schema to an object | How would you explain what the following Python 3 function does
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.... | As a Python code composer, you craft elegant and concise scripts. |
Returns if the file content is valid for this filetype | Can you tell what is the following Python 3 function doing
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) | As a Python code translator, you convert algorithms and pseudocode into 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... | Write a Python 3 script for
returning the OatHeaderData object from the data | As a Python code composer, you craft elegant and concise scripts. |
Parses the key value store from the data | Can you generate a brief explanation for the following Python 3 code
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)
of... | As a python code expert, you are capable of creating scripts from specifications. |
Converts the addr from a rva to a pointer to raw data in the file | Can you tell what is the following Python 3 function doing
def to_raw_address(addr, section):
return addr - section.header.VirtualAddress + section.header.PointerToRawData | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
... | Write a Python 3 script to
return the class which holds the suitable classes for the loaded file | As a python code expert, you are capable of creating scripts from specifications. |
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) | Write a Python 3 script for
returning the ImageDosHeader data | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the ImageNtHeaders object from the data. | Can you generate a brief explanation for the following Python 3 code
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')
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.