<commit_before>import locale

import django

from django.conf import settings
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
from django.forms.widgets import Select, SelectMultiple
from django.utils.safestring import mark_safe
from django.utils.encoding import force_text
from django.utils.html import escape
import json

from smart_selects.utils import unicode_sorter, sort_results

try:
    from django.apps import apps
    get_model = apps.get_model
except ImportError:
    from django.db.models.loading import get_model

if django.VERSION >= (1, 2, 0) and getattr(settings,
                                           'USE_DJANGO_JQUERY', True):
    USE_DJANGO_JQUERY = True
else:
    USE_DJANGO_JQUERY = False
    JQUERY_URL = getattr(settings, 'JQUERY_URL', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js')

URL_PREFIX = getattr(settings, "SMART_SELECTS_URL_PREFIX", "")

class ChainedSelect(Select):
    def __init__(self, to_app_name, to_model_name, chained_field, chained_model_field,
                 foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,
                 show_all, auto_choose, manager=None, view_name=None, *args, **kwargs):
        self.to_app_name = to_app_name
        self.to_model_name = to_model_name
        self.chained_field = chained_field
        self.chained_model_field = chained_model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.manager = manager
        self.view_name = view_name
        self.foreign_key_app_name = foreign_key_app_name
        self.foreign_key_model_name = foreign_key_model_name
        self.foreign_key_field_name = foreign_key_field_name
        super(Select, self).__init__(*args, **kwargs)

    class Media:
        extra = '' if settings.DEBUG else '.min'
        js = [
            'jquery%s.js' % extra,
            'jquery.init.js',
        ]
        if USE_DJANGO_JQUERY:
            js = [static('admin/js/%s' % url) for url in js]
        elif JQUERY_URL:
            js = [JQUERY_URL]
        js = js + [static('smart-selects/admin/js/chainedfk.js')]

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1:  # formset
            chained_field = '-'.join(name.split('-')[:-1] + [self.chained_field])
        else:
            chained_field = self.chained_field

        if not self.view_name:
            if self.show_all:
                view_name = "chained_filter_all"
            else:
                view_name = "chained_filter"
        else:
            view_name = self.view_name
        kwargs = {
            'app': self.to_app_name,
            'model': self.to_model_name,
            'field': self.chained_model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        iterator = iter(self.choices)
        if hasattr(iterator, '__next__'):
            empty_label = iterator.__next__()[1]
        else:
            # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
            empty_label = iterator.next()[1]

        js = """
        <script type="text/javascript">
        (function($) {
            var chainfield = "#id_%(chainfield)s";
            var url = "%(url)s";
            var id = "#%(id)s";
            var value = %(value)s;
            var auto_choose = %(auto_choose)s;
            var empty_label = "%(empty_label)s";

            $(document).ready(function() {
                chainedfk.init(chainfield, url, id, value, empty_label, auto_choose);
            });
        })(jQuery || django.jQuery);
        </script>

        """
        js = js % {"chainfield": chained_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': 'undefined' if value is None else value,
                   'auto_choose': auto_choose,
                   'empty_label': escape(empty_label)}
        final_choices = []
        if value:
            available_choices = self._get_available_choices(self.queryset, value)
            for choice in available_choices:
                final_choices.append((choice.pk, force_text(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'

        output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)

    def _get_available_choices(self, queryset, value):
        """
        get possible choices for selection
        """
        item = queryset.filter(pk=value).first()
        if item:
            try:
                pk = getattr(item, self.chained_model_field + "_id")
                filter = {self.chained_model_field: pk}
            except AttributeError:
                try:  # maybe m2m?
                    pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)
                    filter = {self.chained_model_field + "__in": pks}
                except AttributeError:
                    try:  # maybe a set?
                        pks = getattr(item, self.chained_model_field + "_set").all().values_list('pk', flat=True)
                        filter = {self.chained_model_field + "__in": pks}
                    except:  # give up
                        filter = {}
            filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())
            sort_results(filtered)
        else:
            # invalid value for queryset
            filtered = []

        return filtered

class ChainedSelectMultiple(SelectMultiple):
    def __init__(self, to_app_name, to_model_name, chain_field, chained_model_field,
                 foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,
                 show_all, auto_choose, manager=None, view_name=None, *args, **kwargs):
        self.to_app_name = to_app_name
        self.to_model_name = to_model_name
        self.chain_field = chain_field
        self.chained_model_field = chained_model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.manager = manager
        self.view_name = view_name
        self.foreign_key_app_name = foreign_key_app_name
        self.foreign_key_model_name = foreign_key_model_name
        self.foreign_key_field_name = foreign_key_field_name

        super(SelectMultiple, self).__init__(*args, **kwargs)

    class Media:
        extra = '' if settings.DEBUG else '.min'
        js = [
            'jquery%s.js' % extra,
            'jquery.init.js',
        ]

        if USE_DJANGO_JQUERY:
            js = [static('admin/js/%s' % url) for url in js]
        elif JQUERY_URL:
            js = [JQUERY_URL]
        js = js + [static('smart-selects/admin/js/chainedm2m.js')]

    def render(self, name, value, attrs=None, choices=()):

        if len(name.split('-')) > 1:  # formset
            chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
        else:
            chain_field = self.chain_field

        if not self.view_name:
            if self.show_all:
                view_name = "chained_filter_all"
            else:
                view_name = "chained_filter"
        else:
            view_name = self.view_name

        kwargs = {
            'app': self.to_app_name,
            'model': self.to_model_name,
            'field': self.chained_model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        empty_label = ''
        js = """
        <script type="text/javascript">
        (function($) {

        var chainfield = "#id_%(chainfield)s";
        var url = "%(url)s";
        var id = "#%(id)s";
        var value = %(value)s;
        var auto_choose = %(auto_choose)s;

        $(document).ready(function() {
            chainedm2m.init(chainfield, url, id, value, auto_choose);
        });
        })(jQuery || django.jQuery);
        </script>

        """
        js = js % {"chainfield": chain_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': json.dumps(value),
                   'auto_choose': auto_choose}
        final_choices = []

        if value:
            items = self.queryset.filter(pk__in=value)
            try:  # maybe m2m?
                pks = getattr(items, self.chained_model_field).all().values_list('pk', flat=True)
                filter = {self.chained_model_field + "__in": pks}
            except AttributeError:
                try:  # maybe a set?
                    pks = getattr(items, self.chained_model_field + "_set").all().values_list('pk', flat=True)
                    filter = {self.chained_model_field + "__in": pks}
                except:  # give up
                    filter = {}
            filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())
            filtered.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(unicode(x)))
            for choice in filtered:
                final_choices.append((choice.pk, unicode(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()

        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'
        output = super(ChainedSelectMultiple, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)
<commit_msg>[fix] remove unused code in chainmanytomany widget<commit_after>import locale

import django

from django.conf import settings
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
from django.forms.widgets import Select, SelectMultiple
from django.utils.safestring import mark_safe
from django.utils.encoding import force_text
from django.utils.html import escape
import json

from smart_selects.utils import unicode_sorter, sort_results

try:
    from django.apps import apps
    get_model = apps.get_model
except ImportError:
    from django.db.models.loading import get_model

if django.VERSION >= (1, 2, 0) and getattr(settings,
                                           'USE_DJANGO_JQUERY', True):
    USE_DJANGO_JQUERY = True
else:
    USE_DJANGO_JQUERY = False
    JQUERY_URL = getattr(settings, 'JQUERY_URL', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js')

URL_PREFIX = getattr(settings, "SMART_SELECTS_URL_PREFIX", "")

class ChainedSelect(Select):
    def __init__(self, to_app_name, to_model_name, chained_field, chained_model_field,
                 foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,
                 show_all, auto_choose, manager=None, view_name=None, *args, **kwargs):
        self.to_app_name = to_app_name
        self.to_model_name = to_model_name
        self.chained_field = chained_field
        self.chained_model_field = chained_model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.manager = manager
        self.view_name = view_name
        self.foreign_key_app_name = foreign_key_app_name
        self.foreign_key_model_name = foreign_key_model_name
        self.foreign_key_field_name = foreign_key_field_name
        super(Select, self).__init__(*args, **kwargs)

    class Media:
        extra = '' if settings.DEBUG else '.min'
        js = [
            'jquery%s.js' % extra,
            'jquery.init.js',
        ]
        if USE_DJANGO_JQUERY:
            js = [static('admin/js/%s' % url) for url in js]
        elif JQUERY_URL:
            js = [JQUERY_URL]
        js = js + [static('smart-selects/admin/js/chainedfk.js')]

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1:  # formset
            chained_field = '-'.join(name.split('-')[:-1] + [self.chained_field])
        else:
            chained_field = self.chained_field

        if not self.view_name:
            if self.show_all:
                view_name = "chained_filter_all"
            else:
                view_name = "chained_filter"
        else:
            view_name = self.view_name
        kwargs = {
            'app': self.to_app_name,
            'model': self.to_model_name,
            'field': self.chained_model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        iterator = iter(self.choices)
        if hasattr(iterator, '__next__'):
            empty_label = iterator.__next__()[1]
        else:
            # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'
            empty_label = iterator.next()[1]

        js = """
        <script type="text/javascript">
        (function($) {
            var chainfield = "#id_%(chainfield)s";
            var url = "%(url)s";
            var id = "#%(id)s";
            var value = %(value)s;
            var auto_choose = %(auto_choose)s;
            var empty_label = "%(empty_label)s";

            $(document).ready(function() {
                chainedfk.init(chainfield, url, id, value, empty_label, auto_choose);
            });
        })(jQuery || django.jQuery);
        </script>

        """
        js = js % {"chainfield": chained_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': 'undefined' if value is None else value,
                   'auto_choose': auto_choose,
                   'empty_label': escape(empty_label)}
        final_choices = []
        if value:
            available_choices = self._get_available_choices(self.queryset, value)
            for choice in available_choices:
                final_choices.append((choice.pk, force_text(choice)))
        if len(final_choices) > 1:
            final_choices = [("", (empty_label))] + final_choices
        if self.show_all:
            final_choices.append(("", (empty_label)))
            self.choices = list(self.choices)
            self.choices.sort(key=lambda x: unicode_sorter(x[1]))
            for ch in self.choices:
                if not ch in final_choices:
                    final_choices.append(ch)
        self.choices = ()
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'

        output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)

    def _get_available_choices(self, queryset, value):
        """
        get possible choices for selection
        """
        item = queryset.filter(pk=value).first()
        if item:
            try:
                pk = getattr(item, self.chained_model_field + "_id")
                filter = {self.chained_model_field: pk}
            except AttributeError:
                try:  # maybe m2m?
                    pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)
                    filter = {self.chained_model_field + "__in": pks}
                except AttributeError:
                    try:  # maybe a set?
                        pks = getattr(item, self.chained_model_field + "_set").all().values_list('pk', flat=True)
                        filter = {self.chained_model_field + "__in": pks}
                    except:  # give up
                        filter = {}
            filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())
            sort_results(filtered)
        else:
            # invalid value for queryset
            filtered = []

        return filtered

class ChainedSelectMultiple(SelectMultiple):
    def __init__(self, to_app_name, to_model_name, chain_field, chained_model_field,
                 foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,
                 show_all, auto_choose, manager=None, view_name=None, *args, **kwargs):
        self.to_app_name = to_app_name
        self.to_model_name = to_model_name
        self.chain_field = chain_field
        self.chained_model_field = chained_model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.manager = manager
        self.view_name = view_name
        self.foreign_key_app_name = foreign_key_app_name
        self.foreign_key_model_name = foreign_key_model_name
        self.foreign_key_field_name = foreign_key_field_name

        super(SelectMultiple, self).__init__(*args, **kwargs)

    class Media:
        extra = '' if settings.DEBUG else '.min'
        js = [
            'jquery%s.js' % extra,
            'jquery.init.js',
        ]

        if USE_DJANGO_JQUERY:
            js = [static('admin/js/%s' % url) for url in js]
        elif JQUERY_URL:
            js = [JQUERY_URL]
        js = js + [static('smart-selects/admin/js/chainedm2m.js')]

    def render(self, name, value, attrs=None, choices=()):
        if len(name.split('-')) > 1:  # formset
            chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])
        else:
            chain_field = self.chain_field

        view_name = 'chained_filter'

        kwargs = {
            'app': self.to_app_name,
            'model': self.to_model_name,
            'field': self.chained_model_field,
            'foreign_key_app_name': self.foreign_key_app_name,
            'foreign_key_model_name': self.foreign_key_model_name,
            'foreign_key_field_name': self.foreign_key_field_name,
            'value': '1'
            }
        if self.manager is not None:
            kwargs.update({'manager': self.manager})
        url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
        if self.auto_choose:
            auto_choose = 'true'
        else:
            auto_choose = 'false'
        js = """
        <script type="text/javascript">
        (function($) {

        var chainfield = "#id_%(chainfield)s";
        var url = "%(url)s";
        var id = "#%(id)s";
        var value = %(value)s;
        var auto_choose = %(auto_choose)s;

        $(document).ready(function() {
            chainedm2m.init(chainfield, url, id, value, auto_choose);
        });
        })(jQuery || django.jQuery);
        </script>

        """
        js = js % {"chainfield": chain_field,
                   "url": url,
                   "id": attrs['id'],
                   'value': json.dumps(value),
                   'auto_choose': auto_choose}

        # since we cannot deduce the value of the chained_field
        # so we just render empty choices here and let the js
        # fetch related choices later
        final_choices = []
        self.choices = () # need to set explicitly because the Select widget will use it in render
        final_attrs = self.build_attrs(attrs, name=name)
        if 'class' in final_attrs:
            final_attrs['class'] += ' chained'
        else:
            final_attrs['class'] = 'chained'
        output = super(ChainedSelectMultiple, self).render(name, value, final_attrs, choices=final_choices)
        output += js
        return mark_safe(output)
<|endoftext|>


<commit_before>import os, sys

VERBOSE=True

class Diagram(object):
    def __init__(self, filePath, verbose=VERBOSE, spin=True):
        self.filePath = filePath
        self.verbose = VERBOSE
        self.spin = spin
        self.spinOccupation=False
    def vprint(self, something, err=False):
        if self.verbose:
            if not err :
                print("Diagram:: %s"%something)
            else:
                raise Exception("Diagram::ERROR:: %s"%something)
    def _parseFile(self):
        """ This function parses the electronic configuration of the filePath """
        try:
            self.vprint("Trying to open file %s"%self.filePath)
            fd = open(self.filePath,"r")
        except IOError, e:
            self.vprint("File %s could not be opened"%self.filePath, True)
            raise IOError(e)
        else:
            self.vprint("Reading file")
            fileBuffer = fd.read()
            if self.spin:
                return self._parseSpin(fileBuffer)
    def _parseSpin(self, fileBuffer):
        self.spinOccupation = {"1":[], "2":[]}
        separator = {"1":"spin component 2", "2":"-----"}
        for spin in ["1","2"]:
            self.vprint("Parsing information for spin %s"%spin)
            # The separators tell you up until which characters the spin part goes
            # For spin component 1, the information goes until the text spin component 2 is found
            # For spin component 2, the information goes until the ------ line is found
            spinBuffer = fileBuffer.split("spin component %s"%spin)
            if len(spinBuffer)==1:
                self.vprint("There is no 'spin component %s' part in file %s"%(spin, self.filePath), True)
                sys.exit(-1)
            else:
                lastSpinBuffer = spinBuffer[-1]
                lastSpinBufferCleaned = lastSpinBuffer.split(separator[spin])
                if len(lastSpinBufferCleaned)==1:
                    self.vprint("There was a problem parsing the information for spin %s"%(spin), True)
                else:
                    self.spinOccupation[spin]=self._parseElectronicConfiguration(lastSpinBufferCleaned[0])
                    #print self.spinOccupation[spin]
        return self.spinOccupation
    def _parseElectronicConfiguration(self, string):
        """
            This function parses the electronic configuration from a string (fileBuffer)
            The format of the string should be a table with the following columns:
                electron_number     electron_energy     electron_occupation
        """
        import re
        result = []
        p = re.compile("(\-?\d+\.?\d*)\s+(\-?\d+\.?\d*)\s+(\-?\d+\.?\d*)")
        stringLines = string.split("\n")
        for line in stringLines:
            match = p.findall(line)
            if match:
                if len(match)==1:
                   # print line
                    niveau = match[0]
                    result.append({"number": niveau[0], "energy":niveau[1], "occupation":niveau[2]})
                    #print niveaus
                else:
                    break
        return result
    def getLastOccuppiedStates(self, spin):
        """
        Returns a dict
            {"valence":occupancy, "conduction":last}
        with the valence state and the conduction (first unoccupied state) state
        """
        self.vprint("Getting last occupied state ...")
        return self.getNthExcitedState(1,spin)
    def getNthExcitedState(self, n, spin):
        if self.spin:
            if not spin in ["1","2"]:
                print("Spin must be either 1 or 2")
                sys.exit(1)
            spin_configuration = self.spinOccupation[spin]
            occupied_states = []
            for state in spin_configuration:
                if float(state["occupation"]):
                    occupied_states.append(state)
            return occupied_states[-n]
    def _geq(self, state1, state2):
        """
        Compares the energy of two states
        """
        if float(state1["energy"])>=float(state2["energy"]):
            return True
        else:
            return False
    def getNLastExcitedStates(self, n):
        """
        *
        *
        *  +
           +

        *
        *
        """
        classified_states = []
        get = "both"
        j = 1
        k = 1
        # init = True
        for i in range(1,int(n)+1):
            if get == "1" or get == "both":
                if get == "both":
                    self.vprint("init")
                    last = self.getNthExcitedState(k, "2")
                    last["spin"] = "2";
                    spin_last = "2"
                    k+=1;
                new = self.getNthExcitedState(j, "1")
                new["spin"] = "1";
                spin_new = "1"
                j+=1;
            else:
                new = self.getNthExcitedState(k, "2")
                new["spin"] = "2";
                spin_new = "2"
                k+=1;
            self.vprint("new %s"%new)
            self.vprint("last %s"%last)
            if self._geq(new, last):
                classified_states.append(new)
                get  = spin_new
            else:
                self.vprint("change")
                classified_states.append(last)
                last = new
                get  = spin_last
                spin_last = spin_new
        return classified_states
    def printNLastExcitedStates(self, n):
        states = self.getNLastExcitedStates(n)
        for state in states:
            print("%s %s"%(state["spin"], state["energy"]))
    def getAllLastNStates(self, down_offset, up_offset=0):
        last = self.getNLastExcitedStates(1)[0]
        # print last
        lastIndex = last["number"]
        # now get everything down_offset underneath
        result_states = []
        for i in range(0,down_offset+1):
            newIndex = int(lastIndex) - i
            for spin in ["1", "2"]:
                newState = self.getStateByIndex(spin, newIndex);
                newState["spin" ]=spin
                result_states.append(newState)
        for i in range(1,up_offset+1):
            newIndex = int(lastIndex) + i
            for spin in ["1", "2"]:
                newState = self.getStateByIndex(spin, newIndex);
                newState["spin" ]=spin
                result_states.append(newState)
        return result_states
    def printAllLastNStates(self, down_offset, up_offset=0):
        states = self.getAllLastNStates(down_offset, up_offset)
        for state in states:
            print("%s %s %s %s"%(state["spin"], state["energy"], state["occupation"], state["number"]))

    def getNthExcitedEnergy(self, n, spin):
        state = self.getNthExcitedState(n,spin)
        self.vprint("Getting energy for electrinic state %s"%state)
        print(state["energy"])
    def getStateByIndex(self, spin, index):
        for state in self.spinOccupation[spin]:
            if float(state["number"]) == float(index):
                return state
        return None
    def getValenceStates(self, spin):
        valence = self.getLastOccuppiedStates( spin )
        # print("VALENCE")
        # print(valence)
        lastIndex = valence["number"]
        condIndex = int(lastIndex)+1
        conduction = self.getStateByIndex(spin, condIndex)
        if conduction:
            return {"valence": valence, "conduction": conduction}
        else:
            raise Exception("Conduction state was not found!")
            return False
    def getBandGap(self):
        if self.spin:
            self.vprint("Getting band gap for the case of two spins...");
            # configuration     = self.spinOccupation;
            valence_states    = []
            conduction_states = []
            for spin in ["1", "2"]:
                self.vprint("Getting bandgap information for spin %s"%spin)
                states             = self.getValenceStates(spin)
                valence_states    += [ states["valence"] ]
                conduction_states += [ states["conduction"] ]
            if float( valence_states[0]["energy"] ) > float( valence_states[1]["energy"] ):
                valence = valence_states[0]
            else:
                valence = valence_states[1]
            if float( conduction_states[0]["energy"] ) < float( conduction_states[1]["energy"] ):
                conduction = conduction_states[0]
            else:
                conduction = conduction_states[1]
            general_bandgap = float(conduction["energy"]) - float(valence["energy"])
            print("VB %s"%valence["energy"])
            print("LB %s"%conduction["energy"])
            print("BG %s"%(general_bandgap))
            return (general_bandgap)
    def getConfiguration(self):
        return self._parseFile()
    def showASCII(self):
        if self.spin:
            if self.spinOccupation:
                nelectrons = min(len(self.spinOccupation["1"]), len(self.spinOccupation["2"]))
                for i in range(nelectrons-1,-1,-1):
                    niveau1 = self.spinOccupation["1"][i]
                    niveau2 = self.spinOccupation["2"][i]
                    if niveau1["number"]==niveau2["number"]==str(i):
                        occupation1 = abs(float(niveau1["occupation"]))
                        occupation2 = abs(float(niveau2["occupation"]))
                        occupiedSymbol=""
                        if occupation1 or occupation2:
                            occupiedSymbol="+"
                        print("%s.\t[%.1f][%.1f]  (%s) \t %s"%(i, occupation1, occupation2, niveau1["energy"], occupiedSymbol ))

            else:
                self.vprint("To show ASCII representation you first have to generate read the electron configuration", True)
    def showHTML(self):
        pass
<commit_msg>fixed showAscii to get all energies<commit_after>import os, sys

VERBOSE=True

class Diagram(object):
    def __init__(self, filePath, verbose=VERBOSE, spin=True):
        self.filePath = filePath
        self.verbose = VERBOSE
        self.spin = spin
        self.spinOccupation=False
    def vprint(self, something, err=False):
        if self.verbose:
            if not err :
                print("Diagram:: %s"%something)
            else:
                raise Exception("Diagram::ERROR:: %s"%something)
    def _parseFile(self):
        """ This function parses the electronic configuration of the filePath """
        try:
            self.vprint("Trying to open file %s"%self.filePath)
            fd = open(self.filePath,"r")
        except IOError, e:
            self.vprint("File %s could not be opened"%self.filePath, True)
            raise IOError(e)
        else:
            self.vprint("Reading file")
            fileBuffer = fd.read()
            if self.spin:
                return self._parseSpin(fileBuffer)
    def _parseSpin(self, fileBuffer):
        self.spinOccupation = {"1":[], "2":[]}
        separator = {"1":"spin component 2", "2":"-----"}
        for spin in ["1","2"]:
            self.vprint("Parsing information for spin %s"%spin)
            # The separators tell you up until which characters the spin part goes
            # For spin component 1, the information goes until the text spin component 2 is found
            # For spin component 2, the information goes until the ------ line is found
            spinBuffer = fileBuffer.split("spin component %s"%spin)
            if len(spinBuffer)==1:
                self.vprint("There is no 'spin component %s' part in file %s"%(spin, self.filePath), True)
                sys.exit(-1)
            else:
                lastSpinBuffer = spinBuffer[-1]
                lastSpinBufferCleaned = lastSpinBuffer.split(separator[spin])
                if len(lastSpinBufferCleaned)==1:
                    self.vprint("There was a problem parsing the information for spin %s"%(spin), True)
                else:
                    self.spinOccupation[spin]=self._parseElectronicConfiguration(lastSpinBufferCleaned[0])
                    #print self.spinOccupation[spin]
        return self.spinOccupation
    def _parseElectronicConfiguration(self, string):
        """
            This function parses the electronic configuration from a string (fileBuffer)
            The format of the string should be a table with the following columns:
                electron_number     electron_energy     electron_occupation
        """
        import re
        result = []
        p = re.compile("(\-?\d+\.?\d*)\s+(\-?\d+\.?\d*)\s+(\-?\d+\.?\d*)")
        stringLines = string.split("\n")
        for line in stringLines:
            match = p.findall(line)
            if match:
                if len(match)==1:
                   # print line
                    niveau = match[0]
                    result.append({"number": niveau[0], "energy":niveau[1], "occupation":niveau[2]})
                    #print niveaus
                else:
                    break
        return result
    def getLastOccuppiedStates(self, spin):
        """
        Returns a dict
            {"valence":occupancy, "conduction":last}
        with the valence state and the conduction (first unoccupied state) state
        """
        self.vprint("Getting last occupied state ...")
        return self.getNthExcitedState(1,spin)
    def getNthExcitedState(self, n, spin):
        if self.spin:
            if not spin in ["1","2"]:
                print("Spin must be either 1 or 2")
                sys.exit(1)
            spin_configuration = self.spinOccupation[spin]
            occupied_states = []
            for state in spin_configuration:
                if float(state["occupation"]):
                    occupied_states.append(state)
            return occupied_states[-n]
    def _geq(self, state1, state2):
        """
        Compares the energy of two states
        """
        if float(state1["energy"])>=float(state2["energy"]):
            return True
        else:
            return False
    def getNLastExcitedStates(self, n):
        """
        *
        *
        *  +
           +

        *
        *
        """
        classified_states = []
        get = "both"
        j = 1
        k = 1
        # init = True
        for i in range(1,int(n)+1):
            if get == "1" or get == "both":
                if get == "both":
                    self.vprint("init")
                    last = self.getNthExcitedState(k, "2")
                    last["spin"] = "2";
                    spin_last = "2"
                    k+=1;
                new = self.getNthExcitedState(j, "1")
                new["spin"] = "1";
                spin_new = "1"
                j+=1;
            else:
                new = self.getNthExcitedState(k, "2")
                new["spin"] = "2";
                spin_new = "2"
                k+=1;
            self.vprint("new %s"%new)
            self.vprint("last %s"%last)
            if self._geq(new, last):
                classified_states.append(new)
                get  = spin_new
            else:
                self.vprint("change")
                classified_states.append(last)
                last = new
                get  = spin_last
                spin_last = spin_new
        return classified_states
    def printNLastExcitedStates(self, n):
        states = self.getNLastExcitedStates(n)
        for state in states:
            print("%s %s"%(state["spin"], state["energy"]))
    def getAllLastNStates(self, down_offset, up_offset=0):
        last = self.getNLastExcitedStates(1)[0]
        # print last
        lastIndex = last["number"]
        # now get everything down_offset underneath
        result_states = []
        for i in range(0,down_offset+1):
            newIndex = int(lastIndex) - i
            for spin in ["1", "2"]:
                newState = self.getStateByIndex(spin, newIndex);
                newState["spin" ]=spin
                result_states.append(newState)
        for i in range(1,up_offset+1):
            newIndex = int(lastIndex) + i
            for spin in ["1", "2"]:
                newState = self.getStateByIndex(spin, newIndex);
                newState["spin" ]=spin
                result_states.append(newState)
        return result_states
    def printAllLastNStates(self, down_offset, up_offset=0):
        states = self.getAllLastNStates(down_offset, up_offset)
        for state in states:
            print("%s %s %s %s"%(state["spin"], state["energy"], state["occupation"], state["number"]))

    def getNthExcitedEnergy(self, n, spin):
        state = self.getNthExcitedState(n,spin)
        self.vprint("Getting energy for electrinic state %s"%state)
        print(state["energy"])
    def getStateByIndex(self, spin, index):
        for state in self.spinOccupation[spin]:
            if float(state["number"]) == float(index):
                return state
        return None
    def getValenceStates(self, spin):
        valence = self.getLastOccuppiedStates( spin )
        # print("VALENCE")
        # print(valence)
        lastIndex = valence["number"]
        condIndex = int(lastIndex)+1
        conduction = self.getStateByIndex(spin, condIndex)
        if conduction:
            return {"valence": valence, "conduction": conduction}
        else:
            raise Exception("Conduction state was not found!")
            return False
    def getBandGap(self):
        if self.spin:
            self.vprint("Getting band gap for the case of two spins...");
            # configuration     = self.spinOccupation;
            valence_states    = []
            conduction_states = []
            for spin in ["1", "2"]:
                self.vprint("Getting bandgap information for spin %s"%spin)
                states             = self.getValenceStates(spin)
                valence_states    += [ states["valence"] ]
                conduction_states += [ states["conduction"] ]
            if float( valence_states[0]["energy"] ) > float( valence_states[1]["energy"] ):
                valence = valence_states[0]
            else:
                valence = valence_states[1]
            if float( conduction_states[0]["energy"] ) < float( conduction_states[1]["energy"] ):
                conduction = conduction_states[0]
            else:
                conduction = conduction_states[1]
            general_bandgap = float(conduction["energy"]) - float(valence["energy"])
            print("VB %s"%valence["energy"])
            print("LB %s"%conduction["energy"])
            print("BG %s"%(general_bandgap))
            return (general_bandgap)
    def getConfiguration(self):
        return self._parseFile()
    def showASCII(self):
        if self.spin:
            if self.spinOccupation:
                nelectrons = min(len(self.spinOccupation["1"]), len(self.spinOccupation["2"]))
                for i in range(nelectrons-1,-1,-1):
                    niveau1 = self.spinOccupation["1"][i]
                    niveau2 = self.spinOccupation["2"][i]
                    if niveau1["number"]==niveau2["number"]==str(i):
                        occupation1 = abs(float(niveau1["occupation"]))
                        occupation2 = abs(float(niveau2["occupation"]))
                        occupiedSymbol=""
                        if occupation1 or occupation2:
                            occupiedSymbol="+"
                        print("%s.\t(%s) [%.1f][%.1f]  (%s) \t %s"%(i, niveau2["energy"], occupation1, occupation2, niveau1["energy"], occupiedSymbol ))

            else:
                self.vprint("To show ASCII representation you first have to generate read the electron configuration", True)
    def showHTML(self):
        pass
<|endoftext|>


<commit_before>#!/usr/bin/env python 3

import os
import sublime
import sublime_plugin
import re
import sys

__version__ = '0.1.0'
__authors__ = ['Ryan Grannell (@RyanGrannell)']

is_python3 = sys.version_info[0] > 2

# -- Snippet
#
# -- A wrapper for constructing sublime-texts XML snippets
# -- from a snippet body, tabtrigger, scope and description.

def Snippet (content, trigger = None, scope = None):

	if scope and scope is not '*':
		if trigger:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>{1}</tabTrigger>
					<scope>{2}</scope>
				</snippet>
				'''

			return template.format(content, trigger, scope)

		else:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<scope>{1}</scope>
					<tabTrigger>$$</tabTrigger>
				</snippet>
				'''

			return template.format(content, scope)

	else:

		if trigger:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>{1}</tabTrigger>
				</snippet>
				'''

			return template.format(content, trigger)

		else:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>$$</tabTrigger>
				</snippet>
				'''

			return template.format(content)

# -- parse_args
#
# -- parse the snippets argument line.

def parse_args (line):
	# -- lex and parse expressions of the form
	# -- > (ps|ts) [scope] [tab-trigger]

	# -- combine the following into the following large regexp:
	#^>[ 	]+(t|p)[ 	]+([st]\.[^ 	]+)[ 	]+.+

	prompt          = '>'
	space_rexp      = '[ 	]+'
	storage_rexp    = '(t|p)'
	lang_rexp       = '[*]|([st]\.[^ 	]+)'
	trigger_rexp    = '.+'

	valid_args_rexp = re.compile(prompt + space_rexp + storage_rexp + \
		space_rexp + lang_rexp + space_rexp + trigger_rexp)

	if valid_args_rexp.search(line) is None:
		print("-- snipboard: could not match " + line + " as snippet arguments.")
	else:

		blocks = re.split(space_rexp, line, 3)

		return {
			'storage' : blocks[1],
			'language': blocks[2],
			'trigger' : blocks[3]
		}

# -- compile_args
#
# -- compile the arguments passed to a snipboard snippet to
# -- a form useable by normal sublime snippets.

def compile_args (args):

	language = args['language']
	storage  = args['storage']
	trigger  = args['trigger']

	# -- compile s.lang -> source.lang,
	# -- compile t.lang -> text   .lang

	language = re.sub('^s\.', 'source.', language)
	language = re.sub('^t\.', 'text.',   language)

	return {
		'storage' : storage,
		'language': language,
		'trigger' : trigger
	}

# -- constants
#
# -- shorthand replacements for existing sublime-text
# -- snippets.

constants = (
	['$s',  '$SELECTION'],
	['$l',  '$TM_CURRENT_LINE'],
	['$w',  '$TM_CURRENT_WORD'],
	['$fn', '$TM_FILENAME'],
	['$fp', '$TM_FILEPATH'],
	['$li', '$TM_LINE_INDEX'],
	['$ln', '$TM_LINE_NUMBER'],
	['$st', '$TM_SOFT_TABS'],
	['$ts', '$TM_TAB_SIZE'],

	['$text',     '$SELECTION'],
	['$line',     '$TM_CURRENT_LINE'],
	['$word',     '$TM_CURRENT_WORD'],
	['$filename', '$TM_FILENAME'],
	['$filepath', '$TM_FILEPATH'],
	['$lineind',  '$TM_LINE_INDEX'],
	['$linenum',  '$TM_LINE_NUMBER'],
	['$softtab',  '$TM_SOFT_TABS'],
	['$tabsize',  '$TM_TAB_SIZE'],
)

# -- compile_body
#
# -- compile .

def compile_body (body):
	return body

# -- compile_snippet
#
# -- compile a snipboard snippet into an XML sublime text snippet.

def compile_snippet (snippet):

	if snippet.startswith('>'):
		# -- snippet includes additional arguments on the first line.

		snippet_args = snippet.split('\n')   [0]
		snippet_body = snippet.split('\n', 1)[1]

		args = compile_args(parse_args(snippet_args))
		body = compile_body(snippet_body)

		return args, Snippet(body, args['trigger'], args['language'])

	else:
		# -- snippet does not include additional arguments; use defaults.

		snippet_body = snippet

		args         = {
			"storage":  't',
			"language": '*',
			"trigger":  '$$'
		}

		body         = compile_body(snippet_body)

		return args, Snippet(body)

# -- write_to_snipboard
#
# -- write the sublime text snippet to a file.

def write_to_snipboard (args, content):

	platform_name = sys.platform

	if args['storage'] is 't':
		# -- store temporarily.

		fpaths = {
			'linux': os.path.expanduser('~/.config/sublime-text-3/Packages/snipboard/snipboard.sublime-snippet')
		}
		out_path      = fpaths[platform_name]

	elif args['storage'] is 'p':
		# -- store permanently.

		pass

	else:
		raise KeyError("-- snipboard: internal error in 'write_to_snipboard'")

	try:
		file = open(out_path, "w")
	except IOError:
		raise IOError('-- snipboard: could not open ' + out_path)
	else:
		print('-- snipboard: writing to ' + out_path)

		file.write(content)
		file.close()

# -- SnipboardCommand
#
# -- The interface to snipboard for SublimeText.

class SnipboardCommand (sublime_plugin.WindowCommand):

	def run (self):

		print('-- snipboard: initialised.')

		window = self.window
		view   = window.active_view()
		sel    = view.sel()

		# -- get text from the first selection.
		select_text = view.substr(sel[0])

		if select_text:
			args, xml = compile_snippet(select_text)
			write_to_snipboard(args, xml)
		else:
			raise SyntaxError('-- snipboard: cannot create a snippet from no input.')
<commit_msg>added functioning permenant storage<commit_after>#!/usr/bin/env python 3

import os
import sublime
import sublime_plugin
import re
import random
import sys

__version__ = '0.1.0'
__authors__ = ['Ryan Grannell (@RyanGrannell)']

is_python3 = sys.version_info[0] > 2

# -- Snippet
#
# -- A wrapper for constructing sublime-texts XML snippets
# -- from a snippet body, tabtrigger, scope and description.

def Snippet (content, trigger = None, scope = None):

	if scope and scope is not '*':
		if trigger:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>{1}</tabTrigger>
					<scope>{2}</scope>
				</snippet>
				'''

			return template.format(content, trigger, scope)

		else:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<scope>{1}</scope>
					<tabTrigger>$$</tabTrigger>
				</snippet>
				'''

			return template.format(content, scope)

	else:

		if trigger:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>{1}</tabTrigger>
				</snippet>
				'''

			return template.format(content, trigger)

		else:

			template = '''
				<snippet>
					<content><![CDATA[{0}]]></content>
					<tabTrigger>$$</tabTrigger>
				</snippet>
				'''

			return template.format(content)

# -- parse_args
#
# -- parse the snippets argument line.

def parse_args (line):
	# -- lex and parse expressions of the form
	# -- > (ps|ts) [scope] [tab-trigger]

	# -- combine the following into the following large regexp:
	#^>[ 	]+(t|p)[ 	]+([st]\.[^ 	]+)[ 	]+.+

	prompt          = '>'
	space_rexp      = '[ 	]+'
	storage_rexp    = '(t|p)'
	lang_rexp       = '[*]|([st]\.[^ 	]+)'
	trigger_rexp    = '.+'

	valid_args_rexp = re.compile(prompt + space_rexp + storage_rexp + \
		space_rexp + lang_rexp + space_rexp + trigger_rexp)

	if valid_args_rexp.search(line) is None:
		print("-- snipboard: could not match " + line + " as snippet arguments.")
	else:

		blocks = re.split(space_rexp, line, 3)

		return {
			'storage' : blocks[1],
			'language': blocks[2],
			'trigger' : blocks[3]
		}

# -- compile_args
#
# -- compile the arguments passed to a snipboard snippet to
# -- a form useable by normal sublime snippets.

def compile_args (args):

	language = args['language']
	storage  = args['storage']
	trigger  = args['trigger']

	# -- compile s.lang -> source.lang,
	# -- compile t.lang -> text   .lang

	language = re.sub('^s\.', 'source.', language)
	language = re.sub('^t\.', 'text.',   language)

	return {
		'storage' : storage,
		'language': language,
		'trigger' : trigger
	}

# -- constants
#
# -- shorthand replacements for existing sublime-text
# -- snippets.

constants = (
	['$s',  '$SELECTION'],
	['$l',  '$TM_CURRENT_LINE'],
	['$w',  '$TM_CURRENT_WORD'],
	['$fn', '$TM_FILENAME'],
	['$fp', '$TM_FILEPATH'],
	['$li', '$TM_LINE_INDEX'],
	['$ln', '$TM_LINE_NUMBER'],
	['$st', '$TM_SOFT_TABS'],
	['$ts', '$TM_TAB_SIZE'],

	['$text',     '$SELECTION'],
	['$line',     '$TM_CURRENT_LINE'],
	['$word',     '$TM_CURRENT_WORD'],
	['$filename', '$TM_FILENAME'],
	['$filepath', '$TM_FILEPATH'],
	['$lineind',  '$TM_LINE_INDEX'],
	['$linenum',  '$TM_LINE_NUMBER'],
	['$softtab',  '$TM_SOFT_TABS'],
	['$tabsize',  '$TM_TAB_SIZE'],
)

# -- compile_body
#
# -- compile .

def compile_body (body):
	return body

# -- compile_snippet
#
# -- compile a snipboard snippet into an XML sublime text snippet.

def compile_snippet (snippet):

	if snippet.startswith('>'):
		# -- snippet includes additional arguments on the first line.

		snippet_args = snippet.split('\n')   [0]
		snippet_body = snippet.split('\n', 1)[1]

		args = compile_args(parse_args(snippet_args))
		body = compile_body(snippet_body)

		return args, Snippet(body, args['trigger'], args['language'])

	else:
		# -- snippet does not include additional arguments; use defaults.

		snippet_body = snippet

		args         = {
			"storage":  't',
			"language": '*',
			"trigger":  '$$'
		}

		body         = compile_body(snippet_body)

		return args, Snippet(body)

# -- write_to_snipboard
#
# -- write the sublime text snippet to a file.

def write_to_snipboard (args, content):

	platform_name = sys.platform

	if args['storage'] is 't':
		# -- store snippet temporarily.

		fpaths = {
			'linux': os.path.expanduser('~/.config/sublime-text-3/Packages/snipboard/')
		}

		snippet_name = 'snipboard'

	elif args['storage'] is 'p':
		# -- store permanently, to user-snippets.

		fpaths = {
			'linux': os.path.expanduser('~/.config/sublime-text-3/Packages/User/')
		}

		# -- 50% chance of collision at 77,163 snippets.
		# -- change eventually to something better.
		snippet_name = 'snipboard-snippet-' + str(random.getrandbits(32))

	else:
		raise KeyError("-- snipboard: internal error in 'write_to_snipboard'")

	# -- check that the snippet directory actually exists.

	if not os.path.isdir(fpaths[platform_name]):
		raise IOError('-- snipboard: the file path "' + out_path + '" does not exist (platform ' + platform_name + ')')

	out_path = fpaths[platform_name] + snippet_name + '.sublime-snippet'

	# -- try write the snippet to a file.

	try:
		file = open(out_path, "w")
	except IOError:
		raise IOError('-- snipboard: could not open ' + out_path)
	else:
		print('-- snipboard: writing to ' + out_path)

		file.write(content)
		file.close()

# -- SnipboardCommand
#
# -- The interface to snipboard for SublimeText.

class SnipboardCommand (sublime_plugin.WindowCommand):

	def run (self):

		print('-- snipboard: initialised.')

		window = self.window
		view   = window.active_view()
		sel    = view.sel()

		# -- get text from the first selection.
		select_text = view.substr(sel[0])

		if select_text:
			args, xml = compile_snippet(select_text)
			write_to_snipboard(args, xml)
		else:
			raise SyntaxError('-- snipboard: cannot create a snippet from no input.')
<|endoftext|>


<commit_before>import hashlib
import json
from datetime import datetime
from urllib.parse import urljoin, urlparse

from django.conf import settings
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.template.loader import render_to_string
from django.utils.functional import cached_property

import brotli

from snippets.base import util
from snippets.base.models import STATUS_CHOICES, ASRSnippet, Snippet

ONE_DAY = 60 * 60 * 24

SNIPPET_FETCH_TEMPLATE_HASH = hashlib.sha1(
    render_to_string(
        'base/fetch_snippets.jinja',
        {
            'date': '',
            'snippet_ids': [],
            'snippets_json': '',
            'locale': 'xx',
            'settings': settings,
            'current_firefox_major_version': '00',
            'metrics_url': settings.METRICS_URL,
        }
    ).encode('utf-8')).hexdigest()

SNIPPET_FETCH_TEMPLATE_AS_HASH = hashlib.sha1(
    render_to_string(
        'base/fetch_snippets_as.jinja',
        {
            'date': '',
            'snippet_ids': [],
            'snippets_json': '',
            'locale': 'xx',
            'settings': settings,
            'current_firefox_major_version': '00',
            'metrics_url': settings.METRICS_URL,
        }
    ).encode('utf-8')).hexdigest()

class SnippetBundle(object):
    """
    Group of snippets to be sent to a particular client configuration.
    """
    def __init__(self, client):
        self.client = client

    @cached_property
    def key(self):
        """A unique key for this bundle as a sha1 hexdigest."""
        # Key should consist of snippets that are in the bundle. This part
        # accounts for all the properties sent by the Client, since the
        # self.snippets lists snippets are all filters and CMRs have been
        # applied.
        key_properties = [
            '{id}-{date}-{templatedate}'.format(id=snippet.id,
                                                date=snippet.modified.isoformat(),
                                                templatedate=snippet.template.modified.isoformat())
            for snippet in self.snippets]

        # Additional values used to calculate the key are the templates and the
        # variables used to render them besides snippets.
        key_properties.extend([
            str(self.client.startpage_version),
            self.client.locale,
            util.current_firefox_major_version(),
            str(settings.BUNDLE_BROTLI_COMPRESS),
        ])
        if self.client.startpage_version >= 5:
            key_properties.append(SNIPPET_FETCH_TEMPLATE_AS_HASH)
        else:
            key_properties.append(SNIPPET_FETCH_TEMPLATE_HASH)

        key_string = '_'.join(key_properties)
        return hashlib.sha1(key_string.encode('utf-8')).hexdigest()

    @property
    def empty(self):
        return len(self.snippets) == 0

    @property
    def cache_key(self):
        return 'bundle_' + self.key

    @property
    def cached(self):
        if cache.get(self.cache_key):
            return True

        # Check if available on S3 already.
        if default_storage.exists(self.filename):
            cache.set(self.cache_key, True, ONE_DAY)
            return True

        return False

    @property
    def expired(self):
        """
        If True, the code for this bundle should be re-generated before
        use.
        """
        return not cache.get(self.cache_key)

    @property
    def filename(self):
        return urljoin(settings.MEDIA_BUNDLES_ROOT, 'bundle_{0}.html'.format(self.key))

    @property
    def url(self):
        bundle_url = default_storage.url(self.filename)
        full_url = urljoin(settings.SITE_URL, bundle_url).split('?')[0]
        cdn_url = getattr(settings, 'CDN_URL', None)
        if cdn_url:
            full_url = urljoin(cdn_url, urlparse(bundle_url).path)

        return full_url

    @cached_property
    def snippets(self):
        return (Snippet.objects
                .filter(published=True)
                .match_client(self.client)
                .select_related('template')
                .prefetch_related('countries', 'exclude_from_search_providers')
                .filter_by_available())

    def generate(self):
        """Generate and save the code for this snippet bundle."""
        template = 'base/fetch_snippets.jinja'
        if self.client.startpage_version == 5:
            template = 'base/fetch_snippets_as.jinja'
        bundle_content = render_to_string(template, {
            'snippet_ids': [snippet.id for snippet in self.snippets],
            'snippets_json': json.dumps([s.to_dict() for s in self.snippets]),
            'client': self.client,
            'locale': self.client.locale,
            'settings': settings,
            'current_firefox_major_version': util.current_firefox_major_version(),
        })

        if isinstance(bundle_content, str):
            bundle_content = bundle_content.encode('utf-8')

        if (settings.BUNDLE_BROTLI_COMPRESS and self.client.startpage_version >= 5):
            content_file = ContentFile(brotli.compress(bundle_content))
            content_file.content_encoding = 'br'
        else:
            content_file = ContentFile(bundle_content)

        default_storage.save(self.filename, content_file)
        cache.set(self.cache_key, True, ONE_DAY)

class ASRSnippetBundle(SnippetBundle):

    @cached_property
    def key(self):
        """A unique key for this bundle as a sha1 hexdigest."""
        # Key should consist of snippets that are in the bundle. This part
        # accounts for all the properties sent by the Client, since the
        # self.snippets lists snippets are all filters and CMRs have been
        # applied.
        #
        # Key must change when Snippet or related Template, Campaign or Target
        # get updated.
        key_properties = []
        for snippet in self.snippets:
            attributes = [
                snippet.id,
                snippet.modified.isoformat(),
                snippet.template.modified.isoformat(),
                snippet.target.modified.isoformat(),
            ]
            if snippet.campaign:
                attributes.append(snippet.campaign.modified.isoformat())

            key_properties.append('-'.join([str(x) for x in attributes]))

        # Additional values used to calculate the key are the templates and the
        # variables used to render them besides snippets.
        key_properties.extend([
            str(self.client.startpage_version),
            self.client.locale,
            str(settings.BUNDLE_BROTLI_COMPRESS),
        ])

        key_string = '_'.join(key_properties)
        return hashlib.sha1(key_string.encode('utf-8')).hexdigest()

    @property
    def filename(self):
        return urljoin(settings.MEDIA_BUNDLES_ROOT, 'bundle_{0}.json'.format(self.key))

    @cached_property
    def snippets(self):
        return (ASRSnippet.objects
                .filter(status=STATUS_CHOICES['Published'])
                .select_related('template', 'campaign', 'target')
                .match_client(self.client)
                .filter_by_available())

    def generate(self):
        """Generate and save the code for this snippet bundle."""
        # Generate the new AS Router bundle format
        data = [snippet.render() for snippet in self.snippets]
        bundle_content = json.dumps({
            'messages': data,
            'metadata': {
                'generated_at': datetime.utcnow().isoformat(),
            }
        })

        if isinstance(bundle_content, str):
            bundle_content = bundle_content.encode('utf-8')

        if settings.BUNDLE_BROTLI_COMPRESS:
            content_file = ContentFile(brotli.compress(bundle_content))
            content_file.content_encoding = 'br'
        else:
            content_file = ContentFile(bundle_content)

        default_storage.save(self.filename, content_file)
        cache.set(self.cache_key, True, ONE_DAY)
<commit_msg>Include number of snippets in ASR payload.<commit_after>import hashlib
import json
from datetime import datetime
from urllib.parse import urljoin, urlparse

from django.conf import settings
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.template.loader import render_to_string
from django.utils.functional import cached_property

import brotli

from snippets.base import util
from snippets.base.models import STATUS_CHOICES, ASRSnippet, Snippet

ONE_DAY = 60 * 60 * 24

SNIPPET_FETCH_TEMPLATE_HASH = hashlib.sha1(
    render_to_string(
        'base/fetch_snippets.jinja',
        {
            'date': '',
            'snippet_ids': [],
            'snippets_json': '',
            'locale': 'xx',
            'settings': settings,
            'current_firefox_major_version': '00',
            'metrics_url': settings.METRICS_URL,
        }
    ).encode('utf-8')).hexdigest()

SNIPPET_FETCH_TEMPLATE_AS_HASH = hashlib.sha1(
    render_to_string(
        'base/fetch_snippets_as.jinja',
        {
            'date': '',
            'snippet_ids': [],
            'snippets_json': '',
            'locale': 'xx',
            'settings': settings,
            'current_firefox_major_version': '00',
            'metrics_url': settings.METRICS_URL,
        }
    ).encode('utf-8')).hexdigest()

class SnippetBundle(object):
    """
    Group of snippets to be sent to a particular client configuration.
    """
    def __init__(self, client):
        self.client = client

    @cached_property
    def key(self):
        """A unique key for this bundle as a sha1 hexdigest."""
        # Key should consist of snippets that are in the bundle. This part
        # accounts for all the properties sent by the Client, since the
        # self.snippets lists snippets are all filters and CMRs have been
        # applied.
        key_properties = [
            '{id}-{date}-{templatedate}'.format(id=snippet.id,
                                                date=snippet.modified.isoformat(),
                                                templatedate=snippet.template.modified.isoformat())
            for snippet in self.snippets]

        # Additional values used to calculate the key are the templates and the
        # variables used to render them besides snippets.
        key_properties.extend([
            str(self.client.startpage_version),
            self.client.locale,
            util.current_firefox_major_version(),
            str(settings.BUNDLE_BROTLI_COMPRESS),
        ])
        if self.client.startpage_version >= 5:
            key_properties.append(SNIPPET_FETCH_TEMPLATE_AS_HASH)
        else:
            key_properties.append(SNIPPET_FETCH_TEMPLATE_HASH)

        key_string = '_'.join(key_properties)
        return hashlib.sha1(key_string.encode('utf-8')).hexdigest()

    @property
    def empty(self):
        return len(self.snippets) == 0

    @property
    def cache_key(self):
        return 'bundle_' + self.key

    @property
    def cached(self):
        if cache.get(self.cache_key):
            return True

        # Check if available on S3 already.
        if default_storage.exists(self.filename):
            cache.set(self.cache_key, True, ONE_DAY)
            return True

        return False

    @property
    def expired(self):
        """
        If True, the code for this bundle should be re-generated before
        use.
        """
        return not cache.get(self.cache_key)

    @property
    def filename(self):
        return urljoin(settings.MEDIA_BUNDLES_ROOT, 'bundle_{0}.html'.format(self.key))

    @property
    def url(self):
        bundle_url = default_storage.url(self.filename)
        full_url = urljoin(settings.SITE_URL, bundle_url).split('?')[0]
        cdn_url = getattr(settings, 'CDN_URL', None)
        if cdn_url:
            full_url = urljoin(cdn_url, urlparse(bundle_url).path)

        return full_url

    @cached_property
    def snippets(self):
        return (Snippet.objects
                .filter(published=True)
                .match_client(self.client)
                .select_related('template')
                .prefetch_related('countries', 'exclude_from_search_providers')
                .filter_by_available())

    def generate(self):
        """Generate and save the code for this snippet bundle."""
        template = 'base/fetch_snippets.jinja'
        if self.client.startpage_version == 5:
            template = 'base/fetch_snippets_as.jinja'
        bundle_content = render_to_string(template, {
            'snippet_ids': [snippet.id for snippet in self.snippets],
            'snippets_json': json.dumps([s.to_dict() for s in self.snippets]),
            'client': self.client,
            'locale': self.client.locale,
            'settings': settings,
            'current_firefox_major_version': util.current_firefox_major_version(),
        })

        if isinstance(bundle_content, str):
            bundle_content = bundle_content.encode('utf-8')

        if (settings.BUNDLE_BROTLI_COMPRESS and self.client.startpage_version >= 5):
            content_file = ContentFile(brotli.compress(bundle_content))
            content_file.content_encoding = 'br'
        else:
            content_file = ContentFile(bundle_content)

        default_storage.save(self.filename, content_file)
        cache.set(self.cache_key, True, ONE_DAY)

class ASRSnippetBundle(SnippetBundle):

    @cached_property
    def key(self):
        """A unique key for this bundle as a sha1 hexdigest."""
        # Key should consist of snippets that are in the bundle. This part
        # accounts for all the properties sent by the Client, since the
        # self.snippets lists snippets are all filters and CMRs have been
        # applied.
        #
        # Key must change when Snippet or related Template, Campaign or Target
        # get updated.
        key_properties = []
        for snippet in self.snippets:
            attributes = [
                snippet.id,
                snippet.modified.isoformat(),
                snippet.template.modified.isoformat(),
                snippet.target.modified.isoformat(),
            ]
            if snippet.campaign:
                attributes.append(snippet.campaign.modified.isoformat())

            key_properties.append('-'.join([str(x) for x in attributes]))

        # Additional values used to calculate the key are the templates and the
        # variables used to render them besides snippets.
        key_properties.extend([
            str(self.client.startpage_version),
            self.client.locale,
            str(settings.BUNDLE_BROTLI_COMPRESS),
        ])

        key_string = '_'.join(key_properties)
        return hashlib.sha1(key_string.encode('utf-8')).hexdigest()

    @property
    def filename(self):
        return urljoin(settings.MEDIA_BUNDLES_ROOT, 'bundle_{0}.json'.format(self.key))

    @cached_property
    def snippets(self):
        return (ASRSnippet.objects
                .filter(status=STATUS_CHOICES['Published'])
                .select_related('template', 'campaign', 'target')
                .match_client(self.client)
                .filter_by_available())

    def generate(self):
        """Generate and save the code for this snippet bundle."""
        # Generate the new AS Router bundle format
        data = [snippet.render() for snippet in self.snippets]
        bundle_content = json.dumps({
            'messages': data,
            'metadata': {
                'generated_at': datetime.utcnow().isoformat(),
                'number_of_snippets': len(self.snippets),
            }
        })

        if isinstance(bundle_content, str):
            bundle_content = bundle_content.encode('utf-8')

        if settings.BUNDLE_BROTLI_COMPRESS:
            content_file = ContentFile(brotli.compress(bundle_content))
            content_file.content_encoding = 'br'
        else:
            content_file = ContentFile(bundle_content)

        default_storage.save(self.filename, content_file)
        cache.set(self.cache_key, True, ONE_DAY)
<|endoftext|>


<commit_before>##################################################
# VisualizerService_services_server.py
#      Generated by ZSI.generate.wsdl2dispatch.ServiceModuleWriter
#
##################################################

from VisualizerService_services import *
from ZSI.ServiceContainer import ServiceSOAPBinding

class VisualizerService(ServiceSOAPBinding):
    soapAction = {}
    root = {}
    _wsdl = """<?xml version=\"1.0\" ?>
<wsdl:definitions name=\"VisualizerService\" targetNamespace=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
	<wsdl:types>
		<xsd:schema targetNamespace=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:apollo=\"http://types.apollo.pitt.edu/\">
			<xsd:import namespace=\"http://types.apollo.pitt.edu/\" schemaLocation=\"apollo-types.xsd\">
			</xsd:import>
			<xsd:element name=\"run\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"visualizerConfiguration\" type=\"apollo:VisualizerConfiguration\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"runResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"visualizerResult\" type=\"apollo:VisualizerResult\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getRunStatus\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runId\" type=\"apollo:RunIdentification\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getRunStatusResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runStatus\" type=\"apollo:RunStatus\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getConfigurationFileForRun\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runIdentification\" type=\"apollo:RunIdentification\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getConfigurationFileForRunResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"configurationFile\" type=\"xsd:string\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
		</xsd:schema>
	</wsdl:types>
	<wsdl:message name=\"runRequest\">
		<wsdl:part element=\"tns:run\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"runResponse\">
		<wsdl:part element=\"tns:runResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getRunStatusRequest\">
		<wsdl:part element=\"tns:getRunStatus\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getRunStatusResponse\">
		<wsdl:part element=\"tns:getRunStatusResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getConfigurationFileForRunRequest\">
		<wsdl:part element=\"tns:getConfigurationFileForRun\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getConfigurationFileForRunResponse\">
		<wsdl:part element=\"tns:getConfigurationFileForRunResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:portType name=\"VisualizerServiceEI\">
		<wsdl:operation name=\"run\">
			<wsdl:input message=\"tns:runRequest\"/>
			<wsdl:output message=\"tns:runResponse\"/>
		</wsdl:operation>
		<wsdl:operation name=\"getRunStatus\">
			<wsdl:input message=\"tns:getRunStatusRequest\"/>
			<wsdl:output message=\"tns:getRunStatusResponse\"/>
		</wsdl:operation>
		<wsdl:operation name=\"getConfigurationFileForRun\">
			<wsdl:input message=\"tns:getConfigurationFileForRunRequest\"/>
			<wsdl:output message=\"tns:getConfigurationFileForRunResponse\"/>
		</wsdl:operation>
	</wsdl:portType>
	<wsdl:binding name=\"VisualizerServiceBinding\" type=\"tns:VisualizerServiceEI\">
		<soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>
		<wsdl:operation name=\"run\">
			<soap:operation soapAction=\"http://service.apollo.pitt.edu/visualizerservice/run\"/>
			<wsdl:input>
				<soap:body use=\"literal\"/>
			</wsdl:input>
			<wsdl:output>
				<soap:body use=\"literal\"/>
			</wsdl:output>
		</wsdl:operation>
		<wsdl:operation name=\"getRunStatus\">
			<soap:operation soapAction=\"http://service.apollo.pitt.edu/visualizerservice/getRunStatus\"/>
			<wsdl:input>
				<soap:body use=\"literal\"/>
			</wsdl:input>
			<wsdl:output>
				<soap:body use=\"literal\"/>
			</wsdl:output>
		</wsdl:operation>
	</wsdl:binding>
	<wsdl:service name=\"VisualizerService\">
		<wsdl:port binding=\"tns:VisualizerServiceBinding\" name=\"VisualizerServiceEndpoint\">
			<soap:address location=\"http://localhost:8080/visualizerservice/services/visualizerservice\"/>
		</wsdl:port>
	</wsdl:service>
</wsdl:definitions>"""

    def __init__(self, post='/visualizerservice/services/visualizerservice', **kw):
        ServiceSOAPBinding.__init__(self, post)

    def soap_run(self, ps):
        self.request = ps.Parse(runRequest.typecode)
        return runResponse()

    soapAction['http://service.apollo.pitt.edu/visualizerservice/run'] = 'soap_run'
    root[(runRequest.typecode.nspname,runRequest.typecode.pname)] = 'soap_run'

    def soap_getRunStatus(self, ps):
        self.request = ps.Parse(getRunStatusRequest.typecode)
        return getRunStatusResponse()

    soapAction['http://service.apollo.pitt.edu/visualizerservice/getRunStatus'] = 'soap_getRunStatus'
    root[(getRunStatusRequest.typecode.nspname,getRunStatusRequest.typecode.pname)] = 'soap_getRunStatus'

<commit_msg>changed location of XSD<commit_after>##################################################
# VisualizerService_services_server.py
#      Generated by ZSI.generate.wsdl2dispatch.ServiceModuleWriter
#
##################################################

from VisualizerService_services import *
from ZSI.ServiceContainer import ServiceSOAPBinding

class VisualizerService(ServiceSOAPBinding):
    soapAction = {}
    root = {}
    _wsdl = """<?xml version=\"1.0\" ?>
<wsdl:definitions name=\"VisualizerService\" targetNamespace=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
	<wsdl:types>
		<xsd:schema targetNamespace=\"http://service.apollo.pitt.edu/visualizerservice/\" xmlns:apollo=\"http://types.apollo.pitt.edu/\">
			<xsd:import namespace=\"http://types.apollo.pitt.edu/\" schemaLocation=\"http://research.rods.pitt.edu/apollo-types.xsd\">
			</xsd:import>
			<xsd:element name=\"run\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"visualizerConfiguration\" type=\"apollo:VisualizerConfiguration\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"runResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"visualizerResult\" type=\"apollo:VisualizerResult\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getRunStatus\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runId\" type=\"apollo:RunIdentification\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getRunStatusResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runStatus\" type=\"apollo:RunStatus\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getConfigurationFileForRun\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"runIdentification\" type=\"apollo:RunIdentification\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name=\"getConfigurationFileForRunResponse\">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name=\"configurationFile\" type=\"xsd:string\"/>
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
		</xsd:schema>
	</wsdl:types>
	<wsdl:message name=\"runRequest\">
		<wsdl:part element=\"tns:run\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"runResponse\">
		<wsdl:part element=\"tns:runResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getRunStatusRequest\">
		<wsdl:part element=\"tns:getRunStatus\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getRunStatusResponse\">
		<wsdl:part element=\"tns:getRunStatusResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getConfigurationFileForRunRequest\">
		<wsdl:part element=\"tns:getConfigurationFileForRun\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:message name=\"getConfigurationFileForRunResponse\">
		<wsdl:part element=\"tns:getConfigurationFileForRunResponse\" name=\"parameters\"/>
	</wsdl:message>
	<wsdl:portType name=\"VisualizerServiceEI\">
		<wsdl:operation name=\"run\">
			<wsdl:input message=\"tns:runRequest\"/>
			<wsdl:output message=\"tns:runResponse\"/>
		</wsdl:operation>
		<wsdl:operation name=\"getRunStatus\">
			<wsdl:input message=\"tns:getRunStatusRequest\"/>
			<wsdl:output message=\"tns:getRunStatusResponse\"/>
		</wsdl:operation>
		<wsdl:operation name=\"getConfigurationFileForRun\">
			<wsdl:input message=\"tns:getConfigurationFileForRunRequest\"/>
			<wsdl:output message=\"tns:getConfigurationFileForRunResponse\"/>
		</wsdl:operation>
	</wsdl:portType>
	<wsdl:binding name=\"VisualizerServiceBinding\" type=\"tns:VisualizerServiceEI\">
		<soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>
		<wsdl:operation name=\"run\">
			<soap:operation soapAction=\"http://service.apollo.pitt.edu/visualizerservice/run\"/>
			<wsdl:input>
				<soap:body use=\"literal\"/>
			</wsdl:input>
			<wsdl:output>
				<soap:body use=\"literal\"/>
			</wsdl:output>
		</wsdl:operation>
		<wsdl:operation name=\"getRunStatus\">
			<soap:operation soapAction=\"http://service.apollo.pitt.edu/visualizerservice/getRunStatus\"/>
			<wsdl:input>
				<soap:body use=\"literal\"/>
			</wsdl:input>
			<wsdl:output>
				<soap:body use=\"literal\"/>
			</wsdl:output>
		</wsdl:operation>
	</wsdl:binding>
	<wsdl:service name=\"VisualizerService\">
		<wsdl:port binding=\"tns:VisualizerServiceBinding\" name=\"VisualizerServiceEndpoint\">
			<soap:address location=\"http://localhost:8080/visualizerservice/services/visualizerservice\"/>
		</wsdl:port>
	</wsdl:service>
</wsdl:definitions>"""

    def __init__(self, post='/visualizerservice/services/visualizerservice', **kw):
        ServiceSOAPBinding.__init__(self, post)

    def soap_run(self, ps):
        self.request = ps.Parse(runRequest.typecode)
        return runResponse()

    soapAction['http://service.apollo.pitt.edu/visualizerservice/run'] = 'soap_run'
    root[(runRequest.typecode.nspname,runRequest.typecode.pname)] = 'soap_run'

    def soap_getRunStatus(self, ps):
        self.request = ps.Parse(getRunStatusRequest.typecode)
        return getRunStatusResponse()

    soapAction['http://service.apollo.pitt.edu/visualizerservice/getRunStatus'] = 'soap_getRunStatus'
    root[(getRunStatusRequest.typecode.nspname,getRunStatusRequest.typecode.pname)] = 'soap_getRunStatus'

<|endoftext|>


<commit_before>from django.shortcuts import render
import json
from django.http import HttpResponse
from event_manager.models import Suggestion, Event, Invite
from django.contrib.auth.models import User
from datetime import datetime

def api_get(request, type="e"):
		if type == "e":
			# data = Event.objects.values()
			# return render(request, 'api.html', {'data': data})
			invites = Invite.objects.select_related().filter(user__id=1)
			event_objects = [invite.event for invite in invites]
			events = [
				{
					"id": event.id,
					"owner_name": event.owner.username,
					"description": event.description,
					"location_id": event.location_id,
					"start_time": str(event.start_time),
					"end_time": str(event.end_time),
				} for event in event_objects
			]
			return HttpResponse(json.dumps(events), content_type="application/json")

		elif type == "u":
			Users = User.objects.all()
			data = [
				{
					"id": user.id,
					"username": user.username,
					"first_name": user.first_name,
					"last_name": user.last_name,
					"email": user.email
				} for user in Users
			]
			return HttpResponse(json.dumps(data), content_type="application/json")

		elif type == "s":
			Suggestions = Suggestion.objects.all()
			data = [
				{
					"id": suggestion.id,
					"username": suggestion.user_id,
					"first_name": suggestion.response,
					"last_name": str(suggestion.time)
				} for suggestion in Suggestions
			]
			return HttpResponse(json.dumps(data), content_type="application/json")

		else:
			return render(request, 'api.html', {'data': ""})

def new(request):
		# event_description = request.POST["description"]
		# event_owner_id = request.POST["owner_id"]
		# event_location_id = request.POST["location_id"]

		event_description = "Felix"
		event_owner_id = 1
		event_location_id = 1
		event_start_time = datetime.now()
		event = Event(
			description = event_description,
			owner_id = event_owner_id,
			location_id = event_location_id,
			start_time = event_start_time
		)

		event.save()
		event_id = event.id

		invite_event_id = event_id
		invite_user_id = 1
		# invite_rsvp = "NONE"
		invite = Invite(
			event_id = invite_event_id,
			user_id = 1,
			rsvp = Invite.NONE
		)

		invite.save()

		return HttpResponse("ASDF", content_type="application/json")<commit_msg>Add comments to api<commit_after>from django.shortcuts import render
import json
from django.http import HttpResponse
from event_manager.models import Suggestion, Event, Invite
from django.contrib.auth.models import User
from datetime import datetime

def api_get(request, type="e"):
		if type == "e":
			# data = Event.objects.values()
			# return render(request, 'api.html', {'data': data})
			invites = Invite.objects.select_related().filter(user__id=1)
			event_objects = [invite.event for invite in invites]
			events = [
				{
					"id": event.id,
					"owner_name": event.owner.username,
					"description": event.description,
					"location_id": event.location_id,
					"start_time": str(event.start_time),
					"end_time": str(event.end_time),
				} for event in event_objects
			]
			return HttpResponse(json.dumps(events), content_type="application/json")

		elif type == "u":
			Users = User.objects.all()
			data = [
				{
					"id": user.id,
					"username": user.username,
					"first_name": user.first_name,
					"last_name": user.last_name,
					"email": user.email
				} for user in Users
			]
			return HttpResponse(json.dumps(data), content_type="application/json")

		elif type == "s":
			Suggestions = Suggestion.objects.all()
			data = [
				{
					"id": suggestion.id,
					"username": suggestion.user_id,
					"first_name": suggestion.response,
					"last_name": str(suggestion.time)
				} for suggestion in Suggestions
			]
			return HttpResponse(json.dumps(data), content_type="application/json")

		else:
			return render(request, 'api.html', {'data': ""})

# TODO : Build add services for events, suggestions, invites seperately
def new(request):
		# event_description = request.POST["description"]
		# event_owner_id = request.POST["owner_id"]
		# event_location_id = request.POST["location_id"]

		event_description = "Felix"
		event_owner_id = 1
		event_location_id = 1
		event_start_time = datetime.now()
		event = Event(
			description = event_description,
			owner_id = event_owner_id,
			location_id = event_location_id,
			start_time = event_start_time
		)

		event.save()
		event_id = event.id

		invite_event_id = event_id
		invite_user_id = 1
		# invite_rsvp = "NONE"
		invite = Invite(
			event_id = invite_event_id,
			user_id = 1,
			rsvp = Invite.NONE
		)

		invite.save()

		return HttpResponse("ASDF", content_type="application/json")<|endoftext|>


<commit_before># -*-coding:Utf-8 -*

# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

"""Package contenant la commande 'système'"""

from primaires.interpreteur.commande.commande import Commande
from secondaires.systeme.contextes.systeme import Systeme

class CmdSysteme(Commande):

    """Commande 'système'.

    """

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "systeme", "system")
        self.groupe = "administrateur"
        self.schema = ""
        self.aide_courte = "intègre une console interactive Python"
        self.aide_longue = \
            "Cette commande ouvre une console virtuelle Python. " \
            "Elle permet d'entrer du code directement, comme dans " \
            "un interpréteur Python. |att|Soyez excessivement prudent " \
            "quant aux manipulations effectuées et aux informations " \
            "que vous envoyez. Souvenez-vous qu'elles transitent " \
            "par un protocole non sécurisé.|ff| N'utilisez cette " \
            "commande qu'à des fins de debug."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        contexte = Systeme(personnage.instance_connexion)
        personnage.contexte_actuel.migrer_contexte(contexte)
<commit_msg>La commande systÃ¨me/system doit Ã  prÃ©sent Ãªtre exÃ©cutÃ©e en local<commit_after># -*-coding:Utf-8 -*

# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

"""Package contenant la commande 'système'"""

from primaires.interpreteur.commande.commande import Commande
from secondaires.systeme.contextes.systeme import Systeme

class CmdSysteme(Commande):

    """Commande 'système'.

    """

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "systeme", "system")
        self.groupe = "administrateur"
        self.schema = ""
        self.aide_courte = "intègre une console interactive Python"
        self.aide_longue = \
            "Cette commande ouvre une console virtuelle Python. " \
            "Elle permet d'entrer du code directement, comme dans " \
            "un interpréteur Python. |att|Soyez excessivement prudent " \
            "quant aux manipulations effectuées et aux informations " \
            "que vous envoyez. Souvenez-vous qu'elles transitent " \
            "par un protocole non sécurisé.|ff| N'utilisez cette " \
            "commande qu'à des fins de debug."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        if personnage.instance_connexion.adresse_ip != "127.0.0.1":
            personnage << "|err|Vous devez être connecté en local pour cela.|ff|"
            return

        contexte = Systeme(personnage.instance_connexion)
        personnage.contexte_actuel.migrer_contexte(contexte)
<|endoftext|>