#!/usr/bin/python
# encoding: utf-8

########################################################
# Currently a hot mess...
# This needs to be cleaned up...

class AnkiFx(str):

    def __init__(self, apath):
        from anki import Collection as aopen
        self.col = aopen(apath)
        self.dm  = self.col.decks
        self.mm  = self.col.models

    def create_deck(self, title):
        self.col.decks.id(title)
        self.col.save()
        self.col.close()

    def create_card(self, did, data):

        mname = 'Alfred Dark'

        deck = self.dm.get(did)
        self.dm.select(deck['id'])

        model = self.mm.byName(mname)
        if model is None:
            model = self.dark_theme(mname)

        model['did'] = deck['id']
        self.mm.save(model)
        self.mm.setCurrent(model)

        card = self.col.newNote(forDeck=False)
        #for name in card.keys():

        card['Note ID'] = str(card.id)
        card['Front']   = data[0]
        card['F Note']  = ''
        card['Back']    = data[1]
        card['B Note']  = ''
        card['class']   = ''
        card['Noty']    = ''
        card['http']    = ''
        card['video']   = ''
        self.col.addNote(card)
        self.col.save()
        self.col.close()

    def dark_theme(self, name):
        import os
        abspath = os.path.abspath(__file__)

        path  = os.path.dirname(abspath) + '/template'
        f = path + '/front.txt'
        c = path + '/css.txt'
        b = path + '/back.txt'

        with open(f, 'r') as ft, open(c, 'r') as ct, open (b, 'r') as bt:
            ftemp = ft.read()
            css   = ct.read()
            btemp = bt.read()

        m  = self.mm.new(name)

        fld = self.mm.newField('Note ID'); self.mm.addField(m, fld)
        fld = self.mm.newField('Front');   self.mm.addField(m, fld)
        fld = self.mm.newField('F Note');  self.mm.addField(m, fld)
        fld = self.mm.newField('Back');    self.mm.addField(m, fld)
        fld = self.mm.newField('B Note');  self.mm.addField(m, fld)
        fld = self.mm.newField('class');   self.mm.addField(m, fld)
        fld = self.mm.newField('Noty');    self.mm.addField(m, fld)
        fld = self.mm.newField('http');    self.mm.addField(m, fld)
        fld = self.mm.newField('video');   self.mm.addField(m, fld)

        m['css'] = css

        t = self.mm.newTemplate('Card 1')
        t['qfmt'] = ftemp
        t['afmt'] = btemp
        self.mm.addTemplate(m, t)
        self.mm.add(m)
        return m

    def children(self, did):
        return self.dm.children(did)

    '''
    def did2cids(self, **kwargs):
        options = {'did' : None, 'mid' : None}
        options.update(kwargs)

        if options['did']:
            return self.dm.cids(options['did'], children=True)

        if options['mid']:
            return self.mm.get(options['mid'])
    '''

#    self.col.close()

class Tools(str):

    import sqlite3, json

    def __init__(self, col):
        self.col = col
        self.db  = self.sqlite3.connect(self.col)

    def all_decks(self):
        '''Returns a list of dicts with all deck info'''

        # name, extendRev, collapsed, browserCollapsed,
        # newToday, timeToday, extendNew, conf, revToday
        # lrnToday, id, mod

        results = []

        decks = self.db.execute("SELECT decks FROM col")
        decks = self.json.loads(decks.fetchone()[0])

        for id, deck in decks.items():
            results.append(deck)

        return results

    def deck_info(self, **kwargs):
        '''Returns deck info by -// name or did //-,
           if by name can be more than one deck
           to account for parent decks unless
           the full deck name is provided.'''

        options = {'did' : None, 'name' : None}
        options.update(kwargs)
        #self.db.row_factory = sqlite3.Row

        decks = self.db.execute("SELECT decks FROM col")
        decks = self.json.loads(decks.fetchone()[0])

        results = []

        for id, deck in decks.items():
            if options['did']:
                if id == options['did']:
                    return deck
            if options['name']:
                if deck['name'] == options['name']:
                    results.append(deck)

        return results[0]

    def all_configs(self):
        '''These are the deck options'''
        # name replayq lapse rev timer dyn
        # maxTaken usn new mod id autoplay

        configs = self.db.execute("SELECT dconf FROM col")
        configs = self.json.loads(configs.fetchone()[0])

        results = []

        for id, conf in configs.items():
            results.append(conf)

        return results

    def model_info(self, mid=None):
        '''A lot of info here'''
        #raise Exception('are you sure?')
        # name tags did usn req flds sortf
        # tmpls mod latexPost latexPre
        # type id css
        for _ in range(2):
            try:
                models = self.db.execute("SELECT models FROM col")
                models = self.json.loads(models.fetchone()[0])
                break
            except OperationalError:
                self.db.execute("PRAGMA busy_timeout = 30000")
                pass
        else:
            raise Exception('database is busy')

        #models = self.db.execute("SELECT models FROM col")
        #models = self.json.loads(models.fetchone()[0])

        for id, model in models.items():
            if id == mid:
                return model

    def card_info(self, **kwargs):

        # id nid did ord mod usn queue
        # due ivl factor reps lapses
        # left odue odid flags data

        options = {'nid' : None, 'did' : None, 'count' : False}
        options.update(kwargs)

        # card count by deck id
        # card_info(db, did=DID, count=True)

        if options['did'] and options['count'] is True:

            cards_did = self.db.execute("SELECT COUNT(*) "
                                            "FROM cards "
                                            "WHERE cards.did = ?", (options['did'],) )

            card_count = cards_did.fetchone()
            return card_count[0]

        # card_info(db, nid=NID)

        elif options['nid']:

            rows = self.db.execute("SELECT * FROM cards WHERE cards.nid = ?", (options['nid'],))

            colname = [ d[0] for d in rows.description ]
            for r in rows.fetchall():
                card = dict((colname[i], r[i]) for i in range(len(colname)))
                return card

        # card_info(db, did=DID)

        elif options['did']:

            results = []

            rows = self.db.execute("SELECT cards.id, nid, cards.did, ord, cards.mod, cards.usn, queue, due, ivl, factor, reps, lapses, left, odue, odid, cards.flags, cards.data "
                                 "FROM cards "
                                 "JOIN notes ON notes.id = cards.nid "
                                 "WHERE cards.did = ?", (options['did'],) )

            colname = [ d[0] for d in rows.description ]
            for r in rows:
                card = dict((colname[i], r[i]) for i in range(len(colname)))
                results.append(card)

            return results

    def card_spec(self, v, **kwargs):
        '''Return a specific value. May not be
           needed, as this value is returned
           by card_info() along with all the
           other values '''

        # card_spec(db, 'due', did='1419424106618')
        # card_spec(db, 'due', nid='1419441282918')
        # card_spec(db, 'queue', nid='1419441282918')
        # card_spec(db, 'due', cid='1419441341030')
        # card_spec(db, 'did', cid='1419441341030')

        results = []

        sel = {'v':('card_' + v)}

        options = {'cid' : None, 'nid' : None, 'did' : None}
        options.update(kwargs)

        if options['cid']:
            key, value = 'id', options['cid']
        elif options['nid']:
            key, value = 'nid', options['nid']
        elif options['did']:
            key, value = 'did', options['did']

        rows = self.db.execute("SELECT cards.id, cards.nid, cards.did, cards.ord, cards.mod, cards.usn, cards.queue, cards.due, cards.ivl, cards.factor, cards.reps, cards.lapses, cards.left, cards.odue, cards.odid, cards.flags, cards.data "
                             "FROM cards "
                             "JOIN notes ON notes.id = cards.nid "
                             "WHERE cards."+key+" = ?", (value,) )

        for card in rows:
            card_id, card_nid, card_did, card_ord, card_mod, card_usn, card_queue, card_due, card_ivl, card_factor, card_reps, card_lapses, card_left, card_odue, card_odid, card_flags, card_data = card
            results.append(vars()[sel['v']])

        return results

    def dids2cids(self, dids):
        return self.db.execute("select id from cards where did in " + dids)

    def cid2nid(self, card_id):
        row = self.db.execute("select nid from cards where id = ?", (card_id,)).fetchone()
        if row:
            return row['nid']
        return None

    def nid2cids(self, note_id, return_deck_id=False):
        # one to many relation

        card_ids = []
        deck_id = None
        for row in conn.execute("select id,did from cards where nid = ?", (note_id,)):
            card_ids.append(row['id'])
            deck_id = row['did']
        if return_deck_id:
            return card_ids, deck_id
        return card_ids

    def note_info(self, **kwargs):
        # id guid mod usn tags flds sfld csum flags data mid
        # note_info(db, nid='1232312', count=True)

        options = {'nid' : None, 'count' : False}
        options.update(kwargs)

        if options['count'] is True:
            notes = db.execute("SELECT count() FROM notes")
            total_notes = notes.fetchone()[0]
            return total_notes

        elif options['nid']:

            rows = self.db.execute("SELECT * FROM notes WHERE notes.id = ?", (options['nid'],))

            colname = [ d[0] for d in rows.description ]
            for r in rows.fetchall():
                return dict((colname[i], r[i]) for i in range(len(colname)))

        else:
            '''A lot of info (ALL NOTES)'''
            raise Exception('are you sure?')
            results = []
            rows = self.db.execute("SELECT * FROM notes")
            colname = [ d[0] for d in rows.description ]

            for r in rows.fetchall():
                note = dict((colname[i], r[i]) for i in range(len(colname)))
                results.append(note)

            return results

    def note_spec(self, v, **kwargs):
        '''Return a specific value. May not be
           needed, as this value is returned
           by note_info() along with all the
           other values '''

        # id guid mod usn tags flds sfld csum flags data mid

        # note_spec(db, 'mid', nid=1264521038872)
        # note_spec(db, 'tags', nid=1264521038872)
        # note_spec(db, 'id', mid=1204533978) # all note ids with mid

        #guid: f#z!8<!TCo
        #id: 1264521038872
        results = []

        sel = {'v':('note_' + v)}

        options = {'nid' : None, 'tags' : None, 'mid' : None}
        options.update(kwargs)

        if options['nid']:
            key, value = 'id', options['nid']
        elif options['tags']:
            key, value = 'tags', options['tags']
        elif options['mid']:
            key, value = 'mid', options['mid']

        try:
            rows = self.db.execute("SELECT notes.id, notes.guid, notes.mod, notes.usn, notes.tags, notes.flds, notes.sfld, notes.csum, notes.flags, notes.data, notes.mid "
                                 "FROM notes "
                                 "WHERE notes."+key+" = ?", (value,) )
        except UnboundLocalError:
            return None

        for note in rows:
            note_id, note_guid, note_mod, note_usn, note_tags, note_flds, note_sfld, note_csum, note_flags, note_data, note_mid = note
            results.append(vars()[sel['v']])

        return results

    def cnt_cards(self, did, name):
        cnt = self.card_info(did=did, count=True)
        if cnt > 0:
            return cnt
        else:
            matches = self._match_(name)
            #afx = AnkiFx(self.col)
            #matches = afx.children(did)
            return self.sum_cards(matches)

    def _stat(self, did, multi=False):
        cards = self.card_info(did=did)
        new = learning = review = 0
        for c in cards:

            if c['queue'] == 2:
                review += 1
            elif c['queue'] == 0:
                new += 1
            elif (c['queue'] == 1) or (c['queue'] == 3):
                learning += 1

        if multi is True:
            return {'new': new, 'learning': learning, 'review': review}

        if not (new == 0) and (learning == 0) and (review == 0):
            return {'new': new, 'learning': learning, 'review': review}
        else:
            return None

    def multi_stat(self, decks):
        from collections import Counter
        results = []

        for d in decks:
            stats = self._stat(d['id'], multi=True)
            results.append(stats)

        combine = Counter()
        for dic in results:
            combine.update(dic)

        return dict(combine)

    def deck_stats(self, did, name):

        stats = self._stat(did)

        if stats is None:
            matches = self._match_(name)
            return self.multi_stat(matches)

        return stats

    def base_name(self, name):
        return name.rsplit('::', 1)[0]
        #return name.split('::')[0]

    def _match_(self, base):
        '''match deck name against all names
        return all children if base name'''

        # name, extendRev, collapsed, browserCollapsed,
        # newToday, timeToday, extendNew, conf, revToday
        # lrnToday, id, mod

        results = []
        all_decks = self.all_decks()

        for d in all_decks:
            did  = d['id']
            name = d['name']

            if base in name:
                results.append({'id': did, 'name': name})

        return results

        '''
        results = []
        key = [dk] #['name']

        for d in all_decks:
            d1 = {k: d[k] for k in (key)}
            d2 = {k:v for k, v in d1.items() if dv in str(v)}

            if len(d2.keys()):
                results.append(d2)

        return results
        '''

    def sum_cards(self, matches):

        cnt = []
        for match in matches:
            cnt.append(self.card_info(did=match['id'], count=True))

        return sum(cnt)

        '''
        for match in matches:
            name, did = match
            cnt.append(self.card_info(did=did, count=True))

        return sum(cnt)
        '''

    def cids(self, did, utils):

        dids = [did]
        DECK = self.deck_info(did=did)
        NAME = DECK['name']
        kids = self._match_(NAME)
        kid_list = ()
        for k in kids:
            deck, name = k.values()
            kid_list = kid_list + ((deck, name),)

        for id, name in kid_list:
            dids.append(id)

        _list = list(self.dids2cids(utils.ids2str(dids)))
        return [i for sub in _list for i in sub]

    def deck_notes(self, did):
        import re, os
        from anki import utils

        #afx = AnkiFx(self.col)
        #cids = afx.did2cids(did=did)
        cids = self.cids(did, utils)

        components = self.col.split(os.sep)
        mediadir = ('/'.join(components[:-1]) + '/collection.media')

        nids = []
        for cid in cids:
            card = self.card_spec('nid', cid=cid)
            nids.append(card[0])

        notes = []
        for nid in nids:

            ndict = {'nid': None, 'flds': None, 'tags': None, 'mid': None, 'mname': None, 'img': None}

            # note info for each note id
            note = self.note_info(nid=nid)

            # readable note fields, strip HTML
            flds = filter(None, note['flds'].split('\x1f'))
            m = lambda i: [re.findall('src="([^"]+)"', f, re.DOTALL) for f in i]
            img = [x[0] for x in m(flds) if x]
            f = lambda x: [utils.stripHTMLMedia(i) for i in x]
            flds = f(flds)

            #f = lambda x: [utils.stripHTMLMedia(i) for i in x]
            #flds = f(filter(None, note['flds'].split('\x1f')))

            # from note model id, retrieve model fields
            mid = str(note['mid'])

            #model = afx.did2cids(mid=mid)
            model = self.model_info(mid=mid)

            # get field names for model
            mflds = [mfld['name'] for mfld in model['flds']]

            ndict['nid']   = nid
            #ndict['flds']  = (' '.join(flds)).encode('utf-8')
            ndict['flds']  = flds
            ndict['tags']  = note['tags']
            ndict['mid']   = mid
            ndict['mname'] = model['name']
            if img:
                ndict['img']   = '{}/{}'.format(mediadir, img[0])

            notes.append(ndict)

        return notes

    def create_tags(self, nid, tags):
        import time

        try:
            tags = [t.replace('#', '') for t in tags[0].split()]
        except AttributeError:
            tags = None

        if tags is None:
            tagsstr = ''
        else:
            tagsstr = ' {} '.format(' '.join(tags))

        self.db.execute('UPDATE notes SET tags=?,mod=?,usn=? WHERE id=?', (tagsstr, int(time.time()), -1, nid))
        self.db.commit()
        self.db.close()
        return tags


