import random
import itertools
import time

def right_pad(string, length, character):
    """Pad a string to a certain length on the right side"""
    add_len = length - len(string)
    return f'{string}{character * add_len}'

def validate_character(char, acceptable_characters):
    while True:
        check = input(char)
        if len(check > 1):
            print('Please enter only one character')
            continue
        if check not in acceptable_characters:
            print('Invalid selection, try again')
            continue
        return check

class Card():
    """Standard playing card.
    Init choses a random suit and value if none provided."""
    suits = ('S','H','C','D')
    suits_long = {'S':'Spades','H':'Hearts','C':'Clubs','D':'Diamonds'}
    values = ('A','2','3','4','5','6','7','8','9','10','J','Q','K')
    values_long = {
        'A':'Ace','2':'Two','3':'Three','4':'Four','5':'Five','6':'Six',
        '7':'Seven','8':'Eight','9':'Nine','10':'Ten','J':'Jack','Q':'Queen',
        'K':'King'
        }
    values_plural = {
        'A':'Aces','2':'Twos','3':'Threes','4':'Fours','5':'Fives','6':'Sixes',
        '7':'Sevens','8':'Eights','9':'Nines','10':'Tens','J':'Jacks',
        'Q':'Queens','K':'Kings'
        }
    point_values = {
        'A':14,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':11,
        'Q':12,'K':13
        }
    def __init__(self, suit=None, value=None):
        if (suit):
            self.suit = suit
        else:
            self.suit = Card.suits[random.randint(0,3)]
        if (value):
            self.value = value
        else:
            self.value = Card.values[random.randint(0,12)]
        self.name = f'{self.value}{self.suit}'
        self.long_name = (
            f'{Card.values_long[self.value]} of {Card.suits_long[self.suit]}')

    def __repr__(self):
        return self.name
    def __str__(self):
        return self.long_name

class Deck():
    """Class representing standard deck(s) of cards."""
    def __init__(self, num_decks=1):
        self.ini_cards = []
        self.cards = []
        for i in range(num_decks):
            self.cards.extend(
                [Card(x,y) for x in Card.suits for y in Card.values])
            #Also Works:
            #[Card(x,y) for x,y in itertools.product(Card.suits, Card.Values)]
            self.ini_cards = self.cards

    def __len__(self):
        return len(self.cards)
    def __repr__(self):
        return str(self.cards)
    def __str__(self):
        return str(self.cards)
    def shuffle(self):
        random.shuffle(self.cards)

    def cut(self, percent, side='top'):
        """Cut the deck and use only a percent of the cards"""
        if (side == 'top'):
            self.cards = self.cards[
                0:round((percent / 100) * len(self.cards))]
        elif (side == 'bottom'):
            self.cards = self.cards[
                round((percent / 100) * len(self.cards)):len(self.cards)]

    def reset(self):
        self.cards = self.ini_cards

class Player():
    """Card Game Player"""
    def __init__(self, name, money):
        self.name = name
        self.money = money
        self.hand = None #initialize in game - hands are different in each
        self.out = False

    def draw(self, deck):
        """Extend drawing up to the player level
        Allows player.draw() syntax instead of player.hand.draw()
        """
        if (self.hand):
            self.hand.draw(deck)
            self.score = self.hand.score
        else:
            raise Exception(f'Player {self.name} does not have any hands!')

    def list_cards(self):
        """Extend listing cards up to the player level
        Allows player.list_cards() syntax
        """
        if (self.hand):
            return self.hand.list_cards()
        else:
            raise Exception(f'Player {self.name} does not have any hands!')

    def reset(self):
        """Extend resetting hand up to the player level
        Allows player.reset() syntax"""
        if (self.hand):
            self.hand.reset()
            self.out = False
        else:
            raise Exception(f'Player {self.name} does not have any hands!')

class Dealer(Player):
    pass

class BlackJackHand():
    """Class representing a blackjack-specific hand"""
    bj_scores = {
        'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,
        '8':8,'9':9,'10':10,'J':10,'Q':10,'K':10
        }
    def __init__(self):
        self.cards = []
        self.score = 0
        self.aces = 0
        self.aces_converted = 0
        self.bust = False
        self.blackjack = False

    def __repr__(self):
        return str(self.cards)

    def reset(self):
        self.cards = []
        self.card_list = []
        self.score = 0
        self.acse = 0
        self.aces_converted = 0
        self.bust = False
        self.blackjack = False

    def list_cards(self):
        """Cast cards in hand to list of strings
        For easy printing"""
        card_list = [x.name for x in self.cards]
        if (card_list is not None):
            return card_list
        else:
            return[]

    def draw(self,deck):
        """Draw a card, evaluate, and add to score"""
        self.cards.append(deck.cards.pop())
        if (self.cards[-1].value == 'A'):
            self.aces += 1
        self.score += BlackJackHand.bj_scores[self.cards[-1].value]
        #Apparently the below isn't real, despite playing this way my whole life
        # #if you draw a blackjack, score is 21 automatically
        # if (self.cards[-1].suit in ('S','C') and self.cards[-1].value == 'J'):
        #     self.score = 21
        #if you bust but have an ace, convert ace to 1
        if (self.score > 21 and (self.aces > self.aces_converted)):
            self.score += -10
            self.aces_converted += 1
        #if you draw to 7 cards without busting you win
        if (len(self.cards) >= 7 and self.score < 21):
            self.score = 21
        if (self.score == 21):
            self.blackjack = True
        if (self.score > 21):
            self.bust = True
        self.card_list = self.list_cards()

class BlackJack():
    """Main class for running a blackjack game"""
    def __init__(self):
        self.dealer = Dealer('House', 50000)
        self.dealer.hand = BlackJackHand()
        self.register_players()
        deck_size = int(input('Deck Size? (Number of packs) '))
        self.deck = Deck(deck_size)
        self.deck.shuffle()
        cut = input('Cut the deck. What percent do we keep? ')
        if ('%' in cut):
            cut = cut.replace('%','')
        cut = int(cut)
        self.deck.cut(cut)
        self.round_count = 0
        print('~~~~~~~~~~~~~~~Game Start~~~~~~~~~~~~~~~~')

    def __repr__(self):
        return 'BlackJack'
    def __str__(self):
        return 'BlackJack'

    @classmethod
    def name(cls):
        """Return the name of the class as a string.
        Classmethod so it can be used without an instance
        """
        return 'BlackJack'

    def register_players(self):
        self.players = []
        player_count = int(input('How many people are playing? '))
        for i in range(player_count):
            temp_name = input(f"What's the name of Player {i + 1}? ")
            temp_money = input(f'How much money does {temp_name} have? ')
            player = Player(temp_name, int(temp_money))
            player.hand = BlackJackHand()
            self.players.append(player)

    def deal(self):
        """The initial deal"""
        self.dealer.draw(self.deck)
        for player in self.players:
            player.draw(self.deck)
        self.dealer.draw(self.deck)
        for player in self.players:
            player.draw(self.deck)

    def display_table(self, reveal_dealer = False):
        """Show the current status of the table"""
        #TODO Fixed width of table display with different length names
        if (reveal_dealer):
            dealer_card_0 = self.dealer.hand.card_list[0]
        else:
            dealer_card_0 = 'XX'
        print('~~~~~~~~~~~~~~Current Table~~~~~~~~~~~~~~')
        print(
            f'{right_pad(self.dealer.name, 12, " ")}: {dealer_card_0} '
            f'{" ".join(self.dealer.hand.card_list[1:])}')
        for player in self.players:
            print(f'{right_pad(player.name, 12, " ")}: '
            f'{" ".join(player.hand.card_list)}')
        print('')

    def run(self):
        self.keep_playing = True
        while self.keep_playing:
            #reset hands
            self.dealer.reset()
            for player in self.players:
                player.reset()
            self.round_count += 1
            print(f'Round: {self.round_count}')
            print(f'Cards Left: {len(self.deck)}')
            print(f'{self.dealer.name} has ${self.dealer.money}')
            for player in self.players:
                temp_bet = 0
                while temp_bet == 0:
                    temp_bet = int(input(
                        f'{player.name}, you have ${player.money}.'
                        ' Place your bet: '))
                    if (temp_bet == 0):
                        print('You cannot place a zero bet, try again')
                player.bet = temp_bet
            self.deal()
            self.display_table()
            time.sleep(1)
            player_scores = [x.hand.score for x in self.players]
            if (21 not in player_scores and self.dealer.hand.score != 21):
                pass
            elif (self.dealer.hand.score == 21):
                #if the dealer has 21 on first hand
                #collect bets from all players w/o 21
                print(f"{self.dealer.name}'s first card is "
                    f"{self.dealer.hand.card_list[0]}")
                print(f'{self.dealer.name} has 21!')
                for player in self.players:
                    if (player.score != 21):
                        print(f'{player.name} loses ${player.bet} to '
                            f'{self.dealer.name}')
                        player.money += -(player.bet)
                        self.dealer.money += player.bet
                    elif (player.score == 21):
                        print(f'{player.name} also has 21 and loses nothing.')
                    time.sleep(1)
                print('Round Over...')
                continue
            elif (21 in player_scores):
                for player in self.players:
                    if (player.hand.score == 21):
                        print(f'{player.name} has 21 and collects '
                            f'${player.bet * 1.5}')
                        player.money += (player.bet * 1.5)
                        self.dealer.money += -(player.bet * 1.5)
                        player.bet = 0
                        player.out = True
                        time.sleep(1)
            players_in = [x.out for x in self.players]
            while (False in players_in):
                players_in = self.hit_loop()
                if (False in players_in):
                    self.display_table()
                time.sleep(1)
            print(f'{self.dealer.name} reveals their face down card...')
            self.display_table(reveal_dealer=True)
            time.sleep(1)
            print(f'{self.dealer.name} plays...')
            self.dealer_play_loop()
            if (self.dealer.hand.bust == True):
                continue
            print(f'{right_pad(self.dealer.name, 12, " ")}: '
                f'Score: {self.dealer.hand.score}')
            #final score print and win calc
            for player in self.players:
                if (player.bet != 0):
                    time.sleep(1)
                    print(f'{right_pad(player.name, 12, " ")}: '
                        f'Score: {player.hand.score}')
                    if (player.hand.score > self.dealer.hand.score):
                        print(f'{player.name} beats {self.dealer.name} and '
                            f'collects ${player.bet}')
                        player.money += player.bet
                        self.dealer.money += -(player.bet)
                    elif (player.hand.score == self.dealer.hand.score):
                        print(f'{player.name} ties {self.dealer.name}')
                    elif (player.hand.score < self.dealer.hand.score):
                        print(f'{player.name} loses to {self.dealer.name} '
                            f'and forfeits ${player.bet}.')
                        player.money += -(player.bet)
                        self.dealer.money += player.bet
                    time.sleep(1)
            print('Round Over...')

    def hit_loop(self):
        for player in self.players:
            if (player.out):
                continue
            else:
                hit = validate_character(
                    f'{player.name}, Hit or Stand? h/s: ', 'hs')
            if (hit == 'h'):
                player.draw(self.deck)
                if (player.hand.score > 21):
                    print(f'{player.name} busts and loses ${player.bet}')
                    player.money += -(player.bet)
                    self.dealer.money += player.bet
                    player.bet = 0
                    player.hand.bust = True
                    player.out = True
            else:
                player.out = True
        players_in = [x.out for x in self.players]
        return players_in

    def dealer_play_loop(self):
        while self.dealer.hand.score < 17:
            time.sleep(1)
            self.dealer.draw(self.deck)
            print(f'{self.dealer.name} draws '
                f'{self.dealer.hand.card_list[-1]}')
            if (self.dealer.hand.score > 21):
                print(f'{self.dealer.name} busts!')
                for player in self.players:
                    if (player.bet != 0):
                        player.money += player.bet
                        self.dealer.money += -(player.bet)
                        print(f'{player.name} collects ${player.bet}')
                        time.sleep(1)
                print('Round Over...')
                return None
        time.sleep(1)
        print(f'{self.dealer.name} stands\n')
        time.sleep(1)

