<commit_before>import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from paypal.standard.ipn.signals import subscription_signup

class Profile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name="profile")
    is_premium = models.BooleanField(default=False)
    preferences = models.TextField(default="{}")
    view_settings = models.TextField(default="{}")
    collapsed_folders = models.TextField(default="[]")
    last_seen_on = models.DateTimeField(default=datetime.datetime.now)
    last_seen_ip = models.CharField(max_length=50, blank=True, null=True)

def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    else:
        Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)

def paypal_signup(sender, **kwargs):
    ipn_obj = sender

    user = User.objects.get(username=ipn_obj.custom)
    user.profile.is_premium = True
    user.profile.save()

    from apps.rss_feeds.models import UserSubscription
    subs = UserSubscription.objects.filter(user=user)
    for sub in subs:
        sub.active = True
        sub.save()
        sub.feed.setup_feed_for_premium_subscribers()
subscription_signup.connect(paypal_signup)<commit_msg>Wrong import location.<commit_after>import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from apps.reader.models import UserSubscription
from paypal.standard.ipn.signals import subscription_signup

class Profile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name="profile")
    is_premium = models.BooleanField(default=False)
    preferences = models.TextField(default="{}")
    view_settings = models.TextField(default="{}")
    collapsed_folders = models.TextField(default="[]")
    last_seen_on = models.DateTimeField(default=datetime.datetime.now)
    last_seen_ip = models.CharField(max_length=50, blank=True, null=True)

def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    else:
        Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)

def paypal_signup(sender, **kwargs):
    ipn_obj = sender

    user = User.objects.get(username=ipn_obj.custom)
    user.profile.is_premium = True
    user.profile.save()

    subs = UserSubscription.objects.filter(user=user)
    for sub in subs:
        sub.active = True
        sub.save()
        sub.feed.setup_feed_for_premium_subscribers()
subscription_signup.connect(paypal_signup)<|endoftext|>


<commit_before>from django.db import models
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django_facebook.models import FacebookProfileModel
from django.template.defaultfilters import urlencode
from django.utils.safestring import mark_safe

from util import url_with_domain
from util.model_helpers import unique_slugify
from util.rediz import get_support_key, get_promise_key, get_ids_from_redis

from promise.managers import PromiseManager

PROMISE_STATUSES = (
    (1, "In Progress"),
    (2, "Succeeded"),
    (3, 'Failed'),
)

class Promise(models.Model):
    text = models.TextField()
    creator = models.ForeignKey('promise.Profile', related_name='creator')
    created = models.DateTimeField(auto_now=True)
    deadline = models.DateTimeField()
    status = models.PositiveSmallIntegerField(choices=PROMISE_STATUSES, default=1)
    supporter = models.ManyToManyField('promise.Profile', blank=True, related_name='supporter')
    slug = models.SlugField(unique=True, blank=True)

    objects = PromiseManager()

    def __unicode__(self):
        return u"{}:{}".format(self.text[:15], self.creator)

    @property
    def active(self):
        return self.status == 1

    @property
    def supporters(self):
        return ",".join([unicode(supporter) for supporter in self.supporter.all()])

    @property
    def mailto_url(self):
        body = unicode("'{}' - {}").format(self.text, self.creator) + unicode("\n{}").format(urlencode(self.full_url))
        subject = u"Support {}!".format(self.creator)
        res = u'mailto:?body={}&subject={}'.format(urlencode(body), urlencode(subject))
        return mark_safe(res)

    def get_absolute_url(self):
        return url_with_domain(reverse('promise', args=(self.slug,)))

    # TODO consolidate this and get_absolute_url
    def full_url(self):
        return self.get_absolute_url()

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = unique_slugify(self, self.text[:20])
        super(Promise, self).save(*args, **kwargs)

class Profile(FacebookProfileModel):
    user = models.OneToOneField('auth.User')

    @property
    def name(self):
        return self.facebook_name or unicode(self)

    def get_avatar_url(self, size, local=False):
        convert = {
            'large': '180/200',
            'square': '50/50',
        }

        if local and bool(self.image):
            return url_with_domain(self.image.url)
        return u'https://graph.facebook.com/{}/picture?type={}'.format(
            self.facebook_id, size) if self.facebook_id \
            else 'http://placekitten.com/g/{}'.format(convert.get(size))

    @property
    def avatar_square(self):
        return self.get_avatar_url('square')

    @property
    def avatar(self):
        return self.get_avatar_url('large')

    def __unicode__(self):
        return unicode(self.user)

class PromiseUserState(object):
    """Namespace to store status that relates an user to a promise.

    It's used to decide which widget should be shown to the user when
    accessing the promise page or the promise feed. All Anonymous users
    should be marked as "NOTHING".

    Namespaces are one honking great idea -- let's do more of those!
    """
    OWNER = 0
    SUPPORTER = 1
    NOTHING = 2

    @staticmethod
    def from_string(state):
        return getattr(PromiseUserState, state.upper())

def user_promise_state(user, promise):
    """Returns the status between the promise and the currently logged
    in (or anonymous) user. Just a helper to avoid ifs/elifs to
    proliferate in our codebase.
    """

    # We got an anonymous user here, he obviously can't support
    # anything. Let's give him a chance to show the "support this"
    # button.
    if user.is_anonymous():
        return PromiseUserState.NOTHING

    # For owners
    promise_key = get_promise_key(user.profile.id)
    if promise.id in get_ids_from_redis(promise_key):
        return PromiseUserState.OWNER

    # For supporters
    support_key = get_support_key(user.profile.id)
    if promise.id in get_ids_from_redis(support_key):
        return PromiseUserState.SUPPORTER

    return PromiseUserState.NOTHING

def create_profile(sender, instance, created, **kwargs):
    if created:
        from event.logging import logger
        Profile.objects.create(user=instance)
        logger.log('signup')
post_save.connect(create_profile, sender=User)
<commit_msg>adding model property<commit_after>from django.db import models
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django_facebook.models import FacebookProfileModel
from django.template.defaultfilters import urlencode
from django.utils.safestring import mark_safe

from util import url_with_domain
from util.model_helpers import unique_slugify
from util.rediz import get_support_key, get_promise_key, get_ids_from_redis

from promise.managers import PromiseManager

PROMISE_STATUSES = (
    (1, "In Progress"),
    (2, "Succeeded"),
    (3, 'Failed'),
)

class Promise(models.Model):
    text = models.TextField()
    creator = models.ForeignKey('promise.Profile', related_name='creator')
    created = models.DateTimeField(auto_now=True)
    deadline = models.DateTimeField()
    status = models.PositiveSmallIntegerField(choices=PROMISE_STATUSES, default=1)
    supporter = models.ManyToManyField('promise.Profile', blank=True, related_name='supporter')
    slug = models.SlugField(unique=True, blank=True)

    objects = PromiseManager()

    def __unicode__(self):
        return u"{}:{}".format(self.text[:15], self.creator)

    @property
    def active(self):
        return self.status == 1

    @property
    def success(self):
        return self.status == 2

    @property
    def supporters(self):
        return ",".join([unicode(supporter) for supporter in self.supporter.all()])

    @property
    def mailto_url(self):
        body = unicode("'{}' - {}").format(self.text, self.creator) + unicode("\n{}").format(urlencode(self.full_url))
        subject = u"Support {}!".format(self.creator)
        res = u'mailto:?body={}&subject={}'.format(urlencode(body), urlencode(subject))
        return mark_safe(res)

    def get_absolute_url(self):
        return url_with_domain(reverse('promise', args=(self.slug,)))

    # TODO consolidate this and get_absolute_url
    def full_url(self):
        return self.get_absolute_url()

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = unique_slugify(self, self.text[:20])
        super(Promise, self).save(*args, **kwargs)

class Profile(FacebookProfileModel):
    user = models.OneToOneField('auth.User')

    @property
    def name(self):
        return self.facebook_name or unicode(self)

    def get_avatar_url(self, size, local=False):
        convert = {
            'large': '180/200',
            'square': '50/50',
        }

        if local and bool(self.image):
            return url_with_domain(self.image.url)
        return u'https://graph.facebook.com/{}/picture?type={}'.format(
            self.facebook_id, size) if self.facebook_id \
            else 'http://placekitten.com/g/{}'.format(convert.get(size))

    @property
    def avatar_square(self):
        return self.get_avatar_url('square')

    @property
    def avatar(self):
        return self.get_avatar_url('large')

    def __unicode__(self):
        return unicode(self.user)

class PromiseUserState(object):
    """Namespace to store status that relates an user to a promise.

    It's used to decide which widget should be shown to the user when
    accessing the promise page or the promise feed. All Anonymous users
    should be marked as "NOTHING".

    Namespaces are one honking great idea -- let's do more of those!
    """
    OWNER = 0
    SUPPORTER = 1
    NOTHING = 2

    @staticmethod
    def from_string(state):
        return getattr(PromiseUserState, state.upper())

def user_promise_state(user, promise):
    """Returns the status between the promise and the currently logged
    in (or anonymous) user. Just a helper to avoid ifs/elifs to
    proliferate in our codebase.
    """

    # We got an anonymous user here, he obviously can't support
    # anything. Let's give him a chance to show the "support this"
    # button.
    if user.is_anonymous():
        return PromiseUserState.NOTHING

    # For owners
    promise_key = get_promise_key(user.profile.id)
    if promise.id in get_ids_from_redis(promise_key):
        return PromiseUserState.OWNER

    # For supporters
    support_key = get_support_key(user.profile.id)
    if promise.id in get_ids_from_redis(support_key):
        return PromiseUserState.SUPPORTER

    return PromiseUserState.NOTHING

def create_profile(sender, instance, created, **kwargs):
    if created:
        from event.logging import logger
        Profile.objects.create(user=instance)
        logger.log('signup')
post_save.connect(create_profile, sender=User)
<|endoftext|>