from nltk.corpus import wordnet

class AspectSynonymBank:

    location = ['location', 'placement', 'locating', 'position', 'positioning', 'emplacement', 'localization',
                'localisation', 'fix', 'ocean', 'sea', 'sunset', 'sundown', 'wave', 'beautiful', 'colonial',
                'atmosphere', 'ambiance', 'air', 'aura', 'building', 'construction', 'construct', 'progress',
                'establish', 'place', 'spot', 'property', 'home', 'situation', 'situated', 'station', 'train', 'road',
                'city', 'countryside', 'urban', 'rural', 'identify', 'localize', 'view', 'perspective', 'scene', 'vista',
                'panorama', 'scenery', 'horizon', 'watch', 'heritage', 'inheritance', 'beach', 'traditional', 'elegant',
                'graceful', 'refined', 'charm', 'charming', 'unattractive', 'untempting', 'authentic', 'landscape']

    food = ['food', 'nutrient', 'breakfast', 'drink', 'drinking', 'booze', 'beverage', 'dinner', 'restaurant', 'bar',
            'liquor', 'buffet', 'snack_bar', 'wine', 'lunch', 'meal', 'menu', 'cook', 'prepare', 'cake', 'fruit',
            'desert', 'authentic']

    facilities = ['facility', 'installation', 'facility', 'readiness', 'construction', 'building', 'make', 'progress',
                  'establish', 'swimming', 'swim', 'pool', 'pond', 'ac', 'air conditioner', 'historic', 'historical',
                  'lobby', 'hall', 'accommodation', 'accommodate', 'spa', 'health spa', 'gymnasium', 'gym', 'clean',
                  'renovation', 'redevelopment', 'restoration', 'refurbishment', 'massage', 'comfortable', 'comfy',
                  'well fixed', 'experience', 'feel', 'sport', 'athletics', 'play', 'game', 'pool table', 'parking',
                  'carlot', 'jacuzzi', 'steambath']

    service = ['help', 'serve', 'serving', 'service', 'help', 'servicing', 'serve', 'lovingness', 'caring', 'care',
               'manage', 'handle', 'worry', 'helpful', 'sensational', 'stunning', 'complementary', 'complemental',
               'ascent', 'upgrade', 'promote', 'advance', 'reception', 'receipt', 'response', 'experience', 'receive'
               , 'feel', 'unattractive', 'untempting', 'uncomfortable', 'hospitality', 'family', 'home', 'stay', 'rest'
               , 'delay', 'quality', 'tone', 'valet', 'free', 'class', 'category', 'grade', 'classify']

    room = ['way', 'room', 'board', 'balcony', 'view', 'position', 'aspect', 'scene', 'window', 'bedroom', 'chamber',
            'bathroom', 'bath', 'toilet', 'sleep', 'nap', 'rest', 'accommodation', 'comfortable', 'comfy',
            'unattractive', 'untempting', 'uncomfortable', 'bed', 'washroom', 'interior']

    staff = ['staff', 'faculty', 'friendly', 'helpful', 'management', 'attentive', 'thoughtful', 'attention', 'manager',
             'receptionist', 'office', 'reception']

    value = ['price', 'value', 'treasure', 'appreciate', 'respect', 'measure', 'evaluate', 'valuate', 'assess',
             'appraise', 'rate', 'costly', 'pricey', 'pricy', 'expensive', 'cost', 'toll', 'budget', 'pay', 'paid'
             , 'paying', 'payment', 'wage', 'earnings', 'bill', 'account', 'cheque', 'invoice', 'tax', 'taxation']

    cleanliness = ['cleanliness', 'clean', 'cleanse' 'neat', 'clear', 'fresh', 'scent', 'uninfected', 'fair', 'white',
                   'infected', 'dirty', 'gross']

    def get_synonyms_for_aspect(self, aspect):

        if aspect == 'location':
            return self.location
        elif aspect == 'food':
            return self.food
        elif aspect == 'facilities':
            return self.facilities
        elif aspect == 'service':
            return self.service
        elif aspect == 'room':
            return self.room
        elif aspect == 'staff':
            return self.staff
        elif aspect == 'value':
            return self.value
        elif aspect == 'cleanliness':
            return self.cleanliness
        else:
            synonyms = []
            for syn in wordnet.synsets(aspect):
                for lm in syn.lemmas():
                    synonyms.append(lm.name())
            return synonyms


#  see if the broken words in  a given string s, are found in  the given word_dict
#  DP with Bottum-up

def word_break(word_dict, s):
    memo = [False] * (len(s)+1)
    memo[len(s)] = True
    print(memo)

    for i in range(len(s)-1, -1, -1):
        for w in word_dict:
            if (i + len(w)) <= len(s) and s[i: i + len(w)] == w:
                memo[i] = memo[i + len(w)]
            if memo[i]:
                break
        return memo[0]

def wordBreak(wordList, word):
    if word == '':
        return True
    else:
        wordLen = len(word)
        return any([(word[:i] in wordList) and wordBreak(wordList, word[i:]) for i in range(1, wordLen+1)])

print(wordBreak(['code', 'dp', 'time', 'linear'], 'codetime'))


import sys
from collections import deque

input = sys.stdin.readline

N, M = map(int, input().split())
indegree = [0] * (N + 1)
orders = [[] for _ in range(N+1)]

for _ in range(M):
    tmp = list(map(int, input().split()))[1:]
    for i in range(len(tmp) - 1):
        orders[tmp[i]].append(tmp[i + 1])
        indegree[tmp[i + 1]] += 1

Q = deque()
for i in range(1, N + 1):
    if indegree[i] == 0:
        Q.append(i)

ans = []
while Q:
    num = Q.popleft()
    ans.append(num)
    for order in orders[num]:
        indegree[order] -= 1
        if indegree[order] == 0:
            Q.append(order)

if len(ans) != N:
    print(0)
else:
    print(*ans, sep='\n')


from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F

from sample.pytorch.py_arch.base import BaseCfg, ConvMixerLayer, ConvMixerLayer2

@dataclass
class ConvMixerCfg(BaseCfg):
    num_layers: int = 8
    hidden_dim: int = 256
    kernel_size: int = 5
    patch_size: int = 2
    num_classes: int = 10

    drop_rate: float = 0.

    layer_norm_zero_init: bool = True

# %%
class ConvMixer(nn.Module):
    def __init__(self, cfg: ConvMixerCfg):
        super().__init__()

        self.layers = nn.ModuleList([
            ConvMixerLayer(cfg.hidden_dim, cfg.kernel_size, cfg.drop_rate)
            for _ in range(cfg.num_layers)
        ])

        self.embed = nn.Sequential(
            nn.Conv2d(3, cfg.hidden_dim, kernel_size=cfg.patch_size, stride=cfg.patch_size),
            nn.GELU(),
            nn.BatchNorm2d(cfg.hidden_dim, eps=7e-5),  # eps>6.1e-5 to avoid nan in half precision
        )

        self.digup = nn.Sequential(
            nn.AdaptiveAvgPool2d((1,1)),
            nn.Flatten(),
            nn.Linear(cfg.hidden_dim, cfg.num_classes)
        )

        self.cfg = cfg

    def forward(self, x):
        x = self.embed(x)
        for layer in self.layers:
            x = x + layer(x)
        x = self.digup(x)
        return x