class PokerHand():
    """Poker-specific hand"""
    hand_types = {
        'royal':10, 's_flush':9, 'four_kind':8, 'full_house':7, 'flush':6,
        'straight':5, 'three_kind':4, 'two_pair':3, 'pair':2, 'high_card':1
        }
    hand_types_long = {
        'royal':'Royal Flush', 's_flush':'Straight Flush',
        'four_kind':'Four of a Kind', 'full_house':'Full House',
        'flush':'Flush', 'straight':'Straight',
        'three_kind':'Three of a Kind', 'two_pair':'Two Pair', 'high_card':''
        }

    def __init__(self):
        self.cards = []
        self.shared_cards = [] #for hold'em
        self.final_cards = [] #selected from cards and shared in hold'em
        self.type = 'high_card' #hand type string, default lowest
        self.score = 1
        self.high_card = None #highest value card

    def __repr__(self):
        temp = (
            f'{self.cards} {PokerHand.hand_types_long[self.type]}, '
            f'{self.high_card.long_name} High')
        return temp

    def reset(self):
        self.cards = []
        self.shared_cards = []
        self.final_cards = []
        self.type = 'high_card'
        self.score = 1
        self.high_card = None

    def list_cards(self):
        """Cast cards in hand to list of strings
        For easy printing"""
        card_list = [x.name for x in self.cards]
        if (card_list is not None):
            return card_list
        else:
            return[]

    def draw(self, deck):
        """Draw one card from the deck"""
        self.cards.append(deck.cards.pop())

    def eval_hand(self):
        """Identify the score of this hand"""
        points = [Card.point_values[card.value] for card in self.cards]
        self.high_card = self.cards[points.index(max(points))]
        #How many suits are in the hand?
        suit_counts = {'S':0,'H':0,'C':0,'D':0}
        for card in self.cards:
            suit_counts[card.suit] +=1
        #How many of each value are in the hand?
        value_counts = {
        'A':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0,'10':0,'J':0,
        'Q':0,'K':0}
        for card in self.cards:
            value_counts[card.value] += 1

        #if we only have one suit in the hand, we have a flush
        if ([x != 0 for x in suit_counts.values()].count(True) == 1):
            flush = True
        else:
            flush = False

        # if we never have more than 1 of a value, we might have a straight
        value_count_list = list(value_counts.values())
        aces_high_list = value_count_list[1:]
        aces_high_list.append(value_count_list[0])
        if (True in [x > 1 for x in value_count_list]):
            straight = False
        else:
            #generate a binary number representing the point values in hand
            #with aces low
            value_mask_str_low = '0b'
            for x in value_count_list:
                value_mask_str_low += str(x)
            value_mask_low = int(value_mask_str_low, 2)
            #with aces high
            value_mask_str_high = '0b'
            for x in aces_high_list:
                value_mask_str_high += str(x)
            value_mask_high = int(value_mask_str_high, 2)
            # if our aces high number is 0b0000000011111 and is flush
            # we have a royal flush!
            if (value_mask_high == 31 and flush == True):
                self.type == 'royal'
                self.score == PokerHand.hand_types[self.type]
                return
            #check to see if the value masks equate to any binary number with
            #all 1's next to eachother
            sequence_bins = (31,62,124,248,496,992,1984,3968,7936)
            if (value_mask_low in sequence_bins or
                value_mask_high in sequence_bins):
                straight = True

        if (straight and flush):
            self.type = 's_flush'
            self.score = PokerHand.hand_types[self.type]
            return
        if (value_count_list.count(4) == 1):
            self.type = 'four_kind'
            self.score = PokerHand.hand_types[self.type]
            return
        if (value_count_list.count(3) == 1 and
            value_count_list.count(2) == 1):
            self.type = 'full_house'
            self.score = PokerHand.hand_types[self.type]
            return
        if (flush):
            self.type = 'flush'
            self.score = PokerHand.hand_types[self.type]
            return
        if (straight):
            self.type = 'straight'
            self.score = PokerHand.hand_types[self.type]
            return
        if (value_count_list.count(2) == 2):
            self.type = 'two_pair'
            self.score = PokerHand.hand_types[self.type]
            return
        if (value_count_list.count(2) == 1):
            self.type = 'pair'
            self.score = PokerHand.hand_types[self.type]
            return

class FiveCard():
    """Game runner class for Five Card Draw"""
    def __init__(self):

        pass

    def __repr__(self):
        return 'Five Card Draw'
    def __str__(self):
        return 'Five Card Draw'

    @classmethod
    def name(cls):
        """Return the name of the class as a string.
        Classmethod so it can be used without an instance
        """
        return 'Five Card Draw'

class TexasHoldem():
    """Game runner class for Texas Hold'em"""
    def __init__(self):
        #what do we need for a game of this?
        pass

    def __repr__(self):
        return "Texas Hold'em"
    def __str__(self):
        return "Texas Hold'em"

    @classmethod
    def name(cls):
        """Return the name of the class as a string.
        Classmethod so it can be used without an instance
        """
        return "Texas Hold'em"

class Poker():
    """Prompt the user to pick a poker subtype"""
    POKER_GAMES = {'1':FiveCard, '2':TexasHoldem}

    def __init__(self):
        pass

    def run(self):
        print('Poker Types:')
        for key in POKER_GAMES:
            print(f'{key}> {POKER_GAMES[key].name()}')
        poker_number = validate_character(
            "Enter the number for the type of poker you'd like to play: ",
            '12')
        poker = POKER_GAMES[poker_number].run()

def main():
    GAMES = {'1':BlackJack, '2':Poker, '3':Solitaire}
    print('What game would you like to play? Current Options:')
    for key in GAMES:
        print(f'{key}> {GAMES[key].name()}')
    game_number = validate_character(
        'Enter the number for the game you want: ', '123')
    #Initialize the class of the chosen game
    game = GAMES[game_number]()
    game.run()

if (__name__ == '__main__'):
    main()


"""
- BFS level order traversal
"""

from typing import Optional
import collections

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:

        if depth == 1:
            node = TreeNode(val=val)
            node.left = root
            return node

        queue = collections.deque()
        queue.append(root)

        curr_depth = 1
        while curr_depth < depth - 1:
            for _ in range(len(queue)):
                curr_node = queue.popleft()
                if curr_node.left:
                    queue.append(curr_node.left)
                if curr_node.right:
                    queue.append(curr_node.right)
            curr_depth += 1

        while queue:

            curr_node = queue.popleft()

            tmp = curr_node.left
            new_node = TreeNode(val=val)
            curr_node.left = new_node
            curr_node.left.left = tmp

            tmp = curr_node.right
            new_node = TreeNode(val=val)
            curr_node.right = new_node
            curr_node.right.right = tmp

        return root

if __name__ == '__main__':
    root = TreeNode(4)
    root.left = TreeNode(2)
    root.right = TreeNode(6)
    root.left.left = TreeNode(3)
    root.left.right = TreeNode(1)
    root.right.left = TreeNode(5)
    val = 1
    depth = 2
    print(Solution().addOneRow(root, val, depth))


# while True:
#     try:
#         string = input().strip()
#         buckets = [[] for _ in range(len(string))]
#         d = dict()
#         for s in string:
#             if s not in d:
#                 d[s] = 1
#             else:
#                 d[s] += 1
#         for k, v in d.items():
#             buckets[v].append(k)
#         result = ''
#         for bucket in reversed(buckets):
#             if len(bucket):
#                 bucket.sort()
#                 for units_decimal in bucket:
#                     result += units_decimal
#         print(result)
#     except:
#         break

while True:
    try:
        string = input().strip()
        d = {}
        for s in string:
            if s.isdigit() or s.isalpha() or s == ' ':
                if s in d.keys():
                    d[s] += 1
                else:
                    d[s] = 1
        # 先按字母升序, 后按个数降序
        d2 = sorted(sorted(d.items(), key=lambda x: x[0]), key=lambda item: item[1], reverse=True)
        str1 = ''.join([k for (k, v) in d2])
        print(str1)
    except:
        break


import pygame as pg
import numpy as np
import time as t
import random as r
from perlin_noise import PerlinNoise
pg.init()
pg.font.init()

#CONFIG#
plot_world_gen = False # uses matplotlib (install with pip3 first)
seed = 1
octaves = 15
width_world = 100
height_world = 100
########

grid_size = 16 # how many pixels width and height a tile is

def generate_world(width_world, height_world, seed, octaves):
    noise = PerlinNoise(octaves=octaves, seed=seed)

    world_gen = np.zeros((height_world,width_world),dtype='float')
    for i in range(height_world):
        for j in range(width_world):
            world_gen[j][i] = noise([i/width_world, j/height_world])

    if plot_world_gen:
        import matplotlib.pyplot as plt
        plt.imshow(world_gen)
        plt.show()

    world = np.zeros((height_world, width_world),dtype="int")
    for i in range(height_world):
        for j in range(width_world):
            world[j][i] = 1 # change this later for if's with world_gen

    world_rotation = np.zeros((height_world, width_world),dtype="int")
    for i in range(height_world):
        for j in range(width_world):
            world_rotation[j][i] = r.randint(0,3) # rotation 0: up, 1: right, 2: down, 3: left

    return world, world_rotation

def load_images():
    images = {} # pictures stored as {"1":pg.surface16x16x32 etc.}

    images_path = "ground/"
    images_to_load = [] # all images are .png
    for i in range(44):
        images_to_load.append(str(i))

    for img in images_to_load:
        images[img] = pg.image.load(f"{images_path}{img}.png")

    return images

def scale_images(images, scale):
    scaled_images = {}
    for img in images.keys():
        scaled_images[img] = [pg.transform.rotate(pg.transform.scale(images[img], (
                int(scale * grid_size),
                int(scale * grid_size))), -angle) for angle in range(0, 360, 90)]

    return scaled_images

def draw_world(screen, world, world_rotation, scrollx, scrolly, scale, scaled_images):
    screen = screen
    screen_size = screen.get_size()
    for x in range(max(0, int(abs(scrollx) / (grid_size * scale))), min(world.shape[1],
                                                                        int(int((abs(scrollx) + screen_size[0]) / (
                                                                                grid_size * scale) + 1) + np.ceil(
                                                                            (abs(scrollx) + screen_size[0]) / (
                                                                                grid_size * scale) % 1)))):
        for y in range(max(0, int(abs(scrolly) / (grid_size * scale))), min(world.shape[0],
                                                                            int(int((abs(scrolly) + screen_size[1]) / (
                                                                                grid_size * scale) + 1) + np.ceil(
                                                                                (abs(scrolly) + screen_size[1]) / (
                                                                                grid_size * scale) % 1)))):
            block = world[y, x]
            orientation = world_rotation[y, x]
            x_grid_scale = round(x * grid_size * scale) + scrollx
            y_grid_scale = round(y * grid_size * scale) + scrolly

            screen.blit(scaled_images[str(block)][orientation], (x_grid_scale, y_grid_scale))