<commit_before># Promise.ly -- social commitment platform
#
# Copyright (C) 2012  Promise.ly authors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.db import models
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django_facebook.api import get_persistent_graph
from django_facebook.models import FacebookProfileModel
from django.template.defaultfilters import urlencode
from django.utils.safestring import mark_safe

from util import url_with_domain
from util.model_helpers import unique_slugify
from util.rediz import get_support_key, get_promise_key, get_ids_from_redis

from promise.managers import PromiseManager

PROMISE_STATUSES = (
    (1, "In Progress"),
    (2, "Succeeded"),
    (3, 'Failed'),
)

class Promise(models.Model):
    text = models.TextField()
    creator = models.ForeignKey('promise.Profile', related_name='creator')
    created = models.DateTimeField(auto_now=True)
    deadline = models.DateTimeField()
    status = models.PositiveSmallIntegerField(choices=PROMISE_STATUSES, default=1)
    supporter = models.ManyToManyField('promise.Profile', blank=True, related_name='supporter')
    slug = models.SlugField(unique=True, blank=True)

    objects = PromiseManager()

    def __unicode__(self):
        return u"{}:{}".format(self.text[:15], self.creator)

    @property
    def active(self):
        return self.status == 1

    @property
    def success(self):
        return self.status == 2

    def supporters_ordered_by_friends(self, request):
        supporters = self.supporter.all()
        friends = self.creator.friends(request)
        friend_supporters = [x for x in supporters if x in friends]
        nonfriend_supporters = [x for x in supporters if x not in friends]
        return friend_supporters + nonfriend_supporters

    @property
    def supporters(self):
        maxsupporters = 5
        count = self.supporter.count()
        if count > maxsupporters:
            supporters = self.supporter.all()[:maxsupporters]
            return u'{} and {} others support this'.format(
                ', '.join(unicode(i) for i in supporters), count - maxsupporters)
        return ", ".join(unicode(i) for i in self.supporter.all())

    @property
    def mailto_url(self):
        body = u"'{}' - {}".format(self.text, self.creator) + \
            u"\n{}".format(urlencode(self.get_absolute_url()))
        subject = u"Support {}!".format(self.creator)
        res = u'mailto:?body={}&subject={}'.format(urlencode(body), urlencode(subject))
        return mark_safe(res)

    def get_absolute_url(self):
        return url_with_domain(reverse('promise', args=(self.slug,)))

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = unique_slugify(self, self.text[:20])
        super(Promise, self).save(*args, **kwargs)

class Profile(FacebookProfileModel):
    user = models.OneToOneField('auth.User')

    @property
    def name(self):
        return self.facebook_name or unicode(self)

    def get_avatar_url(self, size, local=False):
        convert = {
            'large': '180/200',
            'square': '50/50',
        }

        if local and bool(self.image):
            return url_with_domain(self.image.url)
        return u'https://graph.facebook.com/{}/picture?type={}'.format(
            self.facebook_id, size) if self.facebook_id \
            else 'http://placekitten.com/g/{}'.format(convert.get(size))

    def friends(self, request):
        """
        Gets Profiles of Facebook Friends
        """
        fb = get_persistent_graph(request)
        if fb:
            # TODO: iterate over the pagination info
            fbids = [int(i['id']) for i in fb.get('me/friends').get('data')]
            return Profile.objects.filter(facebook_id__in=fbids)
        else:
            return Profile.objects.none()

    def wall_post(self, request, message):
        fb = get_persistent_graph(request)
        fb.set('me/feed', message=message)

    @property
    def avatar_square(self):
        return self.get_avatar_url('square')

    @property
    def avatar(self):
        return self.get_avatar_url('large')

    def __unicode__(self):
        return unicode(self.user)

class PromiseUserState(object):
    """Namespace to store status that relates an user to a promise.

    It's used to decide which widget should be shown to the user when
    accessing the promise page or the promise feed. All Anonymous users
    should be marked as "NOTHING".

    Namespaces are one honking great idea -- let's do more of those!
    """
    OWNER = 0
    SUPPORTER = 1
    NOTHING = 2

    @staticmethod
    def from_string(state):
        return getattr(PromiseUserState, state.upper())

def user_promise_state(user, promise):
    """Returns the status between the promise and the currently logged
    in (or anonymous) user. Just a helper to avoid ifs/elifs to
    proliferate in our codebase.
    """

    # We got an anonymous user here, he obviously can't support
    # anything. Let's give him a chance to show the "support this"
    # button.
    if user.is_anonymous():
        return PromiseUserState.NOTHING

    # For owners
    promise_key = get_promise_key(user.profile.id)
    if promise.id in get_ids_from_redis(promise_key):
        return PromiseUserState.OWNER

    # For supporters
    support_key = get_support_key(user.profile.id)
    if promise.id in get_ids_from_redis(support_key):
        return PromiseUserState.SUPPORTER

    return PromiseUserState.NOTHING

def create_profile(sender, instance, created, **kwargs):
    if created:
        from event.logging import logger
        Profile.objects.create(user=instance)
        logger.log('signup')
post_save.connect(create_profile, sender=User)
<commit_msg>if we are not connected to facebook, we are screwed already :P<commit_after># Promise.ly -- social commitment platform
#
# Copyright (C) 2012  Promise.ly authors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.db import models
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django_facebook.api import get_persistent_graph
from django_facebook.models import FacebookProfileModel
from django.template.defaultfilters import urlencode
from django.utils.safestring import mark_safe

from util import url_with_domain
from util.model_helpers import unique_slugify
from util.rediz import get_support_key, get_promise_key, get_ids_from_redis

from promise.managers import PromiseManager

PROMISE_STATUSES = (
    (1, "In Progress"),
    (2, "Succeeded"),
    (3, 'Failed'),
)

class Promise(models.Model):
    text = models.TextField()
    creator = models.ForeignKey('promise.Profile', related_name='creator')
    created = models.DateTimeField(auto_now=True)
    deadline = models.DateTimeField()
    status = models.PositiveSmallIntegerField(choices=PROMISE_STATUSES, default=1)
    supporter = models.ManyToManyField('promise.Profile', blank=True, related_name='supporter')
    slug = models.SlugField(unique=True, blank=True)

    objects = PromiseManager()

    def __unicode__(self):
        return u"{}:{}".format(self.text[:15], self.creator)

    @property
    def active(self):
        return self.status == 1

    @property
    def success(self):
        return self.status == 2

    def supporters_ordered_by_friends(self, request):
        supporters = self.supporter.all()
        friends = self.creator.friends(request)
        friend_supporters = [x for x in supporters if x in friends]
        nonfriend_supporters = [x for x in supporters if x not in friends]
        return friend_supporters + nonfriend_supporters

    @property
    def supporters(self):
        maxsupporters = 5
        count = self.supporter.count()
        if count > maxsupporters:
            supporters = self.supporter.all()[:maxsupporters]
            return u'{} and {} others support this'.format(
                ', '.join(unicode(i) for i in supporters), count - maxsupporters)
        return ", ".join(unicode(i) for i in self.supporter.all())

    @property
    def mailto_url(self):
        body = u"'{}' - {}".format(self.text, self.creator) + \
            u"\n{}".format(urlencode(self.get_absolute_url()))
        subject = u"Support {}!".format(self.creator)
        res = u'mailto:?body={}&subject={}'.format(urlencode(body), urlencode(subject))
        return mark_safe(res)

    def get_absolute_url(self):
        return url_with_domain(reverse('promise', args=(self.slug,)))

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = unique_slugify(self, self.text[:20])
        super(Promise, self).save(*args, **kwargs)

class Profile(FacebookProfileModel):
    user = models.OneToOneField('auth.User')

    @property
    def name(self):
        return self.facebook_name or unicode(self)

    def get_avatar_url(self, size, local=False):
        convert = {
            'large': '180/200',
            'square': '50/50',
        }

        if local and bool(self.image):
            return url_with_domain(self.image.url)
        return u'https://graph.facebook.com/{}/picture?type={}'.format(
            self.facebook_id, size) if self.facebook_id \
            else 'http://placekitten.com/g/{}'.format(convert.get(size))

    def friends(self, request):
        """
        Gets Profiles of Facebook Friends
        """
        fb = get_persistent_graph(request)
        # TODO: iterate over the pagination info
        fbids = [int(i['id']) for i in fb.get('me/friends').get('data')]
        return Profile.objects.filter(facebook_id__in=fbids)

    def wall_post(self, request, message):
        fb = get_persistent_graph(request)
        fb.set('me/feed', message=message)

    @property
    def avatar_square(self):
        return self.get_avatar_url('square')

    @property
    def avatar(self):
        return self.get_avatar_url('large')

    def __unicode__(self):
        return unicode(self.user)

class PromiseUserState(object):
    """Namespace to store status that relates an user to a promise.

    It's used to decide which widget should be shown to the user when
    accessing the promise page or the promise feed. All Anonymous users
    should be marked as "NOTHING".

    Namespaces are one honking great idea -- let's do more of those!
    """
    OWNER = 0
    SUPPORTER = 1
    NOTHING = 2

    @staticmethod
    def from_string(state):
        return getattr(PromiseUserState, state.upper())

def user_promise_state(user, promise):
    """Returns the status between the promise and the currently logged
    in (or anonymous) user. Just a helper to avoid ifs/elifs to
    proliferate in our codebase.
    """

    # We got an anonymous user here, he obviously can't support
    # anything. Let's give him a chance to show the "support this"
    # button.
    if user.is_anonymous():
        return PromiseUserState.NOTHING

    # For owners
    promise_key = get_promise_key(user.profile.id)
    if promise.id in get_ids_from_redis(promise_key):
        return PromiseUserState.OWNER

    # For supporters
    support_key = get_support_key(user.profile.id)
    if promise.id in get_ids_from_redis(support_key):
        return PromiseUserState.SUPPORTER

    return PromiseUserState.NOTHING

