<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2005-2006 Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Daniel Lundin <daniel@edgewall.com>
#

from trac.core import *
from trac.config import *
from trac.notification import NotifyEmail
from trac.util import md5
from trac.util.datefmt import to_timestamp
from trac.util.text import CRLF, wrap, obfuscate_email_address

from genshi.template.text import NewTextTemplate

class TicketNotificationSystem(Component):

    always_notify_owner = BoolOption('notification', 'always_notify_owner',
                                     'false',
        """Always send notifications to the ticket owner (''since 0.9'').""")

    always_notify_reporter = BoolOption('notification', 'always_notify_reporter',
                                        'false',
        """Always send notifications to any address in the ''reporter''
        field.""")

    always_notify_updater = BoolOption('notification', 'always_notify_updater',
                                       'true',
        """Always send notifications to the person who causes the ticket
        property change and to any previous updater of that ticket.""")

    ticket_subject_template = Option('notification', 'ticket_subject_template',
                                     '$prefix #$ticket.id: $summary',
        """A Genshi text template snippet used to get the notification subject.

        By default, the subject template is `$prefix #$ticket.id: $summary`.
        `$prefix` being the value of the `smtp_subject_prefix` option.
        ''(since 0.11)''""")

class TicketNotifyEmail(NotifyEmail):
    """Notification of ticket changes."""

    template_name = "ticket_notify_email.txt"
    ticket = None
    newticket = None
    modtime = 0
    from_email = 'trac+ticket@localhost'
    COLS = 75

    def __init__(self, env):
        NotifyEmail.__init__(self, env)
        self.prev_cc = []

    def notify(self, ticket, newticket=True, modtime=None):
        self.ticket = ticket
        self.modtime = modtime
        self.newticket = newticket

        changes_body = ''
        self.reporter = ''
        self.owner = ''
        changes_descr = ''
        change_data = {}
        link = self.env.abs_href.ticket(ticket.id)
        summary = self.ticket['summary']

        if not self.newticket and modtime:  # Ticket change
            from trac.ticket.web_ui import TicketModule
            for change in TicketModule(self.env).grouped_changelog_entries(
                ticket, self.db, when=modtime):
                if not change['permanent']: # attachment with same time...
                    continue
                change_data.update({
                    'author': obfuscate_email_address(change['author']),
                    'comment': wrap(change['comment'], self.COLS, ' ', ' ',
                                    CRLF)
                    })
                link += '#comment:%s' % str(change.get('cnum', ''))
                for field, values in change['fields'].iteritems():
                    old = values['old']
                    new = values['new']
                    newv = ''
                    if field == 'description':
                        new_descr = wrap(new, self.COLS, ' ', ' ', CRLF)
                        old_descr = wrap(old, self.COLS, '> ', '> ', CRLF)
                        old_descr = old_descr.replace(2*CRLF, CRLF + '>' + \
                                                      CRLF)
                        cdescr = CRLF
                        cdescr += 'Old description:' + 2*CRLF + old_descr + \
                                  2*CRLF
                        cdescr += 'New description:' + 2*CRLF + new_descr + \
                                  CRLF
                        changes_descr = cdescr
                    elif field == 'summary':
                        summary = "%s (was: %s)" % (new, old)
                    elif field == 'cc':
                        (addcc, delcc) = self.diff_cc(old, new)
                        chgcc = ''
                        if delcc:
                            chgcc += wrap(" * cc: %s (removed)" %
                                          ', '.join(delcc),
                                          self.COLS, ' ', ' ', CRLF) + CRLF
                        if addcc:
                            chgcc += wrap(" * cc: %s (added)" %
                                          ', '.join(addcc),
                                          self.COLS, ' ', ' ', CRLF) + CRLF
                        if chgcc:
                            changes_body += chgcc
                        self.prev_cc += old and self.parse_cc(old) or []
                    else:
                        if field in ['owner', 'reporter']:
                            old = obfuscate_email_address(old)
                            new = obfuscate_email_address(new)
                        newv = new
                        l = 7 + len(field)
                        chg = wrap('%s => %s' % (old, new), self.COLS - l, '',
                                   l * ' ', CRLF)
                        changes_body += '  * %s:  %s%s' % (field, chg, CRLF)
                    if newv:
                        change_data[field] = {'oldvalue': old, 'newvalue': new}

        ticket_values = ticket.values.copy()
        ticket_values['description'] = wrap(
            ticket_values.get('description', ''), self.COLS,
            initial_indent=' ', subsequent_indent=' ', linesep=CRLF)
        ticket_values['new'] = self.newticket
        ticket_values['link'] = link

        subject = self.format_subj(summary)
        if not self.newticket:
            subject = 'Re: ' + subject
        self.data.update({
            'ticket_props': self.format_props(),
            'ticket_body_hdr': self.format_hdr(),
            'subject': subject,
            'ticket': ticket_values,
            'changes_body': changes_body,
            'changes_descr': changes_descr,
            'change': change_data
            })
        NotifyEmail.notify(self, ticket.id, subject)

    def format_props(self):
        tkt = self.ticket
        fields = [f for f in tkt.fields
                  if f['name'] not in ('summary', 'cc', 'time', 'changetime')]
        width = [0, 0, 0, 0]
        i = 0
        for f in [f['name'] for f in fields if f['type'] != 'textarea']:
            if not tkt.values.has_key(f):
                continue
            fval = tkt[f] or ''
            if fval.find('\n') != -1:
                continue
            idx = 2 * (i % 2)
            if len(f) > width[idx]:
                width[idx] = len(f)
            if len(fval) > width[idx + 1]:
                width[idx + 1] = len(fval)
            i += 1
        format = ('%%%is:  %%-%is  |  ' % (width[0], width[1]),
                  ' %%%is:  %%-%is%s' % (width[2], width[3], CRLF))
        l = (width[0] + width[1] + 5)
        sep = l * '-' + '+' + (self.COLS - l) * '-'
        txt = sep + CRLF
        big = []
        i = 0
        for f in [f for f in fields if f['name'] != 'description']:
            fname = f['name']
            if not tkt.values.has_key(fname):
                continue
            fval = tkt[fname] or ''
            if fname in ['owner', 'reporter']:
                fval = obfuscate_email_address(fval)
            if f['type'] == 'textarea' or '\n' in unicode(fval):
                big.append((f['label'], CRLF.join(fval.splitlines())))
            else:
                txt += format[i % 2] % (f['label'], fval)
                i += 1
        if i % 2:
            txt += CRLF
        if big:
            txt += sep
            for name, value in big:
                txt += CRLF.join(['', name + ':', value, '', ''])
        txt += sep
        return txt

    def parse_cc(self, txt):
        return filter(lambda x: '@' in x, txt.replace(',', ' ').split())

    def diff_cc(self, old, new):
        oldcc = NotifyEmail.addrsep_re.split(old)
        newcc = NotifyEmail.addrsep_re.split(new)
        added = [obfuscate_email_address(x) \
                                for x in newcc if x and x not in oldcc]
        removed = [obfuscate_email_address(x) \
                                for x in oldcc if x and x not in newcc]
        return (added, removed)

    def format_hdr(self):
        return '#%s: %s' % (self.ticket.id, wrap(self.ticket['summary'],
                                                 self.COLS, linesep=CRLF))

    def format_subj(self, summary):
        template = self.config.get('notification','ticket_subject_template')
        template = NewTextTemplate(template.encode('utf8'))

        prefix = self.config.get('notification', 'smtp_subject_prefix')
        if prefix == '__default__':
            prefix = '[%s]' % self.env.project_name

        data = {
            'prefix': prefix,
            'summary': summary,
            'ticket': self.ticket,
            'env': self.env,
        }

        return template.generate(**data).render('text', encoding=None).strip()

    def get_recipients(self, tktid):
        notify_reporter = self.config.getbool('notification',
                                              'always_notify_reporter')
        notify_owner = self.config.getbool('notification',
                                           'always_notify_owner')
        notify_updater = self.config.getbool('notification',
                                             'always_notify_updater')

        ccrecipients = self.prev_cc
        torecipients = []
        cursor = self.db.cursor()

        # Harvest email addresses from the cc, reporter, and owner fields
        cursor.execute("SELECT cc,reporter,owner FROM ticket WHERE id=%s",
                       (tktid,))
        row = cursor.fetchone()
        if row:
            ccrecipients += row[0] and row[0].replace(',', ' ').split() or []
            self.reporter = row[1]
            self.owner = row[2]
            if notify_reporter:
                torecipients.append(row[1])
            if notify_owner:
                torecipients.append(row[2])

        # Harvest email addresses from the author field of ticket_change(s)
        if notify_updater:
            cursor.execute("SELECT DISTINCT author,ticket FROM ticket_change "
                           "WHERE ticket=%s", (tktid,))
            for author, ticket in cursor:
                torecipients.append(author)

        # Suppress the updater from the recipients
        updater = None
        cursor.execute("SELECT author FROM ticket_change WHERE ticket=%s "
                       "ORDER BY time DESC LIMIT 1", (tktid,))
        for updater, in cursor:
            break
        else:
            cursor.execute("SELECT reporter FROM ticket WHERE id=%s",
                           (tktid,))
            for updater, in cursor:
                break

        if not notify_updater:
            filter_out = True
            if notify_reporter and (updater == self.reporter):
                filter_out = False
            if notify_owner and (updater == self.owner):
                filter_out = False
            if filter_out:
                torecipients = [r for r in torecipients if r and r != updater]
        elif updater:
            torecipients.append(updater)

        return (torecipients, ccrecipients)

    def get_message_id(self, rcpt, modtime=None):
        """Generate a predictable, but sufficiently unique message ID."""
        s = '%s.%08d.%d.%s' % (self.env.project_url,
                               int(self.ticket.id), to_timestamp(modtime),
                               rcpt.encode('ascii', 'ignore'))
        dig = md5(s).hexdigest()
        host = self.from_email[self.from_email.find('@') + 1:]
        msgid = '<%03d.%s@%s>' % (len(s), dig, host)
        return msgid

    def send(self, torcpts, ccrcpts):
        dest = self.reporter or 'anonymous'
        hdrs = {}
        hdrs['Message-ID'] = self.get_message_id(dest, self.modtime)
        hdrs['X-Trac-Ticket-ID'] = str(self.ticket.id)
        hdrs['X-Trac-Ticket-URL'] = self.data['ticket']['link']
        if not self.newticket:
            msgid = self.get_message_id(dest)
            hdrs['In-Reply-To'] = msgid
            hdrs['References'] = msgid
        NotifyEmail.send(self, torcpts, ccrcpts, hdrs)

<commit_msg>db: Follow-up to [9210], also use a microsecond timestamp for generating notification message IDs. Unfortunately, this will break threading to messages prior to the change, but at least we avoid generating message ID collisions for sub-second changes.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2005-2006 Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Daniel Lundin <daniel@edgewall.com>
#

from trac.core import *
from trac.config import *
from trac.notification import NotifyEmail
from trac.util import md5
from trac.util.datefmt import to_utimestamp
from trac.util.text import CRLF, wrap, obfuscate_email_address

from genshi.template.text import NewTextTemplate