def handle_keys(keys_list, dT, scrollx, scrolly):
    speed = 0.3 * dT
    if keys_list[pg.K_w]:
        scrolly += speed
    if keys_list[pg.K_a]:
        scrollx += speed
    if keys_list[pg.K_s]:
        scrolly -= speed
    if keys_list[pg.K_d]:
        scrollx -= speed

    scrollx = min(scrollx, 0)
    scrolly = min(scrolly, 0)

    return scrollx, scrolly

scrollx = 0
scrolly = 0
scale = 1

images = load_images()
scaled_images = scale_images(images,scale)

screen = pg.display.set_mode((500,500), pg.RESIZABLE, pg.HWSURFACE)
playing = True
pg.display.set_caption("Tile level editor")

world, world_rotation = generate_world(width_world, height_world, seed, octaves)

keys = [pg.K_w, pg.K_a, pg.K_s, pg.K_d, pg.K_r]
keys_list = {}

for i in keys:
    keys_list[i] = False

dT = 0
clock = pg.time.Clock()

while playing:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            playing = False

        if e.type == pg.KEYDOWN:
            if e.key == pg.K_ESCAPE:
                playing = False
            for i in keys_list:
                if i == e.key:
                    keys_list[i] = True

        if e.type == pg.KEYUP:
            for i in keys_list:
                if i == e.key:
                    keys_list[i] = False

        if e.type == pg.MOUSEWHEEL:
            scale += e.y / 2
            scale = min(max(scale, 0.5), 5)
            print(scale)
            scaled_images = scale_images(images, scale)

        pg.event.pump()

    scrollx, scrolly = handle_keys(keys_list, dT, scrollx, scrolly)

    screen.fill((0,0,0))
    draw_world(screen, world, world_rotation, scrollx, scrolly, scale, scaled_images)
    pg.display.flip()
    dT = clock.tick()

pg.font.quit()
pg.quit()


import os
import pickle
import sys
from PIL import Image
import imageio
path_to_annos = '/media/ssd2/marine/idd/pickle_annos/Annos.py'
sys.path.append(path_to_annos)
from Annos import Annos

P_HOME = '/media/ssd2/marine/idd/pickle_annos'
V_HOME = '/media/ssd2/marine/idd/vids'
frame_home = '/media/ssd2/marine/idd/frames'

im_cnt = 0
IM_MAX = 10

if __name__ == "__main__":

    piks = os.listdir(P_HOME)

    pname_to_obj = {}

    for pname in piks:
        if 'habs' in pname:
            with open(os.path.join(P_HOME, pname), 'rb') as f:
                habs = pickle.load(f)
            pname_to_obj[pname] = habs
        elif 'specs' in pname:
            with open(os.path.join(P_HOME, pname), 'rb') as f:
                specs = pickle.load(f)
            ide = pname.split('_')[0]

            reader = imageio.get_reader(os.path.join(V_HOME, ide+'.mp4'))

            fnums = list(specs.keys())
            fnums.sort()

            for fnum in fnums:
                di = specs[fnum]
                if len(di['count']) < 3: continue
                print('---- {} ----'.format(fnum))
                print(di)
                # with timeout(seconds=5)j
                frame = reader.get_data(fnum)
                new_id = ide + '_{:07d}'.format(fnum)
                sv_name = os.path.join(frame_home, new_id+'.png')
                img = Image.fromarray(frame)
                img.save(sv_name)
                reader.close()
                im_cnt += 1
                if im_cnt >= IM_MAX:
                    sys.exit()
            pname_to_obj[pname] = specs


import unittest
from datetime import datetime

from .usage_policy import UsagePolicy, CommandFormatError

class UsagePolicyTest(unittest.TestCase):
    def test_chat_limit_clear(self):
        return_date = datetime(2023, 1, 1, 10, 10, 10)

        def current_date():
            return return_date

        up = UsagePolicy(["a"], user_chat_count_per_day={"b": 2}, current_date=current_date, token="c")
        up.on_chat("b")
        up.on_chat("b")
        self.assertTrue(up.reached_limit("b"))
        self.assertTrue(up.reached_limit("b"))
        return_date = datetime(2023, 1, 2, 0, 0, 0)
        self.assertFalse(up.reached_limit("b"))
        up.on_chat("b")
        up.on_chat("b")
        self.assertTrue(up.reached_limit("b"))

    def test_chat_limit(self):
        up = UsagePolicy(["a"], user_chat_count_per_day={"b": 2}, default_user_chat_count_per_day=3, token="c")
        up.on_chat("b")
        up.on_chat("b")
        self.assertTrue(up.reached_limit("b"))

        up.on_chat("c")
        up.on_chat("c")
        self.assertFalse(up.reached_limit("c"))
        up.on_chat("c")
        self.assertTrue(up.reached_limit("c"))

        self.assertFalse(up.handle_usage_change_command("a", "some normal msg", {}))
        self.assertFalse(up.handle_usage_change_command("b", "some normal msg", {}))

        self.assertRaises(Exception, lambda: up.handle_usage_change_command("b", "admin-command:c\nset_limit", {}))
        self.assertRaises(CommandFormatError, lambda: up.handle_usage_change_command("a", "admin-command:c\nset_limit", {}))

        self.assertTrue(up.handle_usage_change_command("a", "admin-command:c\nset_limit\nd,10", {}))
        self.assertEqual(up.user_chat_count_per_day["d"], 10)


from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
from urllib.error import HTTPError
from selenium import webdriver
import re
import csv
import platform

def setUpSelenium():
    host = platform.system()
    if host == 'Linux':
        print("The host is linux")
        return "/home/jack/Desktop/"
    else:
        print("The host is mac")
        return "/Users/jackpincombe/Desktop"

def siteNum(pageNo):
    buttonPath = """/html/body/div[1]/div[2]/div[2]/div/div/div/div[4]/div/div/div/div/div[3]/ol/li["""+ str(pageNo) + """]/a"""
    return(buttonPath)