# %%
class ConvMixer2(ConvMixer):
    def __init__(self, cfg: ConvMixerCfg):
        super().__init__(cfg)
        self.layers = nn.Sequential(*[
            ConvMixerLayer2(cfg.hidden_dim, cfg.kernel_size, cfg.drop_rate)
            for _ in range(cfg.num_layers)
        ])

    def forward(self, x):
        x = self.embed(x)
        x= self.layers(x)
        x= self.digup(x)
        return x

# %%
class BayesConvMixer(ConvMixer):
    def __init__(self, cfg: ConvMixerCfg):
        super().__init__(cfg)

        self.logits_layer_norm = nn.LayerNorm(cfg.hidden_dim)
        if cfg.layer_norm_zero_init:
            self.logits_layer_norm.weight.data = torch.zeros(self.logits_layer_norm.weight.data.shape)

        self.digup = nn.Sequential(
            nn.AdaptiveAvgPool2d((1,1)),
            nn.Flatten(),
        )
        self.fc = nn.Linear(cfg.hidden_dim, cfg.num_classes)

    def forward(self, x):
        x = self.embed(x)
        logits = self.digup(x)
        for layer in self.layers:
            x = x + layer(x)
            logits = logits + self.digup(x)
            logits = self.logits_layer_norm(logits)
        logits = self.fc(logits)
        return logits

# %%
class BayesConvMixer2(ConvMixer2):
    def __init__(self, cfg: ConvMixerCfg):
        super().__init__(cfg)

        self.logits_layer_norm = nn.LayerNorm(cfg.hidden_dim)

        self.digup = nn.Sequential(
            nn.AdaptiveAvgPool2d((1,1)),
            nn.Flatten(),
        )
        self.fc = nn.Linear(cfg.hidden_dim, cfg.num_classes)

    def forward(self, x):
        x = self.embed(x)
        logits = self.digup(x)
        for layer in self.layers:
            x = layer(x)
            logits = logits + self.digup(x)
            logits = self.logits_layer_norm(logits)
        logits = self.fc(logits)
        return logits

# %%
input = torch.randn(2, 3, 256, 256)
cfg = ConvMixerCfg(
    patch_size = 8,
)
model = BayesConvMixer(cfg)

# model = Isotropic(cfg)
output = model(input)
output.shape


def esPalindromico(x):
    flag = False
    cont = 0
    j = len(x)-1
    for i in range(len(x)):
        if x[i] == x[j]:
            if(cont == len(x)-1):
                flag = True
            cont += 1
        j -= 1
    return flag

print(esPalindromico('anitalavalatina'))

ls = 1
mx = 10
ec = 100

print(la, mx, ec)


# 121. Best Time to Buy and Sell Stock - Easy

import sys

# My answer
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min = prices[0]
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] < min:
                min = prices[i]
            if prices[i] - min > profit:
                profit = prices[i] - min
        return profit

sol = Solution()
print(sol.maxProfit([2,4,1]))
print(sol.maxProfit([7,1,5,3,6,4]))

# Study book - 1. Brute Force -> Time Out
def maxProfit(prices: list[int]) -> int:
    result = 0
    for i in range(len(prices) - 1):
        for j in range(i + 1, len(prices)):
            if prices[j] - prices[i] > result:
                result = prices[j] - prices[i]
    return result
print(maxProfit([7,1,5,3,6,4]))

# Study book - 2. updating value / pointer points to current value
def maxProfit(prices: list[int]) -> int:
    profit = 0
    min_price = sys.maxsize
    for price in prices:
        min_price = min(price, min_price)
        profit = max(profit, price - min_price)
    return profit


from datetime import time, date, datetime
from pydantic import BaseModel, ValidationError, validator, field_validator

class Person(BaseModel):
    first_name: str
    last_name: str
    birthdate: date

    @field_validator("birthdate", mode="before")
    def valid_birthdate(cls, v: date):
        delta = date.today() - v
        age = delta.days / 365
        if age > 120:
            raise ValidationError("Invalid data for the field birth_date.")
        return v

try:
    Person(first_name="AAA", last_name="BBB", birth_date="1800-01-01")
except ValidationError as e:
    print(str(e))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 10:01:43 2018