class TicketNotificationSystem(Component):

    always_notify_owner = BoolOption('notification', 'always_notify_owner',
                                     'false',
        """Always send notifications to the ticket owner (''since 0.9'').""")

    always_notify_reporter = BoolOption('notification', 'always_notify_reporter',
                                        'false',
        """Always send notifications to any address in the ''reporter''
        field.""")

    always_notify_updater = BoolOption('notification', 'always_notify_updater',
                                       'true',
        """Always send notifications to the person who causes the ticket
        property change and to any previous updater of that ticket.""")

    ticket_subject_template = Option('notification', 'ticket_subject_template',
                                     '$prefix #$ticket.id: $summary',
        """A Genshi text template snippet used to get the notification subject.

        By default, the subject template is `$prefix #$ticket.id: $summary`.
        `$prefix` being the value of the `smtp_subject_prefix` option.
        ''(since 0.11)''""")

class TicketNotifyEmail(NotifyEmail):
    """Notification of ticket changes."""

    template_name = "ticket_notify_email.txt"
    ticket = None
    newticket = None
    modtime = 0
    from_email = 'trac+ticket@localhost'
    COLS = 75

    def __init__(self, env):
        NotifyEmail.__init__(self, env)
        self.prev_cc = []

    def notify(self, ticket, newticket=True, modtime=None):
        self.ticket = ticket
        self.modtime = modtime
        self.newticket = newticket

        changes_body = ''
        self.reporter = ''
        self.owner = ''
        changes_descr = ''
        change_data = {}
        link = self.env.abs_href.ticket(ticket.id)
        summary = self.ticket['summary']

        if not self.newticket and modtime:  # Ticket change
            from trac.ticket.web_ui import TicketModule
            for change in TicketModule(self.env).grouped_changelog_entries(
                ticket, self.db, when=modtime):
                if not change['permanent']: # attachment with same time...
                    continue
                change_data.update({
                    'author': obfuscate_email_address(change['author']),
                    'comment': wrap(change['comment'], self.COLS, ' ', ' ',
                                    CRLF)
                    })
                link += '#comment:%s' % str(change.get('cnum', ''))
                for field, values in change['fields'].iteritems():
                    old = values['old']
                    new = values['new']
                    newv = ''
                    if field == 'description':
                        new_descr = wrap(new, self.COLS, ' ', ' ', CRLF)
                        old_descr = wrap(old, self.COLS, '> ', '> ', CRLF)
                        old_descr = old_descr.replace(2*CRLF, CRLF + '>' + \
                                                      CRLF)
                        cdescr = CRLF
                        cdescr += 'Old description:' + 2*CRLF + old_descr + \
                                  2*CRLF
                        cdescr += 'New description:' + 2*CRLF + new_descr + \
                                  CRLF
                        changes_descr = cdescr
                    elif field == 'summary':
                        summary = "%s (was: %s)" % (new, old)
                    elif field == 'cc':
                        (addcc, delcc) = self.diff_cc(old, new)
                        chgcc = ''
                        if delcc:
                            chgcc += wrap(" * cc: %s (removed)" %
                                          ', '.join(delcc),
                                          self.COLS, ' ', ' ', CRLF) + CRLF
                        if addcc:
                            chgcc += wrap(" * cc: %s (added)" %
                                          ', '.join(addcc),
                                          self.COLS, ' ', ' ', CRLF) + CRLF
                        if chgcc:
                            changes_body += chgcc
                        self.prev_cc += old and self.parse_cc(old) or []
                    else:
                        if field in ['owner', 'reporter']:
                            old = obfuscate_email_address(old)
                            new = obfuscate_email_address(new)
                        newv = new
                        l = 7 + len(field)
                        chg = wrap('%s => %s' % (old, new), self.COLS - l, '',
                                   l * ' ', CRLF)
                        changes_body += '  * %s:  %s%s' % (field, chg, CRLF)
                    if newv:
                        change_data[field] = {'oldvalue': old, 'newvalue': new}

        ticket_values = ticket.values.copy()
        ticket_values['description'] = wrap(
            ticket_values.get('description', ''), self.COLS,
            initial_indent=' ', subsequent_indent=' ', linesep=CRLF)
        ticket_values['new'] = self.newticket
        ticket_values['link'] = link

        subject = self.format_subj(summary)
        if not self.newticket:
            subject = 'Re: ' + subject
        self.data.update({
            'ticket_props': self.format_props(),
            'ticket_body_hdr': self.format_hdr(),
            'subject': subject,
            'ticket': ticket_values,
            'changes_body': changes_body,
            'changes_descr': changes_descr,
            'change': change_data
            })
        NotifyEmail.notify(self, ticket.id, subject)

    def format_props(self):
        tkt = self.ticket
        fields = [f for f in tkt.fields
                  if f['name'] not in ('summary', 'cc', 'time', 'changetime')]
        width = [0, 0, 0, 0]
        i = 0
        for f in [f['name'] for f in fields if f['type'] != 'textarea']:
            if not tkt.values.has_key(f):
                continue
            fval = tkt[f] or ''
            if fval.find('\n') != -1:
                continue
            idx = 2 * (i % 2)
            if len(f) > width[idx]:
                width[idx] = len(f)
            if len(fval) > width[idx + 1]:
                width[idx + 1] = len(fval)
            i += 1
        format = ('%%%is:  %%-%is  |  ' % (width[0], width[1]),
                  ' %%%is:  %%-%is%s' % (width[2], width[3], CRLF))
        l = (width[0] + width[1] + 5)
        sep = l * '-' + '+' + (self.COLS - l) * '-'
        txt = sep + CRLF
        big = []
        i = 0
        for f in [f for f in fields if f['name'] != 'description']:
            fname = f['name']
            if not tkt.values.has_key(fname):
                continue
            fval = tkt[fname] or ''
            if fname in ['owner', 'reporter']:
                fval = obfuscate_email_address(fval)
            if f['type'] == 'textarea' or '\n' in unicode(fval):
                big.append((f['label'], CRLF.join(fval.splitlines())))
            else:
                txt += format[i % 2] % (f['label'], fval)
                i += 1
        if i % 2:
            txt += CRLF
        if big:
            txt += sep
            for name, value in big:
                txt += CRLF.join(['', name + ':', value, '', ''])
        txt += sep
        return txt

    def parse_cc(self, txt):
        return filter(lambda x: '@' in x, txt.replace(',', ' ').split())

    def diff_cc(self, old, new):
        oldcc = NotifyEmail.addrsep_re.split(old)
        newcc = NotifyEmail.addrsep_re.split(new)
        added = [obfuscate_email_address(x) \
                                for x in newcc if x and x not in oldcc]
        removed = [obfuscate_email_address(x) \
                                for x in oldcc if x and x not in newcc]
        return (added, removed)

    def format_hdr(self):
        return '#%s: %s' % (self.ticket.id, wrap(self.ticket['summary'],
                                                 self.COLS, linesep=CRLF))

    def format_subj(self, summary):
        template = self.config.get('notification','ticket_subject_template')
        template = NewTextTemplate(template.encode('utf8'))

        prefix = self.config.get('notification', 'smtp_subject_prefix')
        if prefix == '__default__':
            prefix = '[%s]' % self.env.project_name

        data = {
            'prefix': prefix,
            'summary': summary,
            'ticket': self.ticket,
            'env': self.env,
        }

        return template.generate(**data).render('text', encoding=None).strip()

    def get_recipients(self, tktid):
        notify_reporter = self.config.getbool('notification',
                                              'always_notify_reporter')
        notify_owner = self.config.getbool('notification',
                                           'always_notify_owner')
        notify_updater = self.config.getbool('notification',
                                             'always_notify_updater')

        ccrecipients = self.prev_cc
        torecipients = []
        cursor = self.db.cursor()

        # Harvest email addresses from the cc, reporter, and owner fields
        cursor.execute("SELECT cc,reporter,owner FROM ticket WHERE id=%s",
                       (tktid,))
        row = cursor.fetchone()
        if row:
            ccrecipients += row[0] and row[0].replace(',', ' ').split() or []
            self.reporter = row[1]
            self.owner = row[2]
            if notify_reporter:
                torecipients.append(row[1])
            if notify_owner:
                torecipients.append(row[2])

        # Harvest email addresses from the author field of ticket_change(s)
        if notify_updater:
            cursor.execute("SELECT DISTINCT author,ticket FROM ticket_change "
                           "WHERE ticket=%s", (tktid,))
            for author, ticket in cursor:
                torecipients.append(author)

        # Suppress the updater from the recipients
        updater = None
        cursor.execute("SELECT author FROM ticket_change WHERE ticket=%s "
                       "ORDER BY time DESC LIMIT 1", (tktid,))
        for updater, in cursor:
            break
        else:
            cursor.execute("SELECT reporter FROM ticket WHERE id=%s",
                           (tktid,))
            for updater, in cursor:
                break

        if not notify_updater:
            filter_out = True
            if notify_reporter and (updater == self.reporter):
                filter_out = False
            if notify_owner and (updater == self.owner):
                filter_out = False
            if filter_out:
                torecipients = [r for r in torecipients if r and r != updater]
        elif updater:
            torecipients.append(updater)

        return (torecipients, ccrecipients)

    def get_message_id(self, rcpt, modtime=None):
        """Generate a predictable, but sufficiently unique message ID."""
        s = '%s.%08d.%d.%s' % (self.env.project_url,
                               int(self.ticket.id), to_utimestamp(modtime),
                               rcpt.encode('ascii', 'ignore'))
        dig = md5(s).hexdigest()
        host = self.from_email[self.from_email.find('@') + 1:]
        msgid = '<%03d.%s@%s>' % (len(s), dig, host)
        return msgid

    def send(self, torcpts, ccrcpts):
        dest = self.reporter or 'anonymous'
        hdrs = {}
        hdrs['Message-ID'] = self.get_message_id(dest, self.modtime)
        hdrs['X-Trac-Ticket-ID'] = str(self.ticket.id)
        hdrs['X-Trac-Ticket-URL'] = self.data['ticket']['link']
        if not self.newticket:
            msgid = self.get_message_id(dest)
            hdrs['In-Reply-To'] = msgid
            hdrs['References'] = msgid
        NotifyEmail.send(self, torcpts, ccrcpts, hdrs)

<|endoftext|>


<commit_before>import random

def merge(L:"list of lists", origLen:int) -> list:
	if len(L[0]) == origLen:
		return L[0]

	L[0].append(L[1])
	L[0].sort()
	del L[1]

	return merge(L, origLen)

def main():
	L = [random.randint(0, 999) for i in range(997)]
	L[0] = [L[0]]

	print(merge(L, len(L)))

if __name__ == "__main__":
	main()
<commit_msg>Delete main.py<commit_after><|endoftext|>


<commit_before># -*- coding:utf-8 -*-
"""
Description:
    Fixed8
Usage:
    from AntShares.Fixed8 import Fixed8
"""

from decimal import Decimal as D
from AntShares.Helper import big_or_little

class Fixed8(float):
    """docstring for Fixed8"""
    def __init__(self, number):
        self.f = D(str(number))

    def getData(self):
        hex_str = hex(int(self.f*D('100000000')))[2:]
        if len(hex_str)%2:
            hex_str = '0' + hex_str
        return big_or_little(hex_str)