def getTitle(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        return None

    if html is None:
        print("Shit has hit the fan")
    else:
        bsObj = bs(html.read(), "html.parser")
        getAllPrices(bsObj)

def getAllPrices(bsObj):
    bikes = bsObj.findAll('h3')
    prices = bsObj.findAll('span', {'class': 'price-is'})
    for bike in range(10):
        bikeDetail = str(bikes[bike].get_text()).strip()
        price =str((getBikePrice(prices[bike].get_text()))).strip()

        bike = [bikeDetail, price]

        list.append(bike)

def getBikePrice(tag):
    price = re.findall('(\S[1-9].*\d)', str(tag))[0]
    return price

def getBikeDetails(tag):
    patern = re.compile('.+?(?=0%)')

    if patern.match(tag):
        return re.findall('.+?(?=0%)', tag)
    else:
        return tag

def siteMove():
    pageNo = 5
    while pageNo != 3:
        getTitle(driver.current_url)

        driver.find_element_by_xpath(
            siteNum(pageNo)).click()
        pageNo -= 1

    for i in range(10):
        driver.find_element_by_xpath(
            siteNum(pageNo)).click()
        getTitle(driver.current_url)

def addToCsv(list):
    with open('bikes.csv', 'w+') as my_csv:
        csvWriter = csv.writer(my_csv, delimiter=',')
        for i in list:
            csvWriter.writerow(i)

def readCSV():
    with open("bikes.csv") as f:
        reader = csv.reader(f)
        for row in reader:
            print("The cost of a" + row[0] + " is " + row[1])

def __main__():
    siteMove()
    addToCsv(list)

driverLocation = setUpSelenium()
driver = webdriver.Firefox(driverLocation)
driver.get('https://www.superbikefactory.co.uk/used-motorcycles-macclesfield-cheshire')
list = []

readCSV()


from random import randrange

#Declaração de variavel

numero = randrange(1,10)
print("Escolhi um numero de 1 a 10 tente advinhar")
tentativa = int(input("Qual numero você escolhe? "))
tentativas = 0

while numero != tentativa:
    if numero >= tentativa:

        print("O numero é maior")
        tentativa = int(input("Tente novamente: "))
    elif numero <= tentativa:
        tentativas = tentativas + 1
        print("O numero é menor")
        tentativa = int(input("Tente novamente: "))

print(f"Você acertou o numero era {numero}, Parabens!")
print(f"Tentativas = {tentativas + 1}")


from PIL import Image, ImageOps
from pytesseract import image_to_string
#from ocr_kemenkes import ocr_date  #versi kemenkes berhenti sejak 25 Februari 2021
from ocr_bnpb import ocr_date
import json
from os import walk
import os

dir_path = os.path.dirname(os.path.realpath(__file__))

f = []
for (dirpath, dirnames, filenames) in walk(dir_path+'/data'):
    f.extend(filenames)
    break
try:
    result = json.loads(open('result.json','r').read())
except:
    result = []
dates = []
for res in result:
    dates.append(res['date'])

for i in f:
    if not i.replace('.jpg','') in dates:
        rslt = ocr_date(i)
        if rslt:
            rslt['date'] = i.replace('.jpg','')
            result.append(rslt)

#result = hasil.items()
#sorted_result = sorted(result)
#hasil = ocr_date('2020-05-09.jpg')
newlist = sorted(result, key=lambda k: k['date'])

with open('result.json','w') as fle:
    fle.write(json.dumps(newlist,indent=4))

print(json.dumps(newlist,indent=4))


import datetime
import pytest

from backend.git_analytics.bitbucket.converter import convert_json_to_repository, convert_json_to_commit, \
    convert_json_to_diff_stat
from backend.git_analytics.bitbucket.model import Repository, DiffStat

def test_convert_json_to_repository():
    json = {
        "scm": "git",
        "website": "",
        "has_wiki": False,
        "uuid": "{1234-567-8910}",
        "links": {
            "self": {
                "href": "https://api.bitbucket.org/2.0/repositories/OWNER/project_name"
            },
        },
        "full_name": "OWNER/project_name",
        "name": "project_name",
        "created_on": "2017-01-05T00:40:53.214665+00:00",
        "mainbranch": {
            "type": "branch",
            "name": "master"
        },
        "updated_on": "2017-09-23T09:53:02.713898+00:00",
        "size": 18855171,
        "type": "repository",
        "slug": "project_name",
        "is_private": True,
        "description": ""
    }
    output = convert_json_to_repository(json)

    assert output.created_on == datetime.datetime(2017, 1, 5, 0, 40, 53, 214665)
    assert output.link == "https://api.bitbucket.org/2.0/repositories/OWNER/project_name"
    assert output.main_branch == "master"
    assert output.name == "project_name"
    assert output.type == "repository"
    assert output.updated_on == datetime.datetime(2017, 9, 23, 9, 53, 2, 713898)
    assert output.uuid == "{1234-567-8910}"
    assert output.size == 18855171
    assert output.slug == "project_name"

def test_convert_json_to_diff_stat():
    json = {
        "status": "modified",
        "lines_removed": 1,
        "lines_added": 4,
        "type": "diffstat",
        "old": {
            "path": "old_path"
        },
        "new": {
            "path": "new_path"
        }
    }

    output = convert_json_to_diff_stat(json)

    assert output.insertions == 4
    assert output.deletions == 1
    assert output.status == 'modified'
    assert output.old_path == 'old_path'
    assert output.new_path == 'new_path'

def test_convert_json_to_commit():
    json = {
        "hash": "abcdef",
        "author": {
            "user": {
                "display_name": "Jenni Hantula",
                "account_id": "123123123"
            }
        },
        "parents": [
            {
                "hash": "aaaaaaaaaaaaaaaa",
            },
            {
                "hash": "bbbbbbbbbbbb",
            }
        ],
        "date": "2020-11-20T07:09:53+00:00",
        "message": "Message",
        "type": "commit"
    }

    diff_stats = [DiffStat(
        insertions=1,
        deletions=2,
        status='status',
        old_path='old_path',
        new_path='new_path'
    )]

    output = convert_json_to_commit(json, diff_stats)

    assert output.hash == 'abcdef'
    assert output.user == 'Jenni Hantula'
    assert output.account_id == '123123123'
    assert output.message == 'Message'
    assert output.date == datetime.datetime(2020, 11, 20, 7, 9, 53)
    assert output.type == 'commit'
    assert output.parent_hashes == ['aaaaaaaaaaaaaaaa', 'bbbbbbbbbbbb']
    assert output.diff_stats == diff_stats


import sqlite3
import json
import hashlib
from pymongo import MongoClient

#with open("mock.json", "r") as file:
    #data = json.load(file)

def connect_to_database(db_name):
    client = MongoClient("mongodb://localhost:27017")

    db = client[db_name]

    return client, db

def create_hash(item, key_selection_array):
    data = {}

    for key_selector in key_selection_array:
        data[list(item)[key_selector]] = list(item.values())[key_selector]

    data_json = json.dumps(data, sort_keys=True)

    sha256_hash = hashlib.sha256()
    sha256_hash.update(data_json.encode("utf-8"))
    hashed_data = sha256_hash.hexdigest()

    return hashed_data

def populate_db(data, db_name, collection_name, key_selection_array,  keep_track_on_changes_keys):
    client, db = connect_to_database(db_name)

    collection = db[collection_name]

    if collection.count_documents({}) == 0:
        for item in data:
            document = {}

            for key in item.keys():
                document[key] = item[key]

                try:
                    for index in keep_track_on_changes_keys:
                        if key in list(item.keys())[index]:
                            document[f"previous_{key}"] = ""
                except IndexError:
                    print(f"IndexError: Index {index} is out of range. Please check that you entered a valid position.")
                    return

            document["hash"] = create_hash(item, key_selection_array)

            collection.insert_one(document)
    else:
        print("Database is already populated, running sync_db")
        sync_db(data, db_name, collection_name, key_selection_array, keep_track_on_changes_keys)

    client.close()

def sync_db(data, db_name, collection_name, key_selection_array, keep_track_on_changes_keys):
    client, db = connect_to_database(db_name)

    collection = db[collection_name]

    existing_hashes = set(doc["hash"] for doc in collection.find({}, {"hash": 1}))
    incoming_hashes = set()

    for item in data:
        keys = item.keys()
        keys_list = list(keys)

        hashed_data = {}

        for key in keys:
            hashed_data[key] = item[key]

        incoming_hash = create_hash(hashed_data, key_selection_array)
        incoming_hashes.add(incoming_hash)

        if incoming_hash in existing_hashes:
            print("Incoming hash exists.")

            if len(keys) <= len(key_selection_array):
                print("No field in the document have been specified to update")
                continue

            for index in keep_track_on_changes_keys:
                key = keys_list[index]
                new_value = item[key]
                row_hash = incoming_hash

                existing_document = collection.find_one({"hash": row_hash})

                collection.update_one(
                    {"hash": row_hash},
                    {
                        "$set": {
                            f"previous_{key}": existing_document[key],
                            key: new_value
                        }
                    }
                )

        else:
            print("Incoming hash does not exist.")
            print(f"INSERT INTO {collection_name}: {item}")

            document = {}

            for key in item.keys():
                document[key] = item[key]

                try:
                    for index in keep_track_on_changes_keys:
                        if key in list(item.keys())[index]:
                            document[f"previous_{key}"] = ""
                except IndexError:
                    print(f"IndexError: Index {index} is out of range. Please check that you entered a valid position.")
                    return

            document["hash"] = create_hash(item, key_selection_array)

            collection.insert_one(document)

    removed_hashes = list(existing_hashes - incoming_hashes)

    collection.delete_many({"hash": {"$in": removed_hashes}})
    print(f"Deleted {len(removed_hashes)} records from the collection")

    client.close()


n = int(input())
ans = [0] * (n + 1)
exp = []
current = n

for i in range(2, n + 1):
    ans[i] = ans[i - 1]
    if ans[i // 2] < ans[i] and i % 2 == 0:
        ans[i] = ans[i // 2]
    if ans[i // 3] < ans[i] and i % 3 == 0:
        ans[i] = ans[i // 3]
    ans[i] += 1

while current > 1:
    if ans[current - 1] + 1 == ans[current]:
        prev = current - 1
    elif ans[current // 2] + 1 == ans[current] and current % 2 == 0:
        prev = current // 2
    else:
        prev = current // 3

    if prev * 3 == current:
        exp.append('3')
    elif prev * 2 == current:
        exp.append('2')
    else:
        exp.append('1')

    current = prev

print(*exp[::-1], sep='')


from yticker import YTicker
import threading
import logging
import time
from datetime import datetime
import boto3
from decimal import Decimal

logging.basicConfig(
    format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
    datefmt="%H:%M:%S",
    level=logging.INFO,
    handlers=[logging.FileHandler("logs.txt"), logging.StreamHandler()],
)

class StockTracker(threading.Thread):
    def __init__(self, symbol, data, reconnect_delay=1):
        threading.Thread.__init__(self)
        self.data = data
        self.symbol = symbol
        self.reconnect_delay = reconnect_delay

    def run(self):
        YTicker(
            on_ticker=self.on_message,
            ticker_names=list([self.symbol]),
            on_close=self.on_close,
        )

    def on_message(self, _, message):
        try:
            self.write_data(message)
        except Exception as e:
            logging.error(e, exc_info=True)

    def on_close(self, *_):
        logging.info(f"connection lost, reconnecting in {self.reconnect_delay}")
        time.sleep(self.reconnect_delay)
        self.run()

    def write_data(self, message):
        dyn_resource = boto3.resource("dynamodb")
        table = dyn_resource.Table(message["id"])
        table.put_item(
            Item={
                "timestamp": Decimal(str(message["timestamp"])),
                "price": Decimal(str(round(message["price"], 4))),
                "writetime": Decimal(str(round(datetime.now().timestamp(), 4))),
                "changePercent": Decimal(str(message["changePercent"])),
                "dayVolume": Decimal(str(message["dayVolume"])),
                "change": Decimal(str(message["change"])),
            }
        )


#Entrada

c_fabrica = float(input("O preço de fábrica do carro: "))

#Processamento

distribuidor = c_fabrica*0.28
imposto = c_fabrica*0.45

p_consumidor = c_fabrica+distribuidor+imposto

#Saída

print("O preço para o consumidor é de R${:.2f}.".format(p_consumidor))

Fabio 01 Parte 02/f1_p2_q18_carro_consumidor.py


def main():
    n = int(input())
    a = input()
    f = [int(x) for x in input().split()]

    max_num = 0
    max_idx = 0
    for i in range(n):
        if int(a[i]) == max(f):
            max_num = max(max_num, int(a[i:]))
            max_idx = i
            break

    for i in range(n - 1, -1, -1):
        if int(a[i]) == max(f):
            max_num = max(max_num, int(a[:i + 1]))

    print(max_num)

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 19:03:30 2017

@author: yml
"""
#用一个数组表示非负整数，+1，需要处理进位

class Solution(object):
#   def plusOne(self, digits):
#       digits = digits[::-1]
#       print(digits)
#
#       digits[0] += 1
#
#       if len(digits) == 1:
#           if digits[0] >= 10:
#               digits[0] = 0
#               digits.append(1)
#           return digits[::-1]
#
#       if digits[0] + 1 > 10:
#           digits[0] = 0
#           digits[1] += 1
#       for i in range(1, len(digits)-1):
#           if digits[i] >= 10:
#               digits[i] = 0
#               digits[i + 1] += 1
#       if digits[len(digits) - 1] >= 10:
#           digits[len(digits) - 1] = 0
#           digits.append(1)
#
#       return digits[::-1]

    def plusOne2(self, digits):
        #beats 3.54%

        plus1 = int(''.join(str(i) for i in digits)) + 1 # 1020 type:int

        seq = []

        for i in str(plus1):
            seq.append(int(i))
        return seq

#        return [int(t) for t in list(str(int(''.join([str(i) for i in digits])) + 1))]

#    def plusOne3(self, digits):
#        carry=1
#        for i in reversed(range(len(digits))):
#            #python3m没有xrange
#            digits[i]+=carry
#            carry=digits[i] / 10
#            digits[i] %= 10
#        if carry:
#            digits = [1] + digits
#        return digits

if __name__ == '__main__':
    digits = [1, 0, 1, 9]
    s = Solution()
    res = s.plusOne2(digits)
    print('*****Result:*****''\n',res)


def recur_fibo(n):
   """Recursive function to
   print Fibonacci sequence"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input("Hasta que numero desea la serie? "))

if nterms <= 0:
   print("El numero ingresado debe ser positivo y mayor a cero.")
else:
   print("Serie de Fibonacci:")
   for i in range(nterms):
       if recur_fibo(i) <= nterms:
           print(recur_fibo(i))
       else:
           break


#!/usr/bin/python3
"""Export to json info of https://jsonplaceholder.typicode.com"""

import csv
import json
import requests
import sys

if __name__ == "__main__":
    employee_username = ''

    dict_user = {}
    array_tasks = []

    page_user = "https://jsonplaceholder.typicode.com/users/{}".format(
        sys.argv[1])

    req_user = requests.get(page_user)
    employee_username = req_user.json()['username']

    page = ("https://jsonplaceholder.typicode.com/todos?userId={}".format
            (sys.argv[1]))
    req = requests.get(page)

    for task in req.json():
        dict_task = {}
        dict_task['task'] = task.get('title')
        dict_task['completed'] = task.get('completed')
        dict_task['username'] = employee_username
        array_tasks.append(dict_task)
    dict_user[str(sys.argv[1])] = array_tasks
    json_object = json.dumps(dict_user)

    with open("{}.json".format(sys.argv[1]), "w") as outfile:
        outfile.write(json_object)


from django.shortcuts import render
from django.shortcuts import render, get_object_or_404

from django.views.generic.list import ListView
from .models import Review
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.views.generic.base import View, TemplateResponseMixin
from django.views.generic.edit import UpdateView, DeleteView
from setup.models import Books, Category, Chapter
from library.library import BookList
from django.db.models import Q
from django.urls import reverse_lazy
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from .forms import ReviewForm
from django.http import JsonResponse, HttpResponse
from django.db import IntegrityError

class HomeV(View, TemplateResponseMixin):
    template_name = 'myview.html'

    def get(self, request, *args, **kwargs):
        library = BookList(request)
        reading_ids = library.read_list.keys()

        chapters_id = [library.read_list[str(book)]['chapter_id'] for book in reading_ids]

        chapter_books = Chapter.objects.filter(id__in=chapters_id)

        new_arrivals = Books.objects.order_by('-publish')[:5]

        # Get that object:

        books_by_popularity = Books.objects.filter(popular=True)
        Featured = Books.objects.filter(Q(genre="action"))[:5]
        our_suggestion = Books.objects.all()[:5]
        stories = Books.objects.filter(bookType="SHORT-STORY")[:5]

        return self.render_to_response({'reading': chapter_books, 'arrival': new_arrivals,
                                         'popular': books_by_popularity, 'featured': Featured, 'suggest':
                                            our_suggestion, "story":stories},
                                       )

class BookDetailView(TemplateResponseMixin, View):
    obj = None
    template_name = 'BookDetail.html'

    def dispatch(self, request, pk, slug):
        self.obj = get_object_or_404(Books,
                                     id=pk,
                                     slug=slug)

        return super(BookDetailView, self).dispatch(request, pk, slug)

    def final_rating(self):
        ratings = Review.objects.filter(book=self.obj)
        num_ratings = ratings.count()
        if num_ratings > 0:
            avg_rating = sum(r.rating for r in ratings) / num_ratings

            return (num_ratings / (num_ratings + 5)) * avg_rating + (5 / (num_ratings + 5)) * 3

    def get(self, *args, **kwargs):
        form = ReviewForm()
        weighted_rating = self.final_rating()
        this_genre = self.obj.genre
        related_books = Books.objects.filter(Q(genre=this_genre)).exclude(id=self.obj.id)

        return self.render_to_response({'review_form': form, 'object': self.obj, "related_books": related_books,
                                        'book_rating': weighted_rating
                                        })

    @method_decorator(login_required)
    def post(self, *args, **kwargs):
        form = ReviewForm(self.request.POST)
        weighted_rating = self.final_rating()
        related_books = Books.objects.all()

        try:

            if form.is_valid():
                new_review = form.save(commit=False)
                new_review.book = self.obj
                new_review.user = self.request.user
                new_review.save()

        except IntegrityError:
            return HttpResponse("You have already review")

        return self.render_to_response({'review_form': form, 'object': self.obj, "related_books": related_books,
                                        'book_rating': weighted_rating})

class Browse(View, TemplateResponseMixin):
    template_name = 'browse.html'

    def get(self, request):
        category = Category.objects.all()
        mystery_books = Books.objects.filter(Q(genre="mystery") | Q(genre="fantasy"))[:5]
        action_books = Books.objects.filter(Q(genre="action"))[:5]
        romance = Books.objects.filter(Q(genre="romance"))[:5]

        return self.render_to_response(
            {'category': category, 'mystery_books': mystery_books, 'action_books': action_books, 'romance': romance})

class Listing(ListView):
    # specify the model for list view
    model = Books
    template_name = 'collection.html'

    def get_queryset(self, *args, **kwargs):
        return super(Listing, self).get_queryset(*args, **kwargs).filter(bookType="NOVEL")

class ListingStory(ListView):
    # specify the model for list view
    model = Books
    template_name = 'story.html'
    context_object_name = 'story'

    def get_queryset(self, *args, **kwargs):
        return super(ListingStory, self).get_queryset(*args, **kwargs).filter(bookType="SHORT-STORY")

class BrowseCategory(View, TemplateResponseMixin):
    template_name = 'BookCategory.html'

    def get(self, request, category_slug):
        books = Category.objects.get(slug=category_slug)
        return self.render_to_response({'books': books})

class ReviewEdit(UpdateView):
    model = Review
    fields = ['rating', 'body']
    template_name = 'ReviewEdit.html'

    def get_success_url(self):
        return reverse_lazy('browse:books_detail',
                            kwargs={'pk': self.get_object().book.id, 'slug': self.get_object().book.slug})

class ReviewDelete(DeleteView):
    model = Review

    def get(self, request, *args, **kwargs):
        return self.delete(request, *args, **kwargs)

    def get_success_url(self):
        return reverse_lazy('browse:books_detail',
                            kwargs={'pk': self.get_object().book.id, 'slug': self.get_object().book.slug})

@require_POST
@login_required
def image_like(request):
    id = request.POST.get('id')
    action = request.POST.get('action')
    if action and id:
        try:
            book = Books.objects.get(id=id)
            if action == 'like':

                book.user_likes.add(request.user)
            else:
                book.user_likes.remove(request.user)
            return JsonResponse({'status': 'ok'})
        except:
            pass

    return JsonResponse({'status': 'ko'})

def search_view(request):
    results = None
    cate = Books.objects.all()[:5]
    search_text = request.GET.get('search_text')

    if search_text:

        results = Books.objects.filter(title__icontains=search_text)

        if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
            html = render_to_string(
                template_name="search_ajax.html",
                context={"results": results}
            )

            data_dict = {"html_from_view": html}

            return JsonResponse(data=data_dict, safe=False)

    return render(request, "search.html", {'cate': cate, 'results': results})


#coding=utf-8
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from article.models import Article
from datetime import datetime
from django.http import Http404
from django.contrib.syndication.views import Feed
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.template import loader,Context
import csv
# Create your views here.

class RSSFeed(Feed):
    title = "RSS Feed"
    link = "/feed/"
    description = "RSS Feed"
    def items(self):
        return Article.objects.order_by('-datetime')

    def item_title(self,item):
        return item.title

    def item_pubdate(self,item):
        return item.datetime

    def item_description(self, item):
        return item.content

def show_request(request):
    request_path = request.path
    request_host = request.get_host()
    request_get_full_path = request.get_full_path()
    request_is_secure = request.is_secure()
    request_dict = {
            'request_path':request_path,
            'request_host':request_host,
            'request_get_full_path':request_get_full_path,
            'request_is_secure':request_is_secure,
            }
    request_meta_items = request.META.items()
    return render(request,'show_request.html',{
            "request_dict":request_dict,
            "request_meta_items":request_meta_items
            })

@csrf_exempt
def login(request):
    username = request.POST.get('username',None)
    if username:
        request.session['username'] = username
        return render(request,'login.html',{'username':username})
    return render(request,'login.html')

@csrf_exempt
def logout(request):
    try:
        del request.session['username']
    except KeyError:
        pass
    return HttpResponseRedirect('/login/')

class GBKHttpResponse(HttpResponse):
    def __init__(self,content=b'',*args,**kwargs):
        super(GBKHttpResponse,self).__init__(content=content,*args,**kwargs)
        self._charset = "GBK"

def output(request,filename):
    address = [(1,2),('三','四'),(1,2)]
    response = GBKHttpResponse(content_type="text/csv")
#    response.encoding = 'gbk'
    response['Content-Disposition'] = 'attachment;filename={0}'.format(filename)
#    writer = csv.writer(response)
#    writer.writerows(address)
    t = loader.get_template('csv.html')
    c = Context({
        'data':address,
        })
    response.write(t.render(c))
    return response

@csrf_exempt
def add(request):
    if request.POST.get('one',None):
        a = int(request.POST['one'])
        b = int(request.POST['two'])
    else:
        a=0
        b=0
    return render(request,'add.html',{'a':a,'b':b,'sum':a+b})

def home(request):
    posts = Article.objects.all()
    paginator = Paginator(posts,3)
    page = request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.paginator(paginator.num_pages)
    return render(request,'home.html',{'post_list':post_list})

def detail(request,id):
    try:
        post = Article.objects.get(id=str(id))
    except Article.DoesNotExist:
        raise Http404
    return render(request,"post.html",{'post':post})

def archive(request):
    try:
        post_list = Article.objects.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request,'archive.html',{'post_list':post_list})

def search_tag(request,tag):
    try:
        post_list=Article.objects.filter(catagory__iexact=tag)
    except Article.DoesNotExist:
        raise Http404
    return render(request,'tag.html',{'post_list':post_list})


from flask import Blueprint, request, session, redirect, url_for, jsonify
from models.db_config import db_pool
import models.message_model as message_model
import models.connect_model as connect_model

message_controller = Blueprint("message", __name__)

#! 這裡為了實現 PRG 的模式，並沒有符合 RESTful API，在新增 api 中包含了 GET 方法
@message_controller.route("/", methods=["POST", "GET"])
def create_message():
    if request.method == "POST":
        content = request.form.get("content")
        # 操控數據庫 添加留言
        data = {
            "id": session["id"],
            "username": session["username"],
            "name": session["name"],
            "content": content,
        }
        connect = connect_model.get_connect(db_pool)
        message_model.create_message(connect["cursor"], data)
        connect_model.connect_close(connect["con"])
        return redirect("/message")
    return redirect(url_for("member.member"))

@message_controller.route("/<int:id>", methods=["DELETE"])
def delete_message(id):
    connect = connect_model.get_connect(db_pool)
    result = message_model.delete_message(connect["cursor"], id)
    connect_model.connect_close(connect["con"])
    if result:
        return jsonify({"message": "Delete successful"}), 200
    return jsonify({"message": "Delete failed"}), 404


# -*- coding: utf-8 -*-
"""
@ Description:
-------------

-------------
@ Time    : 2019/5/21 9:49
@ Author  : Yaoming Cai
@ FileName: GRegConvAE_Base.py
@ Software: PyCharm
@ Blog    ：https://github.com/AngryCai
@ Email   : caiyaomxc@outlook.com
"""
import os
import sys

from munkres import Munkres
from scipy.sparse import csgraph
from scipy.sparse.linalg import svds
from sklearn import cluster
from sklearn.metrics import pairwise_kernels
from sklearn.neighbors import kneighbors_graph
from sklearn.preprocessing import normalize
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.metrics.classification import cohen_kappa_score, accuracy_score

sys.path.append('/home/caiyaom/python_codes/')
import numpy as np
import tensorflow as tf

class GRegConvAE:

    def __init__(self, epoch, n_cluster, image_name, lr=0.01, reg_lap=1., reg_latent=1., weight_decay=0.,
                 verb_per_iter=None, random_state=None):
        """
        :param epoch: the maximum iteration for updating parameters
        :param n_cluster: the number of clusters
        :param image_name: HSI data name, see demo.py
        :param lr: learning rate (float)
        :param reg_lap: laplasian regularization coefficient
        :param reg_latent: self-expression term regularization coefficient
        :param weight_decay: self-expression coef. regularization coefficient (L2 reg.)
        :param verb_per_iter: print clustering accuracy after n iterations (default None means print nothing)
        :param random_state: graph-level random seed (default is None)
        """
        tf.reset_default_graph()
        self.epoch = epoch
        self.reg_lap = reg_lap
        self.image_name = image_name
        self.reg_latent = reg_latent
        self.weight_decay = weight_decay
        self.n_cluster = n_cluster
        self.lr = lr
        self.verb_per_iter = verb_per_iter
        if random_state is not None:
            tf.set_random_seed(random_state)
        if not os.path.exists(self.image_name):
            os.mkdir(self.image_name)
        self.model_root_dir = self.image_name
        self.model_path = self.model_root_dir + '/' + self.image_name + '-model'

    def net(self, x, n_batch, is_training):
        # X = tf.layers.batch_normalization(X, training=is_training)

        # ============ encoder =================
        embed_1, embed_2, code = self.encoder(x, is_training, 'encoder', reuse=tf.AUTO_REUSE)

        # ============ self expression =============
        Z, Z_hat, C, latent_z = self.self_expression(code, n_batch, 'self-expression', reuse=tf.AUTO_REUSE)

        # ============ encoder =================
        decode = self.decoder(latent_z, [embed_1, embed_2, code], x.get_shape().as_list()[-1], is_training, 'decoder', reuse=tf.AUTO_REUSE)

        return code, decode, Z, Z_hat, C

    def self_expression(self, x, n_batch, name, reuse):
        with tf.variable_scope(name, reuse=reuse):
            Z = tf.layers.flatten(x)  # tf.reshape(X, (tf.shape(X)[0], -1))
            C = tf.Variable(1.0e-8 * tf.ones([n_batch, n_batch], tf.float32), name='Coef')
            Z_hat = tf.matmul(C, Z)
            latent_z = tf.reshape(Z_hat, tf.shape(x))
        return Z, Z_hat, C, latent_z

    def encoder(self, x, is_training, name, reuse):
        with tf.variable_scope(name, reuse=reuse):
            """========= Conv 1 ============"""
            hidden = tf.layers.conv2d(x, 24, (3, 3), strides=(1, 1), padding='same',
                                      kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                      bias_initializer=tf.initializers.zeros())
            embed_1 = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))

            """========= Conv 2 ============"""
            hidden = tf.layers.conv2d(embed_1, 24, (3, 3), strides=(1, 1), padding='same',
                                      kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                      bias_initializer=tf.initializers.zeros())
            embed_2 = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))

            """========= Conv 3 ============"""
            hidden = tf.layers.conv2d(embed_2, 32, (3, 3), strides=(1, 1), padding='same',
                                      kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                      bias_initializer=tf.initializers.zeros())
            code = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))
        return embed_1, embed_2, code

    def decoder(self, latent_z, x, out_channel, is_training, name, reuse):
        with tf.variable_scope(name, reuse=reuse):
            """========= Conv 1 ============"""
            hidden = tf.layers.conv2d_transpose(latent_z, 32, (3, 3), strides=(1, 1), padding='same',
                                                kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                                bias_initializer=tf.initializers.zeros())
            embed_1 = tf.layers.batch_normalization(hidden, training=is_training)
            res_1 = tf.nn.relu(tf.add(x[2], embed_1))
            # embed_1 = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))
            # concat_1 = tf.concat([X[0], embed_1], axis=4)

            """========= Conv 2 ============"""
            hidden = tf.layers.conv2d_transpose(res_1, 24, (3, 3), strides=(1, 1), padding='same',
                                                kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                                bias_initializer=tf.initializers.zeros())
            embed_2 = tf.layers.batch_normalization(hidden, training=is_training)
            res_2 = tf.nn.relu(tf.add(x[1], embed_2))
            # embed_2 = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))
            # concat_2 = tf.concat([X[1], embed_2], axis=4)

            """========= Conv 3 ============"""
            hidden = tf.layers.conv2d_transpose(res_2, 24, (3, 3), strides=(1, 1), padding='same',
                                                kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                                bias_initializer=tf.initializers.zeros())
            embed_3 = tf.layers.batch_normalization(hidden, training=is_training)
            res_3 = tf.nn.relu(tf.add(x[0], embed_3))
            # embed_3 = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))
            # concat_3 = tf.concat([X[2], embed_3], axis=4)

            """========= Conv output ============"""
            decode = tf.layers.conv2d(res_3, out_channel, (1, 1), strides=(1, 1), padding='same',
                                      kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),
                                      bias_initializer=tf.initializers.zeros())
            # decode = tf.nn.relu(tf.layers.batch_normalization(hidden, training=is_training))
        return decode

    def __loss(self, x_true, x_predict, z, z_hat, C, L):
        """
        compute loss
        :param x_true: training labels
        :param x_predict: all samples' prediction
        :param C: adjacent matrix
        :return:
        """
        # =========== model reconstruction loss ==============
        loss_recon = tf.reduce_mean(tf.losses.mean_squared_error(x_true, x_predict))
        tf.summary.scalar('loss-recon', loss_recon)

        # =========== coefficient L2 loss ==============
        loss_l2 = tf.nn.l2_loss(C)
        tf.summary.scalar('loss-l2', loss_l2)

        # =========== latent reconstruction loss ==============
        loss_recon_latent = tf.reduce_mean(tf.losses.mean_squared_error(z, z_hat))
        tf.summary.scalar('loss-latent', loss_recon_latent)

        # =========== laplacian loss ==============
        loss_lap = tf.trace(
            tf.matmul(tf.matmul(tf.transpose(C), tf.constant(L, dtype=tf.float32)), C))
        # loss_lap = tf.trace(
        #     tf.matmul(tf.matmul(tf.transpose(z), tf.constant(L, dtype=tf.float32)), z))
        tf.summary.scalar('loss-lap', loss_lap)

        loss = loss_recon + self.reg_lap * loss_lap + self.reg_latent * loss_recon_latent + self.weight_decay * loss_l2
        tf.summary.scalar('loss-total', loss)
        return loss

    def lap_matrix(self, x):
        # A = kneighbors_graph(X.reshape(X.shape[0], -1), n_neighbors=10, include_self=True, n_jobs=3).toarray()
        # A_ = kneighbors_graph(X.reshape(X.shape[0], -1), n_neighbors=5, include_self=True, n_jobs=8).toarray()
        # A_ = 0.5 * (A_ + A_.T)
        A_ = pairwise_kernels(x.reshape(x.shape[0], -1), metric='rbf', gamma=1., n_jobs=8)
        A = 0.5 * (A_ + A_.T)
        # A_[np.nonzero(A_)] = A[np.nonzero(A_)]
        L = csgraph.laplacian(A, normed=True)
        return L

    def __init_net__(self, X):
        x_placeholder = tf.placeholder(tf.float32, shape=(None, X.shape[1], X.shape[2], X.shape[3]))
        is_training = tf.placeholder(tf.bool)
        n_batch = X.shape[0]
        code, decode, Z, Z_hat, C = self.net(x_placeholder, n_batch, is_training)
        L = self.lap_matrix(X)
        loss_p = self.__loss(x_placeholder, decode, Z, Z_hat, C, L)
        tf.summary.histogram('C', C)
        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        with tf.control_dependencies(update_ops):
            train_op = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(loss_p)
        sess = tf.InteractiveSession()
        sess.run(tf.global_variables_initializer())
        self.train_op = train_op
        self.C = C
        self.x_placeholder = x_placeholder
        self.is_training = is_training
        self.prediction_p = decode
        self.loss_p = loss_p
        self.sess = sess

    def fit(self, X, y):
        self.__init_net__(X)
        merged = tf.summary.merge_all()
        writer = tf.summary.FileWriter(self.model_root_dir + '/logs', self.sess.graph)
        saver = tf.train.Saver()
        loss_his = []
        acc_his = {'oa':[], 'nmi':[], 'kappa':[], 'ca':[]} #[]
        for step_i in range(self.epoch):
            train_feed_dict = {self.x_placeholder: X, self.is_training: True}
            _, loss, summary = self.sess.run([self.train_op, self.loss_p, merged], feed_dict=train_feed_dict)
            print('epoch %s ==> loss=%s' % (step_i, loss))
            loss_his.append(loss)
            writer.add_summary(summary, step_i)
            # =============== test ==================
            # loss_eval, C_eval = self.sess.run([loss_p, C], feed_dict={self.x_placeholder: X, self.is_training: False})
            # # print logs after self.verb_per_iter iterations
            if self.verb_per_iter is not None and (step_i + 1) % self.verb_per_iter == 0:
                loss_test, y_pre = self.predict(X)
                acc, nmi, kappa, ca = self.cluster_accuracy(y, y_pre)
                print('epoch %s ==> loss=%s, acc=%s' % (step_i, loss_test, (acc, nmi, kappa, ca)))
                acc_his['oa'].append(acc)
                acc_his['nmi'].append(nmi)
                acc_his['kappa'].append(kappa)
                acc_his['ca'].append(ca)
                saver.save(self.sess, self.model_path, write_meta_graph=False)
        np.savez(self.model_root_dir + '/history.npz', loss=loss_his, acc=acc_his)
        saver.save(self.sess, self.model_path)
        if self.verb_per_iter is not None:
            return acc_his

    def predict(self, X, alpha=0.25):
        loss, Coef = self.sess.run([self.loss_p, self.C], feed_dict={self.x_placeholder: X, self.is_training: False})
        Coef = self.thrC(Coef, alpha)
        y_pre, C = self.post_proC(Coef, self.n_cluster, 8, 18)
        np.savez(self.model_root_dir + '/Affinity.npz', coef=C)
        np.savez(self.model_root_dir + '/y_pre.npz', y_pre=y_pre)
        # missrate_x = self.err_rate(y, y_x)
        # acc = 1 - missrate_x
        return loss, y_pre

    def predict_from_model(self, X, y):
        if not os.path.exists(self.model_root_dir + '/checkpoint'):
            raise Exception('model cannot be found !')
        else:
            self.__init_net__(X)
            # saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta')
            saver = tf.train.Saver()
            saver.restore(self.sess, self.model_path)
            Coef = self.sess.run(self.C, feed_dict={self.x_placeholder: X, self.is_training: False})
            Coef = self.thrC(Coef, 0.25)
            y_pre, C = self.post_proC(Coef, self.n_cluster, 8, 18)
            np.savez(self.model_root_dir + '/Affinity.npz', coef=C)
            acc = self.cluster_accuracy(y, y_pre)
            return y_pre, acc

    def thrC(self, C, ro):
        if ro < 1:
            N = C.shape[1]
            Cp = np.zeros((N, N))
            S = np.abs(np.sort(-np.abs(C), axis=0))
            Ind = np.argsort(-np.abs(C), axis=0)
            for i in range(N):
                cL1 = np.sum(S[:, i]).astype(float)
                stop = False
                csum = 0
                t = 0
                while (stop == False):
                    csum = csum + S[t, i]
                    if csum > ro * cL1:
                        stop = True
                        Cp[Ind[0:t + 1, i], i] = C[Ind[0:t + 1, i], i]
                    t = t + 1
        else:
            Cp = C
        return Cp

    def build_aff(self, C):
        N = C.shape[0]
        Cabs = np.abs(C)
        ind = np.argsort(-Cabs, 0)
        for i in range(N):
            Cabs[:, i] = Cabs[:, i] / (Cabs[ind[0, i], i] + 1e-6)
        Cksym = Cabs + Cabs.T
        return Cksym

    def post_proC(self, C, K, d, alpha):
        # C: coefficient matrix, K: number of clusters, d: dimension of each subspace
        C = 0.5 * (C + C.T)
        r = d * K + 1
        U, S, _ = svds(C, r, v0=np.ones(C.shape[0]))
        U = U[:, ::-1]
        S = np.sqrt(S[::-1])
        S = np.diag(S)
        U = U.dot(S)
        U = normalize(U, norm='l2', axis=1)
        Z = U.dot(U.T)
        Z = Z * (Z > 0)
        L = np.abs(Z ** alpha)
        L = L / L.max()
        L = 0.5 * (L + L.T)
        spectral = cluster.SpectralClustering(n_clusters=K, eigen_solver='arpack', affinity='precomputed',
                                              assign_labels='discretize')
        spectral.fit(L)
        grp = spectral.fit_predict(L) + 1
        return grp, L

    def cluster_accuracy(self, y_true, y_pre):
        Label1 = np.unique(y_true)
        nClass1 = len(Label1)
        Label2 = np.unique(y_pre)
        nClass2 = len(Label2)
        nClass = np.maximum(nClass1, nClass2)
        G = np.zeros((nClass, nClass))
        for i in range(nClass1):
            ind_cla1 = y_true == Label1[i]
            ind_cla1 = ind_cla1.astype(float)
            for j in range(nClass2):
                ind_cla2 = y_pre == Label2[j]
                ind_cla2 = ind_cla2.astype(float)
                G[i, j] = np.sum(ind_cla2 * ind_cla1)
        m = Munkres()
        index = m.compute(-G.T)
        index = np.array(index)
        c = index[:, 1]
        y_best = np.zeros(y_pre.shape)
        for i in range(nClass2):
            y_best[y_pre == Label2[i]] = Label1[c[i]]

        # # calculate accuracy
        err_x = np.sum(y_true[:] != y_best[:])
        missrate = err_x.astype(float) / (y_true.shape[0])
        acc = 1. - missrate
        nmi = normalized_mutual_info_score(y_true, y_pre)
        kappa = cohen_kappa_score(y_true, y_best)
        ca = self.class_acc(y_true, y_best)
        return acc, nmi, kappa, ca

    def class_acc(self, y_true, y_pre):
        """
        calculate each classes's acc
        :param y_true:
        :param y_pre:
        :return:
        """
        ca = []
        for c in np.unique(y_true):
            y_c = y_true[np.nonzero(y_true == c)]  # find indices of each classes
            y_c_p = y_pre[np.nonzero(y_true == c)]
            acurracy = accuracy_score(y_c, y_c_p)
            ca.append(acurracy)
        ca = np.array(ca)
        return ca

    @staticmethod
    def build_laplacian(C):
        C = 0.5 * (np.abs(C) + np.abs(C.T))
        W = np.sum(C, axis=0)
        W = np.diag(1.0 / W)
        L = W.dot(C)
        return L


