<commit_before># Create your views here.
from models import *
from django.http import HttpResponseRedirect
from forms import AdminOptInForm, UploadFileForm
from openflow.optin_manager.flowspace.helper import *
from openflow.optin_manager.users.models import Priority
from openflow.optin_manager.xmlrpc_server.models import FVServerProxy
from django.views.generic import simple
from openflow.optin_manager.opts.helper import opt_fs_into_exp,opt_fses_outof_exp,\
update_match_struct_priority_and_get_fv_args, read_fs
from django.db import transaction
from django.core.mail import send_mail
from django.conf import settings
    
def change_priority(request):
    '''
    The view function to change priorities of previous opt-ins.
    request.POST should have a dictionary of "p_" followed by UserOpts database id as key
    and the new priority as value
    '''

    fv_args = []
    error_msg = []
    max_priority = request.user.get_profile().max_priority_level
    profile = UserProfile.get_or_create_profile(request.user)
         
    keys = request.POST.keys()
    if (request.method == "POST"):
        for key in keys:
            if key.startswith("p_"):
                try:
                    pid = int(key[2:len(key)])
                    new_priority = int(request.POST[key])
                except:
                    error_msg.append("Found invalid pair in request.POST: %s:%s"%(key,request.POST[key]))
                    break
                    
                if (new_priority > max_priority):
                    error_msg.append("Priority %s, is larger than your maximum(%s)"\
                            % (new_priority, max_priority))
                    break
 
                u = UserOpts.objects.get(pk=pid)
                if (u.priority != new_priority):
                    u.priority = new_priority
                    if (u.priority >= max_priority - Priority.Strict_Priority_Offset):
                        u.nice = False
                    else:
                        u.nice = True
                    u.save()
                    new_args = update_match_struct_priority_and_get_fv_args(u)
                    fv_args = fv_args + new_args

        if len(error_msg) == 0:
            try:
                fv = FVServerProxy.objects.all()[0]
                try:
                    if len(fv_args) > 0:
                        fv.proxy.api.changeFlowSpace(fv_args)
                    return simple.direct_to_template(request, 
                        template = 'openflow/optin_manager/opts/change_priority_successful.html', 
                        extra_context = {}, 
                    )
                except Exception,e:
                    import traceback
                    traceback.print_exc()
                    transaction.rollback()
                    error_msg.append("update flowspace priorities failed: %s"%str(e))
            except Exception,e:
                import traceback
                traceback.print_exc()
                transaction.rollback()
                error_msg.append("Flowvisor not set: %s"%str(e))
        else: #error msg has some content
            transaction.rollback()
        
    nice_opts = UserOpts.objects.filter(user=request.user,nice=True).order_by('-priority')
    strict_opts = UserOpts.objects.filter(user=request.user,nice=False).order_by('-priority')
 
    ##################################
    #      Admin Change Priority     #
    ################################## 
    if (profile.is_net_admin):
        return simple.direct_to_template(request, 
                    template = 'openflow/optin_manager/opts/view_opts_admin.html', 
                    extra_context={ 
                        'error_msg':error_msg,
                        'nice_opts':nice_opts , 
                        'strict_opts':strict_opts ,
                        'user':request.user,
                        'max_priority':max_priority,
                    }, 
                ) 
 
    ##################################
    #      User Change Priority      #
    ################################## 
    else:
        return simple.direct_to_template(request, 
                    template = 'openflow/optin_manager/opts/view_opts_user.html', 
                    extra_context={ 
                        'error_msg':error_msg,
                        'nice_opts':nice_opts , 
                        'strict_opts':strict_opts ,
                        'user':request.user,
                        'max_priority':max_priority,
                    }, 
                )           
                  