<commit_msg>Fixed: Fixed8 remove float property<commit_after># -*- coding:utf-8 -*-
"""
Description:
    Fixed8
Usage:
    from AntShares.Fixed8 import Fixed8
"""

from decimal import Decimal as D
from AntShares.Helper import big_or_little

class Fixed8:
    """docstring for Fixed8"""
    def __init__(self, number):
        self.f = D(str(number))

    def getData(self):
        hex_str = hex(int(self.f*D('100000000')))[2:]
        if len(hex_str)%2:
            hex_str = '0' + hex_str
        return big_or_little(hex_str)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
DTI_QA
======

This interface assists in executing `Bennett Landman's DTI_QA <http://www.ncbi.nlm.nih.gov/pubmed/23637895>`_
toolkit.

TBD: More documentation here.

Because DTI_QA is built upon matlab, the generated commands are m-code.

Functions
+++++++++
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'

from v1 import dtiqa_mcode

__all__ = ['dtiqa_mcode']
<commit_msg>Fix py3 import issue<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
DTI_QA
======

This interface assists in executing `Bennett Landman's DTI_QA <http://www.ncbi.nlm.nih.gov/pubmed/23637895>`_
toolkit.

TBD: More documentation here.

Because DTI_QA is built upon matlab, the generated commands are m-code.

Functions
+++++++++
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'

from .v1 import dtiqa_mcode

__all__ = ['dtiqa_mcode']
<|endoftext|>


<commit_before>from setuptools import setup
import sys
import os
import imp
from setuptools import Extension
import platform

dirname = os.path.dirname(__file__)
path_version = os.path.join(dirname, "vaex/core/_version.py")
version = imp.load_source('version', path_version)

name = 'vaex'
author = "Maarten A. Breddels"
author_email = "maartenbreddels@gmail.com"
license = 'MIT'
version = version.__version__
url = 'https://www.github.com/maartenbreddels/vaex'
# TODO: can we do without requests and progressbar2?
# TODO: after python2 supports frops, future and futures can also be dropped
# TODO: would be nice to have astropy only as dep in vaex-astro
install_requires_core = ["numpy>=1.11", "astropy>=2", "aplus", "tabulate>=0.8.3",
                         "future>=0.15.2", "pyyaml", "progressbar2", "psutil>=1.2.1",
                         "requests", "six", "cloudpickle", 'pybind11>=2.2']
if sys.version_info[0] == 2:
    install_requires_core.append("futures>=2.2.0")
install_requires_viz = ["matplotlib>=1.3.1", ]
install_requires_astro = ["kapteyn"]

class get_numpy_include(object):
    """Helper class to determine the numpy include path
    The purpose of this class is to postpone importing numpy
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __init__(self):
        pass

    def __str__(self):
        import numpy as np
        return np.get_include()

class get_pybind_include(object):
    """Helper class to determine the pybind11 include path
    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __init__(self, user=False):
        self.user = user

    def __str__(self):
        import pybind11
        return pybind11.get_include(self.user)

if platform.system().lower() == 'windows':
    extra_compile_args = ["/EHsc"]
else:
    extra_compile_args = ["-std=c++11", "-mfpmath=sse", "-O3", "-funroll-loops"]
if sys.platform == 'darwin':
    extra_compile_args.append("-stdlib=libc++")
    extra_compile_args.append("-mmacosx-version-min=10.7")

# on windows (Conda-forge builds), the dirname is an absolute path
extension_vaexfast = Extension("vaex.vaexfast", [os.path.relpath(os.path.join(dirname, "src/vaexfast.cpp"))],
                               include_dirs=[get_numpy_include()],
                               extra_compile_args=extra_compile_args)
extension_strings = Extension("vaex.strings", [os.path.relpath(os.path.join(dirname, "src/strings.cpp"))],
                               include_dirs=[get_numpy_include(), get_pybind_include(),
                               get_pybind_include(user=True), 'vendor/string-view-lite/include'],
                               extra_compile_args=extra_compile_args)
extension_superutils = Extension("vaex.superutils", [os.path.relpath(os.path.join(dirname, "src/superutils.cpp"))],
                               include_dirs=[get_numpy_include(), get_pybind_include(),
                               get_pybind_include(user=True)],
                               extra_compile_args=extra_compile_args)

setup(name=name + '-core',
      version=version,
      description='Core of vaex',
      url=url,
      author=author,
      author_email=author_email,
      setup_requires=['numpy'],
      install_requires=install_requires_core,
      license=license,
      package_data={'vaex': ['test/files/*.fits', 'test/files/*.vot', 'test/files/*.hdf5']},
      packages=['vaex', 'vaex.core', 'vaex.file', 'vaex.test', 'vaex.ext', 'vaex.misc'],
      ext_modules=[extension_vaexfast, extension_strings, extension_superutils],
      zip_safe=False,
      entry_points={
          'console_scripts': ['vaex = vaex.__main__:main'],
          'gui_scripts': ['vaexgui = vaex.__main__:main']  # sometimes in osx, you need to run with this
      }
      )
<commit_msg>fix building osx<commit_after>from setuptools import setup
import sys
import os
import imp
from setuptools import Extension
import platform

dirname = os.path.dirname(__file__)
path_version = os.path.join(dirname, "vaex/core/_version.py")
version = imp.load_source('version', path_version)

name = 'vaex'
author = "Maarten A. Breddels"
author_email = "maartenbreddels@gmail.com"
license = 'MIT'
version = version.__version__
url = 'https://www.github.com/maartenbreddels/vaex'
# TODO: can we do without requests and progressbar2?
# TODO: after python2 supports frops, future and futures can also be dropped
# TODO: would be nice to have astropy only as dep in vaex-astro
install_requires_core = ["numpy>=1.11", "astropy>=2", "aplus", "tabulate>=0.8.3",
                         "future>=0.15.2", "pyyaml", "progressbar2", "psutil>=1.2.1",
                         "requests", "six", "cloudpickle", 'pybind11>=2.2']
if sys.version_info[0] == 2:
    install_requires_core.append("futures>=2.2.0")
install_requires_viz = ["matplotlib>=1.3.1", ]
install_requires_astro = ["kapteyn"]

if "MACOSX_DEPLOYMENT_TARGET" not in os.environ:
    os.environ["MACOSX_DEPLOYMENT_TARGET"] = "10.9"

class get_numpy_include(object):
    """Helper class to determine the numpy include path
    The purpose of this class is to postpone importing numpy
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __init__(self):
        pass

    def __str__(self):
        import numpy as np
        return np.get_include()

class get_pybind_include(object):
    """Helper class to determine the pybind11 include path
    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __init__(self, user=False):
        self.user = user

    def __str__(self):
        import pybind11
        return pybind11.get_include(self.user)

if platform.system().lower() == 'windows':
    extra_compile_args = ["/EHsc"]
else:
    extra_compile_args = ["-std=c++11", "-mfpmath=sse", "-O3", "-funroll-loops"]
if sys.platform == 'darwin':
    extra_compile_args.append("-mmacosx-version-min=10.9")

# on windows (Conda-forge builds), the dirname is an absolute path
extension_vaexfast = Extension("vaex.vaexfast", [os.path.relpath(os.path.join(dirname, "src/vaexfast.cpp"))],
                               include_dirs=[get_numpy_include()],
                               extra_compile_args=extra_compile_args)
extension_strings = Extension("vaex.strings", [os.path.relpath(os.path.join(dirname, "src/strings.cpp"))],
                               include_dirs=[get_numpy_include(), get_pybind_include(),
                               get_pybind_include(user=True), 'vendor/string-view-lite/include'],
                               extra_compile_args=extra_compile_args)
extension_superutils = Extension("vaex.superutils", [os.path.relpath(os.path.join(dirname, "src/superutils.cpp"))],
                               include_dirs=[get_numpy_include(), get_pybind_include(),
                               get_pybind_include(user=True)],
                               extra_compile_args=extra_compile_args)

setup(name=name + '-core',
      version=version,
      description='Core of vaex',
      url=url,
      author=author,
      author_email=author_email,
      setup_requires=['numpy'],
      install_requires=install_requires_core,
      license=license,
      package_data={'vaex': ['test/files/*.fits', 'test/files/*.vot', 'test/files/*.hdf5']},
      packages=['vaex', 'vaex.core', 'vaex.file', 'vaex.test', 'vaex.ext', 'vaex.misc'],
      ext_modules=[extension_vaexfast, extension_strings, extension_superutils],
      zip_safe=False,
      entry_points={
          'console_scripts': ['vaex = vaex.__main__:main'],
          'gui_scripts': ['vaexgui = vaex.__main__:main']  # sometimes in osx, you need to run with this
      }
      )
<|endoftext|>


<commit_before>#!/usr/bin/env python
import subprocess
import yaml
import sys
import logging
import click
import os
import json
import boto3
import backoff
from botocore.exceptions import ClientError

LOGGER = logging.getLogger(__name__)
logging.basicConfig()
global_list = []
MAX_TRIES = 5

class SESBotoWrapper:
    def __init__(self, **kwargs):
        self.client = boto3.client("ses", **kwargs)

    @backoff.on_exception(backoff.expo,
                          ClientError,
                          max_tries=MAX_TRIES)
    def send_email(self, *args, **kwargs):
        return self.client.send_email(*args, **kwargs)

def parse_yaml(file_name):
    with open(file_name, 'r') as stream:
        try:
            charts_name = yaml.safe_load(stream)
            if "dependencies" in charts_name:
                app_list = charts_name["dependencies"]
                for key in app_list:
                    add_helm(key["repository"], key["name"])
                update_helm()
                for key in app_list:
                    repo_name = get_repo_name(key["repository"])
                    check_version(charts_name["name"], key["name"], repo_name, key["version"])
        except yaml.YAMLError as exc:
            LOGGER.error("error in configuration file: %s" % str(exc))
            sys.exit(1)
        except KeyError as e:
            print(f"I got a KeyError - reason {str(e)}")

def add_helm(repo_url, repo_name):
    try:
        cmd_add = 'helm repo add ' + repo_name + " " + repo_url
        subprocess.check_output(cmd_add, shell=True)
    except subprocess.CalledProcessError as e:
        print(e.output)

def update_helm():
    cmd_update = 'helm repo update'
    subprocess.check_output(cmd_update, shell=True)

def get_repo_name(repo_url):
    try:
        get_repo_cmd = 'helm repo list -o json'
        repositories = subprocess.check_output(get_repo_cmd, shell=True).strip()
        repo_list = json.loads(repositories.decode())
        for repo in repo_list:
            if repo["url"] == repo_url:
                repo['name']
    except subprocess.CalledProcessError as e:
        print(e.output)

def check_version(chart_name, app_name, repo_name, app_version):
    cmd = 'helm show chart ' + repo_name + "/" + app_name + ' | grep version | tail -1'
    output = subprocess.check_output(cmd, shell=True)
    latest_version = output.decode().split(": ")[-1].rstrip()
    if not compare_version(app_version, latest_version):
        temp_dict = {
            chart_name+"/"+app_name: {
                "current_version": app_version,
                "latest_version": latest_version
            },
        }
        global_list.append(temp_dict)

def compare_version(current_version, latest_version):
    return True if current_version == latest_version else False

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            parse_yaml(os.path.join(root, name))

