<commit_before>"""
Created on Jan 11, 2012

@author: brandon_rohrer

A main test harness for a general reinforcement learning agent.
"""

import sys
import argparse
import logging

"""
selects the World that the Agent will be placed in
"""

Default_Save_Period = 20000

from worlds.grid_1D import Grid_1D as worldcreator
#from worlds.grid_1D_ms import Grid_1D_ms as worldcreator
#from worlds.grid_1D_noise import Grid_1D_noise as worldcreator
#from worlds.grid_2D import Grid_2D as worldcreator
#from worlds.grid_2D_dc import Grid_2D_dc as worldcreator
#from worlds.image_1D import Image_1D as worldcreator
#
#    import worlds.listen

#    import worlds.morris  # under development

#from agent.agent_stub import Agent
from agent.agent import Agent
from agent.agent_stub import Agent as RandomAgent

from experiment.experiment import Experiment

def main(args):
    parser = argparse.ArgumentParser(description='tester')
    parser.add_argument('--dummy-agent', dest="dummy_agent", default=False, action="store_true",
                        help="Use an agent that just returns random actions. Good for testing worlds")
    parser.add_argument('-s', '--save-period', dest="save_period", type=int, default=Default_Save_Period,
                        help="How often to take snapshots (default: %(default)s)")
    parser.add_argument('-p', '--pickle-prefix', dest="pickle_prefix", default=None,
                        help="Use pickle prefix specified")
    parser.add_argument('-v', '--verbosity', dest="verbosity", default=1, type=int,
                        help="How verbose to be (default: %(default)s)")

    parameters = parser.parse_args(args)

    if parameters.verbosity <= 0:
        logging_level = logging.ERROR
    elif parameters.verbosity == 1:
        logging_level = logging.WARNING
    elif parameters.verbosity == 2:
        logging_level = logging.INFO
    elif parameters.verbosity == 3:
        logging_level = logging.DEBUG

    logging.basicConfig(level=logging_level, format="%(asctime)s %(levelname)-8s %(message)s")

    if parameters.dummy_agent:
        agent_class = RandomAgent
    else:
        agent_class = Agent

    experiment = Experiment(worldcreator, agent_class, pickle_prefix=parameters.pickle_prefix,
                            backup_period=parameters.save_period)
    experiment.run()

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
<commit_msg>tester: Add command-line option to specify class to test, with wild guessing capabilities<commit_after>"""
Created on Jan 11, 2012

@author: brandon_rohrer

A main test harness for a general reinforcement learning agent.
"""

import sys
import argparse
import logging

"""
selects the World that the Agent will be placed in
"""

Default_Save_Period = 20000

Default_World_Class = 'worlds.grid_1D.Grid_1D'

#from worlds.grid_1D import Grid_1D as worldcreator
#from worlds.grid_1D_ms import Grid_1D_ms as worldcreator
#from worlds.grid_1D_noise import Grid_1D_noise as worldcreator
#from worlds.grid_2D import Grid_2D as worldcreator
#from worlds.grid_2D_dc import Grid_2D_dc as worldcreator
#from worlds.image_1D import Image_1D as worldcreator
#
#    import worlds.listen

#    import worlds.morris  # under development

#from agent.agent_stub import Agent
from agent.agent import Agent
from agent.agent_stub import Agent as RandomAgent

from experiment.experiment import Experiment

def get_world_class(world_name):
    """
    Bit of ugly magic to guess what world the user wants and load the class for it
    """

    def is_suitable_world_creator(klass):
        """
        Return whether the given klass would do as a world creator
        """
        from worlds.world import World

        # do some basic checking to see if the loaded klass looks right.
        # If it's a subclass of World, then that's enough, but maybe they didn't
        # subclass from there, so just check that it is a class, and that it has a step method
        return isinstance(klass, World) or (isinstance(klass, type) and hasattr(klass, 'step'))

    def import_module(path):
        module = __import__(path)
        for sub in path.split('.')[1:]:
            module = getattr(module, sub)

        return module

    # option 1: properly specified dotted class name
    # eg worlds.grid_1D.Grid_1D

    klass = None
    module = None

    if '.' in world_name:
        path, class_name = world_name.rsplit('.', 1)
    else:
        # no dots, we'll go with the theory that it's a module in this directory, or somewhere on the path
        path = world_name
        class_name = None

    try:
        module = import_module(path)
    except ImportError:
        # nah, that didn't work. Maybe they forgot to prefix with 'worlds' and that's what they meant
        if not path.startswith('worlds.'):
            path = 'worlds.' + path
            try:
                module = import_module(path)
            except ImportError:
                # nah, that wasn't it either.  Give up
                pass
            else:
                # warn them
                logging.warn("Taking %s to be the proper path of the module" % path)

    if module is not None:
        if class_name is not None:
            print class_name
            klass = getattr(module, class_name, None)
            print klass
            if not is_suitable_world_creator(klass):
                # Maybe this is a module, then we have to search for the class.
                # Try reimporting
                path += '.' + class_name
                try:
                    module = import_module(path)
                except ImportError:
                    # no. give up
                    klass = None
                else:
                    # ok, we'll search in that module for a suitable class
                    class_name = None
                    klass = None

        if class_name is None:
            logging.info("Searching in %s for suitable world creator" % module.__name__)
            # look through each class in module and see if anything in there is suitable, and defined in the module
            # itself (ie not imported from elsewhere)
            classes = [class_candidate for class_candidate in dir(module)
                       if is_suitable_world_creator(getattr(module, class_candidate, None)) and
                       getattr(module, class_candidate).__module__ == module.__name__]

            if len(classes) > 1:
                # we found many. Just tell the user we don't know which one to use
                logging.error("Found too many possible world creators in %s: %s" % (module.__name__, ', '.join(classes)))
            elif not classes:
                # we found nothing of value
                logging.error("Didn't find any clearly suitable world creator in %s. You'll have to specify it manually" % module.__name__)
            else:
                klass = getattr(module, classes[0])
    else:
        logging.error("Couldn't find module path %s" % path)

    return klass

def main(args):
    parser = argparse.ArgumentParser(description='tester')
    parser.add_argument('world_creator', nargs="?", default=Default_World_Class,
                        help="Class to create world (default: %(default)s)")
    parser.add_argument('--dummy-agent', dest="dummy_agent", default=False, action="store_true",
                        help="Use an agent that just returns random actions. Good for testing worlds")
    parser.add_argument('-s', '--save-period', dest="save_period", type=int, default=Default_Save_Period,
                        help="How often to take snapshots (default: %(default)s)")
    parser.add_argument('-p', '--pickle-prefix', dest="pickle_prefix", default=None,
                        help="Use pickle prefix specified")
    parser.add_argument('-v', '--verbosity', dest="verbosity", default=1, type=int,
                        help="How verbose to be (default: %(default)s)")

    parameters = parser.parse_args(args)

    if parameters.verbosity <= 0:
        logging_level = logging.ERROR
    elif parameters.verbosity == 1:
        logging_level = logging.WARNING
    elif parameters.verbosity == 2:
        logging_level = logging.INFO
    elif parameters.verbosity == 3:
        logging_level = logging.DEBUG

    logging.basicConfig(level=logging_level, format="%(asctime)s %(levelname)-8s %(message)s")

    if parameters.dummy_agent:
        agent_class = RandomAgent
    else:
        agent_class = Agent

    world_creator = get_world_class(parameters.world_creator)
    if world_creator is None:
        parser.error("Couldn't find world creator %s" % parameters.world_creator)

    experiment = Experiment(world_creator, agent_class, pickle_prefix=parameters.pickle_prefix,
                            backup_period=parameters.save_period)
    experiment.run()

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
<|endoftext|>


<commit_before>from collections import OrderedDict
import logging
from decimal import InvalidOperation

from django import forms
from django.conf.urls import url
from django.contrib import admin, messages
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.db.models import Count, Sum
from django.utils.html import format_html
from django.http.response import HttpResponseRedirect, HttpResponseForbidden
from django.utils.translation import ugettext_lazy as _

from daterange_filter.filter import DateRangeFilter
from sorl.thumbnail.admin import AdminImageMixin

from bluebottle.bb_projects.models import ProjectTheme, ProjectPhase
from bluebottle.payouts_dorado.adapters import (
    DoradoPayoutAdapter, PayoutValidationError, PayoutCreationError
)
from bluebottle.rewards.models import Reward
from bluebottle.tasks.admin import TaskAdminInline
from bluebottle.common.admin_utils import ImprovedModelForm
from bluebottle.geo.admin import LocationFilter, LocationGroupFilter
from bluebottle.geo.models import Location
from bluebottle.utils.admin import export_as_csv_action
from bluebottle.votes.models import Vote

from .forms import ProjectDocumentForm
from .models import (ProjectBudgetLine, Project,
                     ProjectDocument, ProjectPhaseLog)

logger = logging.getLogger(__name__)

def mark_as(slug, queryset):
    try:
        status = ProjectPhase.objects.get(slug=slug)
    except ProjectPhase.DoesNotExist:
        return

    Project.objects.filter(
        pk__in=queryset.values_list('pk', flat=True)
    ).update(
        status=status
    )

def mark_as_plan_new(modeladmin, request, queryset):
    mark_as('plan-new', queryset)

mark_as_plan_new.short_description = _("Mark selected projects as status Plan - Draft")