import argparse
import difflib
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile

SUPPORTED_TYPES = ['kernel_cmdline', 'bootfs_filelist', 'static_pkgs']

SOFT_TRANSITION_MESSAGE_TEMPLATE = """
If you are making a change in fuchsia repo that causes this you need a soft transition by:
1: copy the old golden file to *.orig.
2: update the original golden file to a new golden file as suggested above.
3: modify the product configuration GNI file where `{0}` or `{1}` is defined to contain both the old golden file and the new golden file.
4: check in your fuchsia change.
5: remove the original golden file and remove the entry from `{0}` or `{1}`.
"""

def print_error(msg):
    print(msg, file=sys.stderr)

def main(input_args):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--zbi-file', help='Path to the zbi to verify', required=True)
    parser.add_argument(
        '--blobfs-manifest',
        help='Path to blobfs manifest file, required for "static_pkgs"',
        required=False)
    parser.add_argument(
        '--scrutiny',
        help='Path to the scrutiny tool used for verifying kernel cmdline',
        required=True)
    parser.add_argument(
        '--far',
        help=(
            'Path to the far tool used for extracting package, ' +
            'required for "static_pkgs"'),
        required=False)
    parser.add_argument(
        '--golden-files',
        help=(
            'Path to one of the possible golden files to check against, ' +
            'there should only be one golden file in normal case, and only ' +
            'two golden files, one old file and one new file during a soft ' +
            'transition. After the transition, the old golden file should ' +
            'be removed and only leave the new golden file.'),
        nargs='+',
        required=True)
    parser.add_argument(
        '--stamp', help='Path to the victory file', required=True)
    parser.add_argument(
        '--type',
        help=('The type of the ZBI item to verify'),
        choices=SUPPORTED_TYPES,
        required=True)
    parser.add_argument(
        '--depfile',
        help=(
            'Optional generated depfile listing dynamic deps for the script' +
            ', required for "static_pkgs"'),
        required=False)
    args = parser.parse_args(input_args)

    if len(args.golden_files) > 2:
        print_error(
            'At most two optional golden files are supported, ' +
            'is there a soft transition already in place? Please wait for ' +
            'that to finish before starting a new one.')
    try:
        verify_build(args)
    except VerificationError as e:
        print_error(str(e))
        return 1

    with open(args.stamp, 'w') as stamp_file:
        stamp_file.write('Golden!\n')
    return 0