def add_opt_in(request):
    '''
`	The view function for opting in a user or admin flowspace into an experiment
    FOR USER OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    FOR ADMIN OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    key: all flowspace fields as specified in AdminOptInForm
    ''' 
    profile = UserProfile.get_or_create_profile(request.user)
    
    ############################
    #      Admin Opt-In        #
    ############################   
    if (profile.is_net_admin):
        
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs,admin_fs,FlowSpace)
            if (len(intersection)>0):
                exps.append(exp)

        assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
        error_msg = []
        if (request.method == "POST"):
            form = AdminOptInForm(request.POST)
            if form.is_valid():
                all_this_admin_opts = UserOpts.objects.filter(user=request.user,nice=True)
                for admin_opt in all_this_admin_opts:
                    if admin_opt.priority <= assigned_priority:
                        assigned_priority = admin_opt.priority - 1
                        
                if assigned_priority <= 0:
                    error_msg.append("Too many opt-ins")
         
                # check if the selected experiment is valid:
                selected_exp_id = request.POST['experiment']
                try:
                    selexp = Experiment.objects.get(id = selected_exp_id)
                except:
                    error_msg.append("Invalid experiment selected!")
                if len(error_msg)==0:
                    requested_opt = form.get_flowspace(FlowSpace)
                    adminFS = AdminFlowSpace.objects.filter(user = request.user)
                    
                    intersected_flowspace = multi_fs_intersect([requested_opt],adminFS,FlowSpace)
                    print "LEODEBUG FLOWSPACE"
                    for fs in intersected_flowspace:
                        print "\n\nFLOWSPACE"
                        print fs.stringify()
                        print fs.__unicode__()
                    if len(intersected_flowspace) == 0:
                        error_msg.append("Selected flowspace doesn't have any intersection with admin FS")
                if len(error_msg)==0:
                    [fv_args,match_list] = opt_fs_into_exp(intersected_flowspace,
                                selexp,request.user,assigned_priority,True)
                    try:
                        fv = FVServerProxy.objects.all()[0]
                        try:
                            if len(fv_args) > 0:
                                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                            try:
                                allopts = UserOpts.objects.filter(user = request.user).order_by('-priority')
                                for opt in allopts:
                                    this_opt_fses = opt.optsflowspace_set.all()
                                    fs_description = ""
                                    for fs in this_opt_fses:
                                        if fs_description != "":
                                            fs_description = fs_description + " & %s"%fs
                                        else:
                                            fs_description = "%s"%fs
                                send_mail(
                                         settings.EMAIL_SUBJECT_PREFIX + "Your Flowspace request has been attended",
                                         "Your Flowspace request has been attended, go to your project and slice page at https://%s to check the Flowspace granted\n\nFlowSpace Granted:\n%s" % (settings.SITE_DOMAIN,fs_description),
                                         from_email=settings.DEFAULT_FROM_EMAIL,
                                         recipient_list= [selexp.owner_email],
                                         #recipient_list=[settings.ROOT_EMAIL],
                                 )
                            except Exception as e:
                                print "User email notification could no be sent"
                                print e

                            return simple.direct_to_template(request, 
                                template ="openflow/optin_manager/opts/opt_in_successful_admin.html",
                                extra_context = {
                                    'expname':"%s:%s"%(selexp.project_name,selexp.slice_name),
                                },
                            )
                        except Exception,e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Couldn't opt into the requested experiment, Flowvisor error: %s"%str(e))
                    except Exception,e:
                        import traceback
                        traceback.print_exc()
                        transaction.rollback()
                        error_msg.append("Flowvisor not set: %s"%str(e))<commit_msg>testing optin notification with expedient url<commit_after># Create your views here.
from models import *
from django.http import HttpResponseRedirect
from forms import AdminOptInForm, UploadFileForm
from openflow.optin_manager.flowspace.helper import *
from openflow.optin_manager.users.models import Priority
from openflow.optin_manager.xmlrpc_server.models import FVServerProxy
from django.views.generic import simple
from openflow.optin_manager.opts.helper import opt_fs_into_exp,opt_fses_outof_exp,\
update_match_struct_priority_and_get_fv_args, read_fs
from django.db import transaction
from django.core.mail import send_mail
from django.conf import settings
    
def change_priority(request):
    '''
    The view function to change priorities of previous opt-ins.
    request.POST should have a dictionary of "p_" followed by UserOpts database id as key
    and the new priority as value
    '''

    fv_args = []
    error_msg = []
    max_priority = request.user.get_profile().max_priority_level
    profile = UserProfile.get_or_create_profile(request.user)
         
    keys = request.POST.keys()
    if (request.method == "POST"):
        for key in keys:
            if key.startswith("p_"):
                try:
                    pid = int(key[2:len(key)])
                    new_priority = int(request.POST[key])
                except:
                    error_msg.append("Found invalid pair in request.POST: %s:%s"%(key,request.POST[key]))
                    break
                    
                if (new_priority > max_priority):
                    error_msg.append("Priority %s, is larger than your maximum(%s)"\
                            % (new_priority, max_priority))
                    break
 
                u = UserOpts.objects.get(pk=pid)
                if (u.priority != new_priority):
                    u.priority = new_priority
                    if (u.priority >= max_priority - Priority.Strict_Priority_Offset):
                        u.nice = False
                    else:
                        u.nice = True
                    u.save()
                    new_args = update_match_struct_priority_and_get_fv_args(u)
                    fv_args = fv_args + new_args

        if len(error_msg) == 0:
            try:
                fv = FVServerProxy.objects.all()[0]
                try:
                    if len(fv_args) > 0:
                        fv.proxy.api.changeFlowSpace(fv_args)
                    return simple.direct_to_template(request, 
                        template = 'openflow/optin_manager/opts/change_priority_successful.html', 
                        extra_context = {}, 
                    )
                except Exception,e:
                    import traceback
                    traceback.print_exc()
                    transaction.rollback()
                    error_msg.append("update flowspace priorities failed: %s"%str(e))
            except Exception,e:
                import traceback
                traceback.print_exc()
                transaction.rollback()
                error_msg.append("Flowvisor not set: %s"%str(e))
        else: #error msg has some content
            transaction.rollback()
        
    nice_opts = UserOpts.objects.filter(user=request.user,nice=True).order_by('-priority')
    strict_opts = UserOpts.objects.filter(user=request.user,nice=False).order_by('-priority')
 
    ##################################
    #      Admin Change Priority     #
    ################################## 
    if (profile.is_net_admin):
        return simple.direct_to_template(request, 
                    template = 'openflow/optin_manager/opts/view_opts_admin.html', 
                    extra_context={ 
                        'error_msg':error_msg,
                        'nice_opts':nice_opts , 
                        'strict_opts':strict_opts ,
                        'user':request.user,
                        'max_priority':max_priority,
                    }, 
                ) 
 
    ##################################
    #      User Change Priority      #
    ################################## 
    else:
        return simple.direct_to_template(request, 
                    template = 'openflow/optin_manager/opts/view_opts_user.html', 
                    extra_context={ 
                        'error_msg':error_msg,
                        'nice_opts':nice_opts , 
                        'strict_opts':strict_opts ,
                        'user':request.user,
                        'max_priority':max_priority,
                    }, 
                )           
                  