def create_profile(sender, instance, created, **kwargs):
    if created:
        from event.logging import logger
        Profile.objects.create(user=instance)
        logger.log('signup')
post_save.connect(create_profile, sender=User)
<|endoftext|>


<commit_before>"""
Overview
========

This plugin does autocompletion using ycmd.

Install
=======

Key-Commands
============

Namespace: ycmd

Mode: INSERT
Event: <Control-Key-period>
Description: Open the completion window with possible words for
completion.

Commands
========

"""

from vyapp.completion import CompletionWindow, Option
from os.path import expanduser, join, exists, dirname
from base64 import b64encode, b64decode
from vyapp.widgets import LinePicker
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE
from shutil import copyfile
from vyapp.plugins import ENV
from vyapp.app import root
import shlex
import requests
import random
import hashlib
import atexit
import hmac
import json
import sys
import os

HMAC_LENGTH  = 32
IDLE_SUICIDE = 10800  # 3 hours
MAX_WAIT     = 5

# Vim filetypes mapping.
FILETYPES = {
'.c': 'cpp',
'.py': 'python',
'.go': 'golang',
'.c++':'cpp',
'.js':'javascript'
}

class YcmdServer:
    def __init__(self, path, port, settings_file):
        """
        """

        self.settings_file = settings_file
        self.settings      = None
        self.path          = path
        self.port          = port
        self.url           = 'http://127.0.0.1:%s' % port
        self.cmd           = 'python -m ycmd --port %s --options_file  %s'
        self.hmac_secret   = os.urandom(HMAC_LENGTH)

        with open(self.settings_file) as fd:
          self.settings = json.loads(fd.read())

        hmac_secret = b64encode(self.hmac_secret).decode('utf8 ')
        self.settings[ 'hmac_secret' ] = hmac_secret

        with NamedTemporaryFile(mode = 'w+', delete = False) as tmpfile:
            json.dump(self.settings, tmpfile)

        # It is necessary to use stdout=PIPE, stderr=PIPE otherwise
        # we get ycmd outputing stuff even in non verbose mode.
        self.cmd    = self.cmd % (self.port, tmpfile.name)
        self.cmd    = shlex.split(self.cmd)
        self.daemon = Popen(self.cmd, stdout=PIPE, stderr=PIPE, cwd=self.path)

        atexit.register(self.daemon.terminate)

    def load_conf(self, path):
        """
        """

        data = {
       'filepath': path,
        }

        url = '%s/load_extra_conf_file' % self.url
        hmac_secret = self.hmac_req('POST', '/load_extra_conf_file',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers)

        print('File to load:', path)
        print('Load conf response:', req.json())
        print('Loading extra conf...')

    def ready(self, line, col, path, data):
        """
        Send file ready.
        """

        data = {
       'line_num': line,
       'column_num': col,
       'filepath': path,
       'file_data': data,
       'event_name': 'FileReadyToParse',
        }

        url = '%s/event_notification' % self.url
        hmac_secret = self.hmac_req('POST', '/event_notification',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers, timeout=1)

        print('FileReadyToParse JSON:\n', req.json())
        return req

    def post(self, *args, **kwargs):
        """
        Abstract the workings of HTTP POST method to validate
        HMAC in responses.
        """

        req = requests.post(*args, **kwargs)
        is_valid = self.is_vhmac(req.text,
        req.headers['X-YCM-HMAC'], self.hmac_secret)

        if not is_valid:
            raise RuntimeError('Invalid HMAC response')
        return req

    def completions(self, line, col, path, data,
        dir, target=None, cmdargs=None):

        data = {
       'line_num': line,
       'column_num': col,
       'filepath': path,
       'file_data': data
        }

        url = '%s/completions' % self.url

        hmac_secret = self.hmac_req('POST', '/completions',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers, timeout=2)
        print('Request data:', req.json())
        return self.fmt_options(req.json())

    def fmt_options(self, data):
        return [Option(ind.get('insertion_text', ''),
        '\n\n'.join(('Type:\n%s' % ind.get('kind', None),
        'Extra info:\n%s' % ind.get('extra_menu_info', None),
        'Docs:\n%s' % ind.get('detailed_info', None),
        'Data:\n%s' % ind.get('extra_data', {}).get('doc_string', None))))
        for ind in data['completions']]

    def hmac_req(self, method, path, body, hmac_secret):
        """
        Calculate hmac for request. The algorithm is based on what is seen in
        https://github.com/ycm-core/ycmd/blob/master/examples/example_client.py
        at CreateHmacForRequest function.
        """

        method = bytes(method, encoding = 'utf8' )
        path   = bytes(path, encoding = 'utf8' )
        body   = json.dumps(body, ensure_ascii = False)
        body   = bytes(body, encoding = 'utf8' )

        method = bytes(hmac.new(hmac_secret,
        method, digestmod = hashlib.sha256).digest())

        path = bytes(hmac.new(hmac_secret,
        path, digestmod = hashlib.sha256).digest())

        body = bytes(hmac.new(hmac_secret,
        body, digestmod = hashlib.sha256).digest())

        joined = bytes().join((method, path, body))

        data = bytes(hmac.new(hmac_secret, joined,
        digestmod = hashlib.sha256).digest())

        return str(b64encode(data), encoding='utf8 ')

    def is_vhmac(self, body, hmac_header, hmac_secret):
        """
        Check the response hmac.
        """

        body = body.encode('utf8')
        a = b64decode(hmac_header)
        b = bytes(hmac.new(hmac_secret,
        msg = body, digestmod = hashlib.sha256).digest())

        if len(a) != len(b):
            return False

        result = 0
        for x, y in zip(a, b):
            result |= x ^ y
        return result == 0

class YcmdWindow(CompletionWindow):
    """
    """

    def __init__(self, area, server, *args, **kwargs):
        source    = area.get('1.0', 'end')
        line, col = area.indcur()

        data = {area.filename:
        {'filetypes': [FILETYPES[area.extension]], 'contents': source}}

        completions = server.completions(line, col + 1,
        area.filename, data, dirname(area.filename))

        CompletionWindow.__init__(self, area, completions, *args, **kwargs)

class YcmdCompletion:
    server = None
    def __init__(self, area):
        self.area   = area
        completions = lambda event: YcmdWindow(event.widget, self.server)

        wrapper = lambda event: area.after(1000, self.on_ready)
        area.install('ycmd', ('INSERT', '<Control-Key-period>', completions),
        (-1, '<<LoadData>>', wrapper), (-1, '<<SaveData>>', wrapper))

    def on_ready(self):
        """
        This method sends the ReadyToParseEvent to ycmd whenever a file is
        opened or saved. It is necessary to start some
        ycmd language completers.

        When there is a global .ycm_extra_conf.py in the home dir
        then it is loaded automatically otherwise a message is
        displayed to the user to load it using lycm.
        """

        data = {self.area.filename:
        {'filetypes': [FILETYPES[self.area.extension]],
        'contents': self.area.get('1.0', 'end')}}

        req = self.server.ready(1, 1, self.area.filename, data)
        rsp = req.json()

        if req.status_code == 500:
            self.on_exc(rsp)
        elif req.status_code == 200:
            self.on_diagnostics(rsp)

    def on_diagnostics(self, rsp):
        """
        """

        ranges = [(ind['location']['filepath'],
        ind['location']['line_num'], ind['text'])
        for ind in rsp]

        options = LinePicker()
        options(ranges)

    def on_exc(self, rsp):
       exc = rsp.get('exception')
       if exc and exc.get('TYPE') == 'UnknownExtraConf':
           self.is_gxconf(exc['extra_conf_file'])

    @classmethod
    def is_gxconf(cls, xconf):
        gxconf = expanduser('~')
        gxconf = join(gxconf, '.ycm_extra_conf.py')

        if xconf == gxconf:
            cls.server.load_conf(gxconf)
        else:
            root.status.set_msg((('Found %s!'
                ' lycm(path) to load.') % xconf))

    @classmethod
    def setup(cls, path, xconf=expanduser('~')):
        """
        Create the default_settings.json file in case it doesn't exist.
        The file is located in the home dir. It also starts ycmd server.

        It also creates a global ycm_extra_conf.py file in your home dir.
        This file is used for giving completion for c-family languages and
        specifying some specific settings.

        Check ycmd docs for details.
        """
        settings_file = join(expanduser('~'), '.default_settings.json')
        if not exists(settings_file):
            copyfile(join(dirname(__file__),
                'default_settings.json'), settings_file)

        xconf = join(xconf, '.ycm_extra_conf.py')
        if not exists(xconf):
            copyfile(join(dirname(__file__), 'ycm_extra_conf.py'), xconf)

        port        = random.randint(1000, 9999)
        cls.server  = YcmdServer(path, port,  settings_file)
        # wrapper     = lambda event: area.after(1000, self.load_gxconf)
        ENV['lycm'] = cls.lycm

    @classmethod
    def lycm(cls, path=None):
        """
        """
        home = expanduser('~')
        path = path if path else join(home, '.ycm_extra_conf.py')

        cls.server.load_conf(path)
        root.status.set_msg('Loaded %s' % path)

def init_ycm(path):
    """
    Generate a ycm_extra_conf.py file in the given path dir to specify
    compilation flags for a project. This is necessary to get
    semantic analysis for c-family languages.

    Check ycmd docs for more details.
    """

    conf = join(path, '.ycm_extra_conf.py')
    if exists(conf):
        root.status.set_msg('File overwritten: %s' % conf)
    copyfile(join(dirname(__file__), 'ycm_extra_conf.py'), conf)

    return conf

ENV['init_ycm'] = init_ycm
install = YcmdCompletion

<commit_msg>Improving approach to handle ycmd dianogistics.<commit_after>"""
Overview
========

This plugin does autocompletion using ycmd.

Install
=======

Key-Commands
============

Namespace: ycmd

Mode: INSERT
Event: <Control-Key-period>
Description: Open the completion window with possible words for
completion.

Commands
========

"""