def verify_build(args):
    """verify_build verifies a build against specified golden files.

    Raises:
        VerificationError: If verification fails.
    """
    # Check for some necessary files/dirs exist first.
    for file in [args.scrutiny, args.zbi_file]:
        if not os.path.exists(file):
            raise VerificationError('Missing required file: ' + file)

    with tempfile.TemporaryDirectory() as tmp:
        run_scrutiny_command(
            args.scrutiny, ' '.join(
                [
                    'tool.zbi.extract', '--input',
                    shlex.quote(args.zbi_file), '--output',
                    shlex.quote(tmp)
                ]))

        last_error = None
        for golden_file in args.golden_files:
            try:
                if args.type == 'kernel_cmdline':
                    verify_kernel_cmdline(golden_file, tmp)
                elif args.type == 'bootfs_filelist':
                    verify_bootfs_filelist(golden_file, tmp)
                elif args.type == 'static_pkgs':
                    verify_static_pkgs(args, golden_file, tmp)
                # Passes the verification, no error thrown.
                return
            except VerificationError as e:
                # Error thrown, we want to record this error and check next
                # golden_file.
                last_error = e

        raise last_error

def verify_kernel_cmdline(kernel_cmdline_golden_file, scrutiny_out):
    """verify_kernel_cmdline verifies the kernel cmdline in ZBI image.

    Raises:
        VerificationError: If verification fails.
    """
    try:
        with open(kernel_cmdline_golden_file, 'r') as f:
            golden_file_content = f.read().strip()
    except IOError as e:
        raise VerificationError(f'Failed to open golden file: {e}')
    if not os.path.exists(os.path.join(scrutiny_out, 'sections',
                                       'cmdline.blk')):
        # We find no kernel cmdline. Check whether the golden file is empty.
        if not golden_file_content:
            # Golden file is empty. Pass the check.
            return
        else:
            error_msg = (
                'Found no kernel cmdline in ZBI\n' +
                'Please update kernel cmdline golden file at ' +
                kernel_cmdline_golden_file + ' to be an empty file')
            raise VerificationError(error_msg)
    try:
        with open(os.path.join(scrutiny_out, 'sections', 'cmdline.blk'),
                  'r') as f:
            # The cmdline.blk contains a trailing \x00.
            cmdline = f.read().strip().rstrip('\x00')
    except IOError as e:
        raise VerificationError(f'Failed to read cmdline.blk: {e}')

    try:
        compare_cmdline(
            cmdline, golden_file_content, kernel_cmdline_golden_file)
    except CmdlineFormatError as e:
        raise VerificationError(f'Invalid cmdline format: {e}')
    return