def send_an_email(to_addr, from_addr, app_list, region):
    ses_client = SESBotoWrapper(region_name=region)

    message = """

Hello,

Updates are available for the following helm charts

        App Name
        Current version
        Latest Version

    """
    for apps in app_list:
        for data in apps:
            message += """

{AppName}
                {CurrentVersion}
                {LatestVersion}

""".format(
                AppName=data,
                CurrentVersion=apps[data]["current_version"],
                LatestVersion=apps[data]["latest_version"]
            )

    message += """
"""
    print(("Sending the following as email to {}".format(to_addr)))
    print(message)
    ses_client.send_email(
        Source=from_addr,
        Destination={
            'ToAddresses': [
                to_addr
            ]
        },
        Message={
            'Subject': {
                'Data': 'Updates available for helms charts',
                'Charset': 'utf-8'
            },
            'Body': {
                'Html':{
                    'Data': message,
                    'Charset': 'utf-8'
                }
            }
        }
    )

@click.command()
@click.option('--file-name', required=True, help='Filename which have helm chart details.')
@click.option('--file-path', required=True, help='File path where helm chart file exists.')
@click.option('--region', multiple=True, help='Default AWS region')
@click.option('--recipient', multiple=True, help='Recipient Email address')
@click.option('--sender', multiple=True, help='Sender email address')
def controller(file_name, file_path, region, recipient, sender):
    find(file_name, file_path)
    if len(global_list) > 0:
        send_an_email(recipient[0], sender[0], global_list, region[0])

if __name__ == "__main__":
    controller()
<commit_msg>chore: Fix helm script<commit_after>#!/usr/bin/env python
import subprocess
import yaml
import sys
import logging
import click
import os
import json
import boto3
import backoff
from botocore.exceptions import ClientError

LOGGER = logging.getLogger(__name__)
logging.basicConfig()
global_list = []
MAX_TRIES = 5

class SESBotoWrapper:
    def __init__(self, **kwargs):
        self.client = boto3.client("ses", **kwargs)

    @backoff.on_exception(backoff.expo,
                          ClientError,
                          max_tries=MAX_TRIES)
    def send_email(self, *args, **kwargs):
        return self.client.send_email(*args, **kwargs)

def parse_yaml(file_name):
    with open(file_name, 'r') as stream:
        try:
            charts_name = yaml.safe_load(stream)
            if "dependencies" in charts_name:
                app_list = charts_name["dependencies"]
                for key in app_list:
                    add_helm(key["repository"], key["name"])
                update_helm()
                for key in app_list:
                    repo_name = get_repo_name(key["repository"])
                    check_version(charts_name["name"], key["name"], repo_name, key["version"])
        except yaml.YAMLError as exc:
            LOGGER.error("error in configuration file: %s" % str(exc))
            sys.exit(1)
        except KeyError as e:
            print(f"I got a KeyError - reason {str(e)}")

def add_helm(repo_url, repo_name):
    try:
        cmd_add = 'helm repo add ' + repo_name + " " + repo_url
        subprocess.check_output(cmd_add, shell=True)
    except subprocess.CalledProcessError as e:
        print(e.output)

def update_helm():
    cmd_update = 'helm repo update'
    subprocess.check_output(cmd_update, shell=True)

def get_repo_name(repo_url):
    try:
        get_repo_cmd = 'helm repo list -o json'
        repositories = subprocess.check_output(get_repo_cmd, shell=True).strip()
        repo_list = json.loads(repositories.decode())
        for repo in repo_list:
            if repo["url"] == repo_url:
                return repo['name']
    except subprocess.CalledProcessError as e:
        print(e.output)

def check_version(chart_name, app_name, repo_name, app_version):
    cmd = 'helm show chart ' + repo_name + "/" + app_name + ' | grep version | tail -1'
    output = subprocess.check_output(cmd, shell=True)
    latest_version = output.decode().split(": ")[-1].rstrip()
    if not compare_version(app_version, latest_version):
        temp_dict = {
            chart_name+"/"+app_name: {
                "current_version": app_version,
                "latest_version": latest_version
            },
        }
        global_list.append(temp_dict)

def compare_version(current_version, latest_version):
    return True if current_version == latest_version else False

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            parse_yaml(os.path.join(root, name))

def send_an_email(to_addr, from_addr, app_list, region):
    ses_client = SESBotoWrapper(region_name=region)

    message = """

Hello,

Updates are available for the following helm charts

        App Name
        Current version
        Latest Version

    """
    for apps in app_list:
        for data in apps:
            message += """

{AppName}
                {CurrentVersion}
                {LatestVersion}

""".format(
                AppName=data,
                CurrentVersion=apps[data]["current_version"],
                LatestVersion=apps[data]["latest_version"]
            )

    message += """
"""
    print(("Sending the following as email to {}".format(to_addr)))
    print(message)
    ses_client.send_email(
        Source=from_addr,
        Destination={
            'ToAddresses': [
                to_addr
            ]
        },
        Message={
            'Subject': {
                'Data': 'Updates available for helms charts',
                'Charset': 'utf-8'
            },
            'Body': {
                'Html':{
                    'Data': message,
                    'Charset': 'utf-8'
                }
            }
        }
    )

@click.command()
@click.option('--file-name', required=True, help='Filename which have helm chart details.')
@click.option('--file-path', required=True, help='File path where helm chart file exists.')
@click.option('--region', multiple=True, help='Default AWS region')
@click.option('--recipient', multiple=True, help='Recipient Email address')
@click.option('--sender', multiple=True, help='Sender email address')
def controller(file_name, file_path, region, recipient, sender):
    find(file_name, file_path)
    if len(global_list) > 0:
        send_an_email(recipient[0], sender[0], global_list, region[0])

if __name__ == "__main__":
    controller()
<|endoftext|>


<commit_before># ------------------------------------------------
# built-ins
import unittest

# local
from .base import TestPostgapBase
# ------------------------------------------------

class TestPostgapPerDisease(TestPostgapBase):

    def setUp(self):
        self.per_disease = self.pg.groupby('disease_efo_id')

    def test_disease_efo_and_name_combination_unique(self):
        self.assert_groupby_series_is_unique_per_group(
            self.per_disease.disease_name
        )

if __name__ == '__main__':
    unittest.main()
<commit_msg>Rename test<commit_after># ------------------------------------------------
# built-ins
import unittest

# local
from .base import TestPostgapBase
# ------------------------------------------------

class TestPostgapPerDisease(TestPostgapBase):

    def setUp(self):
        self.per_disease = self.pg.groupby('disease_efo_id')

    def test_each_disease_efo_id_has_unique_disease_name(self):
        self.assert_groupby_series_is_unique_per_group(
            self.per_disease.disease_name
        )

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Set of known *current* country and territory names.

Legacy (duplicate) names for some countries have been removed from the
original list.  Also missing are the following U.S. OFAC embargoed and
Commerce Department export-controlled countries:

  Cuba, Iran, Myanmar (formerly Burma), North Korea, Sudan, Syria