def add_opt_in(request):
    '''
`	The view function for opting in a user or admin flowspace into an experiment
    FOR USER OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    FOR ADMIN OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    key: all flowspace fields as specified in AdminOptInForm
    ''' 
    profile = UserProfile.get_or_create_profile(request.user)
    
    ############################
    #      Admin Opt-In        #
    ############################   
    if (profile.is_net_admin):
        
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs,admin_fs,FlowSpace)
            if (len(intersection)>0):
                exps.append(exp)

        assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
        error_msg = []
        if (request.method == "POST"):
            form = AdminOptInForm(request.POST)
            if form.is_valid():
                all_this_admin_opts = UserOpts.objects.filter(user=request.user,nice=True)
                for admin_opt in all_this_admin_opts:
                    if admin_opt.priority <= assigned_priority:
                        assigned_priority = admin_opt.priority - 1
                        
                if assigned_priority <= 0:
                    error_msg.append("Too many opt-ins")
         
                # check if the selected experiment is valid:
                selected_exp_id = request.POST['experiment']
                try:
                    selexp = Experiment.objects.get(id = selected_exp_id)
                except:
                    error_msg.append("Invalid experiment selected!")
                if len(error_msg)==0:
                    requested_opt = form.get_flowspace(FlowSpace)
                    adminFS = AdminFlowSpace.objects.filter(user = request.user)
                    
                    intersected_flowspace = multi_fs_intersect([requested_opt],adminFS,FlowSpace)
                    print "LEODEBUG FLOWSPACE"
                    for fs in intersected_flowspace:
                        print "\n\nFLOWSPACE"
                        print fs.stringify()
                        print fs.__unicode__()
                    if len(intersected_flowspace) == 0:
                        error_msg.append("Selected flowspace doesn't have any intersection with admin FS")
                if len(error_msg)==0:
                    [fv_args,match_list] = opt_fs_into_exp(intersected_flowspace,
                                selexp,request.user,assigned_priority,True)
                    try:
                        fv = FVServerProxy.objects.all()[0]
                        try:
                            if len(fv_args) > 0:
                                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                            try:
                                allopts = UserOpts.objects.filter(user = request.user).order_by('-priority')
                                for opt in allopts:
                                    this_opt_fses = opt.optsflowspace_set.all()
                                    fs_description = ""
                                    for fs in this_opt_fses:
                                        if fs_description != "":
                                            fs_description = fs_description + " & %s"%fs
                                        else:
                                            fs_description = "%s"%fs
                                send_mail(
                                         settings.EMAIL_SUBJECT_PREFIX + "Your Flowspace request has been attended",
                                         "Your Flowspace request has been attended, go to your project and slice page at https://%s to check the Flowspace granted\n\nFlowSpace Granted:\n%s" % (settings.SITE_DOMAIN.split(':')[0],fs_description),
                                         from_email=settings.DEFAULT_FROM_EMAIL,
                                         recipient_list= [selexp.owner_email],
                                         #recipient_list=[settings.ROOT_EMAIL],
                                 )
                            except Exception as e:
                                print "User email notification could no be sent"
                                print e

                            return simple.direct_to_template(request, 
                                template ="openflow/optin_manager/opts/opt_in_successful_admin.html",
                                extra_context = {
                                    'expname':"%s:%s"%(selexp.project_name,selexp.slice_name),
                                },
                            )
                        except Exception,e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Couldn't opt into the requested experiment, Flowvisor error: %s"%str(e))
                    except Exception,e:
                        import traceback
                        traceback.print_exc()
                        transaction.rollback()
                        error_msg.append("Flowvisor not set: %s"%str(e))
{'fraction_non_alphanumeric': 0.09136276391554703, 'fraction_numerical': 0.0012955854126679462, 'mean_word_length': 1.3642654566080545, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 52, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2890698', 'n_tokens_mistral': 5225, 'n_tokens_neox': 4914, 'n_words': 1034}