from vyapp.completion import CompletionWindow, Option
from os.path import expanduser, join, exists, dirname
from base64 import b64encode, b64decode
from vyapp.widgets import LinePicker
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE
from shutil import copyfile
from vyapp.plugins import ENV
from vyapp.app import root
import shlex
import requests
import random
import hashlib
import atexit
import hmac
import json
import sys
import os

HMAC_LENGTH  = 32
IDLE_SUICIDE = 10800  # 3 hours
MAX_WAIT     = 5

# Vim filetypes mapping.
FILETYPES = {
'.c': 'cpp',
'.py': 'python',
'.go': 'golang',
'.c++':'cpp',
'.js':'javascript'
}

class YcmdServer:
    def __init__(self, path, port, settings_file):
        """
        """

        self.settings_file = settings_file
        self.settings      = None
        self.path          = path
        self.port          = port
        self.url           = 'http://127.0.0.1:%s' % port
        self.cmd           = 'python -m ycmd --port %s --options_file  %s'
        self.hmac_secret   = os.urandom(HMAC_LENGTH)

        with open(self.settings_file) as fd:
          self.settings = json.loads(fd.read())

        hmac_secret = b64encode(self.hmac_secret).decode('utf8 ')
        self.settings[ 'hmac_secret' ] = hmac_secret

        with NamedTemporaryFile(mode = 'w+', delete = False) as tmpfile:
            json.dump(self.settings, tmpfile)

        # It is necessary to use stdout=PIPE, stderr=PIPE otherwise
        # we get ycmd outputing stuff even in non verbose mode.
        self.cmd    = self.cmd % (self.port, tmpfile.name)
        self.cmd    = shlex.split(self.cmd)
        self.daemon = Popen(self.cmd, stdout=PIPE, stderr=PIPE, cwd=self.path)

        atexit.register(self.daemon.terminate)

    def load_conf(self, path):
        """
        """

        data = {
       'filepath': path,
        }

        url = '%s/load_extra_conf_file' % self.url
        hmac_secret = self.hmac_req('POST', '/load_extra_conf_file',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers)

        print('File to load:', path)
        print('Load conf response:', req.json())
        print('Loading extra conf...')

    def ready(self, line, col, path, data):
        """
        Send file ready.
        """

        data = {
       'line_num': line,
       'column_num': col,
       'filepath': path,
       'file_data': data,
       'event_name': 'FileReadyToParse',
        }

        url = '%s/event_notification' % self.url
        hmac_secret = self.hmac_req('POST', '/event_notification',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers, timeout=1)

        print('FileReadyToParse JSON:\n', req.json())
        return req

    def post(self, *args, **kwargs):
        """
        Abstract the workings of HTTP POST method to validate
        HMAC in responses.
        """

        req = requests.post(*args, **kwargs)
        is_valid = self.is_vhmac(req.text,
        req.headers['X-YCM-HMAC'], self.hmac_secret)

        if not is_valid:
            raise RuntimeError('Invalid HMAC response')
        return req

    def completions(self, line, col, path, data,
        dir, target=None, cmdargs=None):

        data = {
       'line_num': line,
       'column_num': col,
       'filepath': path,
       'file_data': data
        }

        url = '%s/completions' % self.url

        hmac_secret = self.hmac_req('POST', '/completions',
        data, self.hmac_secret)

        headers = {
            'X-YCM-HMAC': hmac_secret,
        }

        req = self.post(url, json=data, headers=headers, timeout=2)
        print('Request data:', req.json())
        return self.fmt_options(req.json())

    def fmt_options(self, data):
        return [Option(ind.get('insertion_text', ''),
        '\n\n'.join(('Type:\n%s' % ind.get('kind', None),
        'Extra info:\n%s' % ind.get('extra_menu_info', None),
        'Docs:\n%s' % ind.get('detailed_info', None),
        'Data:\n%s' % ind.get('extra_data', {}).get('doc_string', None))))
        for ind in data['completions']]

    def hmac_req(self, method, path, body, hmac_secret):
        """
        Calculate hmac for request. The algorithm is based on what is seen in
        https://github.com/ycm-core/ycmd/blob/master/examples/example_client.py
        at CreateHmacForRequest function.
        """

        method = bytes(method, encoding = 'utf8' )
        path   = bytes(path, encoding = 'utf8' )
        body   = json.dumps(body, ensure_ascii = False)
        body   = bytes(body, encoding = 'utf8' )

        method = bytes(hmac.new(hmac_secret,
        method, digestmod = hashlib.sha256).digest())

        path = bytes(hmac.new(hmac_secret,
        path, digestmod = hashlib.sha256).digest())

        body = bytes(hmac.new(hmac_secret,
        body, digestmod = hashlib.sha256).digest())

        joined = bytes().join((method, path, body))

        data = bytes(hmac.new(hmac_secret, joined,
        digestmod = hashlib.sha256).digest())

        return str(b64encode(data), encoding='utf8 ')

    def is_vhmac(self, body, hmac_header, hmac_secret):
        """
        Check the response hmac.
        """

        body = body.encode('utf8')
        a = b64decode(hmac_header)
        b = bytes(hmac.new(hmac_secret,
        msg = body, digestmod = hashlib.sha256).digest())

        if len(a) != len(b):
            return False

        result = 0
        for x, y in zip(a, b):
            result |= x ^ y
        return result == 0

class YcmdWindow(CompletionWindow):
    """
    """

    def __init__(self, area, server, *args, **kwargs):
        source    = area.get('1.0', 'end')
        line, col = area.indcur()

        data = {area.filename:
        {'filetypes': [FILETYPES[area.extension]], 'contents': source}}

        completions = server.completions(line, col + 1,
        area.filename, data, dirname(area.filename))

        CompletionWindow.__init__(self, area, completions, *args, **kwargs)

class YcmdCompletion:
    server = None
    def __init__(self, area):
        self.area       = area
        self.err_picker = LinePicker()
        completions     = lambda event: YcmdWindow(event.widget, self.server)
        wrapper         = lambda event: area.after(1000, self.on_ready)

        area.install('ycmd', ('INSERT', '<Control-Key-period>', completions),
        (-1, '<<LoadData>>', wrapper), (-1, '<<SaveData>>', wrapper),
        ('NORMAL', '<Control-greater>',
        lambda event: self.err_picker.display()))

    def on_ready(self):
        """
        This method sends the ReadyToParseEvent to ycmd whenever a file is
        opened or saved. It is necessary to start some
        ycmd language completers.

        When there is a global .ycm_extra_conf.py in the home dir
        then it is loaded automatically otherwise a message is
        displayed to the user to load it using lycm.
        """

        data = {self.area.filename:
        {'filetypes': [FILETYPES[self.area.extension]],
        'contents': self.area.get('1.0', 'end')}}

        req = self.server.ready(1, 1, self.area.filename, data)
        rsp = req.json()

        if req.status_code == 500:
            self.on_exc(rsp)
        elif req.status_code == 200 and rsp:
            self.on_diagnostics(rsp)

    def on_diagnostics(self, rsp):
        """
        """

        ranges = [(ind['location']['filepath'],
        ind['location']['line_num'], ind['text'])
        for ind in rsp]

        self.err_picker(ranges)
        root.status.set_msg('Ycmd found errors. Displaying diagnostics!')

    def on_exc(self, rsp):
       exc = rsp.get('exception')
       if exc and exc.get('TYPE') == 'UnknownExtraConf':
           self.is_gxconf(exc['extra_conf_file'])

    @classmethod
    def is_gxconf(cls, xconf):
        gxconf = expanduser('~')
        gxconf = join(gxconf, '.ycm_extra_conf.py')

        if xconf == gxconf:
            cls.server.load_conf(gxconf)
        else:
            root.status.set_msg((('Found %s!'
                ' lycm(path) to load.') % xconf))

    @classmethod
    def setup(cls, path, xconf=expanduser('~')):
        """
        Create the default_settings.json file in case it doesn't exist.
        The file is located in the home dir. It also starts ycmd server.

        It also creates a global ycm_extra_conf.py file in your home dir.
        This file is used for giving completion for c-family languages and
        specifying some specific settings.

        Check ycmd docs for details.
        """
        settings_file = join(expanduser('~'), '.default_settings.json')
        if not exists(settings_file):
            copyfile(join(dirname(__file__),
                'default_settings.json'), settings_file)

        xconf = join(xconf, '.ycm_extra_conf.py')
        if not exists(xconf):
            copyfile(join(dirname(__file__), 'ycm_extra_conf.py'), xconf)

        port        = random.randint(1000, 9999)
        cls.server  = YcmdServer(path, port,  settings_file)
        # wrapper     = lambda event: area.after(1000, self.load_gxconf)
        ENV['lycm'] = cls.lycm

    @classmethod
    def lycm(cls, path=None):
        """
        """
        home = expanduser('~')
        path = path if path else join(home, '.ycm_extra_conf.py')

        cls.server.load_conf(path)
        root.status.set_msg('Loaded %s' % path)

def init_ycm(path):
    """
    Generate a ycm_extra_conf.py file in the given path dir to specify
    compilation flags for a project. This is necessary to get
    semantic analysis for c-family languages.

    Check ycmd docs for more details.
    """

    conf = join(path, '.ycm_extra_conf.py')
    if exists(conf):
        root.status.set_msg('File overwritten: %s' % conf)
    copyfile(join(dirname(__file__), 'ycm_extra_conf.py'), conf)

    return conf

ENV['init_ycm'] = init_ycm
install = YcmdCompletion

<|endoftext|>


<commit_before>version_bits = (0, 2, 0)
version = '.'.join(map(str, version_bits))
<commit_msg>Version bump to 0.3.0<commit_after>version_bits = (0, 3, 0)
version = '.'.join(map(str, version_bits))
<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from sqlalchemy.schema import FetchedValue
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import relationship
from sqlalchemy.sql.expression import text