"""

__authors__ = [
  '"Daniel Hans" <daniel.m.hans@gmail.com>',
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  '"Todd Larsen" <tlarsen@google.com>',
]

COUNTRY_INFO = {
    "Afghanistan, Islamic State of": ('.af', 'Asia'),
    "Albania": ('.al', 'Europe'),
    "Algeria": ('.dz', 'Africa'),
    "American Samoa": ('.as', 'Australia'),
    "Andorra, Principality of": ('.ad', 'Europe'),
    "Angola": ('.ao', 'Africa'),
    "Anguilla": ('.ai', 'North America'),
    "Antarctica": ('.aq', 'Europe'),
    "Antigua and Barbuda": ('.ag', 'North America'),
    "Argentina": ('.ar', 'South America'),
    "Armenia": ('.am', 'Asia'),
    "Aruba": ('.aw', 'North America'),
    "Australia": ('.au', 'Australia'),
    "Austria": ('.at', 'Europe'),
    "Azerbaidjan": ('.az', 'Asia'),
    "Bahamas": ('.bs', 'North America'),
    "Bahrain": ('.bh', 'Asia'),
    "Bangladesh": ('.bd', 'Asia'),
    "Barbados": ('.bb', 'North America'),
    "Belarus": ('.by', 'Europe'),
    "Belgium": ('.be', 'Europe'),
    "Belize": ('.bz', 'North America'),
    "Benin": ('.bj', 'Africa'),
    "Bermuda": ('.bm', 'North America'),
    "Bhutan": ('.bt', 'Asia'),
    "Bolivia": ('.bo', 'South America'),
    "Bosnia-Herzegovina": ('.ba', 'Europe'),
    "Botswana": ('.bw', 'Africa'),
    "Bouvet Island": ('.bv', 'Europe'),
    "Brazil": ('.br', 'South America'),
    "British Indian Ocean Territory": ('.io', 'Asia'),
    "Brunei Darussalam": ('.bn', 'Asia'),
    "Bulgaria": ('', 'Europe'),
    "Burkina Faso": ('.bg', 'Africa'),
    "Burundi": ('.bi', 'Africa'),
    "Cambodia, Kingdom of": ('.kh', 'Asia'),
    "Cameroon": ('.cm', 'Africa'),
    "Canada": ('.ca', 'North America'),
    "Cape Verde": ('.cv', 'Africa'),
    "Cayman Islands": ('.ky', 'North America'),
    "Central African Republic": ('.cf', 'Africa'),
    "Chad": ('.td', 'Africa'),
    "Chile": ('.cl', 'South America'),
    "China": ('.cn', 'Asia'),
    "Christmas Island": ('.cx', 'Australia'),
    "Cocos (Keeling) Islands": ('.cc', 'Australia'),
    "Colombia": ('.co', 'South America'),
    "Comoros": ('.km', 'Africa'),
    "Congo": ('.cg', 'Africa'),
    "Congo, Democratic Republic of the": ('.cd', 'Africa'),
    "Cook Islands": ('.ck', 'Australia'),
    "Costa Rica": ('.cr', 'North America'),
    "Croatia": ('.hr', 'Europe'),
    "Cyprus": ('.cy', 'Asia'),
    "Czech Republic": ('.cz', 'Europe'),
    "Denmark": ('.dk', 'Europe'),
    "Djibouti": ('.dj', 'Africa'),
    "Dominica": ('.dm', 'North America'),
    "Dominican Republic": ('.do', 'North America'),
    "East Timor": ('.tl', 'Asia'),
    "Ecuador": ('.ec', 'South America'),
    "Egypt": ('.eg', 'Africa'),
    "El Salvador": ('.sv', 'North America'),
    "Equatorial Guinea": ('.gq', 'Africa'),
    "Eritrea": ('.er', 'Africa'),
    "Estonia": ('.ee', 'Europe'),
    "Ethiopia": ('.et', 'Africa'),
    "Falkland Islands": ('.fk', 'South America'),
    "Faroe Islands": ('.fo', 'Europe'),
    "Fiji": ('.fj', 'Australia'),
    "Finland": ('.fi', 'Europe'),
    "France": ('.fr', 'Europe'),
    "French Guyana": ('.gf', 'South America'),
    "French Southern Territories": ('.tf', 'Africa'),
    "Gabon": ('.ga', 'Africa'),
    "Gambia": ('.gm', 'Africa'),
    "Georgia": ('.ge', 'Asia'),
    "Germany": ('.de', 'Europe'),
    "Ghana": ('.gh', 'Africa'),
    "Gibraltar": ('.gi', 'Europe'),
    "Greece": ('.gr', 'Europe'),
    "Greenland": ('.gl', 'North America'),
    "Grenada": ('.gd', 'North America'),
    "Guadeloupe (French)": ('.gp', 'North America'),
    "Guam (USA)": ('.gu', 'Australia'),
    "Guatemala": ('.gt', 'North America'),
    "Guinea": ('.gn', 'Africa'),
    "Guinea Bissau": ('.gw', 'Africa'),
    "Guyana": ('.gy', 'South America'),
    "Haiti": ('.ht', 'North America'),
    "Heard and McDonald Islands": ('.hm', 'Australia'),
    "Holy See (Vatican City State)": ('.va', 'Europe'),
    "Honduras": ('.hn', 'North America'),
    "Hong Kong": ('.hk', 'Asia'),
    "Hungary": ('.hu', 'Europe'),
    "Iceland": ('.is', 'Europe'),
    "India": ('.in', 'Asia'),
    "Indonesia": ('.id', 'Asia'),
    "Iraq": ('.iq', 'Asia'),
    "Ireland": ('.ie', 'Europe'),
    "Israel": ('.il', 'Asia'),
    "Italy": ('.it', 'Europe'),
    "Ivory Coast": ('.ci', 'Africa'),
    "Jamaica": ('.jm', 'North America'),
    "Japan": ('.jp', 'Asia'),
    "Jordan": ('.jo', 'Asia'),
    "Kazakhstan": ('.kz', 'Asia'),
    "Kenya": ('.ke', 'Africa'),
    "Kiribati": ('.ki', 'Australia'),
    "Kuwait": ('.kw', 'Asia'),
    "Kyrgyz Republic (Kyrgyzstan)": ('.kg', 'Asia'),
    "Laos": ('.la', 'Asia'),
    "Latvia": ('.lv', 'Europe'),
    "Lebanon": ('.lb', 'Asia'),
    "Lesotho": ('.ls', 'Africa'),
    "Liberia": ('.lr', 'Africa'),
    "Libya": ('.ly', 'Africa'),
    "Liechtenstein": ('.li', 'Europe'),
    "Lithuania": ('.lt', 'Europe'),
    "Luxembourg": ('.lu', 'Europe'),
    "Macau": ('.mo', 'Asia'),
    "Macedonia": ('.mk', 'Europe'),
    "Madagascar": ('.mg', 'Africa'),
    "Malawi": ('.mw', 'Africa'),
    "Malaysia": ('.my', 'Asia'),
    "Maldives": ('.mv', 'Asia'),
    "Mali": ('.ml', 'Africa'),
    "Malta": ('.mt', 'Europe'),
    "Marshall Islands": ('.mh', 'Australia'),
    "Martinique (French)": ('.mq', 'North America'),
    "Mauritania": ('.mr', 'Africa'),
    "Mauritius": ('.mu', 'Africa'),
    "Mayotte": ('.yt', 'Africa'),
    "Mexico": ('.mx', 'North America'),
    "Micronesia": ('.fm', 'Australia'),
    "Moldavia": ('.md', 'Europe'),
    "Monaco": ('.mc', 'Europe'),
    "Mongolia": ('.mn', 'Asia'),
    "Montenegro": ('.me', 'Europe'),
    "Montserrat": ('.ms', 'North America'),
    "Morocco": ('.ma', 'Africa'),
    "Mozambique": ('.mz', 'Africa'),
    "Namibia": ('.na', 'Africa'),
    "Nauru": ('.nr', 'Australia'),
    "Nepal": ('.np', 'Asia'),
    "Netherlands": ('.nl', 'Europe'),
    "Netherlands Antilles": ('.an', 'North America'),
    "New Caledonia (French)": ('.nc', 'Australia'),
    "New Zealand": ('.nz', 'Australia'),
    "Nicaragua": ('.ni', 'North America'),
    "Niger": ('.ne', 'Africa'),
    "Nigeria": ('.ng', 'Africa'),
    "Niue": ('.nu', 'Australia'),
    "Northern Mariana Islands": ('.mp', 'Australia'),
    "Norway": ('.no', 'Europe'),
    "Oman": ('.om', 'Asia'),
    "Pakistan": ('.pk', 'Asia'),
    "Palau": ('.pw', 'Australia'),
    "Palestinian Territories": ('.ps', 'Asia'),
    "Panama": ('.pa', 'North America'),
    "Papua New Guinea": ('.pg', 'Australia'),
    "Paraguay": ('.py', 'South America'),
    "Peru": ('.pe', 'South America'),
    "Philippines": ('.ph', 'Asia'),
    "Pitcairn Island": ('.pn', 'South America'),
    "Poland": ('.pl', 'Europe'),
    "Polynesia (French)": ('.pf', 'Australia'),
    "Portugal": ('.pt', 'Europe'),
    "Puerto Rico": ('.pr', 'North America'),
    "Qatar": ('.qa', 'Asia'),
    "Reunion (French)": ('.re', 'Africa'),
    "Romania": ('.ro', 'Europe'),
    "Russian Federation": ('.ru', 'Europe'),
    "Rwanda": ('.rw', 'Africa'),
    "South Georgia & South Sandwich Islands": ('.gs', 'South America'),
    "Saint Helena": ('.sh', 'Africa'),
    "Saint Kitts & Nevis Anguilla": ('.kn', 'North America'),
    "Saint Lucia": ('.lc', 'North America'),
    "Saint Pierre and Miquelon": ('.pm', 'North America'),
    "Saint Tome (Sao Tome) and Principe": ('.st', 'Africa'),
    "Saint Vincent & Grenadines": ('.vc', 'North America'),
    "Samoa": ('.ws', 'Australia'),
    "San Marino": ('.sm', 'Europe'),
    "Saudi Arabia": ('.sa', 'Asia'),
    "Senegal": ('.sn', 'Africa'),
    "Serbia": ('.rs', 'Europe'),
    "Seychelles": ('.sc', 'Africa'),
    "Sierra Leone": ('.sl', 'Africa'),
    "Singapore": ('.sg', 'Asia'),
    "Slovak Republic": ('.sk', 'Europe'),
    "Slovenia": ('.si', 'Europe'),
    "Solomon Islands": ('.sb', 'Australia'),
    "Somalia": ('.so', 'Africa'),
    "South Africa": ('.za', 'Africa'),
    "South Korea": ('.kr', 'Asia'),
    "Spain": ('.es', 'Europe'),
    "Sri Lanka": ('.lk', 'Asia'),
    "Suriname": ('.sr', 'South America'),
    "Svalbard and Jan Mayen Islands": ('.sj', 'Europe'),
    "Swaziland": ('.sz', 'Africa'),
    "Sweden": ('.se', 'Europe'),
    "Switzerland": ('.ch', 'Europe'),
    "Tadjikistan": ('.tj', 'Asia'),
    "Taiwan": ('.tw', 'Asia'),
    "Tanzania": ('.tz', 'Africa'),
    "Thailand": ('.th', 'Asia'),
    "Togo": ('.tg', 'Africa'),
    "Tokelau": ('.tk', 'Australia'),
    "Tonga": ('.to', 'Australia'),
    "Trinidad and Tobago": ('.tt', 'North America'),
    "Tunisia": ('.tn', 'Africa'),
    "Turkey": ('.tr', 'Asia'),
    "Turkmenistan": ('.tm', 'Asia'),
    "Turks and Caicos Islands": ('.tc', 'North America'),
    "Tuvalu": ('.tv', 'Australia'),
    "USA Minor Outlying Islands": ('.um', 'North America'),
    "Uganda": ('.ug', 'Africa'),
    "Ukraine": ('.ua', 'Europe'),
    "United Arab Emirates": ('.ae', 'Asia'),
    "United Kingdom": ('.uk', 'Europe'),
    "United States": ('.us', 'North America'),
    "Uruguay": ('.uy', 'South America'),
    "Uzbekistan": ('.uz', 'Asia'),
    "Vanuatu": ('.vu', 'Australia'),
    "Venezuela": ('.ve', 'South America'),
    "Vietnam": ('.vn', 'Asia'),
    "Virgin Islands (British)": ('.vg', 'North America'),
    "Virgin Islands (USA)": ('.vi', 'North America'),
    "Wallis and Futuna Islands": ('.wf', 'Australia'),
    "Western Sahara": ('.eh', 'Africa'),
    "Yemen": ('.ye', 'Asia'),
    "Zambia": ('.zm', 'Africa'),
    "Zimbabwe": ('.zw', 'Africa'),
    }

# List of all countries and territories
COUNTRIES_AND_TERRITORIES = sorted(COUNTRY_INFO.keys())

# Mapping of countries to their CCTLD
COUNTRIES_TO_CCTLD = dict((k, c) for k, (c, _) in COUNTRY_INFO.items())

# Mapping of countries to their continent
COUNTRIES_TO_CONTINENT = dict((k, c) for k, (_, c) in COUNTRY_INFO.items())
<commit_msg>Fixed Ivory Coast rename that was introduced in r74f0972f52.<commit_after>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Set of known *current* country and territory names.

Legacy (duplicate) names for some countries have been removed from the
original list.  Also missing are the following U.S. OFAC embargoed and
Commerce Department export-controlled countries:

  Cuba, Iran, Myanmar (formerly Burma), North Korea, Sudan, Syria
"""

__authors__ = [
  '"Daniel Hans" <daniel.m.hans@gmail.com>',
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  '"Todd Larsen" <tlarsen@google.com>',
]

