<commit_before>__author__ = 'rcj1492'
__created__ = '2016.07'
__license__ = 'MIT'

# pip install pytz
# pip install tzlocal

import re
from datetime import datetime
from tzlocal import get_localzone
from dateutil import parser as dTparser
from dateutil import tz
import pytz

class labDT(datetime):

    ''' a class of methods for datetime conversion

    for list of timezones:
        https://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones
    for list of datetime directives:
        https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
    '''

    @classmethod
    def new(cls):

        ''' a method to generate the current datetime as a labDT object

        :return: labDT object
        '''

        dT = datetime.utcnow().replace(tzinfo=pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    def zulu(self):

        ''' a method to report ISO UTC datetime string from a labDT object

        NOTE: for timezone offset string use .isoformat() instead

        :return: string in ISO UTC format
        '''

    # construct ISO UTC string from labDT
        utc_dt = self.astimezone(pytz.utc)
        iso_dt = utc_dt.isoformat()
        return iso_dt.replace('+00:00', 'Z')

    def epoch(self):

        ''' a method to report posix epoch timestamp from a labDT object

        :return: float with timestamp
        '''

    # construct epoch timestamp from labDT
        epoch_dt = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
        delta_time = self - epoch_dt
        return delta_time.total_seconds()

    def rfc2822(self):

        '''
            a method to report a RFC-2822 Compliant Date from a labDT object

            https://tools.ietf.org/html/rfc2822.html#page-14

        :return: string with RFC-2822 compliant date time
        '''

    # define format
        js_format = '%a, %d %b %Y %H:%M:%S GMT'
        utc_time = self.astimezone(pytz.utc)

        return format(utc_time, js_format)

    def pyLocal(self, time_zone=''):

        ''' a method to report a python datetime from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        get_tz = get_localzone()
        title = 'Timezone input for labDT.pyLocal'
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('\n%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct python datetime from labDT
        dT = self.astimezone(get_tz)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    def jsLocal(self, time_zone=''):

        ''' a method to report a javascript string from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        js_format = '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
        title = 'Timezone input for labDT.jsLocal'
        get_tz = get_localzone()
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('\n%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct javascript datetime from labDT
        dtLocal = self.astimezone(get_tz)
        return format(dtLocal, js_format)

    def humanFriendly(self, time_zone=''):

        ''' a method to report a human friendly string from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        zeroHourPattern = re.compile('\s0\d:')
        title = 'Timezone input for labDT.humanFriendly'
        human_format = '%A, %B %d, %Y %I:%M%p %Z'
        get_tz = get_localzone()
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct human friendly string from labDT
        dtLocal = self.astimezone(get_tz)
        dtString = format(dtLocal, human_format)
        zeroHour = zeroHourPattern.findall(dtString)
        if zeroHour:
            noZero = zeroHour[0].replace(' 0',' ')
            dtString = zeroHourPattern.sub(noZero,dtString)
        return dtString

    @classmethod
    def fromEpoch(cls, epoch_time):

        ''' a method for constructing a labDT object from epoch timestamp

        :param epoch_time: number with epoch timestamp info
        :return: labDT object
        '''

    # validate input
        title = 'Epoch time input for labDT.fromEpoch'
        if not isinstance(epoch_time, float) and not isinstance(epoch_time, int):
            raise TypeError('\n%s must be an integer or float.' % title)

    # construct labDT from epoch time
        dT = datetime.utcfromtimestamp(epoch_time).replace(tzinfo=pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromISO(cls, iso_string):

        ''' a method for constructing a labDT object from a timezone aware ISO string

        :param iso_string: string with date and time info in ISO format
        :return: labDT object
        '''

    # validate input
        title = 'ISO time input for labDT.fromISO'
        isopattern = re.compile('\d{4}-?\d{2}-?\d{2}T.*')
        if not isopattern.search(iso_string):
            raise ValueError('\n%s is not a valid ISO string.' % title)
        python_datetime = dTparser.parse(iso_string)
        if not python_datetime.tzinfo:
            raise ValueError('\n%s must have timezone info.' % title)

    # construct labDT from parsed string
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromPython(cls, python_datetime):

        ''' a method for constructing a labDT from a python datetime with timezone info

        :param python_datetime: datetime object with timezone info
        :return: labDT object
        '''

    # validate inputs
        title = 'Python datetime input for labDT.fromPython'
        if not isinstance(python_datetime, datetime):
            raise TypeError('\n%s must be a valid %s object.' % (title, datetime.__class__))
        elif not python_datetime.tzinfo:
            raise ValueError('\n%s must have a timezone.' % title)

    # construct labDT from python datetime
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromJavascript(cls, javascript_datetime):

        ''' a method to construct labDT from a javascript datetime string

        :param javascript_datetime: string with datetime info in javascript formatting
        :return: labDT object
        '''

    # validate inputs
        title = 'Javascript datetime string input for labDT.fromJavascript'
        jsDTpattern = re.compile('\s*\(.*\)$')
        jsGMTpattern = re.compile('GMT[-\+]\d{4}')
        if not jsGMTpattern.findall(javascript_datetime):
            raise Exception('\n%s must have a GMT timezone adjustment.' % title)

    # construct datetime from javascript string
        adj_input = jsDTpattern.sub('', javascript_datetime)
        if '-' in adj_input:
            adj_input = adj_input.replace('-','+')
        elif '+' in adj_input:
            adj_input = adj_input.replace('+','-')
        python_datetime = dTparser.parse(adj_input)
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromPattern(cls, datetime_string, datetime_pattern, time_zone):

        '''
            a method for constructing labDT from a strptime pattern in a string
            https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
            iso_pattern: '%Y-%m-%dT%H:%M:%S.%f%z'
            human_friendly_pattern: '%A, %B %d, %Y %I:%M:%S.%f%p'
        :param datetime_string: string with date and time info
        :param datetime_pattern: string with python formatted pattern
        :param time_zone: string with timezone info
        :return: labDT object with datetime
        '''

    # validate inputs
        title = 'input for labDT.fromPattern'
        dT_req = [['%Y','%y'],['%b','%B','%m'],['%d'],['%H','%I']]
        req_counter = 0
        for i in dT_req:
            for j in i:
                if j in datetime_pattern:
                    req_counter += 1
        if not req_counter == 4:
            raise Exception('Datetime pattern %s must contain at least year, month, day and hour.' % title)
        try:
            get_tz = tz.gettz(time_zone)
        except:
            raise ValueError('Timezone %s is not a valid timezone format.' % title)

    # decipher datetime
        python_datetime = datetime.strptime(datetime_string, datetime_pattern)
        python_datetime = python_datetime.replace(tzinfo=tz.gettz(time_zone))
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

if __name__ == '__main__':
    dt = labDT.new()
    print(dt.humanFriendly('US/Hawaii'))
    print(dt.rfc2822())
    print(dt.isoformat().replace('T', ' ')[0:19])<commit_msg>added arguments to remove day and time from humanFriendly date in labDT;<commit_after>__author__ = 'rcj1492'
__created__ = '2016.07'
__license__ = 'MIT'

# pip install pytz
# pip install tzlocal

import re
from datetime import datetime
from tzlocal import get_localzone
from dateutil import parser as dTparser
from dateutil import tz
import pytz

class labDT(datetime):

    ''' a class of methods for datetime conversion

    for list of timezones:
        https://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones
    for list of datetime directives:
        https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
    '''

    @classmethod
    def new(cls):

        ''' a method to generate the current datetime as a labDT object

        :return: labDT object
        '''

        dT = datetime.utcnow().replace(tzinfo=pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    def zulu(self):

        ''' a method to report ISO UTC datetime string from a labDT object

        NOTE: for timezone offset string use .isoformat() instead

        :return: string in ISO UTC format
        '''

    # construct ISO UTC string from labDT
        utc_dt = self.astimezone(pytz.utc)
        iso_dt = utc_dt.isoformat()
        return iso_dt.replace('+00:00', 'Z')

    def epoch(self):

        ''' a method to report posix epoch timestamp from a labDT object

        :return: float with timestamp
        '''

    # construct epoch timestamp from labDT
        epoch_dt = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
        delta_time = self - epoch_dt
        return delta_time.total_seconds()

    def rfc2822(self):

        '''
            a method to report a RFC-2822 Compliant Date from a labDT object

            https://tools.ietf.org/html/rfc2822.html#page-14

        :return: string with RFC-2822 compliant date time
        '''

    # define format
        js_format = '%a, %d %b %Y %H:%M:%S GMT'
        utc_time = self.astimezone(pytz.utc)

        return format(utc_time, js_format)

    def pyLocal(self, time_zone=''):

        ''' a method to report a python datetime from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        get_tz = get_localzone()
        title = 'Timezone input for labDT.pyLocal'
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('\n%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct python datetime from labDT
        dT = self.astimezone(get_tz)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    def jsLocal(self, time_zone=''):

        ''' a method to report a javascript string from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        js_format = '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
        title = 'Timezone input for labDT.jsLocal'
        get_tz = get_localzone()
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('\n%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct javascript datetime from labDT
        dtLocal = self.astimezone(get_tz)
        return format(dtLocal, js_format)

    def humanFriendly(self, time_zone='', include_day=True, include_time=True):

        ''' a method to report a human friendly string from a labDT object

        :param time_zone: [optional] string with timezone to report in
        :return: string with date and time info
        '''

    # validate inputs
        zeroHourPattern = re.compile('\s0\d:')
        title = 'Timezone input for labDT.humanFriendly'
        human_format = ''
        if include_day:
            human_format += '%A, '
        human_format += '%B %d, %Y'
        if include_time:
            human_format += ' %I:%M%p %Z'
        get_tz = get_localzone()
        if time_zone:
            # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'):
            #     raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)
            try:
                get_tz = tz.gettz(time_zone)
            except:
                raise ValueError('%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n  print tz' % title)

    # construct human friendly string from labDT
        dtLocal = self.astimezone(get_tz)
        dtString = format(dtLocal, human_format)
        zeroHour = zeroHourPattern.findall(dtString)
        if zeroHour:
            noZero = zeroHour[0].replace(' 0',' ')
            dtString = zeroHourPattern.sub(noZero,dtString)
        return dtString

    @classmethod
    def fromEpoch(cls, epoch_time):

        ''' a method for constructing a labDT object from epoch timestamp

        :param epoch_time: number with epoch timestamp info
        :return: labDT object
        '''

    # validate input
        title = 'Epoch time input for labDT.fromEpoch'
        if not isinstance(epoch_time, float) and not isinstance(epoch_time, int):
            raise TypeError('\n%s must be an integer or float.' % title)

    # construct labDT from epoch time
        dT = datetime.utcfromtimestamp(epoch_time).replace(tzinfo=pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromISO(cls, iso_string):

        ''' a method for constructing a labDT object from a timezone aware ISO string

        :param iso_string: string with date and time info in ISO format
        :return: labDT object
        '''

    # validate input
        title = 'ISO time input for labDT.fromISO'
        isopattern = re.compile('\d{4}-?\d{2}-?\d{2}T.*')
        if not isopattern.search(iso_string):
            raise ValueError('\n%s is not a valid ISO string.' % title)
        python_datetime = dTparser.parse(iso_string)
        if not python_datetime.tzinfo:
            raise ValueError('\n%s must have timezone info.' % title)

    # construct labDT from parsed string
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromPython(cls, python_datetime):

        ''' a method for constructing a labDT from a python datetime with timezone info

        :param python_datetime: datetime object with timezone info
        :return: labDT object
        '''

    # validate inputs
        title = 'Python datetime input for labDT.fromPython'
        if not isinstance(python_datetime, datetime):
            raise TypeError('\n%s must be a valid %s object.' % (title, datetime.__class__))
        elif not python_datetime.tzinfo:
            raise ValueError('\n%s must have a timezone.' % title)

    # construct labDT from python datetime
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromJavascript(cls, javascript_datetime):

        ''' a method to construct labDT from a javascript datetime string

        :param javascript_datetime: string with datetime info in javascript formatting
        :return: labDT object
        '''

    # validate inputs
        title = 'Javascript datetime string input for labDT.fromJavascript'
        jsDTpattern = re.compile('\s*\(.*\)$')
        jsGMTpattern = re.compile('GMT[-\+]\d{4}')
        if not jsGMTpattern.findall(javascript_datetime):
            raise Exception('\n%s must have a GMT timezone adjustment.' % title)

    # construct datetime from javascript string
        adj_input = jsDTpattern.sub('', javascript_datetime)
        if '-' in adj_input:
            adj_input = adj_input.replace('-','+')
        elif '+' in adj_input:
            adj_input = adj_input.replace('+','-')
        python_datetime = dTparser.parse(adj_input)
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

    @classmethod
    def fromPattern(cls, datetime_string, datetime_pattern, time_zone):

        '''
            a method for constructing labDT from a strptime pattern in a string
            https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
            iso_pattern: '%Y-%m-%dT%H:%M:%S.%f%z'
            human_friendly_pattern: '%A, %B %d, %Y %I:%M:%S.%f%p'
        :param datetime_string: string with date and time info
        :param datetime_pattern: string with python formatted pattern
        :param time_zone: string with timezone info
        :return: labDT object with datetime
        '''

    # validate inputs
        title = 'input for labDT.fromPattern'
        dT_req = [['%Y','%y'],['%b','%B','%m'],['%d'],['%H','%I']]
        req_counter = 0
        for i in dT_req:
            for j in i:
                if j in datetime_pattern:
                    req_counter += 1
        if not req_counter == 4:
            raise Exception('Datetime pattern %s must contain at least year, month, day and hour.' % title)
        try:
            get_tz = tz.gettz(time_zone)
        except:
            raise ValueError('Timezone %s is not a valid timezone format.' % title)

    # decipher datetime
        python_datetime = datetime.strptime(datetime_string, datetime_pattern)
        python_datetime = python_datetime.replace(tzinfo=tz.gettz(time_zone))
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)

if __name__ == '__main__':
    dt = labDT.new()
    print(dt.humanFriendly('US/Hawaii'))
    print(dt.rfc2822())
    print(dt.isoformat().replace('T', ' ')[0:19])<|endoftext|>


<commit_before># coding: utf-8

# Der WSGI-Server auf PythonAnywhere verwendet diese Datei

import sqlite3
import os
import time

import bottle
from bottle import default_app, route, view
from bottle import request
from bottle_utils.i18n import I18NPlugin
from bottle_utils.i18n import lazy_gettext as _

import input_number as ip
from dbhelper import initialize_database
import hashlib

MOD_PATH = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.abspath(os.path.join(MOD_PATH, '..', '..', "lagesonr.db"))

if not os.path.exists(DB_PATH):
    initialize_database(DB_PATH)

lagesonrdb = sqlite3.connect(DB_PATH)

LANGS = [
    ('de_DE', 'Deutsch'),
    ('en_US', 'English'),
]
# ('ar_AR', 'Arab'),
DEFAULT_LOCALE = 'en_US'

<<<<<<< Temporary merge branch 1
=======
@route('/bla')
def handler():
    """BEISPIEL: probiere im Browser: /en_US/bla und /de_DE/bla"""
    return _('TESTWORD',ip.get_user_id())

@route('/user-agent')
def user_agent():
    """
    returns an identification hash based on information from the user's browser
    :return: string
    """
    usr_agent = str(request.environ.get('HTTP_USER_AGENT'))
    usr_lang = str(request.environ.get('HTTP_ACCEPT_LANGUAGE'))
    usr_ip = str(request.remote_addr)

    usr_fingerprint = usr_agent + usr_lang + usr_ip
    usr_hash = hashlib.md5(usr_fingerprint.encode("utf-8"))

    # no return
    return ()

>>>>>>> Temporary merge branch 2
@route('/')
@view('start_page')
def index():
    """1.Seite: Helfer steht am LaGeSo und gibt Nummern ein [_____] """
    return {'entered': []}

@route('/', method='POST')
@view('start_page')
def do_enter():
    import pdb
    #pdb.set_trace()
    numbers = request.forms.get('numbers')
    timestamp = time.asctime()
    numbers = [num.strip() for num in numbers.split('\n')]
    result_num = []
    with lagesonrdb as con:
        cur = con.cursor()
        for num in set(numbers):
            if ip.is_valid_number(num) and ip.is_ok_with_db(
                    num) and ip.is_valid_user():
                insert = 'INSERT INTO NUMBERS(NUMBER, TIME, PLACE, USER) VALUES ("%s", "%s", "-", "-")' % (
                    num, timestamp)
                cur.execute(insert)
                result_num.append(num)
            else:
                result_num.append("INVALID INPUT: %s" % num)

    return {'entered': result_num, 'timestamp': timestamp}

@route('/query')
@view('query_page')
def query_number():
    """
    2. Seite: Flüchtling fragt ab: Wurde meine Nummer gezogen? [_____]
    => Antwort: X mal am LaGeSo eingetragen von (Erste Eintragung)
    DD.MM.YY hh bis DD.MM.YY hh (LetzteEintragung)
    application = default_app()
    """
    return {'result': '-', 'timestamp_first': '-', 'timestamp_last': '-',
            'n': '0'}

@route('/query', method='POST')
@view('query_page')
def do_query():
    number = request.forms.get('number')

    if ip.is_valid_number(number) and ip.is_ok_with_db(
            number) and ip.is_valid_user():

        with lagesonrdb as con:
            cur = con.cursor()
            query = 'SELECT TIME FROM NUMBERS WHERE NUMBER="%s" ORDER BY TIME' % number
            result = list(cur.execute(query))
            n = len(result)
            if n > 0:
                timestamp_first, timestamp_last = result[0][0], result[-1][0]
                return {'result': number, 'timestamp_first': timestamp_first,
                        'timestamp_last': timestamp_last, 'n': n}
        return {'result': 'number', 'timestamp_first': 'NOT FOUND',
                'timestamp_last': '-', 'n': '0'}

    else:
        return {"INVALID INPUT": number}

# findet templates im gleichen Verzeichnis
bottle.TEMPLATE_PATH.append(MOD_PATH)
app = default_app()
application = I18NPlugin(app, langs=LANGS, default_locale=DEFAULT_LOCALE,
                         domain='messages',
                         locale_dir=os.path.join(MOD_PATH, 'locales'))
<commit_msg>avoid double entry, fix query error<commit_after># coding: utf-8

# Der WSGI-Server auf PythonAnywhere verwendet diese Datei

import sqlite3
import os
import time

import bottle
from bottle import default_app, route, view
from bottle import request
from bottle_utils.i18n import I18NPlugin
from bottle_utils.i18n import lazy_gettext as _

import input_number as ip
from dbhelper import initialize_database
import hashlib

MOD_PATH = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.abspath(os.path.join(MOD_PATH, '..', '..', "lagesonr.db"))

if not os.path.exists(DB_PATH):
    initialize_database(DB_PATH)

lagesonrdb = sqlite3.connect(DB_PATH)

LANGS = [
    ('de_DE', 'Deutsch'),
    ('en_US', 'English'),
]
# ('ar_AR', 'Arab'),
DEFAULT_LOCALE = 'en_US'

@route('/')
@view('start_page')
def index():
    """1.Seite: Helfer steht am LaGeSo und gibt Nummern ein [_____] """
    return {'entered': []}

@route('/', method='POST')
@view('start_page')
def do_enter():
    numbers = request.forms.get('numbers')
    timestamp = time.asctime()
    numbers = [num.strip() for num in numbers.split('\n')]
    result_num = []
    usr_agent = str(request.environ.get('HTTP_USER_AGENT'))
    usr_lang = str(request.environ.get('HTTP_ACCEPT_LANGUAGE'))
    usr_ip = str(request.remote_addr)

    usr_fingerprint = usr_agent + usr_lang + usr_ip
    usr_hash = hashlib.md5(usr_fingerprint.encode("utf-8")).hexdigest()

    with lagesonrdb as con:
        cur = con.cursor()
        for num in set(numbers):
            if ip.is_valid_number(num) and ip.is_ok_with_db(
                    num) and ip.is_valid_user():

                query = 'SELECT * FROM NUMBERS WHERE NUMBER="%s" AND FINGERPRINT="%s" ORDER BY TIME' % (num, usr_hash)
                if len(list(cur.execute(query)))==0:

                    insert = 'INSERT INTO NUMBERS(NUMBER, TIME, PLACE, USER) VALUES ("%s", "%s", "-", "-", %s)' % (
                        num, timestamp, usr_hash)
                    cur.execute(insert)
                    result_num.append(num)
                else:
                    result_num.append("ALREADY ENTERED BY - %s - %s - %s: %s" % (usr_ip, usr_agent, usr_lang, num))
            else:
                result_num.append("INVALID INPUT: %s" % num)

    return {'entered': result_num, 'timestamp': timestamp}

@route('/query')
@view('query_page')
def query_number():
    """
    2. Seite: Flüchtling fragt ab: Wurde meine Nummer gezogen? [_____]
    => Antwort: X mal am LaGeSo eingetragen von (Erste Eintragung)
    DD.MM.YY hh bis DD.MM.YY hh (LetzteEintragung)
    application = default_app()
    """
    return {'result': '-', 'timestamp_first': '-', 'timestamp_last': '-',
            'n': '0'}

@route('/query', method='POST')
@view('query_page')
def do_query():
    number = request.forms.get('number')

    if ip.is_valid_number(number) and ip.is_ok_with_db(
            number) and ip.is_valid_user():

        with lagesonrdb as con:
            cur = con.cursor()
            query = 'SELECT TIME FROM NUMBERS WHERE NUMBER="%s" ORDER BY TIME' % number
            result = list(cur.execute(query))
            n = len(result)
            if n > 0:
                timestamp_first, timestamp_last = result[0][0], result[-1][0]
                return {'result': number, 'timestamp_first': timestamp_first,
                        'timestamp_last': timestamp_last, 'n': n}

        return {'result': 'number', 'timestamp_first': 'NOT FOUND',
                'timestamp_last': '-', 'n': '0'}

    else:
        #todo: may be give indication that input was invalid
        return {'result': 'NOTHING', 'timestamp_first': 'NOT FOUND',
                'timestamp_last': '-', 'n': '0'}

# findet templates im gleichen Verzeichnis
bottle.TEMPLATE_PATH.append(MOD_PATH)
app = default_app()
application = I18NPlugin(app, langs=LANGS, default_locale=DEFAULT_LOCALE,
                         domain='messages',
                         locale_dir=os.path.join(MOD_PATH, 'locales'))
<|endoftext|>


<commit_before>"""
Sends the request to ElasticSearch.

TODO: Implement a higher-level search API.
"""
import os

from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection

from t4_lambda_shared.decorator import api
from t4_lambda_shared.utils import get_default_origins, make_json_response

MAX_QUERY_DURATION = '15s'

@api(cors_origins=get_default_origins())
def lambda_handler(request):
    """
    Proxy the request to the elastic search.
    """
    action = request.args.get('action')
    index = request.args.get('index')

    if action == 'search':
        query = request.args.get('query', '')
        body = {
            "query": {
                "simple_query_string" : {
                    "query": query,
                    "fields": ['content', 'comment', 'key_text', 'meta_text']
                }
            }
        }
        # TODO: should be user settable; we should proably forbid `content` (can be huge)
        _source = ['key', 'version_id', 'updated', 'last_modified', 'size', 'user_meta']
        size = 1000
    elif action == 'stats':
        body = {
            "query": { "match_all": {} },
            "aggs": {
                "totalBytes": { "sum": { "field": 'size' } },
                "exts": {
                    "terms": { "field": 'ext' },
                    "aggs": { "size": { "sum": { "field": 'size' } } },
                },
                "updated": { "max": { "field": 'updated' } },
            }
        }
        size = 0
        _source = []
    else:
        return make_json_response(400, {"title": "Invalid action"})

    es_host = os.environ['ES_HOST']
    region = os.environ['AWS_REGION']

    auth = BotoAWSRequestsAuth(
        aws_host=es_host,
        aws_region=region,
        aws_service='es'
    )

    es_client = Elasticsearch(
        hosts=[{'host': es_host, 'port': 443}],
        http_auth=auth,
        use_ssl=True,
        verify_certs=True,
        connection_class=RequestsHttpConnection
    )

    result = es_client.search(index, body, _source=_source, size=size, timeout=MAX_QUERY_DURATION)

    return make_json_response(200, result)
<commit_msg>Get search index overrides from environment (#1158)<commit_after>"""
Sends the request to ElasticSearch.

TODO: Implement a higher-level search API.
"""
import os

from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection

from t4_lambda_shared.decorator import api
from t4_lambda_shared.utils import get_default_origins, make_json_response

INDEX_OVERRIDES = os.getenv('INDEX_OVERRIDES', '')
MAX_QUERY_DURATION = '15s'

@api(cors_origins=get_default_origins())
def lambda_handler(request):
    """
    Proxy the request to the elastic search.
    """
    action = request.args.get('action')
    indexes = request.args.get('index')

    if action == 'search':
        query = request.args.get('query', '')
        body = {
            "query": {
                "simple_query_string" : {
                    "query": query,
                    "fields": ['content', 'comment', 'key_text', 'meta_text']
                }
            }
        }
        # TODO: should be user settable; we should proably forbid `content` (can be huge)
        _source = ['key', 'version_id', 'updated', 'last_modified', 'size', 'user_meta']
        size = 1000
    elif action == 'stats':
        body = {
            "query": { "match_all": {} },
            "aggs": {
                "totalBytes": { "sum": { "field": 'size' } },
                "exts": {
                    "terms": { "field": 'ext' },
                    "aggs": { "size": { "sum": { "field": 'size' } } },
                },
                "updated": { "max": { "field": 'updated' } },
            }
        }
        size = 0
        _source = []
    else:
        return make_json_response(400, {"title": "Invalid action"})

    es_host = os.environ['ES_HOST']
    region = os.environ['AWS_REGION']

    auth = BotoAWSRequestsAuth(
        aws_host=es_host,
        aws_region=region,
        aws_service='es'
    )

    es_client = Elasticsearch(
        hosts=[{'host': es_host, 'port': 443}],
        http_auth=auth,
        use_ssl=True,
        verify_certs=True,
        connection_class=RequestsHttpConnection
    )

    to_search = f"{indexes},{INDEX_OVERRIDES}" if INDEX_OVERRIDES else indexes
    result = es_client.search(
        to_search,
        body,
        _source=_source,
        size=size,
        timeout=MAX_QUERY_DURATION
    )

    return make_json_response(200, result)
<|endoftext|>


<commit_before>#! /usr/bin/env python
from __future__ import division

import numpy as np
from landlab.grid.structured_quad import links

'''
Functions which can map data contained on nodes to the connecting links.

Each link has a "from" and "to" node. The "from" nodes are located at the link
tail, while the "to" nodes are located at link heads.

Below, the numbering scheme for links in RasterModelGrid is illustrated with an
example of a four-row by five column grid (4x5). In this example, each * (or X)
is a node, the lines represent links, and the ^ and > symbols indicate the
direction and "head" of each link. Link heads in the RasterModelGrid always
point in the cardinal directions North (N) or East (E).

    *--27-->*--28-->*--29-->*--30-->*
    ^       ^       ^       ^       ^
   10      11      12      13      14
    |       |       |       |       |
    *--23-->*--24-->*--25-->*--26-->*
    ^       ^       ^       ^       ^
    5       6       7       8       9
    |       |       |       |       |
    *--19-->*--20-->X--21-->*--22-->*
    ^       ^       ^       ^       ^
    0       1       2       3       4
    |       |       |       |       |
    *--15-->*--16-->*--17-->*--18-->*

For example, node 'X' has four link-neighbors. From south and going clockwise,
these neighbors are [2, 20, 7, 21]. Both link 2 and link 20 have node 'X' as their
'to' node, while links 7 and 21 have node 'X' as their from node.
'''
def map_values_from_link_head_node_to_link(mg, var_name):
    '''
    map_values_from_link_head_node_to_link iterates across the grid and
    identifies the node at the "head", or the "to" node for each link. For
    each link, the value of 'var_name' at the "to" node is mapped to the corresponding
    link.

    In a RasterModelGrid, each one node has two adjacent "link heads". This means
    each node value is mapped to two corresponding links.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('link', var_name)
    values_at_links = mg.at_link[var_name]
    values_at_links[:] = values_at_nodes[mg.node_index_at_link_tail]

def map_values_from_link_tail_node_to_link(mg, var_name):
    '''
    map_values_from_link_tail_node_to_link iterates across the grid and
    identifies the node at the "tail", or the "from" node for each link. For
    each link, the value of 'var_name' at the "from" node is mapped to the
    corresponding link.

    In a RasterModelGrid, each one node has two adjacent "link tails". This means
    each node value is mapped to two corresponding links.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('link', var_name)
    values_at_links = mg.at_link[var_name]
    values_at_links[:] = values_at_nodes[mg.node_index_at_link_head]

def map_link_end_node_min_value_to_link(mg, var_name):
    '''
    map_link_end_node_min_value_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function evaluates the value of 'var_name' at both the "to" and "from" node.
    The minimum value of the two node values is then mapped to the link.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('link', var_name)
    values_at_links = mg.at_link[var_name]
    np.minimum(values_at_nodes[mg.node_index_at_link_head],
               values_at_nodes[mg.node_index_at_link_tail],
               out=values_at_links)

def map_link_end_node_max_value_to_link(mg, var_name):
    '''
    map_link_end_node_max_value_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function evaluates the value of 'var_name' at both the "to" and "from" node.
    The maximum value of the two node values is then mapped to the link.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('link', var_name)
    values_at_links = mg.at_link[var_name]
    np.maximum(values_at_nodes[mg.node_index_at_link_head],
               values_at_nodes[mg.node_index_at_link_tail],
               out=values_at_links)

def map_values_from_link_end_nodes_to_link(mg, var_name):
    '''
    map_values_from_link_end_nodes_to_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function takes the sum of the two values of 'var_name' at both the "to"
    and "from" node. The average value of the two node values of 'var_name'
    is then mapped to the link.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('link', var_name)
    values_at_links = mg.at_link[var_name]
    values_at_links[:] = 0.5 * (values_at_nodes[mg.node_index_at_link_head] +
                                values_at_nodes[mg.node_index_at_link_tail])

def map_values_from_cell_node_to_cell(mg, var_name):
    '''
    map_values_from_cell_node_to_cell iterates across the grid and
    identifies the all node values of 'var_name'.

    This function takes node values of 'var_name' and mapes that value to the
    corresponding cell area for each node.
    '''
    values_at_nodes = mg.at_node[var_name]
    mg.add_empty('cell', var_name)
    values_at_cells = mg.at_cell[var_name]
    values_at_cells[:] = values_at_nodes[mg.node_index_at_cells]

def map_inlink_sums_to_node(mg, var_name):
    '''
    map_inlink_sums_to_node takes a field *at the links* and finds the
    inlink values for each node in the grid. it sums the inlinks and returns
    a field at the nodes with the same var_name as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    south, west = links._node_in_link_ids(mg.shape)
    south = south.flatten()
    west = west.flatten()
    values_at_nodes[:] = values_at_links[south]+values_at_links[west]

def map_inlink_average_to_node(mg, var_name):
    '''
    map_inlink_average_to_node takes a field *at the links* and finds the
    inlink values for each node in the grid. it finds the average of
    the inlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    south, west = links._node_in_link_ids(mg.shape)
    south = south.flatten()
    west = west.flatten()
    values_at_nodes[:] = 0.5 * (values_at_links[south]+values_at_links[west])

def map_max_inlink_value_to_node(mg, var_name):
    '''
    map_max_inlink_value_to_node takes a field *at the links* and finds the
    inlink values for each node in the grid. it finds the maximum value at the
    the inlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    south, west = links._node_in_link_ids(mg.shape)
    south = south.flatten()
    west = west.flatten()
    values_at_nodes[:] = np.maximum(values_at_links[south], values_at_links[west])

def map_min_inlink_value_to_node(mg, var_name):
    '''
    map_min_inlink_value_to_node takes a field *at the links* and finds the
    inlink values for each node in the grid. it finds the minimum value at the
    the inlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''

    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    south, west = links._node_in_link_ids(mg.shape)
    south = south.flatten()
    west = west.flatten()
    values_at_nodes[:] = np.minimum(values_at_links[south], values_at_links[west])

def map_outlink_sums_to_node(mg, var_name):
    '''
    map_outlink_sums_to_node takes a field *at the links* and finds the
    outlink values for each node in the grid. it sums the outlinks and returns
    a field at the nodes with the same var_name as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    north, east = links._node_out_link_ids(mg.shape)
    north = north.flatten()
    east = east.flatten()
    values_at_nodes[:] = values_at_links[north]+values_at_links[east]

def map_outlink_average_to_node(mg, var_name):
    '''
    map_outlink_average_to_node takes a field *at the links* and finds the
    outlink values for each node in the grid. it finds the average of
    the outlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    north, east = links._node_out_link_ids(mg.shape)
    north = north.flatten()
    east = east.flatten()
    values_at_nodes[:] = 0.5 * (values_at_links[north]+values_at_links[east])

def map_max_outlink_value_to_node(mg, var_name):
    '''
    map_max_outlink_value_to_node takes a field *at the links* and finds the
    outlink values for each node in the grid. it finds the maximum value at the
    the outlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''
    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    north, east = links._node_out_link_ids(mg.shape)
    north = north.flatten()
    east = east.flatten()
    values_at_nodes[:] = np.maximum(values_at_links[north], values_at_links[east])

def map_min_outlink_value_to_node(mg, var_name):
    '''
    map_min_outlink_value_to_node takes a field *at the links* and finds the
    outlink values for each node in the grid. it finds the minimum value at the
    the outlinks and returns a field at the nodes with the same var_name
    as the link field.

    This considers all inactive links to have a value of 0.
    '''

    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    north, east = links._node_out_link_ids(mg.shape)
    north = north.flatten()
    east = east.flatten()
    values_at_nodes[:] = np.minimum(values_at_links[north], values_at_links[east])

def map_average_all_links_to_node(mg, var_name):
    '''
    map_average_all_links_to_node takes a field *at the links* and finds the
    average of all ~existing~ link neighbor values for each node in the grid.
    it returns a field at the nodes with the same var_name
    as the link field.

    When calculating the average, no inactive links are considered.
    '''

    values_at_links = mg.at_link[var_name]
    values_at_links = np.append(values_at_links, 0)
    mg.add_empty('node', var_name)
    values_at_nodes = mg.at_node[var_name]
    north, east = links._node_out_link_ids(mg.shape)
    south, west = links._node_in_link_ids(mg.shape)
    south = south.flatten()
    west = west.flatten()
    north = north.flatten()
    east = east.flatten()
    number_of_links = links.number_of_links_per_node(mg.shape)
    number_of_links = number_of_links.flatten()
    number_of_links.astype(float)
    values_at_nodes[:] = (values_at_links[north]+values_at_links[east]+values_at_links[south]+values_at_links[west])/(number_of_links)

<commit_msg>correct mappers.py<commit_after>#! /usr/bin/env python
"""Map values from one grid element to another.

Each link has a *tail* and *head* node. The *tail* nodes are located at the
start of a link, while the head nodes are located at end of a link.

Below, the numbering scheme for links in `RasterModelGrid` is illustrated
with an example of a four-row by five column grid (4x5). In this example,
each * (or X) is a node, the lines represent links, and the ^ and > symbols
indicate the direction and *head* of each link. Link heads in the
`RasterModelGrid` always point in the cardinal directions North (N) or East
(E).::

    *--27-->*--28-->*--29-->*--30-->*
    ^       ^       ^       ^       ^
   10      11      12      13      14
    |       |       |       |       |
    *--23-->*--24-->*--25-->*--26-->*
    ^       ^       ^       ^       ^
    5       6       7       8       9
    |       |       |       |       |
    *--19-->*--20-->X--21-->*--22-->*
    ^       ^       ^       ^       ^
    0       1       2       3       4
    |       |       |       |       |
    *--15-->*--16-->*--17-->*--18-->*

For example, node 'X' has four link-neighbors. From south and going clockwise,
these neighbors are [2, 20, 7, 21]. Both link 2 and link 20 have node 'X' as
their 'head' node, while links 7 and 21 have node 'X' as their tail node.
"""
from __future__ import division

import numpy as np

def map_link_head_node_to_link(mg, var_name, out=None):
    """Map values from a link head nodes to links.

    Iterate over a grid and identify the node at the *head*. For each link,
    the value of *var_name* at the *head* node is mapped to the corresponding
    link.

    In a RasterModelGrid, each one node has two adjacent "link heads". This
    means each node value is mapped to two corresponding links.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at links.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_link_head_node_to_link
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', np.arange(12.))
    >>> map_link_head_node_to_link(rmg, 'z')
    array([  4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,   1.,   2.,   3.,
             5.,   6.,   7.,   9.,  10.,  11.])

    >>> values_at_links = rmg.empty(centering='link')
    >>> rtn = map_link_head_node_to_link(rmg, 'z', out=values_at_links)
    >>> values_at_links
    array([  4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,   1.,   2.,   3.,
             5.,   6.,   7.,   9.,  10.,  11.])
    >>> rtn is values_at_links
    True
    """
    values_at_nodes = mg.at_node[var_name]
    if out is None:
        out = mg.empty(centering='link')
    out[:] = values_at_nodes[mg.node_at_link_head]

    return out

def map_link_tail_node_to_link(mg, var_name, out=None):
    """Map values from a link tail nodes to links.

    map_values_from_link_tail_node_to_link iterates across the grid and
    identifies the node at the "tail", or the "from" node for each link. For
    each link, the value of 'var_name' at the "from" node is mapped to the
    corresponding link.

    In a RasterModelGrid, each one node has two adjacent "link tails". This means
    each node value is mapped to two corresponding links.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at links.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_link_tail_node_to_link
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', np.arange(12.))
    >>> map_link_tail_node_to_link(rmg, 'z')
    array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   0.,   1.,   2.,
             4.,   5.,   6.,   8.,   9.,  10.])

    >>> values_at_links = rmg.empty(centering='link')
    >>> rtn = map_link_tail_node_to_link(rmg, 'z', out=values_at_links)
    >>> values_at_links
    array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   0.,   1.,   2.,
             4.,   5.,   6.,   8.,   9.,  10.])
    >>> rtn is values_at_links
    True
    """
    if out is None:
        out = mg.empty(centering='link')

    values_at_nodes = mg.at_node[var_name]
    out[:] = values_at_nodes[mg.node_at_link_tail]

    return out

def map_min_of_link_nodes_to_link(mg, var_name, out=None):
    """Map the minimum of a link's nodes to the link.

    map_link_end_node_min_value_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function evaluates the value of 'var_name' at both the "to" and "from" node.
    The minimum value of the two node values is then mapped to the link.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at links.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_min_of_link_nodes_to_link
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', [[0, 1, 2, 3], [7, 6, 5, 4], [8, 9, 10, 11]])
    >>> map_min_of_link_nodes_to_link(rmg, 'z')
    array([  0.,   1.,   2.,   3.,   7.,   6.,   5.,   4.,   0.,   1.,   2.,
             6.,   5.,   4.,   8.,   9.,  10.])

    >>> values_at_links = rmg.empty(centering='link')
    >>> rtn = map_min_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
    >>> values_at_links
    array([  0.,   1.,   2.,   3.,   7.,   6.,   5.,   4.,   0.,   1.,   2.,
             6.,   5.,   4.,   8.,   9.,  10.])
    >>> rtn is values_at_links
    True
    """
    if out is None:
        out = mg.empty(centering='link')

    values_at_nodes = mg.at_node[var_name]
    np.minimum(values_at_nodes[mg.node_at_link_head],
               values_at_nodes[mg.node_at_link_tail],
               out=out)

    return out

def map_max_of_link_nodes_to_link(mg, var_name, out=None):
    """Map the maximum of a link's nodes to the link.

    map_link_end_node_max_value_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function evaluates the value of 'var_name' at both the "to" and "from" node.
    The maximum value of the two node values is then mapped to the link.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at links.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_max_of_link_nodes_to_link
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', [[0, 1, 2, 3], [7, 6, 5, 4], [8, 9, 10, 11]])
    >>> map_max_of_link_nodes_to_link(rmg, 'z')
    array([  7.,   6.,   5.,   4.,   8.,   9.,  10.,  11.,   1.,   2.,   3.,
             7.,   6.,   5.,   9.,  10.,  11.])

    >>> values_at_links = rmg.empty(centering='link')
    >>> rtn = map_max_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
    >>> values_at_links
    array([  7.,   6.,   5.,   4.,   8.,   9.,  10.,  11.,   1.,   2.,   3.,
             7.,   6.,   5.,   9.,  10.,  11.])
    >>> rtn is values_at_links
    True
    """
    if out is None:
        out = mg.empty(centering='link')

    values_at_nodes = mg.at_node[var_name]
    np.maximum(values_at_nodes[mg.node_at_link_head],
               values_at_nodes[mg.node_at_link_tail],
               out=out)

    return out

def map_mean_of_link_nodes_to_link(mg, var_name, out=None):
    """Map the mean of a link's nodes to the link.

    map_values_from_link_end_nodes_to_link iterates across the grid and
    identifies the node values at both the "head" and "tail" of a given link.
    This function takes the sum of the two values of 'var_name' at both the "to"
    and "from" node. The average value of the two node values of 'var_name'
    is then mapped to the link.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at links.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_mean_of_link_nodes_to_link
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', np.arange(12.))
    >>> map_mean_of_link_nodes_to_link(rmg, 'z')
    array([  2. ,   3. ,   4. ,   5. ,   6. ,   7. ,   8. ,   9. ,   0.5,
             1.5,   2.5,   4.5,   5.5,   6.5,   8.5,   9.5,  10.5])

    >>> values_at_links = rmg.empty(centering='link')
    >>> rtn = map_mean_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
    >>> values_at_links
    array([  2. ,   3. ,   4. ,   5. ,   6. ,   7. ,   8. ,   9. ,   0.5,
             1.5,   2.5,   4.5,   5.5,   6.5,   8.5,   9.5,  10.5])
    >>> rtn is values_at_links
    True
    """
    if out is None:
        out = mg.empty(centering='link')

    values_at_nodes = mg.at_node[var_name]
    out[:] = 0.5 * (values_at_nodes[mg.node_at_link_head] +
                    values_at_nodes[mg.node_at_link_tail])

    return out

def map_node_to_cell(mg, var_name, out=None):
    """Map values for nodes to cells.

    map_values_from_cell_node_to_cell iterates across the grid and
    identifies the all node values of 'var_name'.

    This function takes node values of 'var_name' and mapes that value to the
    corresponding cell area for each node.

    Parameters
    ----------
    mg : ModelGrid
        A landlab ModelGrid.
    var_name : str
        Name of variable field defined at nodes.
    out : ndarray, optional
        Buffer to place mapped values into or `None` to create a new array.

    Returns
    -------
    ndarray
        Mapped values at cells.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.grid.mappers import map_node_to_cell
    >>> from landlab import RasterModelGrid

    >>> rmg = RasterModelGrid((3, 4))
    >>> _ = rmg.add_field('node', 'z', np.arange(12.))
    >>> map_node_to_cell(rmg, 'z')
    array([ 5., 6.])

    >>> values_at_cells = rmg.empty(centering='cell')
    >>> rtn = map_node_to_cell(rmg, 'z', out=values_at_cells)
    >>> values_at_cells
    array([ 5., 6.])
    >>> rtn is values_at_cells
    True
    """
    if out is None:
        out = mg.empty(centering='cell')

    values_at_nodes = mg.at_node[var_name]
    out[:] = values_at_nodes[mg.node_at_cell]

    return out
<|endoftext|>


<commit_before>from itertools import product
import attr
from .base import Feed
from ..libs.config import get_config

class BraveNewCoin(Feed):
    config = get_config()['bravenewcoin']
    api_key_id = (config.get('api_key_id', '') if config else '')
    api_key_secret = (config.get('api_key_secret', '') if config else '')
    api_url = 'https://bravenewcoin-v1.p.mashape.com/'

    def __init__(self, requester='basic', cache_dir=None):
      super().__init__(requester=requester, cache_dir=cache_dir)
      self.headers = {f'{self.api_key_id}': f'{self.api_key_secret}'}

    def get_list(self):
      api_url = f'{self.api_url}/digital-currency-symbols'
      data = self._make_request(api_url, headers=self.headers)
      response = []

      for json_dict in data['digital_currencies']:
        for key, value in json_dict.items():
          response.insert(0, key)

      return response

    #TODO implement this
    def get_info(self, assets):
      raise NotImplementedError('Not implemented yet')

    #TODO implement this
    def get_prices(self, assets, currencies):
      raise NotImplementedError('Not implemented yet')
<commit_msg>implemented BNC get_prices<commit_after>from itertools import product
import attr
from .base import Feed
from ..libs.config import get_config

class BraveNewCoin(Feed):
    config = get_config()['bravenewcoin']
    api_key_id = (config.get('api_key_id', '') if config else '')
    api_key_secret = (config.get('api_key_secret', '') if config else '')
    api_url = 'https://bravenewcoin-v1.p.mashape.com/'

    def __init__(self, requester='basic', cache_dir=None):
      super().__init__(requester=requester, cache_dir=cache_dir)
      self.headers = {f'{self.api_key_id}': f'{self.api_key_secret}'}

    def get_list(self):
      api_url = f'{self.api_url}/digital-currency-symbols'
      data = self._make_request(api_url, headers=self.headers)
      response = []

      response = [key
                  for json_dict in data['digital_currencies']
                  for key, value in json_dict.items()]

      return response

    #TODO implement this
    def get_info(self, assets):
      raise NotImplementedError('Not implemented yet')

    def get_prices(self, assets, currencies):
      """Not the most efficient method as BNC does not
      allow a list for input. So we iterate over each
      asset and currency and make separate calls"""
      response = []
      for asset in assets.split(','):
        for currency in currencies.split(','):
          api_url = f'{self.api_url}/ticker/?coin={asset}&show={currency}'
          data = self._make_request(api_url, headers=self.headers)
          if data['success'] != True:
            continue

          response.insert(len(response),
            {'asset':asset, 'currency':currency, 'price': float(data['last_price'])})

      return response<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Project metadata

Information describing the project.
"""

# The package name, which is also the "UNIX name" for the project.
package = 'o365_email_processor'
project = "Office 365 Email Processor"
project_no_spaces = project.replace(' ', '')
version = '0.1'
description = """Pulls emails from Office 365, stores them in a database,
    and processes with user defined actions"""
authors = ['Craig Koroscil']
authors_string = ', '.join(authors)
emails = ['sintax@obscurepacket.org']
license = 'MIT'
copyright = '2016 ' + authors_string
url = 'https://github.com/sintax1/o365-email-processor'
<commit_msg>Increased release version<commit_after># -*- coding: utf-8 -*-
"""Project metadata

Information describing the project.
"""

# The package name, which is also the "UNIX name" for the project.
package = 'o365_email_processor'
project = "Office 365 Email Processor"
project_no_spaces = project.replace(' ', '')
version = '0.2'
description = """Pulls emails from Office 365, stores them in a database,
    and processes with user defined actions"""
authors = ['Craig Koroscil']
authors_string = ', '.join(authors)
emails = ['sintax@obscurepacket.org']
license = 'MIT'
copyright = '2016 ' + authors_string
url = 'https://github.com/sintax1/o365-email-processor'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    lantz.drivers.usbtmc
    ~~~~~~~~~~~~~~~~~~~~

    Implements a USBDriver based class to control USBTMC instruments

    Loosely based on PyUSBTMC:python module to handle USB-TMC(Test and Measurement class)　devices.
    by Noboru Yamamot, Accl. Lab, KEK, JAPAN

    :copyright: 2013 by Lantz Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

import time
import struct
from collections import namedtuple

import usb

from lantz.driver import TextualMixin
from lantz.errors import InstrumentError
from lantz.usb import find_devices, find_interfaces, find_endpoint, USBDriver

class MSGID(object):
    """From USB-TMC table2
    """
    DEV_DEP_MSG_OUT = 1
    REQUEST_DEV_DEP_MSG_IN = 2
    DEV_DEP_MSG_IN = 2
    VENDOR_SPECIFIC_OUT = 126
    REQUEST_VENDOR_SPECIFIC_IN = 127
    VENDOR_SPECIFIC_IN = 127
    TRIGGER = 128 # for USB488

class REQUEST(object):
    INITIATE_ABORT_BULK_OUT = 1
    CHECK_ABORT_BULK_OUT_STATUS = 2
    INITIATE_ABORT_BULK_IN = 3
    CHECK_ABORT_BULK_IN_STATUS = 4
    INITIATE_CLEAR = 5
    CHECK_CLEAR_STATUS = 6
    GET_CAPABILITIES = 7
    INDICATOR_PULSE = 64

def find_tmc_devices(vendor=None, product=None, serial_number=None, custom_match=None, **kwargs):
    """Find connected USBTMC devices. See lantz.usb.find_devices for more info.
    """
    def is_usbtmc(dev):
        if custom_match and not custom_match(dev):
            return False
        return bool(find_interfaces(dev, bInterfaceClass=0xfe, bInterfaceSubClass=3))

    return find_devices(vendor, product, serial_number, is_usbtmc, **kwargs)

class BulkOutMessage(object):
    """The Host uses the Bulk-OUT endpoint to send USBTMC command messages to the device.
    """

    @staticmethod
    def build_array(btag, eom, chunk):
        size = len(chunk)
        return struct.pack('BBBx', MSGID.DEV_DEP_MSG_OUT, btag, ~btag & 0xFF) + \
               struct.pack("<LBxxx", size, eom) + \
               chunk + \
               b'\0' * ((4 - size) % 4)

class BulkInMessage(namedtuple('BulkInMessage', 'msgid btag btaginverse '
                                                'transfer_size transfer_attributes data')):
    """The Host uses the Bulk-IN endpoint to read USBTMC response messages from the device.
    The Host must first send a USBTMC command message that expects a response before
    attempting to read a USBTMC response message.
    """

    @classmethod
    def from_bytes(cls, data):
        msgid, btag, btaginverse = struct.unpack_from('BBBx', data)
        assert msgid == MSGID.DEV_DEP_MSG_IN

        transfer_size, transfer_attributes = struct.unpack_from('<LBxxx', data, 4)

        data = data[12:]
        return cls(msgid, btag, btaginverse, transfer_size, transfer_attributes, data)

    @staticmethod
    def build_array(btag, transfer_size, term_char=None):
        """

        :param transfer_size:
        :param btag:
        :param term_char:
        :return:
        """

        if term_char is None:
            transfer_attributes = 0
            term_char = 0
        else:
            transfer_attributes = 2

        return struct.pack('BBBx', MSGID.REQUEST_DEV_DEP_MSG_IN, btag, ~btag & 0xFF) + \
               struct.pack("<LBBxx", transfer_size, transfer_attributes, term_char)

class USBTMCDriver(USBDriver, TextualMixin):

    SEND_TERMINATION = ''
    RECV_TERMINATION = '\n'

    RECV_CHUNK = 1024 ** 2

    find_devices = staticmethod(find_tmc_devices)

    def __init__(self, vendor=None, product=None, serial_number=None, **kwargs):
        super().__init__(vendor, product, serial_number, **kwargs)
        self.usb_intr_in = find_endpoint(self.usb_intf, usb.ENDPOINT_IN, usb.ENDPOINT_TYPE_INTERRUPT)
        self.log_debug('EP Address: intr={}'.format(self.usb_intr_in.bEndpointAddress))

        self.usb_dev.reset()

        time.sleep(0.01)

        self._get_capabilities()

        self.usb_dev.set_configuration()

        self._btag = 0

        if not (self.usb_recv_ep and self.usb_send_ep):
            raise InstrumentError("TMC device must have both Bulk-In and Bulk-out endpoints.")

    def _get_capabilities(self):
        cap = self.usb_dev.ctrl_transfer(
                   usb.util.build_request_type(usb.util.CTRL_IN,
                                               usb.util.CTRL_TYPE_CLASS,
                                               usb.util.CTRL_RECIPIENT_INTERFACE),
                   REQUEST.GET_CAPABILITIES,
                   0x0000,
                   self.usb_intf.index,
                   0x0018,
                   timeout=self.TIMEOUT)

    def _find_interface(self, dev, setting):
        interfaces = find_interfaces(dev, bInterfaceClass=0xFE, bInterfaceSubClass=3)
        if not interfaces:
            raise InstrumentError('USB TMC interface not found.')
        elif len(interfaces) > 1:
            self.log_warning('More than one interface found, selecting first.')

        return interfaces[0]

    def send(self, command, termination=None, encoding=None):
        if termination is None:
            termination = self.SEND_TERMINATION
        if encoding is None:
            encoding = self.ENCODING

        message = bytes(command + termination, encoding)
        self.log_debug('Sending {}', message)

        begin, end, size = 0, 0, len(message)
        bytes_sent = 0
        while not end > size:
            begin, end = end, begin + self.RECV_CHUNK

            self._btag = (self._btag % 255) + 1

            data = BulkOutMessage.build_array(self._btag, end > size, message[begin:end])

            bytes_sent += self.raw_send(data)

        return bytes_sent

    send.__doc__ = TextualMixin.send.__doc__

    def recv(self, termination=None, encoding=None, recv_chunk=None):

        termination = termination or self.RECV_TERMINATION
        encoding = encoding or self.ENCODING
        recv_chunk = recv_chunk or self.RECV_CHUNK

        eom = False

        received = self._received

        while not (termination in received or eom):
            self._btag = (self._btag % 255) + 1

            req = BulkInMessage.build_array(self._btag, recv_chunk, None)

            self.raw_send(req)

            resp = self.raw_recv(recv_chunk)

            response = BulkInMessage.from_bytes(resp)

            received += str(response.data, encoding)
            eom = response.transfer_attributes & 1

        self.log_debug('Received {!r} (len={})', received, len(received))

        received, self._received = received.split(termination, 1)

        return received

    recv.__doc__ = TextualMixin.recv.__doc__

<commit_msg>Migrated to use new Enum class<commit_after># -*- coding: utf-8 -*-
"""
    lantz.drivers.usbtmc
    ~~~~~~~~~~~~~~~~~~~~

    Implements a USBDriver based class to control USBTMC instruments

    Loosely based on PyUSBTMC:python module to handle USB-TMC(Test and Measurement class)　devices.
    by Noboru Yamamot, Accl. Lab, KEK, JAPAN

    :copyright: 2013 by Lantz Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

import enum
import time
import struct
from collections import namedtuple

import usb

from lantz.driver import TextualMixin
from lantz.errors import InstrumentError
from lantz.usb import find_devices, find_interfaces, find_endpoint, USBDriver

class MSGID(enum.IntEnum):
    """From USB-TMC table2
    """
    DEV_DEP_MSG_OUT = 1
    REQUEST_DEV_DEP_MSG_IN = 2
    DEV_DEP_MSG_IN = 2
    VENDOR_SPECIFIC_OUT = 126
    REQUEST_VENDOR_SPECIFIC_IN = 127
    VENDOR_SPECIFIC_IN = 127
    TRIGGER = 128 # for USB488

class REQUEST(enum.IntEnum):
    INITIATE_ABORT_BULK_OUT = 1
    CHECK_ABORT_BULK_OUT_STATUS = 2
    INITIATE_ABORT_BULK_IN = 3
    CHECK_ABORT_BULK_IN_STATUS = 4
    INITIATE_CLEAR = 5
    CHECK_CLEAR_STATUS = 6
    GET_CAPABILITIES = 7
    INDICATOR_PULSE = 64

def find_tmc_devices(vendor=None, product=None, serial_number=None, custom_match=None, **kwargs):
    """Find connected USBTMC devices. See lantz.usb.find_devices for more info.
    """
    def is_usbtmc(dev):
        if custom_match and not custom_match(dev):
            return False
        return bool(find_interfaces(dev, bInterfaceClass=0xfe, bInterfaceSubClass=3))

    return find_devices(vendor, product, serial_number, is_usbtmc, **kwargs)

class BulkOutMessage(object):
    """The Host uses the Bulk-OUT endpoint to send USBTMC command messages to the device.
    """

    @staticmethod
    def build_array(btag, eom, chunk):
        size = len(chunk)
        return struct.pack('BBBx', MSGID.DEV_DEP_MSG_OUT, btag, ~btag & 0xFF) + \
               struct.pack("<LBxxx", size, eom) + \
               chunk + \
               b'\0' * ((4 - size) % 4)

class BulkInMessage(namedtuple('BulkInMessage', 'msgid btag btaginverse '
                                                'transfer_size transfer_attributes data')):
    """The Host uses the Bulk-IN endpoint to read USBTMC response messages from the device.
    The Host must first send a USBTMC command message that expects a response before
    attempting to read a USBTMC response message.
    """

    @classmethod
    def from_bytes(cls, data):
        msgid, btag, btaginverse = struct.unpack_from('BBBx', data)
        assert msgid == MSGID.DEV_DEP_MSG_IN

        transfer_size, transfer_attributes = struct.unpack_from('<LBxxx', data, 4)

        data = data[12:]
        return cls(msgid, btag, btaginverse, transfer_size, transfer_attributes, data)

    @staticmethod
    def build_array(btag, transfer_size, term_char=None):
        """

        :param transfer_size:
        :param btag:
        :param term_char:
        :return:
        """

        if term_char is None:
            transfer_attributes = 0
            term_char = 0
        else:
            transfer_attributes = 2

        return struct.pack('BBBx', MSGID.REQUEST_DEV_DEP_MSG_IN, btag, ~btag & 0xFF) + \
               struct.pack("<LBBxx", transfer_size, transfer_attributes, term_char)

class USBTMCDriver(USBDriver, TextualMixin):

    SEND_TERMINATION = ''
    RECV_TERMINATION = '\n'

    RECV_CHUNK = 1024 ** 2

    find_devices = staticmethod(find_tmc_devices)

    def __init__(self, vendor=None, product=None, serial_number=None, **kwargs):
        super().__init__(vendor, product, serial_number, **kwargs)
        self.usb_intr_in = find_endpoint(self.usb_intf, usb.ENDPOINT_IN, usb.ENDPOINT_TYPE_INTERRUPT)
        self.log_debug('EP Address: intr={}'.format(self.usb_intr_in.bEndpointAddress))

        self.usb_dev.reset()

        time.sleep(0.01)

        self._get_capabilities()

        self.usb_dev.set_configuration()

        self._btag = 0

        if not (self.usb_recv_ep and self.usb_send_ep):
            raise InstrumentError("TMC device must have both Bulk-In and Bulk-out endpoints.")

    def _get_capabilities(self):
        cap = self.usb_dev.ctrl_transfer(
                   usb.util.build_request_type(usb.util.CTRL_IN,
                                               usb.util.CTRL_TYPE_CLASS,
                                               usb.util.CTRL_RECIPIENT_INTERFACE),
                   REQUEST.GET_CAPABILITIES,
                   0x0000,
                   self.usb_intf.index,
                   0x0018,
                   timeout=self.TIMEOUT)

    def _find_interface(self, dev, setting):
        interfaces = find_interfaces(dev, bInterfaceClass=0xFE, bInterfaceSubClass=3)
        if not interfaces:
            raise InstrumentError('USB TMC interface not found.')
        elif len(interfaces) > 1:
            self.log_warning('More than one interface found, selecting first.')

        return interfaces[0]

    def send(self, command, termination=None, encoding=None):
        if termination is None:
            termination = self.SEND_TERMINATION
        if encoding is None:
            encoding = self.ENCODING

        message = bytes(command + termination, encoding)
        self.log_debug('Sending {}', message)

        begin, end, size = 0, 0, len(message)
        bytes_sent = 0
        while not end > size:
            begin, end = end, begin + self.RECV_CHUNK

            self._btag = (self._btag % 255) + 1

            data = BulkOutMessage.build_array(self._btag, end > size, message[begin:end])

            bytes_sent += self.raw_send(data)

        return bytes_sent

    send.__doc__ = TextualMixin.send.__doc__

    def recv(self, termination=None, encoding=None, recv_chunk=None):

        termination = termination or self.RECV_TERMINATION
        encoding = encoding or self.ENCODING
        recv_chunk = recv_chunk or self.RECV_CHUNK

        eom = False

        received = self._received

        while not (termination in received or eom):
            self._btag = (self._btag % 255) + 1

            req = BulkInMessage.build_array(self._btag, recv_chunk, None)

            self.raw_send(req)

            resp = self.raw_recv(recv_chunk)

            response = BulkInMessage.from_bytes(resp)

            received += str(response.data, encoding)
            eom = response.transfer_attributes & 1

        self.log_debug('Received {!r} (len={})', received, len(received))

        received, self._received = received.split(termination, 1)

        return received

    recv.__doc__ = TextualMixin.recv.__doc__

<|endoftext|>


<commit_before># Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundation
#
# LAVA Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with LAVA Server.  If not, see <http://www.gnu.org/licenses/>.

__version__ = (0, 8, 0, "dev", 0)
<commit_msg>bump version<commit_after># Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundation
#
# LAVA Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with LAVA Server.  If not, see <http://www.gnu.org/licenses/>.

__version__ = (0, 8, 0, "final", 0)
<|endoftext|>


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

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np

class StatsWidget(QtGui.QWidget):

    def __init__(self, driver):
        super(StatsWidget, self).__init__()

        self.driver = driver

        self.layout = QtGui.QHBoxLayout()

        self.mean_labels = []
        self.ampl_labels = []
        self.ampl_rms_labels = []
        self.n_channels = 2
        self.window_size = 50

        self.average = np.zeros(self.n_channels)
        self.amplitude = np.zeros(self.n_channels)
        self.amplitude_rms = np.zeros(self.n_channels)

        self.average_vec = np.zeros((self.n_channels, self.window_size))
        self.amplitude_vec = np.zeros((self.n_channels, self.window_size))
        self.amplitude_rms_vec = np.zeros((self.n_channels, self.window_size))

        for i in range(self.n_channels):
            self.average_vec[i,:] = self.get_average(i)
            self.amplitude_vec[i,:] = self.get_amplitude(i)
            self.amplitude_rms_vec[i,:] = self.get_amplitude_rms(i)

        for i in range(self.n_channels+1):
            self.mean_labels.append(QtGui.QLabel(''))
            self.ampl_labels.append(QtGui.QLabel(''))
            self.ampl_rms_labels.append(QtGui.QLabel(''))
            self.mean_labels[i].setAlignment(QtCore.Qt.AlignCenter)
            self.ampl_labels[i].setAlignment(QtCore.Qt.AlignCenter)
            self.ampl_rms_labels[i].setAlignment(QtCore.Qt.AlignCenter)

        self.mean_labels[0].setText('Average')
        self.ampl_labels[0].setText('Peak-Peak')
        self.ampl_rms_labels[0].setText('RMS')

        self.boxes = []
        self.box_names = ['Measures', 'ADC 1', 'ADC 2']
        for i in range(self.n_channels+1):
            self.boxes.append(QtGui.QGroupBox(self.box_names[i]))
            self.boxes[i].setAlignment(5)

        self.name_layout = QtGui.QVBoxLayout()
        self.name_layout.addWidget(self.mean_labels[0])
        self.name_layout.addWidget(self.ampl_labels[0])
        self.name_layout.addWidget(self.ampl_rms_labels[0])
        self.boxes[0].setLayout(self.name_layout)

        self.adc_1_layout = QtGui.QVBoxLayout()
        self.adc_1_layout.addWidget(self.mean_labels[1])
        self.adc_1_layout.addWidget(self.ampl_labels[1])
        self.adc_1_layout.addWidget(self.ampl_rms_labels[1])
        self.boxes[1].setLayout(self.adc_1_layout)

        self.adc_2_layout = QtGui.QVBoxLayout()
        self.adc_2_layout.addWidget(self.mean_labels[2])
        self.adc_2_layout.addWidget(self.ampl_labels[2])
        self.adc_2_layout.addWidget(self.ampl_rms_labels[2])
        self.boxes[2].setLayout(self.adc_2_layout)

        for i in range(self.n_channels+1):
            self.layout.addWidget(self.boxes[i])

    def get_average(self, channel):
        return np.mean(self.driver.adc[channel,:])

    def get_amplitude(self, channel):
        return np.max(self.driver.adc[channel,:])-np.min(self.driver.adc[channel,:])

    def get_amplitude_rms(self, channel):
        return np.std(self.driver.adc[channel,:])

    def format_value(self, value):
        return '{:.2f}'.format(value) if 1e-2 < abs(value) < 1e4 else '%.4e' % value

    def update(self):
        self.average_vec = np.roll(self.average_vec, 1, axis=1)
        self.amplitude_vec = np.roll(self.amplitude_vec, 1, axis=1)
        self.amplitude_rms_vec = np.roll(self.amplitude_rms_vec, 1, axis=1)

        for i in range(self.n_channels):
            self.average_vec[i,0] = self.get_average(i)
            self.amplitude_vec[i,0] = self.get_amplitude(i)
            self.amplitude_rms_vec[i,0] = self.get_amplitude_rms(i)

            self.average[i] = np.mean(self.average_vec[i,:])
            mean_text = self.format_value(self.average[i])
            self.mean_labels[i+1].setText(mean_text)

            self.amplitude[i] = np.mean(self.amplitude_vec[i,:])
            ampl_text = self.format_value(self.amplitude[i])
            self.ampl_labels[i+1].setText(ampl_text)

            self.amplitude_rms[i] = np.mean(self.amplitude_rms_vec[i,:])
            ampl_rms_text = self.format_value(self.amplitude_rms[i])
            self.ampl_rms_labels[i+1].setText(ampl_rms_text)

<commit_msg>clean stats_widget<commit_after># -*- coding: utf-8 -*-

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np

class StatsWidget(QtGui.QWidget):

    def __init__(self, driver):
        super(StatsWidget, self).__init__()

        self.driver = driver

        self.layout = QtGui.QGridLayout()

        self.mean_labels = []
        self.ampl_labels = []
        self.ampl_rms_labels = []
        self.n_channels = 2
        self.window_size = 50

        self.average = np.zeros(self.n_channels)
        self.amplitude = np.zeros(self.n_channels)
        self.amplitude_rms = np.zeros(self.n_channels)

        self.average_vec = np.zeros((self.n_channels, self.window_size))
        self.amplitude_vec = np.zeros((self.n_channels, self.window_size))
        self.amplitude_rms_vec = np.zeros((self.n_channels, self.window_size))

        for i in range(self.n_channels):
            self.average_vec[i,:] = self.get_average(i)
            self.amplitude_vec[i,:] = self.get_amplitude(i)
            self.amplitude_rms_vec[i,:] = self.get_amplitude_rms(i)

        for i in range(self.n_channels+1):
            self.mean_labels.append(QtGui.QLabel(''))
            self.ampl_labels.append(QtGui.QLabel(''))
            self.ampl_rms_labels.append(QtGui.QLabel(''))

        self.mean_labels[0].setText('Average')
        self.ampl_labels[0].setText('Peak-Peak')
        self.ampl_rms_labels[0].setText('RMS')

        for i in range(self.n_channels+1):
            self.layout.addWidget(QtGui.QLabel('DAC '+str(i) if i != 0 else ''), 0, i)
            self.layout.addWidget(self.mean_labels[i], 1, i)
            self.layout.addWidget(self.ampl_labels[i], 2, i)
            self.layout.addWidget(self.ampl_rms_labels[i], 3, i)

    def get_average(self, channel):
        return np.mean(self.driver.adc[channel,:])

    def get_amplitude(self, channel):
        return np.max(self.driver.adc[channel,:])-np.min(self.driver.adc[channel,:])

    def get_amplitude_rms(self, channel):
        return np.std(self.driver.adc[channel,:])

    def format_value(self, value):
        return '{:.2f}'.format(value) if 1e-2 < abs(value) < 1e4 else '%.4e' % value

    def update(self):
        self.average_vec = np.roll(self.average_vec, 1, axis=1)
        self.amplitude_vec = np.roll(self.amplitude_vec, 1, axis=1)
        self.amplitude_rms_vec = np.roll(self.amplitude_rms_vec, 1, axis=1)

        for i in range(self.n_channels):
            self.average_vec[i,0] = self.get_average(i)
            self.amplitude_vec[i,0] = self.get_amplitude(i)
            self.amplitude_rms_vec[i,0] = self.get_amplitude_rms(i)

            self.average[i] = np.mean(self.average_vec[i,:])
            mean_text = self.format_value(self.average[i])
            self.mean_labels[i+1].setText(mean_text)

            self.amplitude[i] = np.mean(self.amplitude_vec[i,:])
            ampl_text = self.format_value(self.amplitude[i])
            self.ampl_labels[i+1].setText(ampl_text)

            self.amplitude_rms[i] = np.mean(self.amplitude_rms_vec[i,:])
            ampl_rms_text = self.format_value(self.amplitude_rms[i])
            self.ampl_rms_labels[i+1].setText(ampl_rms_text)

<|endoftext|>


<commit_before>import time
import random

from neopixel import *

# LED strip configuration:
LED_COUNT = 60  # Number of LED pixels.
LED_PIN = 18  # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5  # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
FULL_COLOR = 255 # maximum brightness of one rgb color part

def testlearna():
    iterations = 10
    color = Color(255, 255, 255)
    wait_ms = 50

    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)

def theaterChase(strip, color, wait_ms=50, iterations=10):
    """Movie theater light style chaser animation."""
    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)

# Main program logic follows:
if __name__ == '__main__':
    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    print 'Press Ctrl-C to quit.'
    while True:
        testlearna()
        #theaterChase(strip, Color(235,   91,   14), 200)<commit_msg>new test / learn file<commit_after>import time
import random

from neopixel import *

# LED strip configuration:
LED_COUNT = 60  # Number of LED pixels.
LED_PIN = 18  # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5  # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
FULL_COLOR = 255 # maximum brightness of one rgb color part

def testlearna():
    iterations = 10
    color = Color(255, 255, 255)
    wait_ms = 5000

    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)

def theaterChase(strip, color, wait_ms=50, iterations=10):
    """Movie theater light style chaser animation."""
    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)

# Main program logic follows:
if __name__ == '__main__':
    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    print 'Press Ctrl-C to quit.'
    while True:
        testlearna()
        #theaterChase(strip, Color(235,   91,   14), 200)<|endoftext|>