@author: yuyi
"""

import numpy as np

import sys
sys.path
sys.path.append('/home/yuyi/Desktop/detect/code')
import utili as u

result_path = '/home/yuyi/Desktop/detect/output/pre_gt_result.npy'
(gt_bboxes_all,gt_class_all,pre_bboxes_all,pre_class_all,pre_score_all) = np.load(result_path)

prediction = (pre_score_all,pre_class_all,pre_bboxes_all)
gt = (gt_class_all,gt_bboxes_all)
yolo_map = u.mAP(prediction,gt,20,0.5)


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication

from Board import Board

class Tetris(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.tBoard = Board(self)
        self.setCentralWidget(self.tBoard)
        self.tBoard.start()

        self.statusbar = self.statusBar()

        self.resize(200, 380)
        self.center()
        self.setWindowTitle('Tetris')

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Tetris()
    ex.show()
    sys.exit(app.exec_())


#import libraries
import  numpy as np
import matplotlib as mat
import matplotlib.pyplot as plt
import pandas as pd
import seaborn
import seaborn as sea

#load the data
dataset = pd.read_csv("C:/Users/sj21399/Downloads/Life_Expectancy_Data (1).csv")
print(dataset)
print (dataset.columns)

#now we have seen all the columns, let us show Hepatitis B, HIV/AIDS, Measles and Polio for
#The countries Nigeria, Ghana, Togo, Ghana, Egypt, Zimbabwe, and Lebanon

#lineplot

#this is our x
Afghanistan = dataset[dataset.Country == 'Afghanistan'].set_index('Year').sort_index()
Belgium = dataset[dataset.Country == 'Belgium'].set_index('Year').sort_index()
Australia = dataset[dataset.Country == 'Australia'].set_index('Year').sort_index()
Colombia = dataset[dataset.Country == 'Colombia'].set_index('Year').sort_index()

fig, ax = plt.subplots(figsize = (15,5))
Afghanistan.plot(kind="line", y = ['Adult Mortality'], label = ["Afghanistan"],  ax = ax )
Belgium.plot(kind="line", y = ['Adult Mortality'], label = ["Belgium"],  ax = ax )
Australia.plot(kind="line", y = ['Adult Mortality'], label = ["Australia"],  ax = ax )
Colombia.plot(kind="line", y = ['Adult Mortality'], label = ["Colombia"],  ax = ax )
ax.set(title = 'Comparing Polio for different countries', xlabel="Year", ylabel="Life expectancy") #Change axis labels and title
plt.show()

#before we start anything...we would look at the data independently
#we import the data .................1
dataset = pd.read_csv("C:/Users/sj21399/Downloads/survey_results_public.csv")
dataset_schema = ("C:/Users/sj21399/Downloads/survey_results_schema.csv")
print (dataset)
#pd.read_csv to see columns of schema
#print(dataset_schema)

#It appears that shortcodes for questions have been used as column names.

#we arrange the data into the columns we want to use..............2
#we want the schema to contain the answers and questions
#we would open dataset_schema here, everything under the second column (QuestionText) would enter under Column
schema_raw = pd.read_csv(dataset_schema , index_col='Column').QuestionText
print(schema_raw)

#we can now look for individual questions
#method for relating the parts of two different columns
#use one column which is indexed, to bring out what is in the other column
print (schema_raw['Age'])
print (schema_raw['Age1stCode'])
print (schema_raw['WelcomeChange'])

#we are looking at the main data, we have chosen the coluns we want to work with..........3
#Because we want to analyze:
#Demographics of the survey respondents and the global programming community
#Distribution of programming skills, experience, and preferences
#Employment-related information, preferences, and opinions

#refer to dataset.columns

selected_info = ['Country','Age','Gender','EdLevel','UndergradMajor','Hobbyist','Age1stCode','YearsCode','YearsCodePro','LanguageWorkedWith',
                 'LanguageDesireNextYear','NEWLearn','NEWStuck','Employment','DevType','WorkWeekHrs', 'JobSat','JobFactors', 'NEWOvertime','NEWEdImpt']

#These are the columns we want to work with...........4
#let us save all of these data in a different dataset
#we are selecting this info from that data set and storing it elsewhere

new_dataset = dataset[selected_info].copy()
print(new_dataset)

#let us assess what this new dataset is like........5
#?can we sample our data set here and clean it the way we like?

print (new_dataset.info())
#Total number of rows = 64460, but the values of the entries for each column vary..hence, some are empty
#there are 20 columns, with two float64...(Only two of the columns were detected as numeric columns (Age and WorkWeekHrs))
# the rest are objects, although some have integers
#we will convert everything (integers and floats) to numeric values to create a balance.............6
#we will leave the strings as strings

new_dataset['Age1stCode'] = pd.to_numeric(new_dataset.Age1stCode, errors='coerce')
new_dataset['YearsCode'] = pd.to_numeric(new_dataset.YearsCode, errors='coerce')
new_dataset['YearsCodePro'] = pd.to_numeric(new_dataset.YearsCodePro, errors='coerce')
new_dataset['Age'] = pd.to_numeric(new_dataset.Age, errors='coerce')
new_dataset['WorkWeekHrs'] = pd.to_numeric(new_dataset.WorkWeekHrs, errors='coerce')

#let us see what they all look like now, the basic stats are seen with describe...........7
print (new_dataset.describe())

#pay attention to the stats and ranges etc..........................8
#The minimum range and maximum range of Age look off
#we are going to sort out ages between 18 and 65

new_dataset.drop(new_dataset[new_dataset.Age < 18].index, inplace=True)
new_dataset.drop(new_dataset[new_dataset.Age > 65].index, inplace=True)

#let us also restrict work hours to 140
new_dataset.drop(new_dataset[new_dataset.WorkWeekHrs > 140].index, inplace=True)

#see the changes made
print (new_dataset.describe())

#let us work with sample 10 rows of this dataset...............9
work = new_dataset.sample(10)
print (work)

#Time to visualize what we have
#REMEMBER
#Because we want to analyze:
#Demographics of the survey respondents and the global programming community
#Distribution of programming skills, experience, and preferences
#Employment-related information, preferences, and opinions

#import important libraries...go to the top........................10
#we have our sample data with 20 columns

#let us set basic parameters for our libraries..............11
sea.set_style('darkgrid')
mat.rcParams['font.size'] = 14
mat.rcParams['figure.figsize'] = (9, 5)
mat.rcParams['figure.facecolor'] = '#00000000'

#let us plot 10 countries with the highest number of responses
# this would be from schema since it had responses...................12

print(schema_raw.Country)
#let us get the number of unique responses from our new dataset
print (new_dataset.Country.nunique())
#There are 183 unique responses

top_countries = new_dataset.Country.value_counts().head(10)
print (top_countries)
#Top 10 countries show
#Time to visualize....................13

plt.figure(figsize=(12,6))
plt.xticks(rotation=75)
plt.title(schema_raw.Country)
#show the countries and their number distribution based on the question from schema
sea.barplot(x=top_countries.index, y=top_countries);
#plt.show()

#look at the age of all respondents.............14

plt.figure(figsize=(12, 6))
plt.title(schema_raw.Age)
plt.xlabel('Age')
plt.ylabel('Number of respondents')
plt.show()

#let us look at employment and education separately


import os
import random

def refresh():
    keys = raw_input('Git Project: ')
    keys = keys.encode("hex")
    keystring = open("data","w")
    keystring.write(keys)
    keystring.close()

def getkey():
    slate = open("data","r")
    key = slate.read()
    slate.close()
    key = key.decode("hex")
    os.system('zenity --title="APOLLON | GitHub Request" --info --text="http://github.com/alectramell/' + key + '.git"')
    os.system("cd ~/Desktop/ && git clone https://github.com/alectramell/" + key + ".git")
    os.system("clear")
    print ("DONE!")
    os.system("sleep 3 && clear")
    os.system("gnome-open ~/Desktop/" + key + "/")


def add_1(r:list, a:int, b:int):
    for i in range(a, b+1):
        r[i] += 1
    return r

def main():
    t = int(input())
    for _ in range(t):
        n = int(input())
        C = list(map(int, input().split()))
        H = list(map(int, input().split()))
        H.sort()
        r = [0]*n
        for i in range(n):
            a, b = max(1, C[i]-(i+1)), min(n, C[i]+(i+1))
            a, b = a-1, b-1
            r = add_1(r, a, b)
        r.sort()
        if r == H:
            print('YES')
        else:
            print('NO')

if __name__ =='__main__':
    main()


from camera_matrix import *

import os
import cv2
from localization import *
import sys
import matplotlib.pyplot as plt

K=get_K()
img_dir="../data/KITTI_sample/images/"
images=[img_dir+d for d in os.listdir(img_dir)]

img_loc=localization()
img1=cv2.imread(images[0], 0)
img2=cv2.imread(images[1], 0)
img_loc.processFirstFrame(img1)
img_loc.process2ndFrame(img2)
for i,img_path in enumerate(images):

    img = cv2.imread(img_path, 0)   #read in grayscale
    if(i>2):
        img_loc.processDefaultFrame(img)
        #print(img_loc.cur_R,img_loc.cur_t[:,0])
        angle=rotationMatrix2Angle(img_loc.cur_R)
        print(angle)


from google.cloud import pubsub_v1
from flask import Flask, jsonify, request, json
from concurrent.futures import TimeoutError
app = Flask(__name__)

@app.route("/createsubscriber", methods=['POST'])
def createsubscriber():
    project_id = "server-less-277317"
    topic_id = "chatmodule"
    subscription_id = request.form['email']
    subscriber = pubsub_v1.SubscriberClient()
    topic_path = subscriber.topic_path(project_id, topic_id)
    subscription_path = subscriber.subscription_path(project_id, subscription_id)
    with subscriber:
        subscription = subscriber.create_subscription(subscription_path, topic_path)

@app.route("/publishmessage", methods=['POST'])
def publishmessage():
    message = request.form['message']
    publisher = pubsub_v1.PublisherClient()
    print(message)
    topic_name = 'projects/server-less-277317/topics/chatmodule';
    sample = message
    sample = sample.encode("utf-8");
    publisher.publish(topic_name,sample)
    return "published"

@app.route("/listsubscription", methods=['GET'])
def listsubscription():
    project_id = "server-less-277317"
    subscriber = pubsub_v1.SubscriberClient()
    project_path = subscriber.project_path(project_id)
    subscribers_names = []
    with subscriber:
        for subscription in subscriber.list_subscriptions(project_path):
            subscribers_names.append(str(subscription.name))

@app.route("/pullmessagesbysubscriber", methods=["POST"])
def pullmessagesbysubscriber():
    project_id = "server-less-277317"
    subscription_id = str(request.form['userid'])
    timeout = 5.0
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(project_id, subscription_id)

    def callback(message):
        print("Received message: {}".format(message))
        message.ack()

    streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
    print("Listening for messages on {}..\n".format(subscription_path))
    with subscriber:
        try:
            streaming_pull_future.result(timeout=timeout)
        except TimeoutError:
            streaming_pull_future.cancel()
    return "messages retrieved"

if __name__ == '__main__':
   app.run(debug = True, port=5000)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import torch
import torchvision.transforms.functional as tvf
from torch.utils.data import Dataset, DataLoader
from natsort import natsorted

from utils import load_hdr_as_tensor

import os
from sys import platform
import numpy as np
import random
from string import ascii_letters
from PIL import Image, ImageFont, ImageDraw

import glob
import os.path
import re
from operator import itemgetter
from itertools import groupby
import psutil

from matplotlib import rcParams
rcParams['font.family'] = 'serif'
import matplotlib
matplotlib.use('agg')

def load_dataset(root_dir, redux, params, shuffled=False, single=False, target_averaging=False, random_order=False):
    """Loads dataset and returns corresponding data loader."""

    # Create Torch dataset
    noise = (params.noise_type, params.noise_param)

    # Instantiate appropriate dataset class
    if params.noise_type == 'intrinsic':
        dataset = IntrinsicNoisyDataset(root_dir, redux, params.crop_size,
                                        seed=params.seed, target_averaging=target_averaging, random_order=random_order)
    elif params.noise_type == 'mc':
        dataset = MonteCarloDataset(root_dir, redux, params.crop_size,
            clean_targets=params.clean_targets)
    else:
        dataset = NoisyDataset(root_dir, redux, params.crop_size,
            clean_targets=params.clean_targets, noise_dist=noise, seed=params.seed)

    # Use batch size of 1, if requested (e.g. test set)
    if single:
        return DataLoader(dataset, batch_size=1, shuffle=shuffled)
    else:
        return DataLoader(dataset, batch_size=params.batch_size, shuffle=shuffled,
                          num_workers=min(psutil.cpu_count(), 9))

class AbstractDataset(Dataset):
    """Abstract dataset class for Noise2Noise."""

    def __init__(self, root_dir, redux=0, crop_size=128, clean_targets=False):
        """Initializes abstract dataset."""

        super(AbstractDataset, self).__init__()

        self.imgs = []
        self.root_dir = root_dir
        self.redux = redux
        self.crop_size = crop_size
        self.clean_targets = clean_targets

    def _random_crop(self, img_list):
        """Performs random square crop of fixed size.
        Works with list so that all items get the same cropped window (e.g. for buffers).
        """

        w, h = img_list[0].size
        assert w >= self.crop_size and h >= self.crop_size, \
            f'Error: Crop size: {self.crop_size}, Image size: ({w}, {h})'
        cropped_imgs = []
        i = np.random.randint(0, h - self.crop_size + 1)
        j = np.random.randint(0, w - self.crop_size + 1)

        for img in img_list:
            # Resize if dimensions are too small
            if min(w, h) < self.crop_size:
                img = tvf.resize(img, (self.crop_size, self.crop_size))

            # Random crop
            cropped_imgs.append(tvf.crop(img, i, j, self.crop_size, self.crop_size))

        return cropped_imgs

    def __getitem__(self, index):
        """Retrieves image from data folder."""

        raise NotImplementedError('Abstract method not implemented!')

    def __len__(self):
        """Returns length of dataset."""

        return len(self.imgs)

class NoisyDataset(AbstractDataset):
    """Class for injecting random noise into dataset."""

    def __init__(self, root_dir, redux, crop_size, clean_targets=False,
        noise_dist=('gaussian', 50.), seed=None):
        """Initializes noisy image dataset."""

        super(NoisyDataset, self).__init__(root_dir, redux, crop_size, clean_targets)

        self.imgs = os.listdir(root_dir)
        if redux:
            self.imgs = self.imgs[:redux]

        # Noise parameters (max std for Gaussian, lambda for Poisson, nb of artifacts for text)
        self.noise_type = noise_dist[0]
        self.noise_param = noise_dist[1]
        self.seed = seed
        if self.seed:
            np.random.seed(self.seed)

    def _add_noise(self, img):
        """Adds Gaussian or Poisson noise to image."""

        w, h = img.size
        c = len(img.getbands())

        # Poisson distribution
        # It is unclear how the paper handles this. Poisson noise is not additive,
        # it is data dependent, meaning that adding sampled valued from a Poisson
        # will change the image intensity...
        if self.noise_type == 'poisson':
            noise = np.random.poisson(img)
            noise_img = img + noise
            noise_img = 255 * (noise_img / np.amax(noise_img))

        # Normal distribution (default)
        else:
            if self.seed:
                std = self.noise_param
            else:
                std = np.random.uniform(0, self.noise_param)
            noise = np.random.normal(0, std, (h, w, c))

            # Add noise and clip
            noise_img = np.array(img) + noise

        noise_img = np.clip(noise_img, 0, 255).astype(np.uint8)
        return Image.fromarray(noise_img)

    def _add_text_overlay(self, img):
        """Adds text overlay to images."""

        assert self.noise_param < 1, 'Text parameter is an occupancy probability'

        c = len(img.getbands())

        # Choose font and get ready to draw
        if platform == 'linux':
            serif = '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf'
        else:
            serif = 'Times New Roman.ttf'
        text_img = img.copy()
        text_draw = ImageDraw.Draw(text_img)

        # Text binary mask to compute occupancy efficiently
        w, h = img.size
        mask_img = Image.new('1', (w, h))
        mask_draw = ImageDraw.Draw(mask_img)

        # Random occupancy in range [0, p]
        if self.seed:
            random.seed(self.seed)
            max_occupancy = self.noise_param
        else:
            max_occupancy = np.random.uniform(0, self.noise_param)
        def get_occupancy(x):
            y = np.array(x, dtype=np.uint8)
            return np.sum(y) / y.size

        # Add text overlay by choosing random text, length, color and position
        while 1:
            font = ImageFont.truetype(serif, np.random.randint(16, 21))
            length = np.random.randint(10, 25)
            chars = ''.join(random.choice(ascii_letters) for _ in range(length))
            color = tuple(np.random.randint(0, 255, c))
            pos = (np.random.randint(0, w), np.random.randint(0, h))
            text_draw.text(pos, chars, color, font=font)

            # Update mask and check occupancy
            mask_draw.text(pos, chars, 1, font=font)
            if get_occupancy(mask_img) > max_occupancy:
                break

        return text_img

    def _corrupt(self, img):
        """Corrupts images (Gaussian, Poisson, or text overlay)."""

        if self.noise_type in ['gaussian', 'poisson']:
            return self._add_noise(img)
        elif self.noise_type == 'text':
            return self._add_text_overlay(img)
        else:
            raise ValueError('Invalid noise type: {}'.format(self.noise_type))

    def __getitem__(self, index):
        """Retrieves image from folder and corrupts it."""

        # Load PIL image
        img_path = os.path.join(self.root_dir, self.imgs[index])
        img =  Image.open(img_path).convert('RGB')

        # Random square crop
        if self.crop_size != 0:
            img = self._random_crop([img])[0]

        # Corrupt source image
        source = tvf.to_tensor(self._corrupt(img))

        # Corrupt target image, but not when clean targets are requested
        if self.clean_targets:
            target = tvf.to_tensor(img)
        else:
            target = tvf.to_tensor(self._corrupt(img))

        return source, target

class MonteCarloDataset(AbstractDataset):
    """Class for dealing with Monte Carlo rendered images."""

    def __init__(self, root_dir, redux, crop_size,
        hdr_buffers=False, hdr_targets=True, clean_targets=False):
        """Initializes Monte Carlo image dataset."""

        super(MonteCarloDataset, self).__init__(root_dir, redux, crop_size, clean_targets)

        # Rendered images directories
        self.root_dir = root_dir
        self.imgs = os.listdir(os.path.join(root_dir, 'render'))
        self.albedos = os.listdir(os.path.join(root_dir, 'albedo'))
        self.normals = os.listdir(os.path.join(root_dir, 'normal'))

        if redux:
            self.imgs = self.imgs[:redux]
            self.albedos = self.albedos[:redux]
            self.normals = self.normals[:redux]

        # Read reference image (converged target)
        ref_path = os.path.join(root_dir, 'reference.png')
        self.reference = Image.open(ref_path).convert('RGB')

        # High dynamic range images
        self.hdr_buffers = hdr_buffers
        self.hdr_targets = hdr_targets

    def __getitem__(self, index):
        """Retrieves image from folder and corrupts it."""

        # Use converged image, if requested
        if self.clean_targets:
            target = self.reference
        else:
            target_fname = self.imgs[index].replace('render', 'target')
            file_ext = '.exr' if self.hdr_targets else '.png'
            target_fname = os.path.splitext(target_fname)[0] + file_ext
            target_path = os.path.join(self.root_dir, 'target', target_fname)
            if self.hdr_targets:
                target = tvf.to_pil_image(load_hdr_as_tensor(target_path))
            else:
                target = Image.open(target_path).convert('RGB')

        # Get buffers
        render_path = os.path.join(self.root_dir, 'render', self.imgs[index])
        albedo_path = os.path.join(self.root_dir, 'albedo', self.albedos[index])
        normal_path =  os.path.join(self.root_dir, 'normal', self.normals[index])

        if self.hdr_buffers:
            render = tvf.to_pil_image(load_hdr_as_tensor(render_path))
            albedo = tvf.to_pil_image(load_hdr_as_tensor(albedo_path))
            normal = tvf.to_pil_image(load_hdr_as_tensor(normal_path))
        else:
            render = Image.open(render_path).convert('RGB')
            albedo = Image.open(albedo_path).convert('RGB')
            normal = Image.open(normal_path).convert('RGB')

        # Crop
        if self.crop_size != 0:
            buffers = [render, albedo, normal, target]
            buffers = [tvf.to_tensor(b) for b in self._random_crop(buffers)]
        else:
            buffers = [render, albedo, normal, target]
            buffers = [tvf.to_tensor(b) for b in buffers]

        # Stack buffers to create input volume
        source = torch.cat(buffers[:3], dim=0)
        target = buffers[3]

        return source, target

class IntrinsicNoisyDataset(AbstractDataset):
    """Class for injecting random noise into dataset."""

    def __init__(self, root_dir, redux, crop_size, image_extension='.png',
                 seed=None, target_averaging=False, random_order=False):
        """Initializes noisy image dataset."""
        self.image_extension = image_extension

        super(IntrinsicNoisyDataset, self).__init__(root_dir, redux, crop_size, False)

        self.image_groups = []

        self._find_files()

        self.interfaces_found = \
            all([ all([ 'interfaces' in entry.keys() for entry in group]) for group in self.image_groups ])

        self.target_averaging = target_averaging
        self.random_order = random_order

        self.seed = seed
        if self.seed:
            np.random.seed(self.seed)

    def _find_files(self):
        # first find all images
        all_files = glob.glob(
            os.path.join(self.root_dir, '**/*' + self.image_extension), recursive=True)

        # extract relative filename and group name and number from the filename
        file_details = [self._filename_processing(filename) for filename in all_files]

        # sort the files by their relative filename
        file_details = natsorted(file_details, key=itemgetter(1))

        # then group them by their group name
        self.image_groups = [
            [{subelem[4]:subelem[0] for subelem in elem} for _, elem in groupby(group, key=itemgetter(3))]
             for key, group in groupby(file_details, key=itemgetter(2))]

    def _filename_processing(self, filename):
        relative_filename = filename.replace(self.root_dir, '')
        if relative_filename.startswith(os.path.sep):
            relative_filename = relative_filename[len(os.path.sep):]
        basename_parts = re.match(r'(.+?)_([0-9]+)(?:_([a-z]+))?' + re.escape(self.image_extension), os.path.split(filename)[1])
        basename = basename_parts[1]
        group_number = basename_parts[2]
        suffix = basename_parts[3]
        if suffix is None:
            suffix = 'image'

        return filename, relative_filename, basename, group_number, suffix

    def __getitem__(self, index):
        """Retrieves image from folder and corrupts it."""

        group = self.image_groups[index]

        # there are just two images
        if self.random_order:
            target_indices = np.random.permutation(len(group))
        else:
            target_indices = range(len(group))

        source = Image.open(group[target_indices[0]]['image'])
        target = Image.open(group[target_indices[1]]['image'])
        if len(group) > 2 and self.target_averaging:
            target = tvf.to_tensor(target)
            for nextImageIndex in range(2, len(group)):
                next_target_image = Image.open(group[target_indices[nextImageIndex]]['image'])
                target = target + tvf.to_tensor(next_target_image)
            target = tvf.to_pil_image(target / float(len(group) - 1))
        if self.interfaces_found:
            target_interfaces = Image.open(group[target_indices[1]]['interfaces'])
        else:
            target_interfaces = None

        if self.crop_size != 0:
            if target_interfaces is not None:
                source, target, target_interfaces = self._random_crop([source, target, target_interfaces])
            else:
                source, target = self._random_crop([source, target])

        source = tvf.to_tensor(source)
        target = tvf.to_tensor(target)
        if target_interfaces is not None:
            target_interfaces = tvf.to_tensor(target_interfaces)

        if target_interfaces is not None:
            return source, {'image': target, 'interfaces': target_interfaces}
        else:
            return source, target

    def __len__(self):
        """Returns length of dataset."""

        return len(self.image_groups)


class Solution:
     def letterCombinations(self, digits: str) -> List[str]:
        map_ = {
            '2' : 'abc',
            '3' : 'def',
            '4' : 'ghi',
            '5' : 'jkl',
            '6' : 'mno',
            '7' : 'pqrs',
            '8' : 'tuv',
            '9' : 'wxyz'
        }
        result = []
        def make_combinations(i, cur):
            if i == len(digits):
                if len(cur) > 0:
                    result.append(''.join(cur))
                return
            for ch in map_[digits[i]]:
                cur.append(ch)
                make_combinations(i+1, cur)
                cur.pop()
        make_combinations(0, [])
        return result


from mixing_env.mixing_env import MixEnv
from mixing_env.wrappers import NormalizeObs

from gymnasium.wrappers.normalize import NormalizeReward

def mixing_env_creator(config):
    obs_filter = config.pop("obs_filter", None)
    reward_filter = config.pop("reward_filter", None)
    env = MixEnv()
    if obs_filter is not None:
        if obs_filter == "normalize_obs":
            env = NormalizeObs(env)

    if reward_filter is not None:
        if reward_filter == "normalize_rewards":
            env = NormalizeReward(env)

    return env


from datetime import timedelta
from typing import Dict

from feathub.common.utils import append_metadata_to_json
from feathub.feature_tables.sinks.sink import Sink

class PrometheusSink(Sink):
    def __init__(
        self,
        server_url: str,
        job_name: str,
        delete_on_shutdown: bool,
        extra_labels: Dict[str, str],
        retry_timeout: timedelta,
    ):
        """
        :param server_url: The PushGateway server server URL including scheme,
                         host name, and port.
        :param job_name: The value of the `job` label of the metrics emitted by
                         this sink.
        :param delete_on_shutdown: Whether to delete metrics from Prometheus
                                   when the job finishes. When set to true,
                                   Feathub will try its best to delete the
                                   metrics but this is not guaranteed.
        :param extra_labels: The extra labels of all metrics pushed by this sink.
        :param retry_timeout: The max timeout this sink may take retrying in case
                              of occasional exceptions.
        """
        super().__init__(
            name="",
            system_name="prometheus",
            table_uri={
                "server_url": server_url,
            },
        )
        self.server_url = server_url
        self.job_name = job_name
        self.delete_on_shutdown = delete_on_shutdown
        self.extra_labels = extra_labels
        self.retry_timeout = retry_timeout

    @append_metadata_to_json
    def to_json(self) -> Dict:
        return {
            "server_url": self.server_url,
            "job_name": self.job_name,
            "delete_on_shutdown": self.delete_on_shutdown,
            "extra_labels": self.extra_labels,
            "retry_timeout_ms": self.retry_timeout / timedelta(milliseconds=1),
        }

    @classmethod
    def from_json(cls, json_dict: Dict) -> "PrometheusSink":
        return PrometheusSink(
            server_url=json_dict["server_url"],
            job_name=json_dict["job_name"],
            delete_on_shutdown=json_dict["delete_on_shutdown"],
            extra_labels=json_dict["extra_labels"],
            retry_timeout=timedelta(milliseconds=json_dict["retry_timeout_ms"]),
        )


#   Programmer: limodou
#   E-mail:     limodou@gmail.com
#
#   Copyleft 2006 limodou
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#   UliPad is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   $Id: Debug.py 1730 2006-11-21 13:46:26Z limodou $
#
#   Update
#   2007/08/27
#       * add time info

DEBUG = True
import types
import sys
import traceback
import os.path
import common
import Globals
import datetime

class Debug:
    def __init__(self, filename=os.path.abspath('debug.txt'), flag=None):
        self.filename = filename
        self.flag = flag
        self.reset(filename)

    def _time(self):
        return datetime.datetime.now().isoformat()[11:-3]

    def log(self, *args):
        self.output(*args)

    def info(self, *args):
        self.output(self._time(), ' [ INFO] -- ', *args)

    def warn(self, *args):
        self.output(self._time(), ' [ WARN] -- ', *args)

    def error(self, *args):
        self.output(self._time(), ' [ERROR] -- ', *args)

    def debug(self, *args):
        self.output(self._time(), ' [DEBUG] -- ', *args)

    def traceback(self, tb=None):
        if tb:
            message = traceback.format_exception(*tb)
        else:
            message = traceback.format_exception(*sys.exc_info())
        self.output('[Traceback]', ''.join(message))
        if debug and debug.is_debug() and Globals.mainframe and Globals.mainframe.IsShown():
            common.warn("There is some thing wrong as running the program")

    def output(self, *args):
        if self.is_debug():
            #encoding = locale.getdefaultlocale()[1]
            encoding = 'utf-8'
            out = open(self.filename, 'a')
            for i in args:
                if not type(i) in [types.UnicodeType, types.StringTypes, types.StringType]:
                    s= repr(i)
                else:
                    s = i
                if type(s) == type(u''):
                    out.write(s.encode(encoding))
                else:
                    out.write(s)
            out.write("\n")
            out.close()

    def reset(self, filename):
        if self.is_debug():
            open(filename, 'w')
            self.filename = filename

    def is_debug(self):
        if not DEBUG:
            return False
        if self.flag is None:
            return DEBUG
        else:
            return self.flag

debug = None
error = None

if __name__ == '__main__':
    debug = Debug()
    error = Debug(os.path.abspath('error.txt'))
    debug.log('log')
    debug.info('info')
    debug.warn('warn')
    debug.error('error')
    debug.debug('debug')


#!/usr/bin/python3
"""Defining the BaseModel class """
from uuid import uuid4
from datetime import datetime
import uuid
import models

class BaseModel:
    """ The parent class ofvthe AIRBNB project
    """
    def __init__(self, *args, **kwargs):
        """ initialization of class attributes
        args:
            id - string - assign with an uuid when an instance is created
            created_at - datetime - shows when an instance was created
            updated_at - datetime - updates an instance created
        """
        time_format = "%Y-%m-%dT%H:%M:%S.%f"
        if len(kwargs) != 0:
            for key, value in kwargs.items():
                if key == "created_at" or key == "updated_at":
                    setattr(self, key, datetime.strptime(value, time_format))
                elif key != '__class__':
                    setattr(self, key, value)
        else:
            self.id = str(uuid.uuid4())
            self.created_at = datetime.now()
            self.updated_at = datetime.now()
            models.storage.new(self)

    def __str__(self):
        """prints the string representation of the objects
        print class name, id, __dict__
        """
        c = self.__class__.__name__
        dic = self.__class__.__dict__
        return (f"[{c}] ({self.id}) {dic}")

    def save(self):
        """ updates the public instance attribute
        updated_at with the current datetime
        """
        self.updated_at = datetime.now()
        """return self.save()"""
        models.storage.save()

    def to_dict(self):
        """returns a dictionary containing all keys/values of __dict__
        by using:
            self.__dict__, only instance attributes set will be returned
            a key __class__ must be added to this dictionary with
            the class name of the object
        """
        new_dict = self.__dict__.copy()
        if "created_at" in new_dict:
            new_dict["created_at"] = self.created_at.isoformat()
        if "updated_at" in new_dict:
            new_dict["updated_at"] = self.updated_at.isoformat()
        new_dict["__class__"] = self.__class__.__name__
        return new_dict


#!/Users/fritjof/anaconda3/bin/python3
# problem: tornbygge, rating: 1.7
n = int(input())
xs = [int(_) for _ in input().split()]

t = 1

for i in range(len(xs) - 1):
    if xs[i] < xs[i+1]:
        t += 1
print(t)


class Cost(object):
	"""A cost to perform an action, chargeable to a user."""
	def __init__(self, ap=0, hp=0, gp=0):
		self.ap = ap
		self.hp = hp
		self.gp = gp

	def __str__(self):
		vs = []

		if self.ap:
			vs += ['%d AP' % self.ap]
		if self.hp:
			vs.append('%d HP' % self.hp)
		if self.gp:
			vs.append('%d GP' % self.gp)

		return ', '.join(vs)

	def can_afford(self, player):
		return (player.has('GoldPiece', self.gp)
				and player.hp > self.hp
				and player.ap > self.ap)

	def charge(self, player):
		player.ap -= self.ap
		player.hp -= self.hp
		if self.gp:
			player.take_items('GoldPiece', self.gp)


"""my_controller controller."""

# You may need to import some classes of the controller module. Ex:
#  from controller import Robot, Motor, DistanceSensor
from controller import Robot
from controller import GPS
from controller import InertialUnit

# create the Robot instance.
robot = Robot()

# get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
# Gps definition
gps = GPS("gps")
gps.enable(timestep)

# Imu defintion
imu = InertialUnit("inertial unit")
imu.enable(timestep)

# Motor defintion
motor_l = robot.getDevice("left wheel")
motor_r = robot.getDevice("right wheel")

motor_l.setPosition(float('inf'))
motor_r.setPosition(float('inf'))

motor_l.setVelocity(0.0)
motor_r.setVelocity(0.0)

# You should insert a getDevice-like function in order to get the
# instance of a device of the robot. Something like:
#  motor = robot.getDevice('motorname')
#  ds = robot.getDevice('dsname')
#  ds.enable(timestep)

# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
    # Read gps values
    data_gps = gps.getValues()
    data_imu = imu.getRollPitchYaw()

    print(data_imu)

    motor_l.setVelocity(1.0)
    motor_r.setVelocity(-1.0)
    # Read the sensors:
    # Enter here functions to read sensor data, like:
    #  val = ds.getValue()

    # Process sensor data here.

    # Enter here functions to send actuator commands, like:
    #  motor.setPosition(10.0)
    pass

# Enter here exit cleanup code.


"""
--- Day 4: Repose Record ---