def mark_as_plan_submitted(modeladmin, request, queryset):
    mark_as('plan-submitted', queryset)

mark_as_plan_submitted.short_description = _("Mark selected projects as status Plan - Submitted")

def mark_as_plan_needs_work(modeladmin, request, queryset):
    mark_as('plan-needs-work', queryset)

mark_as_plan_needs_work.short_description = _("Mark selected projects as status Plan - Needs Work")

def mark_as_voting(modeladmin, request, queryset):
    mark_as('voting', queryset)

mark_as_voting.short_description = _("Mark selected projects as status Voting - Running")

def mark_as_voting_done(modeladmin, request, queryset):
    mark_as('voting-done', queryset)

mark_as_voting_done.short_description = _("Mark selected projects as status Voting - Done")

def mark_as_campaign(modeladmin, request, queryset):
    mark_as('campaign', queryset)

mark_as_campaign.short_description = _("Mark selected projects as status Project - Running")

def mark_as_done_complete(modeladmin, request, queryset):
    mark_as('done-complete', queryset)

mark_as_done_complete.short_description = _("Mark selected projects as status Project - Realised")

def mark_as_done_incomplete(modeladmin, request, queryset):
    mark_as('done-incomplete', queryset)

mark_as_done_incomplete.short_description = _("Mark selected projects as status Project - Done")

def mark_as_closed(modeladmin, request, queryset):
    mark_as('closed', queryset)

mark_as_closed.short_description = _("Mark selected projects as status Rejected / Canceled")

class ProjectThemeAdmin(admin.ModelAdmin):
    list_display = admin.ModelAdmin.list_display + ('slug', 'disabled',)

    def has_delete_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return False

admin.site.register(ProjectTheme, ProjectThemeAdmin)

class ProjectThemeFilter(admin.SimpleListFilter):
    title = _('Theme')
    parameter_name = 'theme'

    def lookups(self, request, model_admin):
        themes = [obj.theme for obj in
                  model_admin.model.objects.order_by('theme__name').distinct(
                      'theme__name').exclude(theme__isnull=True).all()]
        return [(theme.id, _(theme.name)) for theme in themes]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(theme=self.value())
        else:
            return queryset

class ProjectReviewerFilter(admin.SimpleListFilter):
    title = _('Reviewer')
    parameter_name = 'reviewer'

    def lookups(self, request, model_admin):
        return ((True, _('My projects')), )

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(
                reviewer=request.user
            )
        else:
            return queryset

class ProjectDocumentInline(admin.StackedInline):
    model = ProjectDocument
    form = ProjectDocumentForm
    extra = 0
    raw_id_fields = ('author',)
    readonly_fields = ('download_url',)
    fields = readonly_fields + ('file', 'author')

    def download_url(self, obj):
        url = obj.document_url

        if url is not None:
            return format_html(
                u"{}",
                str(url), 'Download'
            )
        return '(None)'

class RewardInlineAdmin(admin.TabularInline):
    model = Reward
    readonly_fields = ('count',)
    extra = 0

    def count(self, obj):
        return obj.count

class ProjectPhaseLogInline(admin.TabularInline):
    model = ProjectPhaseLog
    can_delete = False
    ordering = ('-start',)
    extra = 0

    def has_add_permission(self, request):
        return False

    readonly_fields = ('status', 'start')
    fields = readonly_fields