def verify_bootfs_filelist(bootfs_filelist_golden_file, scrutiny_out):
    """verify_bootfs_filelist verifies the bootFS filelist in ZBI image.

    Raises:
      VerificationError: If verification fails.
    """
    try:
        with open(bootfs_filelist_golden_file, 'r') as f:
            golden_file_content = f.read().strip()
    except IOError as e:
        raise VerificationError(f'Failed to read golden file: {e}')
    bootfs_folder = os.path.join(scrutiny_out, 'bootfs')
    bootfs_files = []
    try:
        for root, _, files in os.walk(bootfs_folder):
            for file in files:
                bootfs_files.append(
                    os.path.relpath(os.path.join(root, file), bootfs_folder))
    except IOError as e:
        raise VerificationError(f'Failed to walk bootfs folder: {e}')
    got_content = '\n'.join(sorted(bootfs_files))

    if golden_file_content == got_content:
        return
    error_msgs = ['BootFS file list mismatch!']
    error_msgs.append(
        'Please update bootFS file list golden file at ' +
        bootfs_filelist_golden_file + ' to:')
    error_msgs.append('```')
    error_msgs.append(got_content)
    error_msgs.append('```')
    error_msgs.append('')
    error_msgs.append('Diff:')
    error_msgs.extend(
        difflib.context_diff(
            golden_file_content.splitlines(keepends=True),
            got_content.splitlines(keepends=True),
            fromfile='want',
            tofile='got'))
    error_msgs.append(
        SOFT_TRANSITION_MESSAGE_TEMPLATE.format(
            'fuchsia_zbi_bootfs_filelist_goldens',
            'recovery_zbi_bootfs_filelist_goldens'))
    raise VerificationError('\n'.join(error_msgs))