You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is as close as you can safely get.

As you search the closet for anything that might help, you discover that you're not the first person to want to sneak in. Covering the walls, someone has spent an hour starting every midnight for the past few months secretly observing this guard post! They've been writing down the ID of the one guard on duty that night - the Elves seem to have decided that one guard was enough for the overnight shift - as well as when they fall asleep or wake up while at their post (your puzzle input).

For example, consider the following records, which have already been organized into chronological order:

[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
Timestamps are written using year-month-day hour:minute format. The guard falling asleep or waking up is always the one whose shift most recently started. Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59) is relevant for those events.

Visually, these records show that the guards are asleep at these times:

Date   ID   Minute
            000000000011111111112222222222333333333344444444445555555555
            012345678901234567890123456789012345678901234567890123456789
11-01  #10  .....####################.....#########################.....
11-02  #99  ........................................##########..........
11-03  #10  ........................#####...............................
11-04  #99  ....................................##########..............
11-05  #99  .............................................##########.....
The columns are Date, which shows the month-day portion of the relevant day; ID, which shows the guard on duty that day; and Minute, which shows the minutes during which the guard was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #.

Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.

If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick that guard into working tonight so you can have the best chance of sneaking in. You have two strategies for choosing the best guard/minute combination.

Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most?

In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day).

While this example listed the entries in chronological order, your entries are in the order you found them. You'll need to organize them before they can be analyzed.