class FundingFilter(admin.SimpleListFilter):
    title = _('Funding')
    parameter_name = 'funding'

    def lookups(self, request, model_admin):
        return (
            ('yes', _('Crowdfunding')),
            ('no', _('Crowdsourcing')),
            ('both', _('Crowdfunding & crowdsourcing')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.filter(amount_asked__gt=0)
        elif self.value() == 'no':
            from django.db.models import Q
            return queryset.filter(Q(amount_asked=None) | Q(amount_asked=0.00))
        return queryset

class ProjectBudgetLineInline(admin.TabularInline):
    model = ProjectBudgetLine
    extra = 0

class ReviewerWidget(admin.widgets.ForeignKeyRawIdWidget):
    def url_parameters(self):
        parameters = super(ReviewerWidget, self).url_parameters()
        parameters['is_staff'] = True
        return parameters

class ProjectAdminForm(forms.ModelForm):
    class Meta:
        widgets = {
            'currencies': forms.CheckboxSelectMultiple
        }

    theme = forms.ModelChoiceField(
        queryset=ProjectTheme.objects.all().filter(disabled=False))

    def __init__(self, *args, **kwargs):
        super(ProjectAdminForm, self).__init__(*args, **kwargs)
        self.fields['currencies'].required = False

        self.fields['reviewer'].widget = ReviewerWidget(
            rel=Project._meta.get_field('reviewer').rel,
            admin_site=admin.sites.site
        )

class ProjectAdmin(AdminImageMixin, ImprovedModelForm):
    form = ProjectAdminForm
    date_hierarchy = 'created'
    ordering = ('-created',)
    save_on_top = True

    search_fields = ('title', 'owner__first_name', 'owner__last_name',
                     'organization__name')

    raw_id_fields = ('owner', 'reviewer', 'organization',)

    prepopulated_fields = {'slug': ('title',)}

    inlines = (ProjectBudgetLineInline, RewardInlineAdmin, TaskAdminInline, ProjectDocumentInline,
               ProjectPhaseLogInline)

    def get_readonly_fields(self, request, obj=None):
        fields = ['vote_count',
                  'amount_donated', 'amount_needed',
                  'popularity', 'payout_status']
        if obj and obj.payout_status and obj.payout_status != 'needs_approval':
            fields += ('status', )
        return fields

    def get_urls(self):
        urls = super(ProjectAdmin, self).get_urls()
        process_urls = [
            url(r'^approve_payout/(?P<pk>\d+)/$',
                self.approve_payout,
                name="projects_project_approve_payout"),
        ]
        return process_urls + urls

    def approve_payout(self, request, pk=None):
        project = Project.objects.get(pk=pk)
        if not request.user.has_perm('projects.approve_payout'):
            return HttpResponseForbidden('Missing permission: projects.approve_payout')
        elif project.payout_status != 'needs_approval':
            self.message_user(request, 'The payout does not have the status "needs approval"')
        else:
            adapter = DoradoPayoutAdapter(project)
            try:
                adapter.trigger_payout()
            except PayoutValidationError, e:
                for field, errors in e.message['errors'].items():
                    for error in errors:
                        self.message_user(
                            request,
                            'Account details: {}, {}.'.format(field, error.lower()),
                            level=messages.ERROR
                        )
            except (PayoutCreationError, ImproperlyConfigured), e:
                logger.warning(
                    'Error approving payout: {}'.format(e),
                    exc_info=1
                )

                self.message_user(
                    request,
                    'Failed to approve payout: {}'.format(e),
                    level=messages.ERROR
                )

        project_url = reverse('admin:projects_project_change', args=(project.id,))
        return HttpResponseRedirect(project_url)

    list_filter = ('country__subregion__region',)

    def get_list_filter(self, request):
        filters = ['status', 'is_campaign', ProjectThemeFilter, ProjectReviewerFilter,
                   'project_type', ('deadline', DateRangeFilter), ]

        if request.user.has_perm('projects.approve_payout'):
            filters.insert(1, 'payout_status')

        # Only show Location column if there are any
        if Location.objects.count():
            filters += [LocationGroupFilter, LocationFilter]
        else:
            filters += ['country__subregion__region', ('country', admin.RelatedOnlyFieldListFilter), ]
        return filters

    def get_list_display(self, request):
        fields = ['get_title_display', 'get_owner_display', 'created',
                  'status', 'deadline', 'donated_percentage']

        if request.user.has_perm('projects.approve_payout'):
            fields.insert(4, 'payout_status')

        # Only show Location column if there are any
        if Location.objects.count():
            fields += ('location',)
        # Only show Vote_count column if there are any votes
        if Vote.objects.count():
            fields += ('vote_count',)
        return fields

    def get_list_editable(self, request):
        return ('is_campaign',)

    export_fields = [
        ('title', 'title'),
        ('owner', 'owner'),
        ('owner__remote_id', 'remote id'),
        ('reviewer', 'reviewer'),
        ('created', 'created'),
        ('status', 'status', 'payout_status'),
        ('theme', 'theme'),
        ('location__group', 'region'),
        ('location', 'location'),
        ('deadline', 'deadline'),
        ('date_submitted', 'date submitted'),
        ('campaign_started', 'campaign started'),
        ('campaign_ended', 'campaign ended'),
        ('campaign_funded', 'campaign funded'),
        ('campaign_payed_out', 'campaign_payed_out'),
        ('task_count', 'task count'),
        ('supporters', 'supporters'),
        ('time_spent', 'time spent'),
        ('amount_asked', 'amount asked'),
        ('amount_donated', 'amount donated'),
        ('organization__name', 'organization'),
        ('amount_extra', 'amount matched'),
    ]

    actions = [export_as_csv_action(fields=export_fields),
               mark_as_closed, mark_as_done_incomplete,
               mark_as_done_complete, mark_as_campaign,
               mark_as_voting_done, mark_as_voting,
               mark_as_plan_needs_work, mark_as_plan_submitted,
               mark_as_plan_new]

    def get_actions(self, request):
        """Order the action in reverse (delete at the bottom)."""
        actions = super(ProjectAdmin, self).get_actions(request)
        return OrderedDict(reversed(actions.items()))

    def get_fieldsets(self, request, obj=None):
        main = {'fields': ['owner', 'reviewer', 'organization',
                           'status', 'title', 'slug', 'project_type',
                           'is_campaign', 'celebrate_results']}

        if request.user.has_perm('projects.approve_payout'):
            main['fields'].insert(3, 'payout_status')

        return (
            (_('Main'), main),

            (_('Story'), {'fields': ('pitch', 'story', 'reach')}),

            (_('Details'), {'fields': ('language', 'theme', 'categories', 'image',
                                       'video_url', 'country',
                                       'latitude', 'longitude',
                                       'location', 'place')}),

            (_('Goal'), {'fields': ('amount_asked', 'amount_extra',
                                    'amount_donated', 'amount_needed',
                                    'currencies',
                                    'popularity', 'vote_count')}),

            (_('Dates'), {'fields': ('voting_deadline', 'deadline',
                                     'date_submitted', 'campaign_started',
                                     'campaign_ended', 'campaign_funded', 'campaign_payed_out')}),

            (_('Bank details'), {'fields': ('account_holder_name',
                                            'account_holder_address',
                                            'account_holder_postal_code',
                                            'account_holder_city',
                                            'account_holder_country',
                                            'account_number',
                                            'account_bic',
                                            'account_bank_country')})
        )

    def vote_count(self, obj):
        return obj.vote_set.count()

    def donated_percentage(self, obj):
        try:
            percentage = "%.2f" % (100 * obj.amount_donated.amount / obj.amount_asked.amount)
            return "{0} %".format(percentage)
        except (AttributeError, InvalidOperation):
            return '-'

    def get_queryset(self, request):
        # Optimization: Select related fields that are used in admin specific
        # display fields.
        queryset = super(ProjectAdmin, self).get_queryset(request)
        queryset = queryset.select_related(
            'owner', 'organization'
        ).annotate(
            admin_vote_count=Count('vote', distinct=True),
            time_spent=Sum('task__members__time_spent')
        )

        return queryset

    def num_votes(self, obj):
        self.queryset(None)
        return obj.admin_vote_count

    num_votes.short_description = _('Vote Count')
    num_votes.admin_order_field = 'admin_vote_count'

    def get_title_display(self, obj):
        if len(obj.title) > 35:
            return format_html(
                u'{} …',
                obj.title, obj.title[:45]
            )
        return obj.title

    get_title_display.admin_order_field = 'title'
    get_title_display.short_description = _('title')

    def get_owner_display(self, obj):
        owner_name = obj.owner.get_full_name()
        if owner_name:
            owner_name = u' ({name})'.format(name=owner_name)
        return u'{email}{name}'.format(name=owner_name, email=obj.owner.email)

    get_owner_display.admin_order_field = 'owner__last_name'
    get_owner_display.short_description = _('owner')

    def project_owner(self, obj):
        object = obj.owner
        url = reverse('admin:{0}_{1}_change'.format(
            object._meta.app_label, object._meta.model_name), args=[object.id])
        return format_html(
            u"{}",
            str(url),
            object.first_name + ' ' + object.last_name
        )

admin.site.register(Project, ProjectAdmin)

admin.site.register(ProjectPhase)
<commit_msg>Fix admin payout errors for single errors<commit_after>from collections import OrderedDict
import logging
from decimal import InvalidOperation

from django import forms
from django.conf.urls import url
from django.contrib import admin, messages
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.db.models import Count, Sum
from django.utils.html import format_html
from django.http.response import HttpResponseRedirect, HttpResponseForbidden
from django.utils.translation import ugettext_lazy as _

from daterange_filter.filter import DateRangeFilter
from sorl.thumbnail.admin import AdminImageMixin

from bluebottle.bb_projects.models import ProjectTheme, ProjectPhase
from bluebottle.payouts_dorado.adapters import (
    DoradoPayoutAdapter, PayoutValidationError, PayoutCreationError
)
from bluebottle.rewards.models import Reward
from bluebottle.tasks.admin import TaskAdminInline
from bluebottle.common.admin_utils import ImprovedModelForm
from bluebottle.geo.admin import LocationFilter, LocationGroupFilter
from bluebottle.geo.models import Location
from bluebottle.utils.admin import export_as_csv_action
from bluebottle.votes.models import Vote

from .forms import ProjectDocumentForm
from .models import (ProjectBudgetLine, Project,
                     ProjectDocument, ProjectPhaseLog)

logger = logging.getLogger(__name__)

def mark_as(slug, queryset):
    try:
        status = ProjectPhase.objects.get(slug=slug)
    except ProjectPhase.DoesNotExist:
        return

    Project.objects.filter(
        pk__in=queryset.values_list('pk', flat=True)
    ).update(
        status=status
    )

def mark_as_plan_new(modeladmin, request, queryset):
    mark_as('plan-new', queryset)

mark_as_plan_new.short_description = _("Mark selected projects as status Plan - Draft")

def mark_as_plan_submitted(modeladmin, request, queryset):
    mark_as('plan-submitted', queryset)

mark_as_plan_submitted.short_description = _("Mark selected projects as status Plan - Submitted")

def mark_as_plan_needs_work(modeladmin, request, queryset):
    mark_as('plan-needs-work', queryset)

mark_as_plan_needs_work.short_description = _("Mark selected projects as status Plan - Needs Work")

def mark_as_voting(modeladmin, request, queryset):
    mark_as('voting', queryset)

mark_as_voting.short_description = _("Mark selected projects as status Voting - Running")

def mark_as_voting_done(modeladmin, request, queryset):
    mark_as('voting-done', queryset)

mark_as_voting_done.short_description = _("Mark selected projects as status Voting - Done")

def mark_as_campaign(modeladmin, request, queryset):
    mark_as('campaign', queryset)

mark_as_campaign.short_description = _("Mark selected projects as status Project - Running")

def mark_as_done_complete(modeladmin, request, queryset):
    mark_as('done-complete', queryset)

mark_as_done_complete.short_description = _("Mark selected projects as status Project - Realised")

def mark_as_done_incomplete(modeladmin, request, queryset):
    mark_as('done-incomplete', queryset)

mark_as_done_incomplete.short_description = _("Mark selected projects as status Project - Done")

def mark_as_closed(modeladmin, request, queryset):
    mark_as('closed', queryset)

mark_as_closed.short_description = _("Mark selected projects as status Rejected / Canceled")

class ProjectThemeAdmin(admin.ModelAdmin):
    list_display = admin.ModelAdmin.list_display + ('slug', 'disabled',)

    def has_delete_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return False

admin.site.register(ProjectTheme, ProjectThemeAdmin)

class ProjectThemeFilter(admin.SimpleListFilter):
    title = _('Theme')
    parameter_name = 'theme'

    def lookups(self, request, model_admin):
        themes = [obj.theme for obj in
                  model_admin.model.objects.order_by('theme__name').distinct(
                      'theme__name').exclude(theme__isnull=True).all()]
        return [(theme.id, _(theme.name)) for theme in themes]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(theme=self.value())
        else:
            return queryset

class ProjectReviewerFilter(admin.SimpleListFilter):
    title = _('Reviewer')
    parameter_name = 'reviewer'

    def lookups(self, request, model_admin):
        return ((True, _('My projects')), )

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(
                reviewer=request.user
            )
        else:
            return queryset

class ProjectDocumentInline(admin.StackedInline):
    model = ProjectDocument
    form = ProjectDocumentForm
    extra = 0
    raw_id_fields = ('author',)
    readonly_fields = ('download_url',)
    fields = readonly_fields + ('file', 'author')

    def download_url(self, obj):
        url = obj.document_url

        if url is not None:
            return format_html(
                u"{}",
                str(url), 'Download'
            )
        return '(None)'

class RewardInlineAdmin(admin.TabularInline):
    model = Reward
    readonly_fields = ('count',)
    extra = 0

    def count(self, obj):
        return obj.count

class ProjectPhaseLogInline(admin.TabularInline):
    model = ProjectPhaseLog
    can_delete = False
    ordering = ('-start',)
    extra = 0

    def has_add_permission(self, request):
        return False

    readonly_fields = ('status', 'start')
    fields = readonly_fields

class FundingFilter(admin.SimpleListFilter):
    title = _('Funding')
    parameter_name = 'funding'

    def lookups(self, request, model_admin):
        return (
            ('yes', _('Crowdfunding')),
            ('no', _('Crowdsourcing')),
            ('both', _('Crowdfunding & crowdsourcing')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            return queryset.filter(amount_asked__gt=0)
        elif self.value() == 'no':
            from django.db.models import Q
            return queryset.filter(Q(amount_asked=None) | Q(amount_asked=0.00))
        return queryset

class ProjectBudgetLineInline(admin.TabularInline):
    model = ProjectBudgetLine
    extra = 0

class ReviewerWidget(admin.widgets.ForeignKeyRawIdWidget):
    def url_parameters(self):
        parameters = super(ReviewerWidget, self).url_parameters()
        parameters['is_staff'] = True
        return parameters

class ProjectAdminForm(forms.ModelForm):
    class Meta:
        widgets = {
            'currencies': forms.CheckboxSelectMultiple
        }

    theme = forms.ModelChoiceField(
        queryset=ProjectTheme.objects.all().filter(disabled=False))

    def __init__(self, *args, **kwargs):
        super(ProjectAdminForm, self).__init__(*args, **kwargs)
        self.fields['currencies'].required = False

        self.fields['reviewer'].widget = ReviewerWidget(
            rel=Project._meta.get_field('reviewer').rel,
            admin_site=admin.sites.site
        )

class ProjectAdmin(AdminImageMixin, ImprovedModelForm):
    form = ProjectAdminForm
    date_hierarchy = 'created'
    ordering = ('-created',)
    save_on_top = True

    search_fields = ('title', 'owner__first_name', 'owner__last_name',
                     'organization__name')

    raw_id_fields = ('owner', 'reviewer', 'organization',)

    prepopulated_fields = {'slug': ('title',)}

    inlines = (ProjectBudgetLineInline, RewardInlineAdmin, TaskAdminInline, ProjectDocumentInline,
               ProjectPhaseLogInline)

    def get_readonly_fields(self, request, obj=None):
        fields = ['vote_count',
                  'amount_donated', 'amount_needed',
                  'popularity', 'payout_status']
        if obj and obj.payout_status and obj.payout_status != 'needs_approval':
            fields += ('status', )
        return fields

    def get_urls(self):
        urls = super(ProjectAdmin, self).get_urls()
        process_urls = [
            url(r'^approve_payout/(?P<pk>\d+)/$',
                self.approve_payout,
                name="projects_project_approve_payout"),
        ]
        return process_urls + urls

    def approve_payout(self, request, pk=None):
        project = Project.objects.get(pk=pk)
        if not request.user.has_perm('projects.approve_payout'):
            return HttpResponseForbidden('Missing permission: projects.approve_payout')
        elif project.payout_status != 'needs_approval':
            self.message_user(request, 'The payout does not have the status "needs approval"')
        else:
            adapter = DoradoPayoutAdapter(project)
            try:
                adapter.trigger_payout()
            except PayoutValidationError, e:
                errors = e.message['errors']
                if type(errors) == unicode:
                    self.message_user(
                        request,
                        'Account details: {}.'.format(errors),
                        level=messages.ERROR
                    )
                else:
                    for field, errors in errors.items():
                        for error in errors:
                            self.message_user(
                                request,
                                'Account details: {}, {}.'.format(field, error.lower()),
                                level=messages.ERROR
                            )
            except (PayoutCreationError, ImproperlyConfigured), e:
                logger.warning(
                    'Error approving payout: {}'.format(e),
                    exc_info=1
                )

                self.message_user(
                    request,
                    'Failed to approve payout: {}'.format(e),
                    level=messages.ERROR
                )

        project_url = reverse('admin:projects_project_change', args=(project.id,))
        return HttpResponseRedirect(project_url)

    list_filter = ('country__subregion__region',)

    def get_list_filter(self, request):
        filters = ['status', 'is_campaign', ProjectThemeFilter, ProjectReviewerFilter,
                   'project_type', ('deadline', DateRangeFilter), ]

        if request.user.has_perm('projects.approve_payout'):
            filters.insert(1, 'payout_status')

        # Only show Location column if there are any
        if Location.objects.count():
            filters += [LocationGroupFilter, LocationFilter]
        else:
            filters += ['country__subregion__region', ('country', admin.RelatedOnlyFieldListFilter), ]
        return filters

    def get_list_display(self, request):
        fields = ['get_title_display', 'get_owner_display', 'created',
                  'status', 'deadline', 'donated_percentage']

        if request.user.has_perm('projects.approve_payout'):
            fields.insert(4, 'payout_status')

        # Only show Location column if there are any
        if Location.objects.count():
            fields += ('location',)
        # Only show Vote_count column if there are any votes
        if Vote.objects.count():
            fields += ('vote_count',)
        return fields

    def get_list_editable(self, request):
        return ('is_campaign',)

    export_fields = [
        ('title', 'title'),
        ('owner', 'owner'),
        ('owner__remote_id', 'remote id'),
        ('reviewer', 'reviewer'),
        ('created', 'created'),
        ('status', 'status', 'payout_status'),
        ('theme', 'theme'),
        ('location__group', 'region'),
        ('location', 'location'),
        ('deadline', 'deadline'),
        ('date_submitted', 'date submitted'),
        ('campaign_started', 'campaign started'),
        ('campaign_ended', 'campaign ended'),
        ('campaign_funded', 'campaign funded'),
        ('campaign_payed_out', 'campaign_payed_out'),
        ('task_count', 'task count'),
        ('supporters', 'supporters'),
        ('time_spent', 'time spent'),
        ('amount_asked', 'amount asked'),
        ('amount_donated', 'amount donated'),
        ('organization__name', 'organization'),
        ('amount_extra', 'amount matched'),
    ]

    actions = [export_as_csv_action(fields=export_fields),
               mark_as_closed, mark_as_done_incomplete,
               mark_as_done_complete, mark_as_campaign,
               mark_as_voting_done, mark_as_voting,
               mark_as_plan_needs_work, mark_as_plan_submitted,
               mark_as_plan_new]

    def get_actions(self, request):
        """Order the action in reverse (delete at the bottom)."""
        actions = super(ProjectAdmin, self).get_actions(request)
        return OrderedDict(reversed(actions.items()))

    def get_fieldsets(self, request, obj=None):
        main = {'fields': ['owner', 'reviewer', 'organization',
                           'status', 'title', 'slug', 'project_type',
                           'is_campaign', 'celebrate_results']}

        if request.user.has_perm('projects.approve_payout'):
            main['fields'].insert(3, 'payout_status')

        return (
            (_('Main'), main),

            (_('Story'), {'fields': ('pitch', 'story', 'reach')}),

            (_('Details'), {'fields': ('language', 'theme', 'categories', 'image',
                                       'video_url', 'country',
                                       'latitude', 'longitude',
                                       'location', 'place')}),

            (_('Goal'), {'fields': ('amount_asked', 'amount_extra',
                                    'amount_donated', 'amount_needed',
                                    'currencies',
                                    'popularity', 'vote_count')}),

            (_('Dates'), {'fields': ('voting_deadline', 'deadline',
                                     'date_submitted', 'campaign_started',
                                     'campaign_ended', 'campaign_funded', 'campaign_payed_out')}),

            (_('Bank details'), {'fields': ('account_holder_name',
                                            'account_holder_address',
                                            'account_holder_postal_code',
                                            'account_holder_city',
                                            'account_holder_country',
                                            'account_number',
                                            'account_bic',
                                            'account_bank_country')})
        )

    def vote_count(self, obj):
        return obj.vote_set.count()

    def donated_percentage(self, obj):
        try:
            percentage = "%.2f" % (100 * obj.amount_donated.amount / obj.amount_asked.amount)
            return "{0} %".format(percentage)
        except (AttributeError, InvalidOperation):
            return '-'

    def get_queryset(self, request):
        # Optimization: Select related fields that are used in admin specific
        # display fields.
        queryset = super(ProjectAdmin, self).get_queryset(request)
        queryset = queryset.select_related(
            'owner', 'organization'
        ).annotate(
            admin_vote_count=Count('vote', distinct=True),
            time_spent=Sum('task__members__time_spent')
        )

        return queryset

    def num_votes(self, obj):
        self.queryset(None)
        return obj.admin_vote_count

    num_votes.short_description = _('Vote Count')
    num_votes.admin_order_field = 'admin_vote_count'

    def get_title_display(self, obj):
        if len(obj.title) > 35:
            return format_html(
                u'{} …',
                obj.title, obj.title[:45]
            )
        return obj.title

    get_title_display.admin_order_field = 'title'
    get_title_display.short_description = _('title')

    def get_owner_display(self, obj):
        owner_name = obj.owner.get_full_name()
        if owner_name:
            owner_name = u' ({name})'.format(name=owner_name)
        return u'{email}{name}'.format(name=owner_name, email=obj.owner.email)

    get_owner_display.admin_order_field = 'owner__last_name'
    get_owner_display.short_description = _('owner')

    def project_owner(self, obj):
        object = obj.owner
        url = reverse('admin:{0}_{1}_change'.format(
            object._meta.app_label, object._meta.model_name), args=[object.id])
        return format_html(
            u"{}",
            str(url),
            object.first_name + ' ' + object.last_name
        )

admin.site.register(Project, ProjectAdmin)

admin.site.register(ProjectPhase)
<|endoftext|>


<commit_before>#From https://gist.github.com/EndingCredits/b5f35e84df10d46cfa716178d9c862a3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.framework import ops
from tensorflow.python.training import optimizer
import tensorflow as tf
import hyperchamber as hc
import numpy as np
import inspect
from operator import itemgetter
from hypergan.train_hooks.base_train_hook import BaseTrainHook

class InputFitnessTrainHook(BaseTrainHook):
  "Keep track of Xs with high discriminator values"
  def __init__(self, gan=None, config=None, trainer=None, name="GpSnMemoryTrainHook", memory_size=2, top_k=1):
    super().__init__(config=config, gan=gan, trainer=trainer, name=name)
    gan_inputs = self.gan.inputs.x

    self.input = tf.split(self.gan.inputs.x, self.gan.batch_size(), axis=0)
    fitness = self.gan.loss.d_real
    if self.config.abs:
        fitness = tf.abs(self.gan.loss.d_real)
    if self.config.reverse:
        fitness = -self.gan.loss.d_real
    if self.config.nabs:
        fitness = -tf.abs(self.gan.loss.d_real)
    self.d_real = tf.split(fitness, self.gan.batch_size(), axis=0)
    self.feed_input = tf.split(self.gan.feed_x, self.gan.batch_size(), axis=0)

    self.sample_batch = self.gan.set_x
    cache_count = self.gan.batch_size()
    self.cache = [tf.Variable(tf.zeros_like(self.input[i])) for i in range(len(self.input))]
    print("C ", self.cache, self.input)
    self.set_cache = [tf.assign(c, x) for c, x in zip(self.cache, self.input)]
    self.restore_cache = [[tf.assign(self.gan.inputs.x[i], tf.reshape(self.cache[j], self.ops.shape(self.gan.inputs.x[i]))) for i in range(self.gan.batch_size())]  for j in range(self.gan.batch_size())]
    #for i in range(self.gan.batch_size()):
    #    restore = []
    #    for j in range(self.gan.batch_size()):
    #        op = tf.assign(self.gan.inputs.x[i], tf.reshape(self.cache[j], self.ops.shape(self.gan.inputs.x[i])))
    #        restore.append(op)
    #    self.restore_cache.append(restore)
    self.loss = [None, None]
    if self.config.k_lipschitz is not None:
        klip = self.gan.configurable_param(self.config.k_lipschitz)
        k_lip = tf.nn.relu(tf.abs(tf.reduce_mean(self.gan.loss.d_real-self.gan.loss.d_fake))-klip)
        self.gan.add_metric("k_lip", k_lip)
        self.loss = [k_lip, None]

  def after_step(self, step, feed_dict):
    pass

  def losses(self):
      return self.loss

  def before_step(self, step, feed_dict):
    def sort():
        raw_winners = np.argsort(np.array(scores).flatten())
        winners = raw_winners[:self.gan.batch_size()]

        sticky = 0
        total = 0
        cache_winners = [ scorei for scorei in winners if scorei < self.gan.batch_size()]
        losers = [ i for i in range(self.gan.batch_size()) if (i+self.gan.batch_size()) not in winners ]

        for loser, cache_winner in zip(cache_winners, losers):
            self.gan.session.run(self.restore_cache[loser][cache_winner])
        #if total == sticky or sticky == 0:
        #    print("Sticky "+str(sticky) + " / "+ str(total))

    if self.config.heuristic is not None:
        count = 0
        previous_last_score = 1000
    for i in range(self.config.search_steps or 1):
        scores = []
        scores += self.gan.session.run(self.d_real)
        self.gan.session.run(self.set_cache)
        self.gan.session.run(self.sample_batch)
        scores += self.gan.session.run(self.d_real)
        sort()
        if self.config.heuristic is not None:
            last_score = np.sort(np.array(scores).flatten())[-1]
            if last_score < previous_last_score:
                count = 0
                previous_last_score = last_score
            else:
                count += 1
                if(count > self.config.heuristic):
                    #print(i+1)
                    break

        if self.config.verify:
            sortedscores = np.sort(np.array(scores).flatten())
            newscores =np.sort(np.array(self.gan.session.run(self.d_real)).flatten())
            print(i)
            print(sortedscores[:self.gan.batch_size()].flatten())
            print(np.sort(np.array(newscores).flatten()))
            print(np.sort(newscores.flatten()) == np.array(sortedscores[:self.gan.batch_size()]).flatten())

<commit_msg>[feature] support search_steps = 0 for input fitness<commit_after>#From https://gist.github.com/EndingCredits/b5f35e84df10d46cfa716178d9c862a3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.framework import ops
from tensorflow.python.training import optimizer
import tensorflow as tf
import hyperchamber as hc
import numpy as np
import inspect
from operator import itemgetter
from hypergan.train_hooks.base_train_hook import BaseTrainHook

class InputFitnessTrainHook(BaseTrainHook):
  "Keep track of Xs with high discriminator values"
  def __init__(self, gan=None, config=None, trainer=None, name="GpSnMemoryTrainHook", memory_size=2, top_k=1):
    super().__init__(config=config, gan=gan, trainer=trainer, name=name)
    gan_inputs = self.gan.inputs.x

    self.input = tf.split(self.gan.inputs.x, self.gan.batch_size(), axis=0)
    fitness = self.gan.loss.d_real
    if self.config.abs:
        fitness = tf.abs(self.gan.loss.d_real)
    if self.config.reverse:
        fitness = -self.gan.loss.d_real
    if self.config.nabs:
        fitness = -tf.abs(self.gan.loss.d_real)
    self.d_real = tf.split(fitness, self.gan.batch_size(), axis=0)
    self.feed_input = tf.split(self.gan.feed_x, self.gan.batch_size(), axis=0)

    self.sample_batch = self.gan.set_x
    cache_count = self.gan.batch_size()
    self.cache = [tf.Variable(tf.zeros_like(self.input[i])) for i in range(len(self.input))]
    print("C ", self.cache, self.input)
    self.set_cache = [tf.assign(c, x) for c, x in zip(self.cache, self.input)]
    self.restore_cache = [[tf.assign(self.gan.inputs.x[i], tf.reshape(self.cache[j], self.ops.shape(self.gan.inputs.x[i]))) for i in range(self.gan.batch_size())]  for j in range(self.gan.batch_size())]
    #for i in range(self.gan.batch_size()):
    #    restore = []
    #    for j in range(self.gan.batch_size()):
    #        op = tf.assign(self.gan.inputs.x[i], tf.reshape(self.cache[j], self.ops.shape(self.gan.inputs.x[i])))
    #        restore.append(op)
    #    self.restore_cache.append(restore)
    self.loss = [None, None]
    if self.config.k_lipschitz is not None:
        klip = self.gan.configurable_param(self.config.k_lipschitz)
        k_lip = tf.nn.relu(tf.abs(tf.reduce_mean(self.gan.loss.d_real-self.gan.loss.d_fake))-klip)
        self.gan.add_metric("k_lip", k_lip)
        self.loss = [k_lip, None]

  def after_step(self, step, feed_dict):
    pass

  def losses(self):
      return self.loss

  def before_step(self, step, feed_dict):
    def sort():
        raw_winners = np.argsort(np.array(scores).flatten())
        winners = raw_winners[:self.gan.batch_size()]

        sticky = 0
        total = 0
        cache_winners = [ scorei for scorei in winners if scorei < self.gan.batch_size()]
        losers = [ i for i in range(self.gan.batch_size()) if (i+self.gan.batch_size()) not in winners ]

        for loser, cache_winner in zip(cache_winners, losers):
            self.gan.session.run(self.restore_cache[loser][cache_winner])
        #if total == sticky or sticky == 0:
        #    print("Sticky "+str(sticky) + " / "+ str(total))

    if self.config.heuristic is not None:
        count = 0
        previous_last_score = 1000
    search_steps = self.config.search_steps
    if self.config.search_steps is None:
        search_steps = 1

    if search_steps == 0:
        self.gan.session.run(self.sample_batch)

    for i in range(search_steps):
        scores = []
        scores += self.gan.session.run(self.d_real)
        self.gan.session.run(self.set_cache)
        self.gan.session.run(self.sample_batch)
        scores += self.gan.session.run(self.d_real)
        sort()
        if self.config.heuristic is not None:
            last_score = np.sort(np.array(scores).flatten())[-1]
            if last_score < previous_last_score:
                count = 0
                previous_last_score = last_score
            else:
                count += 1
                if(count > self.config.heuristic):
                    #print(i+1)
                    break

        if self.config.verify:
            sortedscores = np.sort(np.array(scores).flatten())
            newscores =np.sort(np.array(self.gan.session.run(self.d_real)).flatten())
            print(i)
            print(sortedscores[:self.gan.batch_size()].flatten())
            print(np.sort(np.array(newscores).flatten()))
            print(np.sort(newscores.flatten()) == np.array(sortedscores[:self.gan.batch_size()]).flatten())

<|endoftext|>


<commit_before>from flask import Blueprint, request, jsonify, render_template

bp = Blueprint('views', __name__, url_prefix='')

@bp.route('/ip', methods=['GET'])
def get_ip():
    return jsonify(ip=request.remote_addr)

@bp.route('/', methods=['GET'])
def index():
    return render_template('index.html')
<commit_msg>Remove json route for retrieving the ip.<commit_after>from flask import Blueprint, request, render_template

bp = Blueprint('views', __name__, url_prefix='')

@bp.route('/', methods=['GET'])
def index():
    return render_template('index.html', ip=request.remote_addr)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from models import EveCharacter
from models import EveApiKeyPair
from models import EveAllianceInfo
from models import EveCorporationInfo
from models import AuthInfo
from models import User

import datetime as dt

from .eve_api_manager import EveApiManager

class EveManager:
    def __init__(self):
        pass

    @staticmethod
    def create_character(character_id, character_name, corporation_id, alliance_id, user_id, api_id):
        if not EveCharacter.query.filter_by(character_id=str(character_id)).all():
            eve_char = EveCharacter()
            eve_char.character_id = character_id
            eve_char.character_name = character_name
            eve_char.corporation_id = str(corporation_id)
            if alliance_id != 0:
                eve_char.alliance_id = str(alliance_id)
            eve_char.user_id = user_id
            eve_char.api_id = api_id
            eve_char.save()

    @staticmethod
    def create_characters_from_list(chars, user_id, api_id):
        for char in chars.result:
            if not EveManager.check_if_character_exist(chars.result[char]['name']):
                EveManager.create_character(chars.result[char]['id'],
                                            chars.result[char]['name'],
                                            chars.result[char]['corp']['id'],
                                            chars.result[char]['alliance']['id'],
                                            user_id, api_id)

    @staticmethod
    def create_corporations_from_list(characters):
        for character in characters.result:
            if not EveManager.check_if_corporation_exists_by_id(characters.result[character]['corp']['id']):
                corpinfo = EveApiManager.get_corporation_information(characters.result[character]['corp']['id'])
                if corpinfo:
                    EveManager.create_corporation_info(corp_id=corpinfo['id'], corp_name=corpinfo['name'], corp_ticker=corpinfo['ticker'], corp_member_count=corpinfo['members']['current'], alliance_id=corpinfo['alliance']['id'])

    @staticmethod
    def create_alliances_from_list(characters):
        for character in characters.result:
            if characters.result[character]['alliance']['id'] != 0:
                if not EveManager.check_if_alliance_exists_by_id(characters.result[character]['alliance']['id']):
                    alliance_info = EveApiManager.get_alliance_information(characters.result[character]['alliance']['id'])
                    print alliance_info
                    if alliance_info:
                        EveManager.create_alliance_info(alliance_id=alliance_info['id'], alliance_name=alliance_info['name'], alliance_ticker=alliance_info['ticker'], alliance_executor_corp_id=alliance_info['executor_id'],alliance_member_count=alliance_info['member_count'])

    @staticmethod
    def update_characters_from_list(characters):
        for character in characters:
            if EveManager.check_if_character_exist(chars.result[char]['name']):
                eve_char = EveManager.get_character_by_character_name(chars.result[char]['name'])
                eve_char.corporation_id = chars.result[char]['corp']['id']
                eve_char.alliance_id = chars.result[char]['alliance']['id']
                eve_char.save()

    @staticmethod
    def create_api_keypair(api_id, api_key, user_id):
        if not EveApiKeyPair.query.filter_by(api_id=api_id).all():
            api_pair = EveApiKeyPair()
            api_pair.api_id = api_id
            api_pair.api_key = api_key
            api_pair.last_update_time = dt.datetime.now()
            api_pair.user_id = user_id
            api_pair.save()

    @staticmethod
    def update_api_keypair(api_id, api_key):
        if EveApiKeyPair.query.filter_by(api_id=api_id).first():
            api_pair = EveApiKeyPair.query.filter_by(api_id=api_id).first()
            characters = EveApiManager.get_characters_from_api(api_id=api_id, api_key=api_key)
            update_characters_from_list(characters=characters)
            api_pair.update_time = dt.datetime.now()
            api_pair.save()

    @staticmethod
    def create_alliance_info(alliance_id, alliance_name, alliance_ticker, alliance_executor_corp_id,
                             alliance_member_count, is_blue=None):
        if not EveManager.check_if_alliance_exists_by_id(str(alliance_id)):
            alliance_info = EveAllianceInfo()
            alliance_info.alliance_id = str(alliance_id)
            alliance_info.alliance_name = alliance_name
            alliance_info.alliance_ticker = alliance_ticker
            alliance_info.executor_corp_id = str(alliance_executor_corp_id)
            alliance_info.member_count = alliance_member_count
            alliance_info.is_blue = is_blue
            alliance_info.save()

    @staticmethod
    def update_alliance_info(alliance_id, alliance_executor_corp_id, alliance_member_count, is_blue=None):
        if EveManager.check_if_alliance_exists_by_id(alliance_id):
            alliance_info = EveAllianceInfo.query.filter_by(alliance_id=alliance_id).all()
            alliance_info.executor_corp_id = str(alliance_executor_corp_id)
            alliance_info.member_count = alliance_member_count
            alliance_info.is_blue = is_blue
            alliance_info.save()

    @staticmethod
    def create_corporation_info(corp_id, corp_name, corp_ticker, corp_member_count, alliance_id, is_blue=None):
        if not EveManager.check_if_corporation_exists_by_id(corp_id):
            corp_info = EveCorporationInfo()
            corp_info.corporation_id = str(corp_id)
            corp_info.corporation_name = corp_name
            corp_info.corporation_ticker = corp_ticker
            corp_info.member_count = corp_member_count
            corp_info.is_blue = is_blue
            if alliance_id:
                corp_info.alliance_id = alliance_id
            corp_info.save()

    @staticmethod
    def update_corporation_info(corp_id, corp_member_count, alliance_id, is_blue):
        if EveManager.check_if_corporation_exists_by_id(corp_id):
            corp_info = EveCorporationInfo.query.filter_by(corporation_id=str(corp_id)).all()
            corp_info.member_count = corp_member_count
            corp_info.alliance_id = str(alliance_id)
            corp_info.is_blue = is_blue
            corp_info.save()

    @staticmethod
    def get_api_key_pairs(user_id):
        if EveApiKeyPair.query.filter_by(user_id=user_id).all():
            return EveApiKeyPair.query.filter_by(user_id=user_id).all()

    @staticmethod
    def check_if_api_key_pair_exist(api_id):
        if EveApiKeyPair.query.filter_by(api_id=api_id).first():
            return True
        else:
            return False

    @staticmethod
    def delete_api_key_pair(api_id, user_id):
        if EveApiKeyPair.query.filter_by(api_id=api_id).all():
            # Check that its owned by our user_id
            apikeypair = EveApiKeyPair.query.filter_by(api_id=api_id).first()
            if unicode(apikeypair.user_id) == unicode(user_id):
                apikeypair.delete()

    @staticmethod
    def delete_characters_by_api_id(api_id, user_id):
        if EveCharacter.query.filter_by(api_id=api_id).all():
            # Check that its owned by our user_id
            characters = EveCharacter.query.filter_by(api_id=api_id).all()

            for character in characters:
                if unicode(character.user_id) == unicode(user_id):
                    character.delete()

    @staticmethod
    def check_if_character_exist(character_id):
        if EveCharacter.query.filter_by(character_id=character_id).first():
            return True
        return False

    @staticmethod
    def get_characters_by_owner_id(user_id):
        if EveCharacter.query.filter_by(user_id=user_id).all():
            return EveCharacter.query.filter_by(user_id=user_id).all()
        return None

    @staticmethod
    def get_character_by_character_name(character_name):
        if EveCharacter.query.filter_by(character_name=character_name).first():
            return EveCharacter.query.filter_by(character_name=character_name).first()
        return None

    @staticmethod
    def get_character_by_id(character_id):
        if EveCharacter.query.filter_by(character_id=character_id).first():
            return EveCharacter.query.filter_by(character_id=character_id).first()
        return None

    @staticmethod
    def get_character_alliance_id_by_id(char_id):
        if EveCharacter.query.filter_by(character_id=char_id).all():
            return EveCharacter.query.filter_by(character_id=char_id).first().alliance_id

    @staticmethod
    def check_if_character_owned_by_user(character_id, user_id):
        character = EveCharacter.query.filter_by(character_id=character_id).first()
        print character
        if unicode(character.user_id) == unicode(user_id):
            return True

        return False

    @staticmethod
    def check_if_alliance_exists_by_id(alliance_id):
        return EveAllianceInfo.query.filter_by(alliance_id=alliance_id).all()

    @staticmethod
    def check_if_corporation_exists_by_id(corporation_id):
        if EveCorporationInfo.query.filter_by(corporation_id=corporation_id).first():
            return True
        return False

    @staticmethod
    def get_alliance_info_by_id(alliance_id):
        if EveManager.check_if_alliance_exists_by_id(alliance_id):
            return EveAllianceInfo.query.filter_by(alliance_id=alliance_id).first()
        else:
            return None

    @staticmethod
    def get_corporation_info_by_id(corp_id):
        if EveManager.check_if_corporation_exists_by_id(corp_id):
            return EveCorporationInfo.query.filter_by(corporation_id=corp_id).all()
        else:
            return None

    @staticmethod
    def get_all_corporation_info():
        return EveCorporationInfo.query.order_by(EveCorporationInfo.corporation_id)

    @staticmethod
    def get_all_alliance_info():
        return EveAllianceInfo.query.order_by(EveAllianceInfo.alliance_id)

class AuthInfoManager:
    def __init__(self):
        pass

    @staticmethod
    def get_or_create(user_id):
        if AuthInfo.query.filter_by(user_id=user_id).all():
            return AuthInfo.query.filter_by(user_id=user_id).first()
        else:
            # We have to create
            authinfo = AuthInfo()
            authinfo.user_id = user_id
            authinfo.save()
            return authinfo

    @staticmethod
    def update_main_character_id(char_id, user_id):
        if User.query.filter_by(id=user_id).all():
            authinfo = AuthInfoManager.get_or_create(user_id)
            authinfo.main_character_id = char_id
            authinfo.save()
<commit_msg>ofofofofof<commit_after># -*- coding: utf-8 -*-
from models import EveCharacter
from models import EveApiKeyPair
from models import EveAllianceInfo
from models import EveCorporationInfo
from models import AuthInfo
from models import User

import datetime as dt

from .eve_api_manager import EveApiManager

class EveManager:
    def __init__(self):
        pass

    @staticmethod
    def create_character(character_id, character_name, corporation_id, alliance_id, user_id, api_id):
        if not EveCharacter.query.filter_by(character_id=str(character_id)).all():
            eve_char = EveCharacter()
            eve_char.character_id = character_id
            eve_char.character_name = character_name
            eve_char.corporation_id = str(corporation_id)
            if alliance_id != 0:
                eve_char.alliance_id = str(alliance_id)
            eve_char.user_id = user_id
            eve_char.api_id = api_id
            eve_char.save()

    @staticmethod
    def create_characters_from_list(chars, user_id, api_id):
        for char in chars.result:
            if not EveManager.check_if_character_exist(chars.result[char]['name']):
                EveManager.create_character(chars.result[char]['id'],
                                            chars.result[char]['name'],
                                            chars.result[char]['corp']['id'],
                                            chars.result[char]['alliance']['id'],
                                            user_id, api_id)

    @staticmethod
    def create_corporations_from_list(characters):
        for character in characters.result:
            if not EveManager.check_if_corporation_exists_by_id(characters.result[character]['corp']['id']):
                corpinfo = EveApiManager.get_corporation_information(characters.result[character]['corp']['id'])
                if corpinfo:
                    EveManager.create_corporation_info(corp_id=corpinfo['id'], corp_name=corpinfo['name'], corp_ticker=corpinfo['ticker'], corp_member_count=corpinfo['members']['current'], alliance_id=corpinfo['alliance']['id'])

    @staticmethod
    def create_alliances_from_list(characters):
        for character in characters.result:
            if characters.result[character]['alliance']['id'] != 0:
                if not EveManager.check_if_alliance_exists_by_id(characters.result[character]['alliance']['id']):
                    alliance_info = EveApiManager.get_alliance_information(characters.result[character]['alliance']['id'])
                    print alliance_info
                    if alliance_info:
                        EveManager.create_alliance_info(alliance_id=alliance_info['id'], alliance_name=alliance_info['name'], alliance_ticker=alliance_info['ticker'], alliance_executor_corp_id=alliance_info['executor_id'],alliance_member_count=alliance_info['member_count'])

    @staticmethod
    def update_characters_from_list(characters):
        for character in characters:
            if EveManager.check_if_character_exist(chars.result[char]['name']):
                eve_char = EveManager.get_character_by_character_name(chars.result[char]['name'])
                eve_char.corporation_id = chars.result[char]['corp']['id']
                eve_char.alliance_id = chars.result[char]['alliance']['id']
                eve_char.save()

    @staticmethod
    def create_api_keypair(api_id, api_key, user_id):
        if not EveApiKeyPair.query.filter_by(api_id=api_id).all():
            api_pair = EveApiKeyPair()
            api_pair.api_id = api_id
            api_pair.api_key = api_key
            api_pair.last_update_time = dt.datetime.now()
            api_pair.user_id = user_id
            api_pair.save()

    @staticmethod
    def update_api_keypair(api_id, api_key):
        if EveApiKeyPair.query.filter_by(api_id=api_id).first():
            api_pair = EveApiKeyPair.query.filter_by(api_id=api_id).first()
            characters = EveApiManager.get_characters_from_api(api_id=api_id, api_key=api_key)
            update_characters_from_list(characters=characters)
            api_pair.update_time = dt.datetime.now()
            api_pair.save()

    @staticmethod
    def create_alliance_info(alliance_id, alliance_name, alliance_ticker, alliance_executor_corp_id,
                             alliance_member_count, is_blue=None):
        if not EveManager.check_if_alliance_exists_by_id(str(alliance_id)):
            alliance_info = EveAllianceInfo()
            alliance_info.alliance_id = str(alliance_id)
            alliance_info.alliance_name = alliance_name
            alliance_info.alliance_ticker = alliance_ticker
            alliance_info.executor_corp_id = str(alliance_executor_corp_id)
            alliance_info.member_count = alliance_member_count
            alliance_info.is_blue = is_blue
            alliance_info.save()

    @staticmethod
    def update_alliance_info(alliance_id, alliance_executor_corp_id, alliance_member_count, is_blue=None):
        if EveManager.check_if_alliance_exists_by_id(alliance_id):
            alliance_info = EveAllianceInfo.query.filter_by(alliance_id=alliance_id).all()
            alliance_info.executor_corp_id = str(alliance_executor_corp_id)
            alliance_info.member_count = alliance_member_count
            alliance_info.is_blue = is_blue
            alliance_info.save()

    @staticmethod
    def create_corporation_info(corp_id, corp_name, corp_ticker, corp_member_count, alliance_id, is_blue=None):
        if not EveManager.check_if_corporation_exists_by_id(corp_id):
            corp_info = EveCorporationInfo()
            corp_info.corporation_id = str(corp_id)
            corp_info.corporation_name = corp_name
            corp_info.corporation_ticker = corp_ticker
            corp_info.member_count = corp_member_count
            corp_info.is_blue = is_blue
            if alliance_id:
                corp_info.alliance_id = alliance_id
            corp_info.save()

    @staticmethod
    def update_corporation_info(corp_id, corp_member_count, alliance_id, is_blue):
        if EveManager.check_if_corporation_exists_by_id(corp_id):
            corp_info = EveCorporationInfo.query.filter_by(corporation_id=str(corp_id)).all()
            corp_info.member_count = corp_member_count
            corp_info.alliance_id = str(alliance_id)
            corp_info.is_blue = is_blue
            corp_info.save()

    @staticmethod
    def get_api_key_pairs(user_id):
        if EveApiKeyPair.query.filter_by(user_id=user_id).all():
            return EveApiKeyPair.query.filter_by(user_id=user_id).all()

    @staticmethod
    def check_if_api_key_pair_exist(api_id):
        if EveApiKeyPair.query.filter_by(api_id=api_id).first():
            return True
        else:
            return False

    @staticmethod
    def delete_api_key_pair(api_id, user_id):
        if EveApiKeyPair.query.filter_by(api_id=api_id).all():
            # Check that its owned by our user_id
            apikeypair = EveApiKeyPair.query.filter_by(api_id=api_id).first()
            if unicode(apikeypair.user_id) == unicode(user_id):
                apikeypair.delete()

    @staticmethod
    def delete_characters_by_api_id(api_id, user_id):
        if EveCharacter.query.filter_by(api_id=api_id).all():
            # Check that its owned by our user_id
            characters = EveCharacter.query.filter_by(api_id=api_id).all()

            for character in characters:
                if unicode(character.user_id) == unicode(user_id):
                    character.delete()

    @staticmethod
    def check_if_character_exist(character_id):
        if EveCharacter.query.filter_by(character_id=character_id).first():
            return True
        return False

    @staticmethod
    def get_characters_by_owner_id(user_id):
        if EveCharacter.query.filter_by(user_id=user_id).all():
            return EveCharacter.query.filter_by(user_id=user_id).all()
        return None

    @staticmethod
    def get_character_by_character_name(character_name):
        if EveCharacter.query.filter_by(character_name=character_name).first():
            return EveCharacter.query.filter_by(character_name=character_name).first()
        return None

    @staticmethod
    def get_character_by_id(character_id):
        if EveCharacter.query.filter_by(character_id=character_id).first():
            return EveCharacter.query.filter_by(character_id=character_id).first()
        return None

    @staticmethod
    def get_character_alliance_id_by_id(char_id):
        if EveCharacter.query.filter_by(character_id=char_id).all():
            return EveCharacter.query.filter_by(character_id=char_id).first().alliance_id

    @staticmethod
    def check_if_character_owned_by_user(character_id, user_id):
        character = EveCharacter.query.filter_by(character_id=character_id).first()
        print character
        if unicode(character.user_id) == unicode(user_id):
            return True

        return False

    @staticmethod
    def check_if_alliance_exists_by_id(alliance_id):
        return EveAllianceInfo.query.filter_by(alliance_id=str(alliance_id)).all()

    @staticmethod
    def check_if_corporation_exists_by_id(corporation_id):
        if EveCorporationInfo.query.filter_by(corporation_id=corporation_id).first():
            return True
        return False

    @staticmethod
    def get_alliance_info_by_id(alliance_id):
        if EveManager.check_if_alliance_exists_by_id(alliance_id):
            return EveAllianceInfo.query.filter_by(alliance_id=str(alliance_id)).first()
        else:
            return None

    @staticmethod
    def get_corporation_info_by_id(corp_id):
        if EveManager.check_if_corporation_exists_by_id(corp_id):
            return EveCorporationInfo.query.filter_by(corporation_id=corp_id).all()
        else:
            return None

    @staticmethod
    def get_all_corporation_info():
        return EveCorporationInfo.query.order_by(EveCorporationInfo.corporation_id)

    @staticmethod
    def get_all_alliance_info():
        return EveAllianceInfo.query.order_by(EveAllianceInfo.alliance_id)

class AuthInfoManager:
    def __init__(self):
        pass

    @staticmethod
    def get_or_create(user_id):
        if AuthInfo.query.filter_by(user_id=user_id).all():
            return AuthInfo.query.filter_by(user_id=user_id).first()
        else:
            # We have to create
            authinfo = AuthInfo()
            authinfo.user_id = user_id
            authinfo.save()
            return authinfo

    @staticmethod
    def update_main_character_id(char_id, user_id):
        if User.query.filter_by(id=user_id).all():
            authinfo = AuthInfoManager.get_or_create(user_id)
            authinfo.main_character_id = char_id
            authinfo.save()
<|endoftext|>


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

'''
Handler for reply.
'''

import json

from torcms.core.base_handler import BaseHandler
from torcms.model.reply_model import MReply
from torcms.model.replyid_model import MReplyid
from torcms.model.reply2user_model import MReply2User
from torcms.core.tools import logger
from config import CMS_CFG

class ReplyHandler(BaseHandler):
    '''
    Handler for reply.
    '''

    def initialize(self):
        super(ReplyHandler, self).initialize()

    def get(self, *args, **kwargs):
        url_str = args[0]
        url_arr = self.parse_url(url_str)
        if url_arr[0] == 'get':
            self.get_by_id(url_arr[1])
        if url_arr[0] == 'list':
            self.list(url_arr[1])
        elif url_arr[0] == 'delete':
            self.delete(url_arr[1])
        elif url_arr[0] == 'delete_com':
            self.delete_com(url_arr[1])
        elif url_arr[0] == 'zan':
            self.zan(url_arr[1])

    def post(self, *args, **kwargs):
        url_str = args[0]
        url_arr = self.parse_url(url_str)

        if url_arr[0] == 'add':
            self.add(url_arr[1])
        elif url_arr[0]=='add_reply':
            self.add_reply(url_arr[1],url_arr[2])
        elif url_arr[0]=='modify':
            self.modify(url_arr[1],url_arr[2])

    def list(self, cur_p=''):
        '''
        List the replies.
        '''
        if cur_p == '':
            current_page_number = 1
        else:
            current_page_number = int(cur_p)

        current_page_number = 1 if current_page_number < 1 else current_page_number

        pager_num = int(MReply.total_number() / CMS_CFG['list_num'])

        kwd = {'pager': '',
               'current_page': current_page_number,
               'title': '单页列表'}
        self.render('admin/reply_ajax/reply_list.html',
                    kwd=kwd,
                    view_all=MReply.query_all(),
                    infos=MReply.query_pager(current_page_num=current_page_number),
                    userinfo=self.userinfo
                    )

    def get_by_id(self, reply_id):
        '''
        Get the reply by id.
        '''
        reply = MReply.get_by_uid(reply_id)
        logger.info('get_reply: {0}'.format(reply_id))

        self.render('misc/reply/show_reply.html',
                    reply=reply,
                    username=reply.user_name,
                    date=reply.date,
                    vote=reply.vote,
                    uid=reply.uid,
                    userinfo=self.userinfo,
                    kwd={})

    def add(self, post_id):
        '''
        Adding reply to a post.
        '''
        post_data = self.get_post_data()

        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['post_id'] = post_id
        post_data['category'] = '0'
        replyid = MReply.create_reply(post_data)
        if replyid:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': replyid}
            logger.info('add reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)

    # @tornado.web.authenticated
    def zan(self, id_reply):
        '''
        先在外部表中更新，然后更新内部表字段的值。
        有冗余，但是查看的时候避免了联合查询
        '''

        logger.info('zan: {0}'.format(id_reply))

        MReply2User.create_reply(self.userinfo.uid, id_reply)
        cur_count = MReply2User.get_voter_count(id_reply)
        if cur_count:
            MReply.update_vote(id_reply, cur_count)
            output = {'text_zan': cur_count}
        else:
            output = {'text_zan': 0}
        logger.info('zan dic: {0}'.format(cur_count))

        return json.dump(output, self)

    def delete(self, del_id):
        '''
        Delete the id
        '''
        if MReply2User.delete(del_id):
            output = {'del_zan': 1}
        else:
            output = {'del_zan': 0}
        return json.dump(output, self)
    def delete_com(self, del_id):
        '''
        Delete the reply id
        '''

        if MReply.delete_by_uid(del_id):
            output = '删除成功'
        else:
            output = '删除失败'
        return json.dump(output,self)
    def add_reply(self, post_id,reply_id):
        '''
        Adding reply
        '''
        post_data = self.get_post_data()

        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['post_id'] = post_id
        post_data['category'] = '1'
        # 表里添加回复内容返回存储id
        replyid = MReply.create_reply(post_data)
        # 在关联表里存储评论id与回复id
        MReplyid.create_replyid(reply_id, replyid)
        if replyid:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': replyid}
            logger.info('add reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)

    def modify(self, pid,cat):
        '''
        Adding comment to a post.
        '''
        post_data = self.get_post_data()
        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['category'] = cat
        reply = MReply.modify_by_uid(pid,post_data)

        if reply:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': reply}
            logger.info('Modify reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)<commit_msg>xiugai<commit_after># -*- coding:utf-8 -*-

'''
Handler for reply.
'''

import json

from torcms.core.base_handler import BaseHandler
from torcms.model.reply_model import MReply
from torcms.model.replyid_model import MReplyid
from torcms.model.reply2user_model import MReply2User
from torcms.core.tools import logger
from config import CMS_CFG

class ReplyHandler(BaseHandler):
    '''
    Handler for reply.
    '''

    def initialize(self):
        super(ReplyHandler, self).initialize()

    def get(self, *args, **kwargs):
        url_str = args[0]
        url_arr = self.parse_url(url_str)
        if url_arr[0] == 'get':
            self.get_by_id(url_arr[1])
        if url_arr[0] == 'list':
            self.list(url_arr[1])
        elif url_arr[0] == 'delete':
            self.delete(url_arr[1])
        elif url_arr[0] == 'delete_com':
            self.delete_com(url_arr[1])
        elif url_arr[0] == 'zan':
            self.zan(url_arr[1])

    def post(self, *args, **kwargs):
        url_str = args[0]
        url_arr = self.parse_url(url_str)

        if url_arr[0] == 'add':
            self.add(url_arr[1])
        elif url_arr[0]=='add_reply':
            self.add_reply(url_arr[1],url_arr[2])
        elif url_arr[0]=='modify':
            self.modify(url_arr[1],url_arr[2])

    def list(self, cur_p=''):
        '''
        List the replies.
        '''
        if cur_p == '':
            current_page_number = 1
        else:
            current_page_number = int(cur_p)

        current_page_number = 1 if current_page_number < 1 else current_page_number

        pager_num = int(MReply.total_number() / CMS_CFG['list_num'])

        kwd = {'pager': '',
               'current_page': current_page_number,
               'title': '单页列表'}
        self.render('admin/reply_ajax/reply_list.html',
                    kwd=kwd,
                    view_all=MReply.query_all(),
                    infos=MReply.query_pager(current_page_num=current_page_number),
                    userinfo=self.userinfo
                    )

    def get_by_id(self, reply_id):
        '''
        Get the reply by id.
        '''
        reply = MReply.get_by_uid(reply_id)
        logger.info('get_reply: {0}'.format(reply_id))

        self.render('misc/reply/show_reply.html',
                    reply=reply,
                    username=reply.user_name,
                    date=reply.date,
                    vote=reply.vote,
                    uid=reply.uid,
                    userinfo=self.userinfo,
                    kwd={})

    def add(self, post_id):
        '''
        Adding reply to a post.
        '''
        post_data = self.get_post_data()

        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['post_id'] = post_id
        post_data['category'] = '0'
        replyid = MReply.create_reply(post_data)
        if replyid:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': replyid}
            logger.info('add reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)

    # @tornado.web.authenticated
    def zan(self, id_reply):
        '''
        先在外部表中更新，然后更新内部表字段的值。
        有冗余，但是查看的时候避免了联合查询
        '''

        logger.info('zan: {0}'.format(id_reply))

        MReply2User.create_reply(self.userinfo.uid, id_reply)
        cur_count = MReply2User.get_voter_count(id_reply)
        if cur_count:
            MReply.update_vote(id_reply, cur_count)
            output = {'text_zan': cur_count}
        else:
            output = {'text_zan': 0}
        logger.info('zan dic: {0}'.format(cur_count))

        return json.dump(output, self)

    def delete(self, del_id):
        '''
        Delete the id
        '''
        if MReply2User.delete(del_id):
            output = {'del_zan': 1}
        else:
            output = {'del_zan': 0}
        return json.dump(output, self)
    def delete_com(self, del_id):
        '''
        Delete the reply id
        '''

        if MReply.delete_by_uid(del_id):
            output = {'del_reply': 1}
        else:
             output = {'del_reply': 0}
        return json.dump(output,self)
    def add_reply(self, post_id,reply_id):
        '''
        Adding reply
        '''
        post_data = self.get_post_data()

        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['post_id'] = post_id
        post_data['category'] = '1'
        # 表里添加回复内容返回存储id
        replyid = MReply.create_reply(post_data)
        # 在关联表里存储评论id与回复id
        MReplyid.create_replyid(reply_id, replyid)
        if replyid:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': replyid}
            logger.info('add reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)

    def modify(self, pid,cat):
        '''
        Adding comment to a post.
        '''
        post_data = self.get_post_data()
        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['category'] = cat
        reply = MReply.modify_by_uid(pid,post_data)

        if reply:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': reply}
            logger.info('Modify reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)<|endoftext|>