from warehouse import db
from warehouse.database.mixins import UUIDPrimaryKeyMixin, TimeStampedMixin
from warehouse.database.schema import TableDDL
from warehouse.database.types import Enum
from warehouse.database.utils import table_args

class Project(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "projects"
    __table_args__ = declared_attr(table_args((
        TableDDL("""
            CREATE OR REPLACE FUNCTION normalize_name()
            RETURNS trigger AS $$
            BEGIN
                NEW.normalized = lower(regexp_replace(new.name, '[^A-Za-z0-9.]+', '-'));
                return NEW;
            END;
            $$ LANGUAGE plpgsql;

            CREATE TRIGGER %(table)s_normalize_name
            BEFORE INSERT OR UPDATE
            ON %(table)s
            FOR EACH ROW
            EXECUTE PROCEDURE normalize_name();
        """),
    )))

    name = db.Column(db.UnicodeText, unique=True, nullable=False)
    normalized = db.Column(db.UnicodeText, unique=True, nullable=False,
                           server_default=FetchedValue(),
                           server_onupdate=FetchedValue())

    versions = relationship("Version", backref="project")

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "<Project: {name}>".format(name=self.name)

class Version(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "versions"
    __table_args__ = declared_attr(table_args((
        db.Index("idx_project_version", "project_id", "version", unique=True),
    )))

    project_id = db.Column(pg.UUID(as_uuid=True),
                           db.ForeignKey("projects.id", ondelete="RESTRICT"),
                           nullable=False)
    version = db.Column(db.UnicodeText, nullable=False)

    summary = db.Column(db.UnicodeText, nullable=False, server_default="")
    description = db.Column(db.UnicodeText, nullable=False, server_default="")

    keywords = db.Column(pg.ARRAY(db.UnicodeText, dimensions=1),
                         nullable=False, server_default="{}")

    author = db.Column(db.UnicodeText, nullable=False, server_default="")
    author_email = db.Column(db.UnicodeText, nullable=False, server_default="")

    maintainer = db.Column(db.UnicodeText, nullable=False, server_default="")
    maintainer_email = db.Column(db.UnicodeText, nullable=False,
                                 server_default="")

    license = db.Column(db.UnicodeText, nullable=False, server_default="")

    # URIs
    uris = db.Column(pg.HSTORE, nullable=False,
                     server_default=text("''::hstore"))
    download_uri = db.Column(db.UnicodeText, nullable=False, server_default="")

    # Requirements
    requires_python = db.Column(db.UnicodeText, nullable=False,
                                server_default="")
    requires_external = db.Column(pg.ARRAY(db.UnicodeText, dimensions=1),
                                  nullable=False, server_default="{}")

    files = relationship("File", backref="version")

    def __repr__(self):
        ctx = {"name": self.project.name, "version": self.version}
        return "<Version: {name} {version}>".format(**ctx)

class FileType(Enum):
    source = "sdist", "Source"
    egg = "bdist_egg", "Egg"
    msi = "bdist_msi", "MSI"
    dmg = "bdist_dmg", "DMG"
    rpm = "bdist_rpm", "RPM",
    dumb = "bdist_dumb", "Dumb Binary Distribution"
    windows_installer = "bdist_wininst", "Windows Installer"
    wheel = "bdist_wheel", "Wheel"

class File(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "files"

    version_id = db.Column(pg.UUID(as_uuid=True),
                           db.ForeignKey("versions.id", ondelete="RESTRICT"),
                           nullable=False)

    filename = db.Column(db.UnicodeText, nullable=False, unique=True)
    filesize = db.Column(db.Integer, nullable=False)

    type = db.Column(FileType.db_type(), nullable=False)

    python_version = db.Column(db.UnicodeText, nullable=False, server_default="")

    comment = db.Column(db.UnicodeText, nullable=False, server_default="")

    hashes = db.Column(pg.HSTORE, nullable=False,
                       server_default=text("''::hstore"))
<commit_msg>Add a field to store the path to the file<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from sqlalchemy.schema import FetchedValue
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import relationship
from sqlalchemy.sql.expression import text

from warehouse import db
from warehouse.database.mixins import UUIDPrimaryKeyMixin, TimeStampedMixin
from warehouse.database.schema import TableDDL
from warehouse.database.types import Enum
from warehouse.database.utils import table_args

class Project(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "projects"
    __table_args__ = declared_attr(table_args((
        TableDDL("""
            CREATE OR REPLACE FUNCTION normalize_name()
            RETURNS trigger AS $$
            BEGIN
                NEW.normalized = lower(regexp_replace(new.name, '[^A-Za-z0-9.]+', '-'));
                return NEW;
            END;
            $$ LANGUAGE plpgsql;

            CREATE TRIGGER %(table)s_normalize_name
            BEFORE INSERT OR UPDATE
            ON %(table)s
            FOR EACH ROW
            EXECUTE PROCEDURE normalize_name();
        """),
    )))

    name = db.Column(db.UnicodeText, unique=True, nullable=False)
    normalized = db.Column(db.UnicodeText, unique=True, nullable=False,
                           server_default=FetchedValue(),
                           server_onupdate=FetchedValue())

    versions = relationship("Version", backref="project")

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "<Project: {name}>".format(name=self.name)

class Version(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "versions"
    __table_args__ = declared_attr(table_args((
        db.Index("idx_project_version", "project_id", "version", unique=True),
    )))

    project_id = db.Column(pg.UUID(as_uuid=True),
                           db.ForeignKey("projects.id", ondelete="RESTRICT"),
                           nullable=False)
    version = db.Column(db.UnicodeText, nullable=False)

    summary = db.Column(db.UnicodeText, nullable=False, server_default="")
    description = db.Column(db.UnicodeText, nullable=False, server_default="")

    keywords = db.Column(pg.ARRAY(db.UnicodeText, dimensions=1),
                         nullable=False, server_default="{}")

    author = db.Column(db.UnicodeText, nullable=False, server_default="")
    author_email = db.Column(db.UnicodeText, nullable=False, server_default="")

    maintainer = db.Column(db.UnicodeText, nullable=False, server_default="")
    maintainer_email = db.Column(db.UnicodeText, nullable=False,
                                 server_default="")

    license = db.Column(db.UnicodeText, nullable=False, server_default="")

    # URIs
    uris = db.Column(pg.HSTORE, nullable=False,
                     server_default=text("''::hstore"))
    download_uri = db.Column(db.UnicodeText, nullable=False, server_default="")

    # Requirements
    requires_python = db.Column(db.UnicodeText, nullable=False,
                                server_default="")
    requires_external = db.Column(pg.ARRAY(db.UnicodeText, dimensions=1),
                                  nullable=False, server_default="{}")

    files = relationship("File", backref="version")

    def __repr__(self):
        ctx = {"name": self.project.name, "version": self.version}
        return "<Version: {name} {version}>".format(**ctx)

class FileType(Enum):
    source = "sdist", "Source"
    egg = "bdist_egg", "Egg"
    msi = "bdist_msi", "MSI"
    dmg = "bdist_dmg", "DMG"
    rpm = "bdist_rpm", "RPM",
    dumb = "bdist_dumb", "Dumb Binary Distribution"
    windows_installer = "bdist_wininst", "Windows Installer"
    wheel = "bdist_wheel", "Wheel"

class File(UUIDPrimaryKeyMixin, TimeStampedMixin, db.Model):

    __tablename__ = "files"

    version_id = db.Column(pg.UUID(as_uuid=True),
                           db.ForeignKey("versions.id", ondelete="RESTRICT"),
                           nullable=False)

    file = db.Column(db.UnicodeText, nullable=False, unique=True)

    filename = db.Column(db.UnicodeText, nullable=False, unique=True)
    filesize = db.Column(db.Integer, nullable=False)

    type = db.Column(FileType.db_type(), nullable=False)

    python_version = db.Column(db.UnicodeText, nullable=False, server_default="")

    comment = db.Column(db.UnicodeText, nullable=False, server_default="")

    hashes = db.Column(pg.HSTORE, nullable=False,
                       server_default=text("''::hstore"))
<|endoftext|>


<commit_before>import numpy as np
"""
dataset object fields:
- N: number of objects (images, sentences) in dataset
- n_labels: number of possible labels for each atom in an object
- object_size[n]: how many atoms (eg pixels or words) in object n ?
- n_points : object_size.sum(), # atoms in the entire data set
- X: X data (might be sparse matrix); X has shape (n_points, # input features), so each row represents X features for an input atom
- Y: list of length N
- Y[n]: array of shape corresponding to the type of data (2D array (grid_size, grid_size) for image, 1D (object_size[n]) for sentences)
- unaries: list of size N
- unaries[n]: array of shape (object_size[n], n_labels) indexed by [t,y]
- binaries: array of shape (n_labels, n_labels) to be indexed with [y_{t-1}, y_{t}], yields an index into f pointing to the binary (edge) MRF parameter corresponding to [y_{t-1}, y_{t}] (remember the edge factor parameters are all tied)
"""

def posterior_marginals(f, dataset, marginals_function):
    """
    def posterior_marginals(f : "learnt log potentials, shape column",
                        dataset : "dataset object") -> "list of (normalized) posterior marginals, length N":
    """
    pm = []
    for n in range(dataset.N):
        log_node_pot = f[dataset.unaries[n]]
        log_edge_pot = f[dataset.binaries]
        posterior_marginals_single = marginals_function(log_node_pot, log_edge_pot, dataset.object_size[n], dataset.n_labels) # in grid case, object_size will be ignored
        pm.append(posterior_marginals_single)
    return pm

def average_marginals(marginals_list):
    """
    this function is passed around as variable so that learn_predict must not depend on prepare_from_data through import
    """
    # Python 2 support: in py2, reduce is builtin
    try:
        from functools import reduce
    except ImportError:
        pass
    number_marginals = len(marginals_list)
    if (number_marginals == 1):
        return marginals_list[0]
    else:
        averaged_marginals = []
        N = len(marginals_list[0]) # says how many objects there are
        for n in range(N): # assumes all lists of marginals are the same length, namely N
            marginals_object_n = [marginals_all_objects[n] for marginals_all_objects in marginals_list]
            averaged_marginals.append(reduce(lambda x,y : add_marginals(x,y), marginals_object_n) / number_marginals) # mean of marginals for object n
        return averaged_marginals

def add_marginals(x,y):
    """
    x,y : marginals for one object
    adds marginals, and returns their sum
    """
    return x+y

import numba
import warnings
#@numba.jit
def log_likelihood_dataset(f, dataset, log_likelihood_datapoint, logger, ll_fun_wants_log_domain):
    """
    f : log-domain potentials
    ll_fun_wants_log_domain : whether or not the log-likelihood function needs f to be in log-domain (this is false only for the native chain LL implementation)
    """
    #print("f.dtype : %s" % f.dtype)
    #import hashlib
    #print("before " + str(int(hashlib.sha1(f.view(np.uint8)).hexdigest(), 16)))
    if not ll_fun_wants_log_domain:
        try:
            with warnings.catch_warnings():
                warnings.filterwarnings('error')
                f = np.exp(f) # changing semantics of f instead of inserting if's on edge_pot=... and node_pot=...
        except RuntimeWarning as rtw:
            logger.debug("RuntimeWarning: " + str(rtw))
    #print("after " + str(int(hashlib.sha1(f.view(np.uint8)).hexdigest(), 16)))
    ll = 0
    edge_pot = f[dataset.binaries]
#    print(dataset.binaries)
#    print(log_edge_pot)
    #assert(log_edge_pot.shape == (dataset.n_labels, dataset.n_labels))
    for n in range(dataset.N):
        node_pot = f[dataset.unaries[n]]
        logger.log(2,dataset.unaries[n])
        logger.log(2,node_pot.dtype)
        logger.log(2,dataset.N)
        logger.log(2,dataset.Y[n])
        logger.log(2,dataset.object_size[n])
        ll_datapoint = log_likelihood_datapoint(node_pot, edge_pot, dataset.Y[n], dataset.object_size[n], dataset.n_labels)
        # if (ll_datapoint >0):
            # info_string = ""
            # info_string += 'log_likelihood_datapoint as computed: %g\n' % ll_datapoint
            # info_string += 'n: %g\n' % n
            # info_string += 'node_pot.tolist(): %s\n' % node_pot.tolist()
            # info_string += 'edge_pot.tolist(): %s\n' % edge_pot.tolist()
            # info_string += 'dataset.Y[n]: %s\n' % dataset.Y[n].tolist()
            # raise Exception("positive log-likelihood is not allowed. More information:\n" + info_string)
        ll += ll_datapoint
        # in grid case, object_size will be ignored
    return ll # LL should not be scaled !
<commit_msg>remove costly log messages<commit_after>import numpy as np
"""
dataset object fields:
- N: number of objects (images, sentences) in dataset
- n_labels: number of possible labels for each atom in an object
- object_size[n]: how many atoms (eg pixels or words) in object n ?
- n_points : object_size.sum(), # atoms in the entire data set
- X: X data (might be sparse matrix); X has shape (n_points, # input features), so each row represents X features for an input atom
- Y: list of length N
- Y[n]: array of shape corresponding to the type of data (2D array (grid_size, grid_size) for image, 1D (object_size[n]) for sentences)
- unaries: list of size N
- unaries[n]: array of shape (object_size[n], n_labels) indexed by [t,y]
- binaries: array of shape (n_labels, n_labels) to be indexed with [y_{t-1}, y_{t}], yields an index into f pointing to the binary (edge) MRF parameter corresponding to [y_{t-1}, y_{t}] (remember the edge factor parameters are all tied)
"""

def posterior_marginals(f, dataset, marginals_function):
    """
    def posterior_marginals(f : "learnt log potentials, shape column",
                        dataset : "dataset object") -> "list of (normalized) posterior marginals, length N":
    """
    pm = []
    for n in range(dataset.N):
        log_node_pot = f[dataset.unaries[n]]
        log_edge_pot = f[dataset.binaries]
        posterior_marginals_single = marginals_function(log_node_pot, log_edge_pot, dataset.object_size[n], dataset.n_labels) # in grid case, object_size will be ignored
        pm.append(posterior_marginals_single)
    return pm

def average_marginals(marginals_list):
    """
    this function is passed around as variable so that learn_predict must not depend on prepare_from_data through import
    """
    # Python 2 support: in py2, reduce is builtin
    try:
        from functools import reduce
    except ImportError:
        pass
    number_marginals = len(marginals_list)
    if (number_marginals == 1):
        return marginals_list[0]
    else:
        averaged_marginals = []
        N = len(marginals_list[0]) # says how many objects there are
        for n in range(N): # assumes all lists of marginals are the same length, namely N
            marginals_object_n = [marginals_all_objects[n] for marginals_all_objects in marginals_list]
            averaged_marginals.append(reduce(lambda x,y : add_marginals(x,y), marginals_object_n) / number_marginals) # mean of marginals for object n
        return averaged_marginals

def add_marginals(x,y):
    """
    x,y : marginals for one object
    adds marginals, and returns their sum
    """
    return x+y

import numba
import warnings
#@numba.jit
def log_likelihood_dataset(f, dataset, log_likelihood_datapoint, logger, ll_fun_wants_log_domain):
    """
    f : log-domain potentials
    ll_fun_wants_log_domain : whether or not the log-likelihood function needs f to be in log-domain (this is false only for the native chain LL implementation)
    """
    #print("f.dtype : %s" % f.dtype)
    #import hashlib
    #print("before " + str(int(hashlib.sha1(f.view(np.uint8)).hexdigest(), 16)))
    if not ll_fun_wants_log_domain:
        try:
            with warnings.catch_warnings():
                warnings.filterwarnings('error')
                f = np.exp(f) # changing semantics of f instead of inserting if's on edge_pot=... and node_pot=...
        except RuntimeWarning as rtw:
            logger.debug("RuntimeWarning: " + str(rtw))
    #print("after " + str(int(hashlib.sha1(f.view(np.uint8)).hexdigest(), 16)))
    ll = 0
    edge_pot = f[dataset.binaries]
#    print(dataset.binaries)
#    print(log_edge_pot)
    #assert(log_edge_pot.shape == (dataset.n_labels, dataset.n_labels))
    for n in range(dataset.N):
        node_pot = f[dataset.unaries[n]]
        ll_datapoint = log_likelihood_datapoint(node_pot, edge_pot, dataset.Y[n], dataset.object_size[n], dataset.n_labels)
        # if (ll_datapoint >0):
            # info_string = ""
            # info_string += 'log_likelihood_datapoint as computed: %g\n' % ll_datapoint
            # info_string += 'n: %g\n' % n
            # info_string += 'node_pot.tolist(): %s\n' % node_pot.tolist()
            # info_string += 'edge_pot.tolist(): %s\n' % edge_pot.tolist()
            # info_string += 'dataset.Y[n]: %s\n' % dataset.Y[n].tolist()
            # raise Exception("positive log-likelihood is not allowed. More information:\n" + info_string)
        ll += ll_datapoint
        # in grid case, object_size will be ignored
    return ll # LL should not be scaled !
<|endoftext|>


<commit_before># Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php

# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <coherence@beebits.net>

from twisted.python import failure
from twisted.python.util import OrderedDict

from coherence import log

class Argument:

    def __init__(self, name, direction, state_variable):
        self.name = name
        self.direction = direction
        self.state_variable = state_variable

    def get_name(self):
        return self.name

    def get_direction(self):
        return self.direction

    def get_state_variable(self):
        return self.state_variable

    def __repr__(self):
        return ("Argument(%(name)r, %(direction)r, %(state_variable)r"
                % vars(self))

    def as_tuples(self):
        r = [
            ('Name', self.name),
            ('Direction', self.direction),
            ('Related State Variable', self.state_variable)
            ]
        return r

    def as_dict(self):
        return {
            'name': self.name,
            'direction': self.direction,
            'related_state_variable': self.state_variable
            }

class Action(log.Loggable):
    logCategory = 'action'

    def __init__(self, service, name, implementation, arguments_list):
        log.Loggable.__init__(self)
        self.service = service
        self.name = name
        self.implementation = implementation
        self.arguments_list = arguments_list

    def _get_client(self):
        client = self.service._get_client(self.name)
        return client

    def get_name(self):
        return self.name

    def get_implementation(self):
        return self.implementation

    def get_arguments_list(self):
        return self.arguments_list

    def get_in_arguments(self):
        return [arg for arg in self.arguments_list
                if arg.direction == 'in']

    def get_out_arguments(self):
        return [arg for arg in self.arguments_list
                if arg.direction == 'out']

    def get_service(self):
        return self.service

    def set_callback(self, callback):
        self.callback = callback

    def get_callback(self):
        try:
            return self.callback
        except:
            return None

    def call(self, *args, **kwargs):
        self.info("calling %s", self.name)
        in_arguments = self.get_in_arguments()
        self.info("in arguments %s", [a.get_name() for a in in_arguments])
        instance_id = 0
        for arg_name, arg in kwargs.iteritems():
            l = [a for a in in_arguments if arg_name == a.get_name()]
            if len(l) > 0:
                in_arguments.remove(l[0])
            else:
                self.error("argument %s not valid for action %s", arg_name, self.name)
                return
            if arg_name == 'InstanceID':
                instance_id = int(arg)
        if len(in_arguments) > 0:
            self.error("argument %s missing for action %s", [a.get_name() for a in in_arguments], self.name)
            return

        action_name = self.name

        if(hasattr(self.service.device.client, 'overlay_actions') and
           self.service.device.client.overlay_actions.has_key(self.name)):
            self.info("we have an overlay method %r for action %r", self.service.device.client.overlay_actions[self.name], self.name)
            action_name, kwargs = self.service.device.client.overlay_actions[self.name](**kwargs)
            self.info("changing action to %r %r", action_name, kwargs)

        def got_error(failure):
            self.warning("error on %s request with %s %s", self.name, self.
                                                            service.service_type,
                                                            self.service.control_url)
            self.info(failure)
            return failure

        if hasattr(self.service.device.client, 'overlay_headers'):
            self.info("action call has headers %r", kwargs.has_key('headers'))
            if kwargs.has_key('headers'):
                kwargs['headers'].update(self.service.device.client.overlay_headers)
            else:
                kwargs['headers'] = self.service.device.client.overlay_headers
            self.info("action call with new/updated headers %r", kwargs['headers'])

        client = self._get_client()

        ordered_arguments = OrderedDict()
        for argument in self.get_in_arguments():
            ordered_arguments[argument.name] = kwargs[argument.name]
        if kwargs.has_key('headers'):
            ordered_arguments['headers'] = kwargs['headers']

        d = client.callRemote(action_name, ordered_arguments)
        d.addCallback(self.got_results, instance_id=instance_id, name=action_name)
        d.addErrback(got_error)
        return d

    def got_results(self, results, instance_id, name):
        instance_id = int(instance_id)
        out_arguments = self.get_out_arguments()
        self.info("call %s (instance %d) returns %d arguments: %r", name,
                                                                    instance_id,
                                                                    len(out_arguments),
                                                                    results)

        # XXX A_ARG_TYPE_ arguments probably don't need a variable update
        #if len(out_arguments) == 1:
        #    self.service.get_state_variable(out_arguments[0].get_state_variable(), instance_id).update(results)
        #elif len(out_arguments) > 1:

        # Update state-variables from the result. NB: This silently
        # ignores missing and extraneous result values. I'm not sure
        # if this is according to the DLNA specs. :todo: check the DLNS-specs
        for outarg in out_arguments:
            if outarg.get_name() in results:
                var = self.service.get_state_variable(
                    outarg.get_state_variable(), instance_id)
                var.update(results[outarg.get_name()])

        return results

    def __repr__(self):
        return ("Action(%(name)r, %(implementation)r, (%arguments_list)r"
                % vars(self))

    def as_tuples(self):
        r = [
            ('Name', self.name),
            ("Number of 'in' arguments", len(self.get_in_arguments())),
            ("Number of 'out' arguments", len(self.get_out_arguments())),
            ]
        return r

    def as_dict(self):
        return {
            'name': self.name,
            'arguments': [a.as_dict() for a in self.arguments_list]
            }
<commit_msg>Minor cleanup for handling argument `InstanceID`.<commit_after># Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php

# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <coherence@beebits.net>

from twisted.python import failure
from twisted.python.util import OrderedDict

from coherence import log

class Argument:

    def __init__(self, name, direction, state_variable):
        self.name = name
        self.direction = direction
        self.state_variable = state_variable

    def get_name(self):
        return self.name

    def get_direction(self):
        return self.direction

    def get_state_variable(self):
        return self.state_variable

    def __repr__(self):
        return ("Argument(%(name)r, %(direction)r, %(state_variable)r"
                % vars(self))

    def as_tuples(self):
        r = [
            ('Name', self.name),
            ('Direction', self.direction),
            ('Related State Variable', self.state_variable)
            ]
        return r

    def as_dict(self):
        return {
            'name': self.name,
            'direction': self.direction,
            'related_state_variable': self.state_variable
            }

class Action(log.Loggable):
    logCategory = 'action'

    def __init__(self, service, name, implementation, arguments_list):
        log.Loggable.__init__(self)
        self.service = service
        self.name = name
        self.implementation = implementation
        self.arguments_list = arguments_list

    def _get_client(self):
        client = self.service._get_client(self.name)
        return client

    def get_name(self):
        return self.name

    def get_implementation(self):
        return self.implementation

    def get_arguments_list(self):
        return self.arguments_list

    def get_in_arguments(self):
        return [arg for arg in self.arguments_list
                if arg.direction == 'in']

    def get_out_arguments(self):
        return [arg for arg in self.arguments_list
                if arg.direction == 'out']

    def get_service(self):
        return self.service

    def set_callback(self, callback):
        self.callback = callback

    def get_callback(self):
        try:
            return self.callback
        except:
            return None

    def call(self, *args, **kwargs):
        self.info("calling %s", self.name)
        in_arguments = self.get_in_arguments()
        self.info("in arguments %s", [a.get_name() for a in in_arguments])
        instance_id = kwargs.get('InstanceID', 0)
        for arg_name, arg in kwargs.iteritems():
            l = [a for a in in_arguments if arg_name == a.get_name()]
            if len(l) > 0:
                in_arguments.remove(l[0])
            else:
                self.error("argument %s not valid for action %s", arg_name, self.name)
                return
        if len(in_arguments) > 0:
            self.error("argument %s missing for action %s", [a.get_name() for a in in_arguments], self.name)
            return

        action_name = self.name

        if(hasattr(self.service.device.client, 'overlay_actions') and
           self.service.device.client.overlay_actions.has_key(self.name)):
            self.info("we have an overlay method %r for action %r", self.service.device.client.overlay_actions[self.name], self.name)
            action_name, kwargs = self.service.device.client.overlay_actions[self.name](**kwargs)
            self.info("changing action to %r %r", action_name, kwargs)

        def got_error(failure):
            self.warning("error on %s request with %s %s", self.name, self.
                                                            service.service_type,
                                                            self.service.control_url)
            self.info(failure)
            return failure

        if hasattr(self.service.device.client, 'overlay_headers'):
            self.info("action call has headers %r", kwargs.has_key('headers'))
            if kwargs.has_key('headers'):
                kwargs['headers'].update(self.service.device.client.overlay_headers)
            else:
                kwargs['headers'] = self.service.device.client.overlay_headers
            self.info("action call with new/updated headers %r", kwargs['headers'])

        client = self._get_client()

        ordered_arguments = OrderedDict()
        for argument in self.get_in_arguments():
            ordered_arguments[argument.name] = kwargs[argument.name]
        if kwargs.has_key('headers'):
            ordered_arguments['headers'] = kwargs['headers']

        d = client.callRemote(action_name, ordered_arguments)
        d.addCallback(self.got_results, instance_id=instance_id, name=action_name)
        d.addErrback(got_error)
        return d

    def got_results(self, results, instance_id, name):
        instance_id = int(instance_id)
        out_arguments = self.get_out_arguments()
        self.info("call %s (instance %d) returns %d arguments: %r", name,
                                                                    instance_id,
                                                                    len(out_arguments),
                                                                    results)

        # XXX A_ARG_TYPE_ arguments probably don't need a variable update
        #if len(out_arguments) == 1:
        #    self.service.get_state_variable(out_arguments[0].get_state_variable(), instance_id).update(results)
        #elif len(out_arguments) > 1:

        # Update state-variables from the result. NB: This silently
        # ignores missing and extraneous result values. I'm not sure
        # if this is according to the DLNA specs. :todo: check the DLNS-specs
        for outarg in out_arguments:
            if outarg.get_name() in results:
                var = self.service.get_state_variable(
                    outarg.get_state_variable(), instance_id)
                var.update(results[outarg.get_name()])

        return results

    def __repr__(self):
        return ("Action(%(name)r, %(implementation)r, (%arguments_list)r"
                % vars(self))

    def as_tuples(self):
        r = [
            ('Name', self.name),
            ("Number of 'in' arguments", len(self.get_in_arguments())),
            ("Number of 'out' arguments", len(self.get_out_arguments())),
            ]
        return r

    def as_dict(self):
        return {
            'name': self.name,
            'arguments': [a.as_dict() for a in self.arguments_list]
            }
<|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.

"""Fichier contenant la classe PNJ, détaillée plus bas."""

import sys

from abstraits.id import ObjetID
from primaires.perso.personnage import Personnage

class PNJ(Personnage):
    """Classe représentant un PNJ, c'est-à-dire un personnage virtuel.

    Ce personnage est géré par l'univers et n'est pas connecté, à
    la différence d'un joueur.

    """

    groupe = "pnjs"
    sous_rep = "pnj/pnj"

    def __init__(self, prototype):
        """Constructeur du PNJ"""
        Personnage.__init__(self)
        self.prototype = prototype
        if prototype:
            self.identifiant = prototype.cle + "_" + str(
                    prototype.no)
            prototype.no += 1
            prototype.pnj.append(self)

            # On copie les attributs propres à l'objet
            # Ils sont disponibles dans le prototype, dans la variable
            # _attributs
            # C'est un dictionnaire contenant en clé le nom de l'attribut
            # et en valeur le constructeur de l'objet
            for nom, val in prototype._attributs.items():
                setattr(self, nom, val.construire(self))

    def __getnewargs__(self):
        return (None, )

    def __getattr__(self, nom_attr):
        """Si le nom d'attribut n'est pas trouvé, le chercher
        dans le prototype

        """
        if nom_attr == "prototype":
            return object.__getattr__(self, nom_attr)
        else:
            try:
                return Personnage.__getattr__(self, nom_attr)
            except AttributeError:
                return getattr(self.prototype, nom_attr)

    def envoyer(self, msg):
        """Envoie un message"""
        pass

    def detruire(self):
        """Destruction du PNJ."""
        if self in self.prototype.pnj:
            self.prototype.pnj.remove(self)
        ObjetID.detruire(self)

ObjetID.ajouter_groupe(PNJ)
<commit_msg>Ajout d'un patch sur les PNJ et correction d'un bug : -   A présent, le nom du PNJ est le nom singulier de son prototype.     On peut y accéder via prototype.nom, comme d'habitude.     Notez que si vous modifiez le nom par ce biais (pnj.nom = "autre nom"),     le nom est bel et bien modifié (sans affecter celui du prototype     derrière).     Cela permet de modifier le nom d'un PNJ en cours de jeu sans toucher     au prototype. -   Les identifiants des prototypes sont maintenant créés à partir de la     clé prototype_1 (et non prototype_0, moins jolie)<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.

"""Fichier contenant la classe PNJ, détaillée plus bas."""

import sys

from abstraits.id import ObjetID
from primaires.perso.personnage import Personnage

class PNJ(Personnage):
    """Classe représentant un PNJ, c'est-à-dire un personnage virtuel.

    Ce personnage est géré par l'univers et n'est pas connecté, à
    la différence d'un joueur.

    """

    groupe = "pnjs"
    sous_rep = "pnj/pnj"

    def __init__(self, prototype):
        """Constructeur du PNJ"""
        Personnage.__init__(self)
        self._nom = ""
        self.prototype = prototype
        if prototype:
            prototype.no += 1
            self.identifiant = prototype.cle + "_" + str(
                    prototype.no)
            prototype.pnj.append(self)

            # On copie les attributs propres à l'objet
            # Ils sont disponibles dans le prototype, dans la variable
            # _attributs
            # C'est un dictionnaire contenant en clé le nom de l'attribut
            # et en valeur le constructeur de l'objet
            for nom, val in prototype._attributs.items():
                setattr(self, nom, val.construire(self))

    def __getnewargs__(self):
        return (None, )

    def __getattr__(self, nom_attr):
        """Si le nom d'attribut n'est pas trouvé, le chercher
        dans le prototype

        """
        if nom_attr == "prototype":
            return object.__getattr__(self, nom_attr)
        else:
            try:
                return Personnage.__getattr__(self, nom_attr)
            except AttributeError:
                return getattr(self.prototype, nom_attr)

    def _get_nom(self):
        """Retourne le nom singulier définit dans le prototype.

        Toutefois, si le nom est définit dans le PNJ lui-même
        (l'attribut _nom n'est pas vide), retourne celui-ci.

        """
        nom = self._nom
        if not nom:
            nom = self.prototype.nom_singulier

        return nom
    def _set_nom(self, nouveau_nom):
        """Ecrit le nom dans self._nom.

        Note contextuelle : si le nouveau nom est vide, le nom redeviendra
        le nom singulier du prototype.

        """
        self._nom = nouveau_nom

    nom = property(_get_nom, _set_nom)

    def envoyer(self, msg):
        """Envoie un message"""
        pass

    def detruire(self):
        """Destruction du PNJ."""
        if self in self.prototype.pnj:
            self.prototype.pnj.remove(self)
        ObjetID.detruire(self)

ObjetID.ajouter_groupe(PNJ)
<|endoftext|>


<commit_before>import os
import sys
from syn.type import Type, AnyType
from argparse import ArgumentParser
from .dependency import Dependencies
from .apt import Apt
from .pip import Pip

#-------------------------------------------------------------------------------

DESCRIPTION = 'A lightweight dependency manager.'

parser = ArgumentParser(prog='depman', description=DESCRIPTION)
parser.add_argument('-f', '--depfile', dest='depfile', type=str,
                    default=os.path.join(os.getcwd(), 'requirements.yml'),
                    metavar='<depfile>', help='The requirements file to load')
parser.add_argument('-t', '--type', dest='type', type=str,
                    default='all', metavar='<type>',
                    help='Restrict operations to dependencies of this type')
parser.add_argument('-o', '--outfile', dest='outfile', type=str, default='',
                    metavar='<outfile>', help='File to write results to')
parser.add_argument('command', metavar='<command>',
                    choices=['satisfy', 'validate', 'export'],
                    help="'satisfy' satisfies the dependcies specified in "
                    "<depfile>.  'validate' only validates <depfile> and does "
                    "not perform any system operations.  'export' exports "
                    "requirements to a specified file (using -o)")
parser.add_argument('context', metavar='<context>', type=str, default='all',
                    nargs='?',
                    help='The dependency context to perform <command> on')

USAGE = parser.format_usage().strip()

#-------------------------------------------------------------------------------
# Dispatch type

TYPES = dict(apt = Apt,
             pip = Pip)

def dispatch_type(typ):
    if typ == 'all':
        return AnyType()
    if ',' in typ:
        return Type.dispatch(tuple([dispatch_type(t) for t in typ.split(',')]))
    if typ in TYPES:
        return Type.dispatch(TYPES[typ])
    raise TypeError("Unknown type: {}".format(typ))

#-------------------------------------------------------------------------------
# Dispatch outfile

def dispatch_outfile(f):
    if not f:
        return sys.stdout
    return open(f, 'wt')

#-------------------------------------------------------------------------------

def _main(*args):
    opts = parser.parse_args(args)

    command = opts.command
    context = opts.context
    path = opts.depfile

    deptype = dispatch_type(opts.type)

    with open(path, 'rt') as f:
        deps = Dependencies.from_yaml(f)

    outfile = dispatch_outfile(opts.outfile)
    if command == 'satisfy':
        deps.satisfy(context, deptype)
    elif command == 'validate':
        # We will get an error of some sort before this if it isn't valid
        print("Validation successful")
    elif command == 'export':
        deps.export(context, deptype, outfile)

    if outfile is not sys.stdout:
        outfile.close()

#-------------------------------------------------------------------------------

def main():
    _main(*sys.argv[1:]) # pragma: no cover

#-------------------------------------------------------------------------------
<commit_msg>Removing redundant redundancy<commit_after>import os
import sys
from syn.type import Type, AnyType
from argparse import ArgumentParser
from .dependency import Dependencies, DEPENDENCY_KEYS

#-------------------------------------------------------------------------------

DESCRIPTION = 'A lightweight dependency manager.'

parser = ArgumentParser(prog='depman', description=DESCRIPTION)
parser.add_argument('-f', '--depfile', dest='depfile', type=str,
                    default=os.path.join(os.getcwd(), 'requirements.yml'),
                    metavar='<depfile>', help='The requirements file to load')
parser.add_argument('-t', '--type', dest='type', type=str,
                    default='all', metavar='<type>',
                    help='Restrict operations to dependencies of this type')
parser.add_argument('-o', '--outfile', dest='outfile', type=str, default='',
                    metavar='<outfile>', help='File to write results to')
parser.add_argument('command', metavar='<command>',
                    choices=['satisfy', 'validate', 'export'],
                    help="'satisfy' satisfies the dependcies specified in "
                    "<depfile>.  'validate' only validates <depfile> and does "
                    "not perform any system operations.  'export' exports "
                    "requirements to a specified file (using -o)")
parser.add_argument('context', metavar='<context>', type=str, default='all',
                    nargs='?',
                    help='The dependency context to perform <command> on')

USAGE = parser.format_usage().strip()

#-------------------------------------------------------------------------------
# Dispatch type

def dispatch_type(typ):
    if typ == 'all':
        return AnyType()
    if ',' in typ:
        return Type.dispatch(tuple([dispatch_type(t) for t in typ.split(',')]))
    if typ in DEPENDENCY_KEYS:
        return Type.dispatch(DEPENDENCY_KEYS[typ])
    raise TypeError("Unknown type: {}".format(typ))

#-------------------------------------------------------------------------------
# Dispatch outfile

def dispatch_outfile(f):
    if not f:
        return sys.stdout
    return open(f, 'wt')

#-------------------------------------------------------------------------------

def _main(*args):
    opts = parser.parse_args(args)

    command = opts.command
    context = opts.context
    path = opts.depfile

    deptype = dispatch_type(opts.type)

    with open(path, 'rt') as f:
        deps = Dependencies.from_yaml(f)

    outfile = dispatch_outfile(opts.outfile)
    if command == 'satisfy':
        deps.satisfy(context, deptype)
    elif command == 'validate':
        # We will get an error of some sort before this if it isn't valid
        print("Validation successful")
    elif command == 'export':
        deps.export(context, deptype, outfile)

    if outfile is not sys.stdout:
        outfile.close()

#-------------------------------------------------------------------------------

def main():
    _main(*sys.argv[1:]) # pragma: no cover

#-------------------------------------------------------------------------------
<|endoftext|>


<commit_before>import random
import smtplib
import time
from settings import people, couples, email, from_addr

# Make the couple exclusions two-way for easy dict lookups
for person in couples.keys():
    couples[couples[person]] = person

# Match people up
possible_recipients = people.keys()
pairings = {}
for name in people.keys():
    recipient = None
    # Sample until the recipient is neither themselves nor their partner
    while recipient in (None, name, couples.get(name, None)):
        recipient = random.choice(possible_recipients)
    possible_recipients.remove(recipient)
    pairings[name] = recipient

# Email each person
for name, recipient in pairings.iteritems():
    to_addrs = people[name]
    msg = '{0}, your secret santa recipient is {1}.'.format(name, recipient)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(email['username'], email['password'])
    server.sendmail(from_addr, to_addrs, msg)
    server.quit()

    # Try not to anger the Gods o' Spam
    print 'Sent to ' + to_addrs
    time.sleep(5)<commit_msg>Small tweak<commit_after>import random
import smtplib
import time
from settings import people, couples, email, from_addr

# Make the couple exclusions two-way for easy dict lookups
for person in couples.keys():
    couples[couples[person]] = person

# Match people up
possible_recipients = people.keys()
pairings = {}
for name in people.keys():
    recipient = None
    # Sample until the recipient is neither themselves nor their partner
    while recipient in (None, name, couples.get(name, None)):
        recipient = random.choice(possible_recipients)
    possible_recipients.remove(recipient)
    pairings[name] = recipient

# Email each person
for name, recipient in pairings.iteritems():
    to_addrs = people[name]
    msg = '{0}, your secret santa recipient is {1}.'.format(name, recipient)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(email['username'], email['password'])
    server.sendmail(from_addr, to_addrs, msg)
    server.quit()

    print 'Sent to ' + to_addrs

    # Try not to anger the Gods o' Spam
    time.sleep(5)
<|endoftext|>