# Path: labshare/decorators.py
# def render_to(template_name, title = ""):
#     def renderer(func):
#         def wrapper(request, *args, **kw):
#             output = func(request, *args, **kw)
#             if not isinstance(output, dict): return output
#             return render(request, template_name, output)
#         return wrapper
#     return renderer
# 
# Path: labshare/utils.py
# def publish_device_state(device_data, channel_name=None):
#     channel_layer = channels.layers.get_channel_layer()
#     name = device_data['name']
#     if 'gpus' not in device_data:
#         device_data['gpus'] = []
# 
#     if channel_name is None:
#         send_function = async_to_sync(channel_layer.group_send)
#     else:
#         send_function = async_to_sync(channel_layer.send)
#     send_function(channel_name if channel_name else name, {'type': 'update_info', 'message': json.dumps(device_data)})
# 
# Path: labshare/forms.py
# class MessageForm(forms.Form):
#     message_all_users = forms.BooleanField(required=False)
#     recipients = forms.ModelMultipleChoiceField(
#         queryset=User.objects.all(),
#         required=False,
#         widget=SelectMultiple(attrs={"id": "recipients-field", "multiple": "multiple"})
#     )
#     subject = forms.CharField(required=True)
#     message = forms.CharField(widget=forms.Textarea, required=True)
# 
# class ViewAsForm(forms.Form):
#     username = forms.ModelChoiceField(
#         queryset=User.objects.all().exclude(username__endswith="_user").exclude(username=settings.ALLOCATION_UPDATE_USERNAME),
#         empty_label="Select a user",
#         required=True,
#         widget=Select(attrs={"id": "username-field"})
#     )
# 
# Path: labshare/models.py
# class Device(models.Model):
#     name = models.CharField(max_length=255)
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
# 
#     class Meta:
#         permissions = (
#             ('use_device', 'User/Group is allowed to use that device'),
#         )
# 
#     def __str__(self):
#         return self.name
# 
#     def can_be_used_by(self, user):
#         content_type = ContentType.objects.get_for_model(self)
#         permission_name = "{app}.use_{model}".format(app=content_type.app_label, model=content_type.model)
#         return user.has_perm(permission_name, self) or user.has_perm(permission_name)
# 
#     def serialize(self):
#         return {
#             'name': self.name,
#         }
# 
# class GPU(models.Model):
#     uuid = models.CharField(max_length=255)
#     model_name = models.CharField(max_length=255)
#     reserved = models.BooleanField(default=False)
#     device = models.ForeignKey(Device, related_name='gpus', on_delete=models.CASCADE)
# 
#     def serialize(self):
#         return {
#             'uuid': self.uuid,
#             'model_name': self.model_name,
#             'reserved': self.reserved
#         }


import json
import logging
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied, SuspiciousOperation, ObjectDoesNotExist
from django.core.mail import EmailMessage
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from labshare.decorators import render_to
from labshare.utils import publish_device_state
from .forms import MessageForm, ViewAsForm
from .models import Device, GPU
                })
        serialized_gpu = gpu.serialize()
        gpu = {
            "used_memory": gpu_data["memory"]["used"],
            "total_memory": gpu_data["memory"]["total"],
            "utilization": gpu_data["gpu_util"],
            "in_use": gpu_in_use,
            "marked_as_failed": False,
            "processes": processes,
        }
        gpu.update(serialized_gpu)
        gpus.append(gpu)

    device_data = device.serialize()
    device_data["gpus"] = gpus
    publish_device_state(device_data)

    return HttpResponse()


@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def update_allocations(request):
    if request.user != User.objects.get(username=settings.ALLOCATION_UPDATE_USERNAME):
        raise PermissionDenied

    data = json.loads(request.read().decode("utf-8"))
    for device_name, allocated_gpus in data.items():
        try:

# Path: labshare/decorators.py
# def render_to(template_name, title = ""):
#     def renderer(func):
#         def wrapper(request, *args, **kw):
#             output = func(request, *args, **kw)
#             if not isinstance(output, dict): return output
#             return render(request, template_name, output)
#         return wrapper
#     return renderer
# 
# Path: labshare/utils.py
# def publish_device_state(device_data, channel_name=None):
#     channel_layer = channels.layers.get_channel_layer()
#     name = device_data['name']
#     if 'gpus' not in device_data:
#         device_data['gpus'] = []
# 
#     if channel_name is None:
#         send_function = async_to_sync(channel_layer.group_send)
#     else:
#         send_function = async_to_sync(channel_layer.send)
#     send_function(channel_name if channel_name else name, {'type': 'update_info', 'message': json.dumps(device_data)})
# 
# Path: labshare/forms.py
# class MessageForm(forms.Form):
#     message_all_users = forms.BooleanField(required=False)
#     recipients = forms.ModelMultipleChoiceField(
#         queryset=User.objects.all(),
#         required=False,
#         widget=SelectMultiple(attrs={"id": "recipients-field", "multiple": "multiple"})
#     )
#     subject = forms.CharField(required=True)
#     message = forms.CharField(widget=forms.Textarea, required=True)
# 
# class ViewAsForm(forms.Form):
#     username = forms.ModelChoiceField(
#         queryset=User.objects.all().exclude(username__endswith="_user").exclude(username=settings.ALLOCATION_UPDATE_USERNAME),
#         empty_label="Select a user",
#         required=True,
#         widget=Select(attrs={"id": "username-field"})
#     )
# 
# Path: labshare/models.py
# class Device(models.Model):
#     name = models.CharField(max_length=255)
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
# 
#     class Meta:
#         permissions = (
#             ('use_device', 'User/Group is allowed to use that device'),
#         )
# 
#     def __str__(self):
#         return self.name
# 
#     def can_be_used_by(self, user):
#         content_type = ContentType.objects.get_for_model(self)
#         permission_name = "{app}.use_{model}".format(app=content_type.app_label, model=content_type.model)
#         return user.has_perm(permission_name, self) or user.has_perm(permission_name)
# 
#     def serialize(self):
#         return {
#             'name': self.name,
#         }
# 
# class GPU(models.Model):
#     uuid = models.CharField(max_length=255)
#     model_name = models.CharField(max_length=255)
#     reserved = models.BooleanField(default=False)
#     device = models.ForeignKey(Device, related_name='gpus', on_delete=models.CASCADE)
# 
#     def serialize(self):
#         return {
#             'uuid': self.uuid,
#             'model_name': self.model_name,
#             'reserved': self.reserved
#         }


# Path: labshare/views.py
import json
import logging
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied, SuspiciousOperation, ObjectDoesNotExist
from django.core.mail import EmailMessage
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from labshare.decorators import render_to
from labshare.utils import publish_device_state
from .forms import MessageForm, ViewAsForm
from .models import Device, GPU

                })
        serialized_gpu = gpu.serialize()
        gpu = {
            "used_memory": gpu_data["memory"]["used"],
            "total_memory": gpu_data["memory"]["total"],
            "utilization": gpu_data["gpu_util"],
            "in_use": gpu_in_use,
            "marked_as_failed": False,
            "processes": processes,
        }
        gpu.update(serialized_gpu)
        gpus.append(gpu)

    device_data = device.serialize()
    device_data["gpus"] = gpus
    publish_device_state(device_data)

    return HttpResponse()


@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def update_allocations(request):
    if request.user != User.objects.get(username=settings.ALLOCATION_UPDATE_USERNAME):
        raise PermissionDenied

    data = json.loads(request.read().decode("utf-8"))
    for device_name, allocated_gpus in data.items():
        try:

            device = Device.objects.get(name=device_name)