def verify_static_pkgs(
    args,
    golden_file,
    scrutiny_out,
):
    """verify_static_pkgs verifies static packages list.

    Raises:
      VerificationError: If verification fails.
    """
    deps = []
    if not args.blobfs_manifest:
        raise VerificationError(
            '"blobfs-manifest" must be specified for "static_pkgs" check')
    if not args.far:
        raise VerificationError(
            '"far" must be specified for "static_pkgs" check')
    if not args.depfile:
        raise VerificationError(
            '"depfile" must be specified for "static_pkgs" check')
    try:
        system_image_hash = get_system_image_hash(scrutiny_out)
    except IOError as e:
        raise VerificationError(f'Failed to get devmgr config: {e}')
    except KeyError as e:
        raise VerificationError(f'Invalid devmgr config: {e}')

    try:
        blob_manifest = parse_key_value_file(args.blobfs_manifest)
    except IOError as e:
        raise VerificationError(f'Failed to open blob manifest: {e}')

    try:
        system_image_blob = os.path.join(
            os.path.dirname(args.blobfs_manifest),
            blob_manifest[system_image_hash])
        # Add system_image_blob as dynamic dependency.
        deps.append(system_image_blob)
    except KeyError as e:
        raise VerificationError(f'System image blob not found: {e}')
    system_image_folder = os.path.join(scrutiny_out, 'system_image')
    try:
        extract_package(args.far, system_image_blob, system_image_folder)
    except subprocess.CalledProcessError as e:
        raise VerificationError(
            f'Failed to extract system_image package: {e.stderr}')

    try:
        static_packages_hash = parse_key_value_file(
            os.path.join(system_image_folder, 'meta',
                         'contents'))['data/static_packages']
    except KeyError:
        raise VerificationError(
            'No "data/static_packages" found in "system_image"')
    except IOError as e:
        raise VerificationError(
            f'Failed to read system_image/meta/contents file: {e}')
    try:
        static_packages_blob = os.path.join(
            os.path.dirname(args.blobfs_manifest),
            blob_manifest[static_packages_hash])

        # Add static_packages_blob as dynamic dependency.
        deps.append(static_packages_blob)
    except KeyError as e:
        raise VerificationError(f'Static pkgs blob not found: {e}')
    try:
        with open(static_packages_blob, 'r') as f:
            static_packages_content = f.read().strip()
    except IOError as e:
        raise VerificationError(f'Failed to read static packages blob: {e}')

    # Write depfile.
    try:
        with open(args.depfile, 'w') as f:
            f.write(args.stamp + ': ' + ' '.join(deps) + '\n')
    except IOError as e:
        raise VerificationError(f'Failed to write depfile: {e}')

    pkgs = []
    for pkg in static_packages_content.splitlines():
        pkgs.append(re.split(r'/[0-9]=', pkg)[0])
    got_content = '\n'.join(sorted(pkgs))

    try:
        with open(golden_file, 'r') as f:
            golden_file_content = f.read().strip()
    except IOError as e:
        raise VerificationError(f'Failed to read golden file: {e}')

    if golden_file_content == got_content:
        return
    error_msgs = ['Static packages list mismatch!']
    error_msgs.append(
        'Please update static packages list golden file at ' + golden_file +
        ' to:')
    error_msgs.append('```')
    error_msgs.append(got_content)
    error_msgs.append('```')
    error_msgs.append('')
    error_msgs.append('Diff:')
    error_msgs.extend(
        difflib.context_diff(
            golden_file_content.splitlines(keepends=True),
            got_content.splitlines(keepends=True),
            fromfile='want',
            tofile='got'))
    error_msgs.append(
        SOFT_TRANSITION_MESSAGE_TEMPLATE.format(
            'fuchsia_static_pkgs_goldens', 'recovery_static_pkgs_goldens'))
    raise VerificationError('\n'.join(error_msgs))

def get_system_image_hash(scrutiny_out):
    """Get the system image merkle root.

    Args:
        scrutiny_out: the scrutiny output directory.

    Raises:
        IOError: If fails to read devmgr config.
        KeyError: If the config entry for system image hash is not found.
    """
    devmgr_config_file = os.path.join(
        scrutiny_out, 'bootfs', 'config', 'devmgr')
    key_value_map = parse_key_value_file(devmgr_config_file)
    return key_value_map['zircon.system.pkgfs.cmd'].replace('bin/pkgsvr+', '')

def run_scrutiny_command(scrutiny_path, command):
    """Runs scrutiny command.

    Args:
        scrutiny_path: The path to the scrutiny tool.
        command: The scrutiny command to run.

    Raises:
        VerificationError: If the command fails or the output is not
            '{"status":"ok"}'.
    """
    try:
        output = subprocess.run(
            [scrutiny_path, '-c', command], capture_output=True,
            check=True).stdout
    except subprocess.CalledProcessError as e:
        raise VerificationError(f'Failed to run scrutiny: {e.stederr}')

    try:
        if json.loads(output)['status'] != 'ok':
            raise VerificationError(f'Unexpected scrutiny output: {output}')
    except (KeyError, json.JSONDecodeError) as e:
        raise VerificationError(f'Unexpected scrutiny output: {e}')

def extract_package(far_path, package_path, output_dir):
    """Extract a package from a blob using "fx far extract".

    Args:
        far_path: The path to far tool.
        package_path: The path to the package blob file.
        output_dir: The output directory to put the extracted package.

    Raises:
        subprocess.CalledProcessError: If failed to extract.
    """
    subprocess.run(
        [
            far_path, 'extract', '--archive=' + package_path,
            '--output=' + output_dir
        ],
        capture_output=True,
        check=True)

class CmdlineFormatError(Exception):
    """Exception thrown when kernel cmdline is in invalid format."""

    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return self.msg

class VerificationError(Exception):
    """Exception thrown when verification fails."""

    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return self.msg

def compare_cmdline(actual_cmdline, golden_cmdline, golden_file):
    """compare_cmdline compares the actual cmdline with the golden cmdline.

    Raises:
      CmdlineFormatError: If the kernel cmdline is not formatted correctly.
    """
    golden_cmd = generate_sorted_cmdline(golden_cmdline, '\n')
    actual_cmd = generate_sorted_cmdline(actual_cmdline, ' ')
    if golden_cmd == actual_cmd:
        return
    error_msgs = ['Kernel cmdline mismatch!']
    error_msgs.append(
        'Please update kernel cmdline golden file at ' + golden_file + ' to:')
    error_msgs.append('```')
    error_msgs.append(actual_cmd)
    error_msgs.append('```')
    error_msgs.append('')
    error_msgs.append('Diff:')
    error_msgs.extend(
        difflib.context_diff(
            golden_cmd.splitlines(keepends=True),
            actual_cmd.splitlines(keepends=True),
            fromfile='want',
            tofile='got'))
    error_msgs.append(
        SOFT_TRANSITION_MESSAGE_TEMPLATE.format(
            'fuchsia_zbi_kernel_cmdline_goldens',
            'recovery_zbi_kernel_cmdline_goldens'))
    raise VerificationError('\n'.join(error_msgs))

def generate_sorted_cmdline(cmdline, splitter):
    """generate_sorted_cmdline generates a kernel cmdline sorted by entry keys.

    Raises:
      CmdlineFormatError: If the kernel cmdline is not formatted correctly.
    """
    cmdline_entries = {}
    entries = cmdline.split(splitter)
    for entry in entries:
        if len(entry.split('=')) > 2:
            raise CmdlineFormatError(
                'invalid kernel cmdline, key value pair: ' + entry)
        key, _, value = entry.partition('=')
        if key in cmdline_entries:
            raise CmdlineFormatError('duplicate kernel cmdline key: ' + key)
        cmdline_entries[key] = value

    return '\n'.join(
        ('%s=%s' % (key, value)) if value else key
        for key, value in sorted(cmdline_entries.items()))

def parse_key_value_file(file_path):
    """Parses a file in 'key=value' format.

  Args:
    file_path: The path to the file.

  Returns:
    A {key:value} map

  Raises:
    IOError: if failed to read the file.
  """
    with open(file_path, 'r') as f:
        content = f.read()
    key_value_map = {}
    for line in content.splitlines():
        split_array = line.split('=')
        if len(split_array) == 2:
            key_value_map[split_array[0]] = split_array[1]
    return key_value_map

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


from django.shortcuts import render, request
from models import *

def get_new_role_data(request):
    if request.session['failed_role_creation']:
       request.session.pop['failed_role_creation']
    else:
        request.session.pop['errors']
    return ("template")

def create_new_role(request):
    response_from_model = RoleManager.create_new_role(request)
    # Successful creation
    if response_from_model['status']:
        request.sessions['status'] = True
        request.sessions['new_role_added'] = response_from_model['new_role']
        if request.session['errors']:
            request.session.pop['errors']
        return ("template")
    else:
        request.session['status'] = False
        request.session['errors'] = response_from_model['error_list']
        request.session['failed_role_creation'] = True
        return get_new_role_data(request)


# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.

# This program is free software; you can redistribute it and/or modify it under
# the terms of the MIT license.

# 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 MIT License for more details.

"""
Bayesian optimisation collaborated with NJU
"""

import numpy as np
import pandas as pd
import torch

from hebo.design_space import DesignSpace
from hebo.acquisitions.acq import SingleObjectiveAcq
from .abstract_optimizer import AbstractOptimizer
from .bo import BO
from .hebo import HEBO

class AbsEtaDifference(SingleObjectiveAcq):
    def __init__(self, model, kappa=3.0, eta=0.7, **conf):
        super().__init__(model, **conf)
        self.kappa = kappa
        self.eta = eta
        assert model.num_out == 1

    def eval(self, x: torch.FloatTensor, xe: torch.LongTensor) -> torch.FloatTensor:
        py, ps2 = self.model.predict(x, xe)
        return torch.abs(py-self.eta) - self.kappa * ps2.sqrt()

class NoMR_BO(AbstractOptimizer):
    support_parallel_opt  = False
    support_combinatorial = True
    support_contextual    = False

    def __init__(self,
            space : DesignSpace,
            eta   : float = None,
            opt1  : AbstractOptimizer = None,
            opt2  : AbstractOptimizer = None
            ):
        super().__init__(space)
        self.eta  = eta
        self.opt1 = opt1
        self.opt2 = opt2

        if self.eta is None:
            self.eta = np.inf # prior optimu

        if self.opt1 is None:
            # NOTE: optimizer for stage one, vallina BO
            self.opt1 = HEBO(space)

        if  self.opt2 is None:
            # NOTE: optimizer for stage two, focus more on exploitation
            self.opt2 = BO(space, acq_conf = {'kappa' : 0.6})

    def observe(self, x : pd.DataFrame, y : np.ndarray):
        self.opt1.observe(x, y)
        self.opt2.observe(x, y)

    def suggest(self, n_suggestions = 1, fix_input : dict = None):
        assert n_suggestions == 1
        if self.opt1.y is None or self.opt1.y.shape[0] == 0 or self.opt1.y.min() > self.eta:
            return self.opt1.suggest(n_suggestions, fix_input)
        return self.opt2.suggest(n_suggestions, fix_input)

    @property
    def best_x(self) -> pd.DataFrame:
        return self.opt1.best_x if self.opt1.best_y < self.opt2.best_y else self.opt2.best_x

    @property
    def best_y(self) -> float:
        return self.opt1.best_y if self.opt1.best_y < self.opt2.best_y else self.opt2.best_y


# -*- coding: utf-8 -*-
"""
@author: Dinesh
"""

import rasterio
import pandas as pd
import numpy as np
from rasterio import plot
import matplotlib.pyplot as plt

def return_indices(raster):
    np.seterr(divide='ignore', invalid='ignore')
    blue, green, red = raster[0], raster[1], raster[2]
    vre5, vre6, vre7 = raster[3], raster[4], raster[5]
    nir, vre8a, swir11, swir12 = raster[6], raster[7], raster[8], raster[9]

    # Initialize indices
    ndvi = np.empty(blue.shape, dtype=rasterio.float32)
    mndwi = np.empty(blue.shape, dtype=rasterio.float32)
    ndbi = np.empty(blue.shape, dtype=rasterio.float32)

    # Checks
    check_mndwi = np.logical_or(swir11 > 0, red > 0)
    check_ndvi = np.logical_or(red > 0, nir > 0)
    check_ndbi = np.logical_or(swir11 > 0, nir > 0)

    # Calc indices
    ndvi = np.where(check_ndvi, (nir - red) / (nir + red), 0)
    mndwi = np.where(check_mndwi, (red - swir11) / (red + swir11), 0)
    ndbi = np.where(check_ndbi, (swir11 - nir) / (swir11 + nir), 0)

    # Normalize
    # mndwi = (mndwi - mndwi.min()) / (mndwi.max() - mndwi.min())
    # ndvi = (ndvi - ndvi.min()) / (ndvi.max() - ndvi.min())
    # ndbi = (ndbi - ndbi.min()) / (ndbi.max() - ndbi.min())
    return ndvi, mndwi, ndbi