What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 10 * 24 = 240.)
"""

import os
import time
import re
import numpy as np

start_time = time.time()
f = open("./inputs/day4-test","r")

inputs = []
time_dict = {}

for line in f:
    inputs = inputs + [line]
guard = 0
guards = []

for n in inputs:
    hours_and_minutes = re.findall("[0-9][0-9]\:[0-9][0-9]", n)
    hours, minutes = hours_and_minutes[0].split(":")
    text = n.split("]")[1]
    if "#" in text:
        guard = int(re.findall("[0-9]+",text)[0])
        if guard not in time_dict:
            time_dict[guard] = np.zeros(60)
        if guard not in guards:
            guards+=[guard]
    if "falls" in text:
        minute_falled = int(minutes)
    if "wakes" in text:
        minute_awake = int(minutes)
        for i in range(minute_falled, minute_awake):
            time_dict[guard][i] += 1
maxim = 0
guard_maxim = 0
for g in guards:
    suma = 0
    for i in range(60):
        suma += time_dict[g][i]
    if suma > maxim:
        maxim = suma
        guard_maxim = g

maxim_slept = 0
for i in range(60):
    if time_dict[guard_maxim][i] > maxim_slept:
        maxim_slept = time_dict[guard_maxim][i]
        minute_maxim_slept = i

print(minute_maxim_slept*guard_maxim)
print("--- Part ONE %s seconds ---" % (time.time() - start_time))


"""Assorted Fluxes, in  (m^2 sec sr GeV)^-1"""

import gzip
import logging
import io
import re

import numpy as np
import numpy.lib.recfunctions as rfn

import scipy.interpolate
from scipy.integrate import romberg, simps
from scipy.interpolate import splrep, splev, RectBivariateSpline

from km3flux.data import basepath

logger = logging.getLogger(__name__)

class BaseFlux(object):
    """Base class for fluxes.

    Methods
    =======
    __call__(energy, zenith=None)
        Return the flux on energy, optionally on zenith.
    integrate(zenith=None, emin=1, emax=100, **integargs)
        Integrate the flux via romberg integration.
    integrate_samples(energy, zenith=None, emin=1, emax=100)
        Integrate the flux from given samples, via simpson integration.

    Example
    =======
    >>> zen = np.linspace(0, np.pi, 5)
    >>> ene = np.logspace(0, 2, 5)

    >>> from km3flux.flux import MyFlux
    >>> flux = MyFlux(flavor='nu_mu')

    >>> flux(ene)
    array([6.68440000e+01, 1.83370000e+01, 4.96390000e+00,
           1.61780000e+00, 5.05350000e-01,])
    >>> flux(ene, zen)
    array([2.29920000e-01, 2.34160000e-02, 2.99460000e-03,
           3.77690000e-04, 6.87310000e-05])
    """

    def __init__(self, **kwargs):
        pass

    def __call__(self, energy, zenith=None, interpolate=True):
        logger.debug("Interpolate? {}".format(interpolate))
        energy = np.atleast_1d(energy)
        logger.debug("Entering __call__...")
        if zenith is None:
            logger.debug("Zenith is none, using averaged table...")
            return self._averaged(energy, interpolate=interpolate)
        zenith = np.atleast_1d(zenith)
        if len(zenith) != len(energy):
            raise ValueError("Zenith and energy need to have the same length.")
        logger.debug("Zenith available, using angle-dependent table...")
        return self._with_zenith(energy=energy, zenith=zenith, interpolate=interpolate)

    def _averaged(self, energy, interpolate=True):
        logger.debug("Interpolate? {}".format(interpolate))
        raise NotImplementedError

    def _with_zenith(self, energy, zenith, interpolate=True):
        logger.debug("Interpolate? {}".format(interpolate))
        raise NotImplementedError

    def integrate(self, zenith=None, emin=1, emax=100, interpolate=True, **integargs):
        logger.debug("Interpolate? {}".format(interpolate))
        return romberg(self, emin, emax, vec_func=True, **integargs)

    def integrate_samples(
        self, energy, zenith=None, emin=1, emax=100, interpolate=True, **integargs
    ):
        logger.debug("Interpolate? {}".format(interpolate))
        energy = np.atleast_1d(energy)
        mask = (emin <= energy) & (energy <= emax)
        energy = energy[mask]
        if zenith:
            logger.debug("Zenith available, using angle-dependent table...")
            zenith = np.atleast_1d(zenith)
            zenith = zenith[mask]
        flux = self(energy, zenith=zenith, interpolate=interpolate)
        return simps(flux, energy, **integargs)

class PowerlawFlux(BaseFlux):
    """E^-gamma flux."""

    def __init__(self, gamma=2, scale=1e-4):
        self.gamma = gamma
        self.scale = scale

    def _averaged(self, energy, interpolate=True):
        return self.scale * np.power(energy, -1 * self.gamma)

    def integrate(self, zenith=None, emin=1, emax=100, **integargs):
        """Compute analytic integral instead of numeric one."""
        if np.around(self.gamma, decimals=1) == 1.0:
            return np.log(emax) - np.log(emin)
        num = np.power(emax, 1 - self.gamma) - np.power(emin, 1 - self.gamma)
        den = 1.0 - self.gamma
        return self.scale * (num / den)

class IsotropicFlux:
    def __init__(self, data, flavors):
        self._data = data
        self._flavors = flavors
        for flavor in flavors:
            flux = scipy.interpolate.InterpolatedUnivariateSpline(
                data.energy, data[flavor]
            )
            setattr(self, flavor, flux)

    def __getitem__(self, flavor):
        if flavor in self._flavors:
            return getattr(self, flavor)
        raise KeyError(
            f"Flavor '{flavor}' not present in data. "
            "Available flavors: {', '.join(self._flavors)}"
        )

class HondaFlux:
    """Base class for Honda fluxes

    Methods
    =======
    make_regular_grid(axes_keys, flavor)
        Create a n_dim grid based on data.
    interpolation_method(axes_keys, flavor)
        Select the interpolation method.
    parse_categories(f)
        Integrate the flux from given samples, via simpson integration.
    """

    def __init__(self, data, flavors):

        # Add cosz and phi_az bin center
        data = rfn.append_fields(
            data, "cosz_mean", (data.cosz_min + data.cosz_max) / 2.0, dtypes=float
        ).view(np.recarray)
        data = rfn.append_fields(
            data, "phi_az_mean", (data.phi_az_min + data.phi_az_max) / 2.0, dtypes=float
        ).view(np.recarray)

        self._flavors = flavors
        self._data = data
        self._axes = ["energy"]

        # Check number of input dimensions
        if len(np.unique(data.cosz_mean)) > 1:
            self._axes.append("cosz_mean")
        if len(np.unique(data.phi_az_mean)) > 1:
            self._axes.append("phi_az_mean")

        self._n_dim = len(self._axes)

        # Set the interpolation method accordingly
        for flavor in flavors:
            flux = self.interpolation_method(self._axes, flavor)
            setattr(self, flavor, flux)

    def make_regular_grid(self, axes_keys, flavor):
        """
        Create a n_dim grid based on data.

        Parameters
        ----------
        axes_keys : list of str
            axes to be used, define dimensions order
        flavor : str
            column to use to fill the grid
        """
        axes = []
        dim = []

        for key in axes_keys:
            r = np.sort(np.unique(self._data[key]))
            axes.append(r)
            dim.append(len(r))

        self._data.sort(order=axes_keys)
        grid = np.reshape(self._data[flavor], np.array(dim))
        return grid, axes

    def interpolation_method(self, axes_keys, flavor):
        """
        Select the interpolation method.

        For 1D interpolation:
        - InterpolatedUnivariateSpline
        For 2D interpolation:
        - RectBivariateSpline
        For >= 3D interpolation:
        - RegularGridInterpolator

        Parameters
        ----------
        axes_keys : list of str
            axes to be used, define dimensions order
        flavor : str
            column to use to fill the grid
        """
        if len(axes_keys) == 1:
            return scipy.interpolate.InterpolatedUnivariateSpline(
                self._data.energy, self._data[flavor]
            )

        elif len(axes_keys) == 2:
            grid, axes = self.make_regular_grid(axes_keys, flavor)
            return scipy.interpolate.RectBivariateSpline(*axes, grid).ev

        else:
            grid, axes = self.make_regular_grid(axes_keys, flavor)
            flux = scipy.interpolate.RegularGridInterpolator(
                axes, grid, bounds_error=False, fill_value=None
            )

            def columnar_interface(*args):
                return flux(np.stack(args).T)

            return columnar_interface

    def __getitem__(self, flavor):
        if flavor in self._flavors:
            return getattr(self, flavor)
        raise KeyError(
            f"Flavor '{flavor}' not present in data. "
            "Available flavors: {', '.join(self._flavors)}"
        )

    @classmethod
    def from_hondafile(cls, filepath):

        with gzip.open(filepath, "r") as fobj:
            flavors = ["numu", "anumu", "nue", "anue"]

            cats = cls.parse_categories(cls, fobj)

            data = []
            for header, content in cats:

                # Split the header to get cosZ and phi_Az ranges (4 numbers)
                header = " ".join(re.findall(r"[-+]?(?:\d*\.\d+|\d+)", header))
                header_cols = ["cosz_min", "cosz_max", "phi_az_min", "phi_az_max"]

                # Create a dummy file object from sub range content +
                # additional columns for the cos Zenith and phi
                # Azimuth
                f = io.StringIO(header.join([""] + content))

                # Create a recarray from the file
                data_tmp = np.recfromcsv(
                    f,
                    names=header_cols + ["energy"] + flavors,
                    skip_header=2,
                    delimiter=" ",
                )
                data.append(data_tmp)

            # Merge invidual rec arrays to one
            data = rfn.stack_arrays(data, asrecarray=True, usemask=False)

            return cls(data, flavors)

    def parse_categories(self, f):
        """
        Select the interpolation method.

        Parameters
        ----------
        f : file object
            Honda file to be parsed
        """
        cats = []
        last_cat_start = -1
        last_cat_header = ""
        lines = []
        for i, line in enumerate(f):
            line = line.decode("ascii")
            if bool(line.count("average flux in")):
                if len(lines) != 0:
                    cats.append((last_cat_header, lines))
                    lines = []
                last_cat_header = line
            lines.append(line)
        cats.append((last_cat_header, lines))
        f.seek(0)
        return cats

class Honda:
    _experiments = {
        "Frejus": "frj",
        "Gran Sasso": "grn",
        "Homestake": "hms",
        "INO": "ino",
        "JUNO": "juno",
        "Kamioka": "kam",
        "Pythasalmi": "pyh",
        "Soudan Mine": "sdn",
        "South Pole": "spl",
        "Sudbury": "sno",
    }
    _datapath = basepath / "honda"

    #    def __init__(self):
    #        self._years = [p.name for p in self._datapath.glob("????") if p.is_dir()]

    def flux(
        self, year, experiment, solar="min", mountain=False, season=None, averaged=None
    ):
        """
        Return the flux for a given year and experiment.

        Parameters
        ----------
        year : int
            The year of the publication.
        experiment : str
            The experiment name, can be one of the following:
            "Kamioka", "Gran Sasso", "Sudbury", "Frejus", "INO", "South Pole",
            "Pythasalmi", "Homestake", "JUNO"
        solar : str (optional)
            The solar parameter, can be "min" or "max". Default is "min" for Solar
            minimum.
        mountain : bool (optional)
            With or without mountain over the detector. Default is "False" => without.
        season : None or (int, int) (optional)
            The season of interest. If `None`, the dataset for the full period is taken.
            If a tuple is provided, the first entry is the starting and the last the
            ending month. Notice that the corresponding dataset might not be available.
        averaged : None or str (optional)
            The type of averaging. Default is `None`. Also available are "all" for all
            direction averaging and "azimuth" for azimuth averaging only.
        """
        filepath = self._filepath_for(
            year, experiment, solar, mountain, season, averaged
        )
        if not filepath.exists():
            raise FileNotFoundError(
                f"The requested data file {filepath} could not be found in the archive. "
                "Try running `km3flux update` (see `km3flux -h` for more information) and "
                "also make sure the requested combination of parameters is available."
            )

        return HondaFlux.from_hondafile(filepath)

    def _filepath_for(self, year, experiment, solar, mountain, season, averaged):
        """Generate the filename and path according to the naming conventions of Honda

        Does some sanity checks too.
        """
        exp = self.experiment_abbr(experiment)
        filename = exp

        if year >= 2014:  # seasonal data was added in 2014
            if season is None:
                filename += "-ally"
            else:
                filename += f"-{season[0]:02d}{season[1]:02d}"

            if averaged is None:
                filename += "-20-12"
            elif averaged == "azimuth":
                filename += "-20-01"
            elif averaged == "all":
                filename += "-01-01"
            else:
                raise ValueError(
                    f"Unsupported averageing '{averaged}', "
                    "please use `None`, 'all', or 'azimuth'."
                )

            if mountain:
                filename += "-mtn"

        if solar in ("min", "max"):
            filename += f"-sol{solar}"
        else:
            raise ValueError(
                f"Unsupported solar parameter '{solar}' "
                "please use either 'min' or 'max'."
            )

        if year <= 2011:
            if season:
                raise ValueError(
                    "No seasonal tables available for year 2011 and earlier."
                )

            if mountain:
                if averaged == "all":
                    raise ValueError(
                        "No published mountain data for all directions averaged."
                    )
                filename += "-mountain"

            if averaged is None:
                filename += ""
            elif averaged == "azimuth":
                filename += "-aa"
            elif averaged == "all":
                filename += "-alldir"
            else:
                raise ValueError(
                    f"Unsupported averageing '{averaged}', "
                    "please use `None`, 'all', or 'azimuth'."
                )

        filename += ".d.gz"
        filepath = self._datapath / str(year) / filename
        return filepath

    @property
    def experiments(self):
        """Return a list of supported experiments."""
        return sorted(list(self._experiments.keys()))

    def experiment_abbr(self, experiment):
        """Return the abbreviation used in filenames for a given experiment."""
        try:
            return self._experiments[experiment]
        except KeyError:
            experiments = ", ".join(self.experiments)
            raise KeyError(
                f"The '{experiment}' is not in the list of available experiments: {experiments}"
            )


import pandas as pd
import numpy as np

train = pd.read_csv('C:\\Users\\49210\Desktop\\21.csv')

#训练样本特征因子化
from pyecharts.charts import Pie, Bar, Map, WordCloud,Line,Grid,Scatter,Radar,Page  #可视化
from pyecharts import options as opts
from pyecharts.globals import SymbolType
from pyecharts.globals import ThemeType
from pyecharts.faker import Faker
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import string
import seaborn as sns

df = train
df['Dates'] = pd.to_datetime(df['Dates'])
df['year'] = pd.to_datetime(df['Dates']).dt.year
df['month'] = pd.to_datetime(df['Dates']).dt.month
df['day'] = pd.to_datetime(df['Dates']).dt.day

df['week']=pd.to_datetime(df['Dates']).dt.dayofweek+1
df.head()
df_cat = df['Category'].value_counts()
district = df['PdDistrict'].value_counts()
Category10 = df_cat.index.tolist()[:10]
Category10_num = df_cat.tolist()[:10]
df_cat10 = df.loc[df['Category'].isin(Category10)]
gp_cat_h = df_cat10.groupby(['Category','month']).size()
gp_cat_h.unstack().T

c = (
        Pie()
            .add(
            "",
            [list(z) for z in zip(district.index.tolist(),
                                  district.values.tolist())],
            radius=["30%", "75%"],
            center=["50%", "50%"],
            rosetype="radius",
            label_opts=opts.LabelOpts(is_show=False),
        )
            .set_global_opts(title_opts=opts.TitleOpts(title="区域占比"),
                             legend_opts=opts.LegendOpts(
                                 orient="vertical", pos_top="20%", pos_left="0.5%"
                             ))
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
            .render("pie_base.html")
    )


# Snake

import random
import pygame
import pickle

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512
CELLSIZE = 16
ROWS = HEIGHT // CELLSIZE
COLS = WIDTH // CELLSIZE

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
	win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
	win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)

FPS = 10
clock = pygame.time.Clock()

# COLORS *********************************************************************

BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)

# LOADING FONTS **************************************************************

smallfont = pygame.font.SysFont('Corbel', 25)

# GAME MODES *****************************************************************

gameoptions = ['Classic', 'Boxed','Arcade', 'Exit']
cmode = 0

# LOADING IMAGES *************************************************************

bg = pygame.image.load('Assets/bg.png')
logo = pygame.image.load('Assets/logo.jpg')
logo2 = pygame.image.load('Assets/logo2.jpg')

gameover_img = pygame.image.load('Assets/gameover.png')
bar_img = pygame.image.load('Assets/bar.png')

# LOADING TILES **************************************************************

tile_list = []
for i in range(5):
	tile = pygame.image.load(f'Tiles/{i+1}.png')
	tile_list.append(tile)

tile_size = {
	1 : (16, 64),
	2 : (64, 16),
	3 : (32, 32),
	4 : (32, 32),
	5 : (32, 32)
}

# FUNCTIONS & CLASSES ********************************************************

def drawGrid():
	for row in range(ROWS):
		pygame.draw.line(win, WHITE, (0, row*CELLSIZE), (WIDTH, row*CELLSIZE), 1)
	for col in range(COLS):
		pygame.draw.line(win, WHITE, (col*CELLSIZE, 0), (col*CELLSIZE, HEIGHT))

def loadlevel(level):
	if level == 'boxed':
		file = f'Levels/boxed'
	else:
		file = f'Levels/level{level}_data'
	with open(file, 'rb') as f:
		data = pickle.load(f)
		for y in range(len(data)):
			for x in range(len(data[0])):
				if data[y][x] >= 0:
					data[y][x] += 1
	return data, len(data[0])

def tile_collide(leveld, head):
	for y in range(ROWS):
		for x in range(COLS):
			if leveld[y][x] > 0:
				tile = leveldata[y][x]
				pos = (x*CELLSIZE, y*CELLSIZE)

				rect = pygame.Rect(pos[0], pos[1], tile_size[tile][0],
								tile_size[tile][1])
				if rect.collidepoint(head):
					return True

	return False

class Snake:
	def __init__(self):
		self.length = 3
		self.direction = None
		self.x = COLS // 2
		self.y = ROWS // 2
		self.head = COLS//2 * CELLSIZE, ROWS//2 * CELLSIZE
		self.body = [[self.head[0]-2*CELLSIZE, self.head[1]],
					[self.head[0]-CELLSIZE, self.head[1]],
					self.head]
		print(self.body)

		self.headup = pygame.image.load('Assets/body/uhead.png')
		self.headdown = pygame.image.load('Assets/body/dhead.png')
		self.headleft = pygame.image.load('Assets/body/lhead.png')
		self.headright = pygame.image.load('Assets/body/rhead.png')

	def update(self):
		head = self.body[-1]
		if self.direction == 'up':
			head = [head[0], head[1] - CELLSIZE]
		elif self.direction == 'down':
			head = [head[0], head[1] + CELLSIZE]
		elif self.direction == 'left':
			head = [head[0] - CELLSIZE, head[1]]
		elif self.direction == 'right':
			head = [head[0] + CELLSIZE, head[1]]

		self.head = head
		self.body.append(self.head)
		if self.length < len(self.body):
			self.body.pop(0)

		snake.outOfBound()
		# if snake.tailCollision():
		# 	print(True)

	def outOfBound(self):
		for index, block in enumerate(self.body):
			if block[0] > WIDTH:
				self.body[index][0] = 0
			elif block[0] < 0:
				self.body[index][0] = WIDTH - CELLSIZE
			elif block[1] > HEIGHT:
				self.body[index][1] = 0
			elif block[1] < 0:
				self.body[index][1] = HEIGHT - CELLSIZE

	def eatFood(self):
		self.length += 1

	def checkFood(self, food):
		if self.head[0] == food.x and self.head[1] == food.y:
			return True
		return False

	def tailCollision(self):
		head = self.body[-1]
		has_eaten_tail = False

		for i in range(len(self.body)-2):
			block = self.body[i]
			if head[0] == block[0] or head[1] == block[1]:
				has_eaten_tail = True

		return has_eaten_tail

	def draw(self):
		for index, block in enumerate(self.body):
			x, y = block
			rect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
			if index == self.length - 1:
				head = self.body[index]
				neck = self.body[index-1]
				image = self.headright
				if head[0] == neck[0] and head[1] < neck[1]:
					image = self.headup
				elif head[0] == neck[0] and head[1] > neck[1]:
					image = self.headdown
				elif head[1] == neck[1] and head[0] < neck[0]:
					image = self.headleft
				elif head[1] == neck[1] and head[0] > neck[0]:
					image = self.headright
				win.blit(image, (x, y))

			# if block == self.head:
			# 	win.blit(self.headright, rect)
			# else:
			# 	pygame.draw.rect(win, GREEN, rect)

class Food:
	def __init__(self):
		type_ = random.randint(1, 3)
		self.image = self.temp = pygame.image.load(f'Assets/{type_}.png')
		self.size = 16
		self.ds = 1
		self.counter = 0
		self.respawn()

	def respawn(self):
		self.x = random.randint(0,COLS-1) * CELLSIZE
		self.y = random.randint(0,ROWS-1) * CELLSIZE

		if tile_collide(leveldata, (self.x, self.y)):
			self.respawn()

	def update(self):
		self.counter += 1
		if self.counter % 3 == 0:
			self.size += self.ds
			if self.size < 15 or self.size > 17:
				self.ds *= -1

			self.temp = pygame.transform.scale(self.image, (self.size, self.size))

	def draw(self):
		win.blit(self.temp, (self.x, self.y))

class Tree:
	def __init__(self, x, y):
		self.x = x
		self.y = y
		self.counter = self.index = 0

		self.imglist = []
		for i in range(4):
			img = pygame.image.load(f'Assets/tree{i}.png')
			self.imglist.append(img)
		self.image = self.imglist[self.index]

	def update(self):
		self.counter += 1
		if self.counter % 3 == 0:
			self.index = (self.index + 1) % 3
			self.counter = 0
			self.image = self.imglist[self.index]

	def draw(self):
		win.blit(self.image, (self.x, self.y))

# GAME VARIABLES *************************************************************

level = 1
MAX_LEVEL = 4
score = 0

snake = Snake()
tree = Tree(WIDTH//2 - 8, HEIGHT//2 - 52)

homepage = True
gamepage = False
gameover = False

running = True
while running:
	selected = False
	win.fill(BLACK)
	win.blit(bg, (0, 0))
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = False

		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_ESCAPE:
				running = False

			if homepage:
				if event.key == pygame.K_UP:
					cmode -= 1
					if cmode < 0:
						cmode = 3

				if event.key == pygame.K_DOWN:
					cmode += 1
					if cmode > 3:
						cmode = 0

				if event.key == pygame.K_RETURN:
					selected = True
					if cmode == 3:
						running = False

			if event.key == pygame.K_RIGHT and snake.direction != 'left':
				snake.direction = 'right'

			if event.key == pygame.K_LEFT and snake.direction != 'right':
				snake.direction = 'left'

			if event.key == pygame.K_UP and snake.direction != 'down':
				snake.direction = 'up'

			if event.key == pygame.K_DOWN and snake.direction != 'up':
				snake.direction = 'down'

	if homepage:
		win.blit(logo, (0,0))
		win.blit(logo2, (0,225))

		for index, mode in enumerate(gameoptions):
			color = (32, 32, 32)
			if cmode == index:
				color = WHITE
			shadow = smallfont.render(mode, True, color)
			text = smallfont.render(mode, True, WHITE)
			win.blit(text, (WIDTH//2 - text.get_width()//2+1, HEIGHT//2 + 55*index+1))
			win.blit(shadow, (WIDTH//2 - text.get_width()//2, HEIGHT//2 + 55*index))

		if selected:
			if cmode == 0:
				leveldata = [[0 for i in range(COLS)] for j in range(ROWS)]

			if cmode == 1:
				level = 'boxed'
				leveldata, length = loadlevel(level)

			if cmode == 2:
				level = 1
				leveldata, length = loadlevel(level)

			snake.__init__()
			food = Food()

			homepage = False
			gamepage = True
			score = 0

		pygame.draw.rect(win, BLUE, (0,0,WIDTH,HEIGHT), 2)

	if gamepage:
		# drawGrid()

		if not gameover:
			# draw level
			for y in range(ROWS):
				for x in range(COLS):
					if leveldata[y][x] > 0:
						tile = leveldata[y][x]
						pos = (x*CELLSIZE, y*CELLSIZE)
						rect = pygame.Rect(pos[0], pos[1], tile_size[tile][0],
								tile_size[tile][1])

						if tile != 3:
							pygame.draw.rect(win, (18, 18, 18), (rect.x+2, rect.y+2,
										 rect.width, rect.height))
						win.blit(tile_list[tile-1], pos)
						if rect.collidepoint(snake.head):
							gameover = True

			snake.update()
			snake.checkFood(food)
			snake.draw()
			food.update()
			food.draw()

			if snake.checkFood(food):
				snake.eatFood()
				food.respawn()
				score += 1

			if cmode == 0 or cmode == 1:
				tree.update()
				tree.draw()

				score_img = smallfont.render(f'{score}', True, WHITE)
				win.blit(score_img, (WIDTH-30 - score_img.get_width()//2, HEIGHT - 50))

			elif cmode == 2:
				bar = pygame.transform.scale(bar_img, (score*10, 10))
				win.blit(bar, (WIDTH//2-50, HEIGHT-50))
				pygame.draw.rect(win, WHITE, (WIDTH//2-50, HEIGHT-51, 100, 10),1 , border_radius=10)

				if score and score % 10 == 0:
					level += 1
					if level <= MAX_LEVEL:
						leveldata, length = loadlevel(level)
						score = 0
						snake.__init__()
					else:
						gameover = True
		else:
			win.blit(gameover_img, (WIDTH//2 - gameover_img.get_width()//2, 80))
			pygame.draw.rect(win, BLUE, (0,0,WIDTH,HEIGHT), 2)

	clock.tick(FPS)
	pygame.display.update()
pygame.quit()


# -*- coding: utf-8 -*-
import json
import requests

from django.contrib.auth import login, authenticate
from django.http import HttpResponse
from django.shortcuts import redirect
from .utils import get_config

def process_login(request):
    """
    Default handler to login user
    :param request: HttpRequest
    """
    code = request.GET.get('code', '')
    config = get_config()
    json_header = {'content-type': 'application/json'}
    token_url = 'https://%s/oauth/token' % config['AUTH0_DOMAIN']

    token_payload = {
        'client_id': config['AUTH0_CLIENT_ID'],
        'client_secret': config['AUTH0_SECRET'],
        'redirect_uri': config['AUTH0_CALLBACK_URL'],
        'code': code,
        'grant_type': 'authorization_code'
    }

    token_info = requests.post(token_url,
                               data=json.dumps(token_payload),
                               headers=json_header).json()

    url = 'https://%s/userinfo?access_token=%s'
    user_url = url % (config['AUTH0_DOMAIN'],
                      token_info.get('access_token', ''))

    user_info = requests.get(user_url).json()

    # We're saving all user information into the session
    request.session['profile'] = user_info
    user = authenticate(**user_info)

    if user:
        login(request, user)
        return redirect(config['AUTH0_SUCCESS_URL'])

    return HttpResponse(status=400)


import py5
import requests
from random import sample
# headers = {
#     'Content-Type': 'application/json;charset=UTF-8',
#     }
distritos = 'https://servicodados.ibge.gov.br/api/v1/localidades/distritos?orderBy=nome'
request = requests.get(distritos)#, headers=headers)
json_ibge = request.json()
print(len(json_ibge))

def extract(record):
    return "{}  - {} - {}".format(
        record['nome'],
        record['municipio']['nome'],
        record['municipio']['microrregiao']['nome']
        )

def setup():
    py5.size(600, 600)
    py5.text_size(20)
    py5.fill(0)
    for record in sample(json_ibge, 10):
        distrito_municipio_microrregiao = extract(record)
        py5.text(distrito_municipio_microrregiao, 20, 40)
        py5.translate(0, 30)

py5.run_sketch()