COUNTRY_INFO = {
    "Afghanistan, Islamic State of": ('.af', 'Asia'),
    "Albania": ('.al', 'Europe'),
    "Algeria": ('.dz', 'Africa'),
    "American Samoa": ('.as', 'Australia'),
    "Andorra, Principality of": ('.ad', 'Europe'),
    "Angola": ('.ao', 'Africa'),
    "Anguilla": ('.ai', 'North America'),
    "Antarctica": ('.aq', 'Europe'),
    "Antigua and Barbuda": ('.ag', 'North America'),
    "Argentina": ('.ar', 'South America'),
    "Armenia": ('.am', 'Asia'),
    "Aruba": ('.aw', 'North America'),
    "Australia": ('.au', 'Australia'),
    "Austria": ('.at', 'Europe'),
    "Azerbaidjan": ('.az', 'Asia'),
    "Bahamas": ('.bs', 'North America'),
    "Bahrain": ('.bh', 'Asia'),
    "Bangladesh": ('.bd', 'Asia'),
    "Barbados": ('.bb', 'North America'),
    "Belarus": ('.by', 'Europe'),
    "Belgium": ('.be', 'Europe'),
    "Belize": ('.bz', 'North America'),
    "Benin": ('.bj', 'Africa'),
    "Bermuda": ('.bm', 'North America'),
    "Bhutan": ('.bt', 'Asia'),
    "Bolivia": ('.bo', 'South America'),
    "Bosnia-Herzegovina": ('.ba', 'Europe'),
    "Botswana": ('.bw', 'Africa'),
    "Bouvet Island": ('.bv', 'Europe'),
    "Brazil": ('.br', 'South America'),
    "British Indian Ocean Territory": ('.io', 'Asia'),
    "Brunei Darussalam": ('.bn', 'Asia'),
    "Bulgaria": ('', 'Europe'),
    "Burkina Faso": ('.bg', 'Africa'),
    "Burundi": ('.bi', 'Africa'),
    "Cambodia, Kingdom of": ('.kh', 'Asia'),
    "Cameroon": ('.cm', 'Africa'),
    "Canada": ('.ca', 'North America'),
    "Cape Verde": ('.cv', 'Africa'),
    "Cayman Islands": ('.ky', 'North America'),
    "Central African Republic": ('.cf', 'Africa'),
    "Chad": ('.td', 'Africa'),
    "Chile": ('.cl', 'South America'),
    "China": ('.cn', 'Asia'),
    "Christmas Island": ('.cx', 'Australia'),
    "Cocos (Keeling) Islands": ('.cc', 'Australia'),
    "Colombia": ('.co', 'South America'),
    "Comoros": ('.km', 'Africa'),
    "Congo": ('.cg', 'Africa'),
    "Congo, Democratic Republic of the": ('.cd', 'Africa'),
    "Cook Islands": ('.ck', 'Australia'),
    "Costa Rica": ('.cr', 'North America'),
    "Croatia": ('.hr', 'Europe'),
    "Cyprus": ('.cy', 'Asia'),
    "Czech Republic": ('.cz', 'Europe'),
    "Denmark": ('.dk', 'Europe'),
    "Djibouti": ('.dj', 'Africa'),
    "Dominica": ('.dm', 'North America'),
    "Dominican Republic": ('.do', 'North America'),
    "East Timor": ('.tl', 'Asia'),
    "Ecuador": ('.ec', 'South America'),
    "Egypt": ('.eg', 'Africa'),
    "El Salvador": ('.sv', 'North America'),
    "Equatorial Guinea": ('.gq', 'Africa'),
    "Eritrea": ('.er', 'Africa'),
    "Estonia": ('.ee', 'Europe'),
    "Ethiopia": ('.et', 'Africa'),
    "Falkland Islands": ('.fk', 'South America'),
    "Faroe Islands": ('.fo', 'Europe'),
    "Fiji": ('.fj', 'Australia'),
    "Finland": ('.fi', 'Europe'),
    "France": ('.fr', 'Europe'),
    "French Guyana": ('.gf', 'South America'),
    "French Southern Territories": ('.tf', 'Africa'),
    "Gabon": ('.ga', 'Africa'),
    "Gambia": ('.gm', 'Africa'),
    "Georgia": ('.ge', 'Asia'),
    "Germany": ('.de', 'Europe'),
    "Ghana": ('.gh', 'Africa'),
    "Gibraltar": ('.gi', 'Europe'),
    "Greece": ('.gr', 'Europe'),
    "Greenland": ('.gl', 'North America'),
    "Grenada": ('.gd', 'North America'),
    "Guadeloupe (French)": ('.gp', 'North America'),
    "Guam (USA)": ('.gu', 'Australia'),
    "Guatemala": ('.gt', 'North America'),
    "Guinea": ('.gn', 'Africa'),
    "Guinea Bissau": ('.gw', 'Africa'),
    "Guyana": ('.gy', 'South America'),
    "Haiti": ('.ht', 'North America'),
    "Heard and McDonald Islands": ('.hm', 'Australia'),
    "Holy See (Vatican City State)": ('.va', 'Europe'),
    "Honduras": ('.hn', 'North America'),
    "Hong Kong": ('.hk', 'Asia'),
    "Hungary": ('.hu', 'Europe'),
    "Iceland": ('.is', 'Europe'),
    "India": ('.in', 'Asia'),
    "Indonesia": ('.id', 'Asia'),
    "Iraq": ('.iq', 'Asia'),
    "Ireland": ('.ie', 'Europe'),
    "Israel": ('.il', 'Asia'),
    "Italy": ('.it', 'Europe'),
    "Ivory Coast (Cote D'Ivoire)": ('.ci', 'Africa'),
    "Jamaica": ('.jm', 'North America'),
    "Japan": ('.jp', 'Asia'),
    "Jordan": ('.jo', 'Asia'),
    "Kazakhstan": ('.kz', 'Asia'),
    "Kenya": ('.ke', 'Africa'),
    "Kiribati": ('.ki', 'Australia'),
    "Kuwait": ('.kw', 'Asia'),
    "Kyrgyz Republic (Kyrgyzstan)": ('.kg', 'Asia'),
    "Laos": ('.la', 'Asia'),
    "Latvia": ('.lv', 'Europe'),
    "Lebanon": ('.lb', 'Asia'),
    "Lesotho": ('.ls', 'Africa'),
    "Liberia": ('.lr', 'Africa'),
    "Libya": ('.ly', 'Africa'),
    "Liechtenstein": ('.li', 'Europe'),
    "Lithuania": ('.lt', 'Europe'),
    "Luxembourg": ('.lu', 'Europe'),
    "Macau": ('.mo', 'Asia'),
    "Macedonia": ('.mk', 'Europe'),
    "Madagascar": ('.mg', 'Africa'),
    "Malawi": ('.mw', 'Africa'),
    "Malaysia": ('.my', 'Asia'),
    "Maldives": ('.mv', 'Asia'),
    "Mali": ('.ml', 'Africa'),
    "Malta": ('.mt', 'Europe'),
    "Marshall Islands": ('.mh', 'Australia'),
    "Martinique (French)": ('.mq', 'North America'),
    "Mauritania": ('.mr', 'Africa'),
    "Mauritius": ('.mu', 'Africa'),
    "Mayotte": ('.yt', 'Africa'),
    "Mexico": ('.mx', 'North America'),
    "Micronesia": ('.fm', 'Australia'),
    "Moldavia": ('.md', 'Europe'),
    "Monaco": ('.mc', 'Europe'),
    "Mongolia": ('.mn', 'Asia'),
    "Montenegro": ('.me', 'Europe'),
    "Montserrat": ('.ms', 'North America'),
    "Morocco": ('.ma', 'Africa'),
    "Mozambique": ('.mz', 'Africa'),
    "Namibia": ('.na', 'Africa'),
    "Nauru": ('.nr', 'Australia'),
    "Nepal": ('.np', 'Asia'),
    "Netherlands": ('.nl', 'Europe'),
    "Netherlands Antilles": ('.an', 'North America'),
    "New Caledonia (French)": ('.nc', 'Australia'),
    "New Zealand": ('.nz', 'Australia'),
    "Nicaragua": ('.ni', 'North America'),
    "Niger": ('.ne', 'Africa'),
    "Nigeria": ('.ng', 'Africa'),
    "Niue": ('.nu', 'Australia'),
    "Northern Mariana Islands": ('.mp', 'Australia'),
    "Norway": ('.no', 'Europe'),
    "Oman": ('.om', 'Asia'),
    "Pakistan": ('.pk', 'Asia'),
    "Palau": ('.pw', 'Australia'),
    "Palestinian Territories": ('.ps', 'Asia'),
    "Panama": ('.pa', 'North America'),
    "Papua New Guinea": ('.pg', 'Australia'),
    "Paraguay": ('.py', 'South America'),
    "Peru": ('.pe', 'South America'),
    "Philippines": ('.ph', 'Asia'),
    "Pitcairn Island": ('.pn', 'South America'),
    "Poland": ('.pl', 'Europe'),
    "Polynesia (French)": ('.pf', 'Australia'),
    "Portugal": ('.pt', 'Europe'),
    "Puerto Rico": ('.pr', 'North America'),
    "Qatar": ('.qa', 'Asia'),
    "Reunion (French)": ('.re', 'Africa'),
    "Romania": ('.ro', 'Europe'),
    "Russian Federation": ('.ru', 'Europe'),
    "Rwanda": ('.rw', 'Africa'),
    "South Georgia & South Sandwich Islands": ('.gs', 'South America'),
    "Saint Helena": ('.sh', 'Africa'),
    "Saint Kitts & Nevis Anguilla": ('.kn', 'North America'),
    "Saint Lucia": ('.lc', 'North America'),
    "Saint Pierre and Miquelon": ('.pm', 'North America'),
    "Saint Tome (Sao Tome) and Principe": ('.st', 'Africa'),
    "Saint Vincent & Grenadines": ('.vc', 'North America'),
    "Samoa": ('.ws', 'Australia'),
    "San Marino": ('.sm', 'Europe'),
    "Saudi Arabia": ('.sa', 'Asia'),
    "Senegal": ('.sn', 'Africa'),
    "Serbia": ('.rs', 'Europe'),
    "Seychelles": ('.sc', 'Africa'),
    "Sierra Leone": ('.sl', 'Africa'),
    "Singapore": ('.sg', 'Asia'),
    "Slovak Republic": ('.sk', 'Europe'),
    "Slovenia": ('.si', 'Europe'),
    "Solomon Islands": ('.sb', 'Australia'),
    "Somalia": ('.so', 'Africa'),
    "South Africa": ('.za', 'Africa'),
    "South Korea": ('.kr', 'Asia'),
    "Spain": ('.es', 'Europe'),
    "Sri Lanka": ('.lk', 'Asia'),
    "Suriname": ('.sr', 'South America'),
    "Svalbard and Jan Mayen Islands": ('.sj', 'Europe'),
    "Swaziland": ('.sz', 'Africa'),
    "Sweden": ('.se', 'Europe'),
    "Switzerland": ('.ch', 'Europe'),
    "Tadjikistan": ('.tj', 'Asia'),
    "Taiwan": ('.tw', 'Asia'),
    "Tanzania": ('.tz', 'Africa'),
    "Thailand": ('.th', 'Asia'),
    "Togo": ('.tg', 'Africa'),
    "Tokelau": ('.tk', 'Australia'),
    "Tonga": ('.to', 'Australia'),
    "Trinidad and Tobago": ('.tt', 'North America'),
    "Tunisia": ('.tn', 'Africa'),
    "Turkey": ('.tr', 'Asia'),
    "Turkmenistan": ('.tm', 'Asia'),
    "Turks and Caicos Islands": ('.tc', 'North America'),
    "Tuvalu": ('.tv', 'Australia'),
    "USA Minor Outlying Islands": ('.um', 'North America'),
    "Uganda": ('.ug', 'Africa'),
    "Ukraine": ('.ua', 'Europe'),
    "United Arab Emirates": ('.ae', 'Asia'),
    "United Kingdom": ('.uk', 'Europe'),
    "United States": ('.us', 'North America'),
    "Uruguay": ('.uy', 'South America'),
    "Uzbekistan": ('.uz', 'Asia'),
    "Vanuatu": ('.vu', 'Australia'),
    "Venezuela": ('.ve', 'South America'),
    "Vietnam": ('.vn', 'Asia'),
    "Virgin Islands (British)": ('.vg', 'North America'),
    "Virgin Islands (USA)": ('.vi', 'North America'),
    "Wallis and Futuna Islands": ('.wf', 'Australia'),
    "Western Sahara": ('.eh', 'Africa'),
    "Yemen": ('.ye', 'Asia'),
    "Zambia": ('.zm', 'Africa'),
    "Zimbabwe": ('.zw', 'Africa'),
    }

