<commit_before># -*- coding: utf-8 -*-
from django.views.generic import TemplateView, DetailView
from django.views.generic.base import TemplateResponseMixin, ContextMixin, View
from django.views.generic.edit import ModelFormMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse_lazy
from django.core.files import File as DjangoFile
from django.contrib.auth import get_user_model
from django.utils.text import slugify
from django.conf import settings
from django.utils.six import BytesIO
from braces import views
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions
from core.models import Course, CourseProfessor
from course_material.models import File as TimtecFile
from .serializer import CourseExportSerializer, CourseImportSerializer

from accounts.models import TimtecUser
from django.utils import timezone
from datetime import timedelta, time, datetime
from core.models import CourseStudent
from joca.models import JocaUser

import tarfile
import StringIO
import os
import csv


User = get_user_model()


class AdminMixin(TemplateResponseMixin, ContextMixin,):
    def get_context_data(self, **kwargs):
        context = super(AdminMixin, self).get_context_data(**kwargs)
        context['in_admin'] = True
        return context

    def get_template_names(self):
        """
        Returns two template options, either the administration specific
        or the common template
        """
        return ['administration/' + self.template_name, self.template_name]


class AdminView(AdminMixin, TemplateView, views.AccessMixin):
    raise_exception = True

    def dispatch(self, request, *args, **kwargs):

        response = super(AdminView, self).dispatch(
            request, *args, **kwargs)

        if not (request.user.is_superuser or CourseProfessor.objects.filter(user=request.user, role='coordinator').exists()):
            if self.raise_exception:  # *and* if an exception was desired
                raise PermissionDenied  # return a forbidden response.

        return response


class UserAdminView(AdminView):
    def get_context_data(self, **kwargs):
        context = super(UserAdminView, self).get_context_data(**kwargs)
        context['total_users_number'] = User.objects.count()
        print context
        return context

class ExportUsersView(View):
    def generate_string_from_array(self, array):
        first = True
        string_from_array = ''
        for o in array.all():
            print o.name
            if first:
                first = False
                string_from_array = ''.join((string_from_array, o.name.encode('utf-8')))
            else:
                string_from_array = '|'.join((string_from_array, o.name.encode('utf-8')))
        return string_from_array

    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="alunos.csv"'

        writer = csv.writer(response)
        writer.writerow([
            'Nome',
            'Email',
            'Email Adicional',
            'Ocupação',
            'Ano/Série',
            'Disciplinas',
            'Estado',
            'Cidade',
            'Administrador',
            'Ativo',
        ])
        for u in User.objects.all():
            adm = 'N'
            ativo = 'N'
            if(u.is_staff):
                adm = 'S'
            if(u.is_active):
                ativo = 'S'
            occupations = self.generate_string_from_array(u.occupations)
            education = self.generate_string_from_array(u.education_degrees)
            disciplines = self.generate_string_from_array(u.disciplines)
            print occupations
            writer.writerow([
                u.first_name + ' ' + u.last_name,
                u.email,
                u.business_email,
                occupations,
                education,
                disciplines,
                u.city.uf.name,
                u.city.name,
                adm,
                ativo,
            ])

        return response


class CourseAdminView(AdminMixin, DetailView, views.AccessMixin):
    model = Course
    context_object_name = 'course'
    pk_url_kwarg = 'course_id'<commit_msg>remove console.logs<commit_after># -*- coding: utf-8 -*-
from django.views.generic import TemplateView, DetailView
from django.views.generic.base import TemplateResponseMixin, ContextMixin, View
from django.views.generic.edit import ModelFormMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse_lazy
from django.core.files import File as DjangoFile
from django.contrib.auth import get_user_model
from django.utils.text import slugify
from django.conf import settings
from django.utils.six import BytesIO
from braces import views
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions
from core.models import Course, CourseProfessor
from course_material.models import File as TimtecFile
from .serializer import CourseExportSerializer, CourseImportSerializer

from accounts.models import TimtecUser
from django.utils import timezone
from datetime import timedelta, time, datetime
from core.models import CourseStudent
from joca.models import JocaUser

import tarfile
import StringIO
import os
import csv


User = get_user_model()


class AdminMixin(TemplateResponseMixin, ContextMixin,):
    def get_context_data(self, **kwargs):
        context = super(AdminMixin, self).get_context_data(**kwargs)
        context['in_admin'] = True
        return context

    def get_template_names(self):
        """
        Returns two template options, either the administration specific
        or the common template
        """
        return ['administration/' + self.template_name, self.template_name]


class AdminView(AdminMixin, TemplateView, views.AccessMixin):
    raise_exception = True

    def dispatch(self, request, *args, **kwargs):

        response = super(AdminView, self).dispatch(
            request, *args, **kwargs)

        if not (request.user.is_superuser or CourseProfessor.objects.filter(user=request.user, role='coordinator').exists()):
            if self.raise_exception:  # *and* if an exception was desired
                raise PermissionDenied  # return a forbidden response.

        return response


class UserAdminView(AdminView):
    def get_context_data(self, **kwargs):
        context = super(UserAdminView, self).get_context_data(**kwargs)
        context['total_users_number'] = User.objects.count()
        return context

class ExportUsersView(View):
    def generate_string_from_array(self, array):
        first = True
        string_from_array = ''
        for o in array.all():
            if first:
                first = False
                string_from_array = ''.join((string_from_array, o.name.encode('utf-8')))
            else:
                string_from_array = '|'.join((string_from_array, o.name.encode('utf-8')))
        return string_from_array

    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="alunos.csv"'

        writer = csv.writer(response)
        writer.writerow([
            'Nome',
            'Email',
            'Email Adicional',
            'Ocupação',
            'Ano/Série',
            'Disciplinas',
            'Estado',
            'Cidade',
            'Administrador',
            'Ativo',
        ])
        for u in User.objects.all():
            adm = 'N'
            ativo = 'N'
            if(u.is_staff):
                adm = 'S'
            if(u.is_active):
                ativo = 'S'
            occupations = self.generate_string_from_array(u.occupations)
            education = self.generate_string_from_array(u.education_degrees)
            disciplines = self.generate_string_from_array(u.disciplines)
            writer.writerow([
                u.first_name + ' ' + u.last_name,
                u.email,
                u.business_email,
                occupations,
                education,
                disciplines,
                u.city.uf.name,
                u.city.name,
                adm,
                ativo,
            ])

        return response


class CourseAdminView(AdminMixin, DetailView, views.AccessMixin):
    model = Course
    context_object_name = 'course'
    pk_url_kwarg = 'course_id'
{'fraction_non_alphanumeric': 0.08591026650174294, 'fraction_numerical': 0.0006746879568199708, 'mean_word_length': 2.5718875502008034, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7113566', 'n_tokens_mistral': 2443, 'n_tokens_neox': 2337, 'n_words': 606}