# List of all countries and territories
COUNTRIES_AND_TERRITORIES = sorted(COUNTRY_INFO.keys())

# Mapping of countries to their CCTLD
COUNTRIES_TO_CCTLD = dict((k, c) for k, (c, _) in COUNTRY_INFO.items())

# Mapping of countries to their continent
COUNTRIES_TO_CONTINENT = dict((k, c) for k, (_, c) in COUNTRY_INFO.items())
<|endoftext|>


<commit_before>#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#  http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

import collections

S2N_SSLv3 = 30
S2N_TLS10 = 31
S2N_TLS11 = 32
S2N_TLS12 = 33

# namedtuple makes iterating through ciphers across libraries easier.
S2N_CIPHER = collections.namedtuple('S2N_CIPHER', 'openssl_name gnutls_priority_str min_tls_vers openssl_1_1_0_compatible')

# Specifying a single cipher suite in GnuTLS requires specifying a "priority string" that removes all cipher suites,
# and then adds each algorithm(kx,auth,enc,mac) for a given suite. See https://www.gnutls.org/manual/html_node/Priority-Strings.html
S2N_GNUTLS_PRIORITY_PREFIX="NONE:+COMP-NULL:+CTYPE-ALL:+CURVE-ALL:+SIGN-ALL"

S2N_CIPHERS= [
    S2N_CIPHER("DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+3DES-CBC:+SHA1", S2N_SSLv3, False),
    S2N_CIPHER("EDH-RSA-DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+3DES-CBC:+SHA1", S2N_SSLv3, False),
    S2N_CIPHER("AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("DHE-RSA-AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("DHE-RSA-AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("AES256-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES256-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-256-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("AES256-GCM-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+3DES-CBC:+SHA1", S2N_TLS10, False),
    S2N_CIPHER("ECDHE-RSA-AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("ECDHE-RSA-AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("ECDHE-RSA-AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES256-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-CBC:+SHA384", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES256-GCM-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-GCM:+AEAD", S2N_TLS12, True),
]

S2N_PROTO_VERS_TO_STR = {
    S2N_SSLv3 : "SSLv3",
    S2N_TLS10 : "TLSv1.0",
    S2N_TLS11 : "TLSv1.1",
    S2N_TLS12 : "TLSv1.2",
}

S2N_PROTO_VERS_TO_GNUTLS = {
    S2N_SSLv3 : "VERS-SSL3.0",
    S2N_TLS10 : "VERS-TLS1.0",
    S2N_TLS11 : "VERS-TLS1.1",
    S2N_TLS12 : "VERS-TLS1.2",
}
<commit_msg>Add RC4 integration tests with GnuTLS client<commit_after>#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#  http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

import collections

S2N_SSLv3 = 30
S2N_TLS10 = 31
S2N_TLS11 = 32
S2N_TLS12 = 33

# namedtuple makes iterating through ciphers across libraries easier.
S2N_CIPHER = collections.namedtuple('S2N_CIPHER', 'openssl_name gnutls_priority_str min_tls_vers openssl_1_1_0_compatible')

# Specifying a single cipher suite in GnuTLS requires specifying a "priority string" that removes all cipher suites,
# and then adds each algorithm(kx,auth,enc,mac) for a given suite. See https://www.gnutls.org/manual/html_node/Priority-Strings.html
S2N_GNUTLS_PRIORITY_PREFIX="NONE:+COMP-NULL:+CTYPE-ALL:+CURVE-ALL:+SIGN-ALL"

S2N_CIPHERS= [
    S2N_CIPHER("RC4-MD5", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+ARCFOUR-128:+MD5", S2N_SSLv3, False),
    S2N_CIPHER("RC4-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+ARCFOUR-128:+SHA1", S2N_SSLv3, False),
    S2N_CIPHER("DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+3DES-CBC:+SHA1", S2N_SSLv3, False),
    S2N_CIPHER("EDH-RSA-DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+3DES-CBC:+SHA1", S2N_SSLv3, False),
    S2N_CIPHER("AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("DHE-RSA-AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("DHE-RSA-AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("AES256-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES256-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-256-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("AES256-GCM-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+RSA:+AES-256-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("DHE-RSA-AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+DHE-RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-DES-CBC3-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+3DES-CBC:+SHA1", S2N_TLS10, False),
    S2N_CIPHER("ECDHE-RSA-AES128-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("ECDHE-RSA-AES256-SHA", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-CBC:+SHA1", S2N_TLS10, True),
    S2N_CIPHER("ECDHE-RSA-AES128-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-CBC:+SHA256", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES256-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-CBC:+SHA384", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES128-GCM-SHA256", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-128-GCM:+AEAD", S2N_TLS12, True),
    S2N_CIPHER("ECDHE-RSA-AES256-GCM-SHA384", S2N_GNUTLS_PRIORITY_PREFIX + ":+ECDHE-RSA:+AES-256-GCM:+AEAD", S2N_TLS12, True),
]

S2N_PROTO_VERS_TO_STR = {
    S2N_SSLv3 : "SSLv3",
    S2N_TLS10 : "TLSv1.0",
    S2N_TLS11 : "TLSv1.1",
    S2N_TLS12 : "TLSv1.2",
}

S2N_PROTO_VERS_TO_GNUTLS = {
    S2N_SSLv3 : "VERS-SSL3.0",
    S2N_TLS10 : "VERS-TLS1.0",
    S2N_TLS11 : "VERS-TLS1.1",
    S2N_TLS12 : "VERS-TLS1.2",
}
<|endoftext|>


<commit_before>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains the Group Application Model."""

__authors__ = [
  '"Todd Larsen" <tlarsen@google.com>',
]

from google.appengine.ext import db

from django.utils.translation import ugettext

import soc.models.document
import soc.models.linkable
import soc.models.user

class GroupApplication(soc.models.linkable.Linkable):
  """Common application questions for all groups.

  Eventually, this will be replaced with a Question/Answer/Quiz/Response
  approach.  At that time, existing OrgApplication entities will be migrated
  (converted) to their new representations in the Datastore.
  """

  #: Required field that will become the name of the Group in the profile,
  #: if the Group Application is accepted.
  #: See also:  soc.models.group.Group.name
  name = db.StringProperty(required=True,
      verbose_name=ugettext('Group Name'))
  name.help_text = ugettext('Complete, formal name of the group.')

  #: Required many:1 relationship indicating the User who is applying on
  #: behalf of the Group.  If the Group Application is accepted, this User
  #: will become the founding User of the Group.
  #: See also:  soc.models.group.Group.founder
  applicant = db.ReferenceProperty(reference_class=soc.models.user.User,
    required=True, collection_name='group_apps',
    verbose_name=ugettext('Applicant'))

  #: Required field indicating the home page URL of the applying Group.
  #: See also:  soc.models.group.Group.home_page
  home_page = db.LinkProperty(required=True,
      verbose_name=ugettext('Home Page URL'))

  #: Required email address used as the "public" contact mechanism for
  #: the Group (as opposed to the applicant.account email address which is
  #: kept secret, revealed only to Developers).
  #: See also:  soc.models.group.Group.email
  email = db.EmailProperty(required=True,
    verbose_name=ugettext('Public Email'))

  #: Required description of the Group.
  description = db.TextProperty(required=True,
      verbose_name=ugettext('Description'))

  why_applying = db.TextProperty(required=True,
    verbose_name=ugettext(
      'Why is your group applying to participate?'
      ' What do you hope to gain by participating?'))

  pub_mailing_list = db.StringProperty(required=False,
    verbose_name=ugettext(
      'What is the main public mailing list for your group?'))
  pub_mailing_list.help_text = ugettext(
    'Mailing list email address, URL to sign-up page, etc.')

  irc_channel = db.StringProperty(required=False,
    verbose_name=ugettext(
      'Where is the main IRC channel for your group?'))
  irc_channel.help_text = ugettext('IRC network and channel.')

  backup_admin = db.ReferenceProperty(reference_class=soc.models.user.User,
    required=False, collection_name='group_app_backup_admin',
    verbose_name=ugettext(
      'Please select your backup group administrator.'))

  member_criteria = db.TextProperty(required=True,
    verbose_name=ugettext(
      'What criteria do you use to select the members of your group?'
      ' Please be as specific as possible.'))
  member_criteria.help_text = ugettext(
    'Members include mentors, admininstrators, and the like.')

  # property containing the status of the application
  # completed means that the application has been processed into a real group
  # pre-accepted: used to indicate that the application has been accepted
  # but the group cannot be made yet.
  # pre-rejected: used to indicate that the application has been rejected
  # but the applicant has not been informed yet.
  status = db.StringProperty(required=True,
      choices=['accepted','rejected','ignored','needs review','completed',
          'pre-accepted', 'pre-rejected'],
      default='needs review',
      verbose_name=ugettext('Application Status'))

  # timestamp to record the time on which this application has been created
  created_on = db.DateTimeProperty(required=True, auto_now_add=True,
      verbose_name=ugettext('Created on'))

  # timestamp to record the time on which this application has been last modified
  # also changes when the review properties change
  last_modified_on = db.DateTimeProperty(required=True, auto_now=True,
      verbose_name=ugettext('Last modified on'))
<commit_msg>Fixed typo in soc/models/group_app.<commit_after>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains the Group Application Model."""

__authors__ = [
  '"Todd Larsen" <tlarsen@google.com>',
]

from google.appengine.ext import db

from django.utils.translation import ugettext

import soc.models.document
import soc.models.linkable
import soc.models.user

class GroupApplication(soc.models.linkable.Linkable):
  """Common application questions for all groups.

  Eventually, this will be replaced with a Question/Answer/Quiz/Response
  approach.  At that time, existing OrgApplication entities will be migrated
  (converted) to their new representations in the Datastore.
  """

  #: Required field that will become the name of the Group in the profile,
  #: if the Group Application is accepted.
  #: See also:  soc.models.group.Group.name
  name = db.StringProperty(required=True,
      verbose_name=ugettext('Group Name'))
  name.help_text = ugettext('Complete, formal name of the group.')

  #: Required many:1 relationship indicating the User who is applying on
  #: behalf of the Group.  If the Group Application is accepted, this User
  #: will become the founding User of the Group.
  #: See also:  soc.models.group.Group.founder
  applicant = db.ReferenceProperty(reference_class=soc.models.user.User,
    required=True, collection_name='group_apps',
    verbose_name=ugettext('Applicant'))

  #: Required field indicating the home page URL of the applying Group.
  #: See also:  soc.models.group.Group.home_page
  home_page = db.LinkProperty(required=True,
      verbose_name=ugettext('Home Page URL'))

  #: Required email address used as the "public" contact mechanism for
  #: the Group (as opposed to the applicant.account email address which is
  #: kept secret, revealed only to Developers).
  #: See also:  soc.models.group.Group.email
  email = db.EmailProperty(required=True,
    verbose_name=ugettext('Public Email'))

  #: Required description of the Group.
  description = db.TextProperty(required=True,
      verbose_name=ugettext('Description'))

  why_applying = db.TextProperty(required=True,
    verbose_name=ugettext(
      'Why is your group applying to participate?'
      ' What do you hope to gain by participating?'))

  pub_mailing_list = db.StringProperty(required=False,
    verbose_name=ugettext(
      'What is the main public mailing list for your group?'))
  pub_mailing_list.help_text = ugettext(
    'Mailing list email address, URL to sign-up page, etc.')

  irc_channel = db.StringProperty(required=False,
    verbose_name=ugettext(
      'Where is the main IRC channel for your group?'))
  irc_channel.help_text = ugettext('IRC network and channel.')

  backup_admin = db.ReferenceProperty(reference_class=soc.models.user.User,
    required=False, collection_name='group_app_backup_admin',
    verbose_name=ugettext(
      'Please select your backup group administrator.'))

  member_criteria = db.TextProperty(required=True,
    verbose_name=ugettext(
      'What criteria do you use to select the members of your group?'
      ' Please be as specific as possible.'))
  member_criteria.help_text = ugettext(
    'Members include mentors, administrators, and the like.')

  # property containing the status of the application
  # completed means that the application has been processed into a real group
  # pre-accepted: used to indicate that the application has been accepted
  # but the group cannot be made yet.
  # pre-rejected: used to indicate that the application has been rejected
  # but the applicant has not been informed yet.
  status = db.StringProperty(required=True,
      choices=['accepted','rejected','ignored','needs review','completed',
          'pre-accepted', 'pre-rejected'],
      default='needs review',
      verbose_name=ugettext('Application Status'))

  # timestamp to record the time on which this application has been created
  created_on = db.DateTimeProperty(required=True, auto_now_add=True,
      verbose_name=ugettext('Created on'))

  # timestamp to record the time on which this application has been last modified
  # also changes when the review properties change
  last_modified_on = db.DateTimeProperty(required=True, auto_now=True,
      verbose_name=ugettext('Last modified on'))
<|endoftext|>


<commit_before>if __name__ == "__main__":
    import gizeh
    import moviepy.editor as mpy

    from vectortween.ParametricAnimation import ParametricAnimation

    H = 250
    W = 500
    duration = 5
    fps=25

    def make_frame(t):
        surface = gizeh.Surface(W, H)
        x = ParametricAnimation(equation="250+200*sin(2*pi*t)", tween=["easeOutQuad"])
        y = ParametricAnimation(equation="125+80*cos(2*pi*t)", tween=["easeOutQuad"])
        xy = [ x.make_frame(t, 0.2, 1, 4, 5),
               y.make_frame(t, 0.2, 1, 4, 5) ]
        if None not in xy:
            gizeh.circle(30, xy=xy, fill=(1, 1, 0)).draw(surface)
        return surface.get_npimage()

    clip = mpy.VideoClip(make_frame, duration=duration)
    clip.write_videofile("example_parametric.mp4", fps=fps, codec="libx264")
<commit_msg>update example<commit_after>if __name__ == "__main__":
    import gizeh
    import moviepy.editor as mpy

    from vectortween.ParametricAnimation import ParametricAnimation

    H = 250
    W = 500
    duration = 15
    fps=25

    def add(a,b):
        if a is None or b is None:
            return None
        return a+b

    def make_frame(t):
        surface = gizeh.Surface(W, H)
        # big ellipse
        x1 = ParametricAnimation(equation="250+200*sin(2*pi*t)", tween=["easeInOutQuad"])
        y1 = ParametricAnimation(equation="125+80*cos(2*pi*t)", tween=["easeInOutQuad"])
        # smaller circles on top of the ellipse
        x2 = ParametricAnimation(equation="10*sin(50*pi*t)", tween=["linear"])
        y2 = ParametricAnimation(equation="10*cos(50*pi*t)", tween=["linear"])
        xy = [ add(x1.make_frame(t, 0.2, 1, 14, 15), x2.make_frame(t, 0.2, 1, 14, 15)),
               add(y1.make_frame(t, 0.2, 1, 14, 15), y2.make_frame(t, 0.2, 1, 14, 15)) ]
        if None not in xy:
            gizeh.circle(5, xy=xy, fill=(1, 1, 0)).draw(surface)
        return surface.get_npimage()

    clip = mpy.VideoClip(make_frame, duration=duration)
    clip.write_videofile("example_parametric.mp4", fps=fps, codec="libx264")
<|endoftext|>


<commit_before>#!/usr/bin/env python3

"""
focus-next-visible.py - cycles input focus between visible windows on workspace

 Usage:

    # focus next visible window
    bindsym $mod+n exec --no-startup-id focus-next-visible.py

    # focus previous visible window
    bindsym $mod+Shift+n exec --no-startup-id focus-next-visible.py reverse

https://faq.i3wm.org/question/6937/move-focus-from-tabbed-container-to-win...

"""

from sys import argv
from itertools import cycle
from subprocess import check_output

import i3ipc

def get_windows_on_ws(conn):
    return filter(lambda x: x.window,
                  conn.get_tree().find_focused().workspace().descendents())

def find_visible_windows(windows_on_workspace):
    visible_windows = []
    for w in windows_on_workspace:

        try:
            xprop = check_output(['xprop', '-id', str(w.window)]).decode()
        except FileNotFoundError:
            raise SystemExit("The `xprop` utility is not found!"
                             " Please install it and retry.")

        if '_NET_WM_STATE_HIDDEN' not in xprop:
            visible_windows.append(w)

    return visible_windows

if __name__ == '__main__':

    conn = i3ipc.Connection()

    visible_windows = find_visible_windows(get_windows_on_ws(conn))

    if len(argv) > 1 and argv[1] == "reverse":
        cycle_windows = cycle(reversed(visible_windows))
    else:
        cycle_windows = cycle(visible_windows)

    for window in cycle_windows:
        if window.focused:
            focus_to = next(cycle_windows)
            conn.command('[id="%d"] focus' % focus_to.window)
            break
<commit_msg>Add a requirement section<commit_after>#!/usr/bin/env python3

"""
focus-next-visible.py - cycles input focus between visible windows on workspace

- requires the `xprop` utility

 Usage:

    # focus next visible window
    bindsym $mod+n exec --no-startup-id focus-next-visible.py

    # focus previous visible window
    bindsym $mod+Shift+n exec --no-startup-id focus-next-visible.py reverse

https://faq.i3wm.org/question/6937/move-focus-from-tabbed-container-to-win...

"""

from sys import argv
from itertools import cycle
from subprocess import check_output

import i3ipc

def get_windows_on_ws(conn):
    return filter(lambda x: x.window,
                  conn.get_tree().find_focused().workspace().descendents())

def find_visible_windows(windows_on_workspace):
    visible_windows = []
    for w in windows_on_workspace:

        try:
            xprop = check_output(['xprop', '-id', str(w.window)]).decode()
        except FileNotFoundError:
            raise SystemExit("The `xprop` utility is not found!"
                             " Please install it and retry.")

        if '_NET_WM_STATE_HIDDEN' not in xprop:
            visible_windows.append(w)

    return visible_windows

if __name__ == '__main__':

    conn = i3ipc.Connection()

    visible_windows = find_visible_windows(get_windows_on_ws(conn))

    if len(argv) > 1 and argv[1] == "reverse":
        cycle_windows = cycle(reversed(visible_windows))
    else:
        cycle_windows = cycle(visible_windows)

    for window in cycle_windows:
        if window.focused:
            focus_to = next(cycle_windows)
            conn.command('[id="%d"] focus' % focus_to.window)
            break
<|endoftext|>


<commit_before>"""
Tests for the mock of the database summary endpoint.
"""

import pytest
import requests
from requests import codes
from requests_mock import GET

from common.constants import ResultCodes
from tests.mock_vws.utils import assert_vws_response
from tests.utils import VuforiaServerCredentials
from vws._request_utils import target_api_request

def database_summary(
    vuforia_server_credentials: VuforiaServerCredentials,
) -> requests.Response:
    """
    Return the response of a request to the database summary endpoint.

    Args:
        vuforia_server_credentials: The credentials to use to connect to
            Vuforia.
    """
    return target_api_request(
        access_key=vuforia_server_credentials.access_key,
        secret_key=vuforia_server_credentials.secret_key,
        method=GET,
        content=b'',
        request_path='/summary',
    )

@pytest.mark.usefixtures('verify_mock_vuforia')
class TestDatabaseSummary:
    """
    Tests for the mock of the database summary endpoint at `GET /summary`.
    """

    def test_success(
        self,
        vuforia_server_credentials: VuforiaServerCredentials,
    ) -> None:
        """
        It is possible to get a success response.
        """
        response = database_summary(
            vuforia_server_credentials=vuforia_server_credentials
        )

        assert_vws_response(
            response=response,
            status_code=codes.OK,
            result_code=ResultCodes.SUCCESS,
        )

        assert response.json().keys() == {
            'active_images',
            'current_month_recos',
            'failed_images',
            'inactive_images',
            'name',
            'previous_month_recos',
            'processing_images',
            'reco_threshold',
            'request_quota',
            'request_usage',
            'result_code',
            'target_quota',
            'total_recos',
            'transaction_id',
        }

        assert response.json()['name'] == (
            vuforia_server_credentials.database_name
        )
<commit_msg>Inactive project test for database summary<commit_after>"""
Tests for the mock of the database summary endpoint.
"""

import pytest
import requests
from requests import codes
from requests_mock import GET

from common.constants import ResultCodes
from tests.mock_vws.utils import assert_vws_response
from tests.utils import VuforiaServerCredentials
from vws._request_utils import target_api_request

def database_summary(
    vuforia_server_credentials: VuforiaServerCredentials,
) -> requests.Response:
    """
    Return the response of a request to the database summary endpoint.

    Args:
        vuforia_server_credentials: The credentials to use to connect to
            Vuforia.
    """
    return target_api_request(
        access_key=vuforia_server_credentials.access_key,
        secret_key=vuforia_server_credentials.secret_key,
        method=GET,
        content=b'',
        request_path='/summary',
    )

@pytest.mark.usefixtures('verify_mock_vuforia')
class TestDatabaseSummary:
    """
    Tests for the mock of the database summary endpoint at `GET /summary`.
    """

    def test_success(
        self,
        vuforia_server_credentials: VuforiaServerCredentials,
    ) -> None:
        """
        It is possible to get a success response.
        """
        response = database_summary(
            vuforia_server_credentials=vuforia_server_credentials
        )

        assert_vws_response(
            response=response,
            status_code=codes.OK,
            result_code=ResultCodes.SUCCESS,
        )

        assert response.json().keys() == {
            'active_images',
            'current_month_recos',
            'failed_images',
            'inactive_images',
            'name',
            'previous_month_recos',
            'processing_images',
            'reco_threshold',
            'request_quota',
            'request_usage',
            'result_code',
            'target_quota',
            'total_recos',
            'transaction_id',
        }

        assert response.json()['name'] == (
            vuforia_server_credentials.database_name
        )

@pytest.mark.usefixtures('verify_mock_vuforia_inactive')
class TestInactiveProject:
    """
    Tests for inactive projects.
    """

    def test_inactive_project(
        self,
        inactive_server_credentials: VuforiaServerCredentials,
    ) -> None:
        """
        The project's active state does not affect the database summary.
        """
        response = database_summary(
            vuforia_server_credentials=inactive_server_credentials,
        )

        assert_vws_response(
            response=response,
            status_code=codes.OK,
            result_code=ResultCodes.SUCCESS,
        )
<|endoftext|>