from TexasHoldemConstants import *
from TexasHoldemDeck import *
from Player import *
from TexasHoldemComparisonEngine import *
from random import randint
import time

import pymongo
from bson.objectid import ObjectId

class TexasHoldem:
    def __init__(self,
            humans=0,
            bots=2,
            ante=0,
            buyIn=None,
            minimumFirstBet=10,
            statisticsMode=False,
            clearDB=False,
            pymongoClientHost="localhost",
            pymongoClientPort=27017,
            autoStart=True,
            verbose=False,
            debug=False,
            showBotCards=False,
            readable=False,
            readTime=3
        ):

        if(buyIn is None):
            buyIn = 500

        self.Verbose = verbose
        self.Debug = debug
        self.ShowBotCards = (self.Verbose and showBotCards)
        self.Readable = readable
        self.ReadTime = readTime
        self.PlayerCount = humans + bots
        self.Humans = humans
        self.Bots = bots
        self.BUY_IN = buyIn
        self.MINIMUM_FIRST_BET = minimumFirstBet
        self.Deck = TexasHoldemDeck()
        self.FlopCards = []
        self.TurnCard = None
        self.RiverCard = None
        self.CommunityCards = []
        self.Pot = 0
        self.Rounds = 0
        self.Comparison = TexasHoldemComparisonEngine()
        self.StatisticsMode = statisticsMode
        self.PymongoClientHost = pymongoClientHost
        self.PymongoClientPort = pymongoClientPort
        self.PymongoClient = pymongo.MongoClient(self.PymongoClientHost, self.PymongoClientPort)
        self.PymongoDB = self.PymongoClient.texasholdem
        self.GameId = None
        self.RoundId = None
        self.HumansInRound = 0
        self.FirstBetMade = False
        self.MinimumBet = 0

        if self.Debug:
            self.Verbose = True

        if clearDB:
            self.PymongoDB.hands.drop()
            self.PymongoDB.winning_hands.drop()
            self.PymongoDB.split_hands.drop()
            self.PymongoDB.losing_hands.drop()
            self.PymongoDB.games.drop()
            self.PymongoDB.rounds.drop()

        if(autoStart):
            self.NewGame()

    def CanShowCards(self, player):
        if self.HumansInRound <= 0:
            return True

        if player.IsHuman():
            return True

        if player.IsBot() and self.ShowBotCards:
            return True

        if self.RoundSection == SHOWDOWN:
            return True

        return False

    def __str__(self):
        s = "\nGame Status: \n"

        if(len(self.FlopCards) > 0):
            s += "Flop: "
            for c in range(len(self.FlopCards)):
                card = self.FlopCards[c]
                s += str(card)
                if(not c == len(self.FlopCards)-1):
                    s += ', '
            s += "\n"

        if(self.TurnCard is not None):
            s += "Turn: " + str(self.TurnCard) + "\n"

        if(self.RiverCard is not None):
            s += 'River: ' + str(self.RiverCard) + "\n"

        if(len(self.Players) > 0):
            s += '\n'
            for p in range(len(self.Players)):
                player = self.Players[p]
                s += player.Name + ' (' + str(player.Chips) + '): '
                if self.CanShowCards(player):
                    for c in range(len(player.Hand)):
                        s += str(player.Hand[c])
                        if(not c == len(player.Hand) - 1):
                            s += ', '

                    if(player.HandValue >= HIGH_CARD):
                        s += ' (' + str(self.Comparison.HandValueString(player.HandValue)) + ')'

                if(player.Folded):
                    s += ' [FOLDED]'

                s += '\n'

        return s

    def AddPlayer(self, name=None, buyIn=None, controlled=False):
        playerNumber = len(self.Players)

        if(buyIn is None):
            buyIn = self.BUY_IN

        if(name is None):
            name = "Player " + str(playerNumber+1)

        self.Players.append(Player(playerNumber=playerNumber, name=name, chips=buyIn, controlled=controlled))

    def Deal(self):
        if self.Verbose:
            print("-------------------------------- DEAL -----------------------------------------")

        for r in range(2):
            for i in range(len(self.Players)):
                player = self.Players[i]
                card = self.Deck.DrawCardFromTop()
                player.TakeCard(card)

                if(self.Verbose and self.CanShowCards(player)):
                    print(player.Name + ' dealt ' + str(card))

    def PlayerBet(self, player):
        if self.Debug and self.Verbose:
            print(player.Name, ' is making a player bet')

        bet = 0
        if player.Chips > 1:
            if player.IsHuman():
                while bet < self.MINIMUM_FIRST_BET:
                    betInput = input(player.Name + ', place a bet: ')
                    bet = int(betInput)

                    if bet > player.Chips:
                        bet = player.Chips

                    if bet < self.MINIMUM_FIRST_BET and self.Verbose:
                        print(player.Name, ', you must bet at least: ', self.MINIMUM_FIRST_BET)
            else:
                while bet < 1 or bet > player.Chips:
                    minBet = self.MinimumBet
                    maxBet = self.MinimumBet + int(0.5*player.Chips) + 1
                    bet = randint(minBet, maxBet)

                    if self.Debug and self.Verbose:
                        print('Min Bet: ', minBet, ', Max Bet: ', maxBet, ', Bet: ', bet)
        else:
            bet = player.Chips

            if self.Debug and self.Verbose:
                print(player.Name, ' only has ', bet, ' chips to bet')

        self.Pot += player.PlaceBet(bet)
        self.MinimumBet = bet

        self.FirstBetMade = True

        if self.Verbose:
            print(player.Name, ' bets ', bet)

    def PlayerCall(self, player):
        self.Pot += player.Call(self.MinimumBet)

        if self.Verbose:
            print(player.Name, ' calls')

    def PlayerCheck(self, player):
        player.Check()

        if self.Verbose:
            print(player.Name, ' checks')

    def PlayerRaise(self, player):
        if self.Debug and self.Verbose:
            print('Player has chosen to raise')

        if player.Chips > self.MinimumBet:
            raiseChips = 0
            if player.IsHuman():
                while raiseChips <= 0:
                    raiseChips = int(input(player.Name + ', enter the amount you would like to raise by: '))
            else:
                while raiseChips < 1 or raiseChips > (player.Chips):
                    minRaise = self.MinimumBet + 1
                    maxRaise = player.Chips
                    raiseChips = randint(minRaise, maxRaise)

                    if self.Debug and self.Verbose:
                        print('Min Raise: ', minRaise, ', Max Raise: ', maxRaise, ', Actual Raise: ', raiseChips)

            self.Pot += player.Raise(self.MinimumBet, raiseChips)
            self.MinimumBet = self.MinimumBet + raiseChips

            if self.Verbose:
                print(player.Name, ' raises by ', raiseChips)
        else:
            # assume they meant 'call'
            self.Pot += player.Call(self.MinimumBet)

            if self.Verbose:
                print('Player could not raise, called instead')

    def PlayerFold(self, player):
        player.Fold()

        if player.IsHuman():
            self.HumansInRound -= 1

        if self.Verbose:
            print(player.Name, ' folds')

    def TakeBets(self):
        if self.Verbose:
            print("------------------------------- TAKING BETS ------------------------------------")

        self.FirstBetMade = False
        doneBetting = False
        self.MinimumBet = 0
        # while not doneBetting:

        if self.Debug and self.Verbose:
            print('About to take first round of bets')

        for p in range(len(self.Players)):
            player = self.Players[p]

            if not player.Folded:
                if not self.FirstBetMade:
                    if self.Debug and self.Verbose:
                        print('Have not made first bet')

                    # options are to bet, check
                    check = False
                    if player.IsHuman():
                        checkBet = input(player.Name + ' check or bet? (K/b)')
                        if checkBet == 'k' or checkBet == 'K' or checkBet == 'c' or checkBet == 'C':
                            check = True
                    else:
                        check = (randint(0, 10) == 5)

                    if check and not self.StatisticsMode:
                        self.PlayerCheck(player)
                    else:
                        self.PlayerBet(player)
                else:
                    if self.Debug and self.Verbose:
                        print('We have made the first bet')

                    # options are to call, raise, check, or fold
                    calls = False
                    raises = False
                    checks = False
                    folds = True

                    if player.IsHuman():
                        callRaiseCheckFold = input(player.Name + ', would you like to call, raise, check, or fold? (C/r/k/f)')
                        if callRaiseCheckFold == 'C' or callRaiseCheckFold == 'c':
                            calls = True
                        elif callRaiseCheckFold == 'R' or callRaiseCheckFold == 'r':
                            raises = True
                        elif callRaiseCheckFold == 'K' or callRaiseCheckFold == 'k':
                            checks = True
                    else:
                        calls = (randint(0, 1) == 1)
                        raises = (randint(0, 1) == 1)
                        checks = (randint(0, 1) == 1)

                    if calls or self.StatisticsMode:
                        self.PlayerCall(player)
                    elif raises:
                        self.PlayerRaise(player)
                    elif checks:
                        self.PlayerCheck(player)
                    else:
                        self.PlayerFold(player)

        if not self.EverybodyFolded():
            for p in range(len(self.Players)):
                if self.EverybodyFolded():
                    break
                else:
                    player = self.Players[p]
                    if (not player.Folded) and player.Checked:
                        if not self.FirstBetMade:
                            # options are to bet or fold
                            bets = False
                            if player.IsHuman():
                                betFold = input(player.Name + ', either bet or fold (B/f): ')
                                if betFold == 'B' or betFold == 'b':
                                    bets = True
                                else:
                                    bets = False
                            else:
                                bets = (randint(0, 1) == 1)

                            if bets or self.StatisticsMode:
                                self.PlayerBet(player)
                            else:
                                self.PlayerFold(player)

                        else:
                            # options are call, raise, fold
                            calls = False
                            raises = False
                            checks = False
                            folds = True

                            if player.IsHuman():
                                callRaiseFold = input(player.Name + ', would you like to call, raise, or fold? (C/r/k/f)')
                                if callRaiseFold == 'C' or callRaiseFold == 'c':
                                    calls = True
                                elif callRaiseFold == 'R' or callRaiseFold == 'r':
                                    raises = True
                            else:
                                calls = (randint(0, 1) == 1)
                                raises = (randint(0, 1) == 1)

                            if calls or self.StatisticsMode:
                                self.PlayerCall(player)
                            elif raises:
                                self.PlayerRaise(player)
                            else:
                                self.PlayerFold(player)

            if not self.EverybodyFolded():
                for p in range(len(self.Players)):
                    if self.EverybodyFolded():
                        break
                    else:
                        player = self.Players[p]
                        if not (player.Bet >= self.MinimumBet or player.Folded):
                            # if they aren't up to bet, they need to meet the raise
                            calls = False
                            if player.IsHuman():
                                callFold = input(player.Name + ', either call the raise amount or fold (C/f): ')

                                if callFold == 'C' or callFold == 'c':
                                    calls = True

                            else:
                                calls = (randint(0, 1) == 1)

                            if calls or self.StatisticsMode:
                                self.PlayerCall(player)
                            else:
                                self.PlayerFold(player)

        # now set all of the checked players back to normal Status
        for p in range(len(self.Players)):
            self.Players[p].Checked = False
            self.Players[p].Bet = 0

    def Flop(self):
        if self.Verbose:
            print("------------------------------------ FLOP -------------------------------------")

        self.Deck.BurnCard()
        for c in range(3):
            card = self.Deck.DrawCardFromTop()
            self.FlopCards.append(card)

            if self.Verbose:
                print('Flop Card ' + str(c) + ': ' + str(card))

        self.UpdateCommunityCards()

    def Turn(self):
        if self.Verbose:
            print("------------------------------------- TURN -------------------------------------")

        self.Deck.BurnCard()
        self.TurnCard = self.Deck.DrawCardFromTop()
        self.UpdateCommunityCards()

        if self.Verbose:
            print('Turn Card: ' + str(self.TurnCard))

    def River(self):
        if self.Verbose:
            print("--------------------------------- RIVER -----------------------------------------")

        self.Deck.BurnCard()
        self.RiverCard = self.Deck.DrawCardFromTop()
        self.UpdateCommunityCards()

        if self.Verbose:
            print('River Card: ' + str(self.RiverCard))

    def UpdateCommunityCards(self):
        self.CommunityCards = []
        if(len(self.FlopCards) > 0):
            for c in range(len(self.FlopCards)):
                self.CommunityCards.append(self.FlopCards[c])

            if(not self.TurnCard is None):
                self.CommunityCards.append(self.TurnCard)

                if(not self.RiverCard is None):
                    self.CommunityCards.append(self.RiverCard)

    def SortPlayersByHandValue(self):
        n = len(self.Players)

        swapped = False
        for i in range(n):
            swapped = False
            for j in range(0, n-1):
                shouldSwap = False

                if(self.Players[j].HandValue > self.Players[j+1].HandValue):
                    shouldSwap = True
                else:
                    if(self.Players[j].HandValue == self.Players[j+1].HandValue):
                        handComparison = self.Comparison.CompareHandValue(self.Players[j].Hand, self.Players[j+1].Hand, self.CommunityCards, self.Players[j].HandValue)
                        if(handComparison == 1):
                            shouldSwap = True
                        elif(handComparison == 0):
                            self.Players[j].SameHandValueAs = self.Players[j+1].PlayerNumber
                            self.Players[j+1].SameHandValueAs = self.Players[j].PlayerNumber

                if(shouldSwap):
                    tempPlayer = self.Players[j+1]
                    self.Players[j+1] = self.Players[j]
                    self.Players[j] = tempPlayer
                    swapped = True

            if not swapped:
                break

        for i in range(n):
            swapped = False
            for j in range(0, n-1):
                shouldSwap = False

                if(self.Players[j+1].Folded):
                    shouldSwap = True

                if(shouldSwap):
                    tempPlayer = self.Players[j+1]
                    self.Players[j+1] = self.Players[j]
                    self.Players[j] = tempPlayer
                    swapped = True

            if not swapped:
                break

        self.Players = self.Players[::-1]

    def Showdown(self):
        if self.Verbose:
            print("----------------------------- SHOWDOWN ----------------------------------------")

        highestPlayer = None

        for p in range(len(self.Players)):
            player = self.Players[p]
            handValue = self.Comparison.HandValue(player.Hand, self.CommunityCards)
            self.Players[p].HandValue = handValue

        self.SortPlayersByHandValue()

        leader = self.Players[0]
        winners = []
        winners.append(leader)
        p = 1
        while p < len(self.Players):
            player = self.Players[p]
            if(player.SameHandValueAs == leader.PlayerNumber):
                winners.append(player)

            p += 1

        return winners

    def EverybodyFolded(self):
        playersFolded = 0
        p = 0
        while p < len(self.Players):
            if self.Players[p].Folded:
                playersFolded += 1

            p += 1

        if(playersFolded >= len(self.Players) - 1):
            return True
        else:
            return False

    def NewGame(self):
        self.Deck = TexasHoldemDeck()
        self.FlopCards = []
        self.TurnCard = None
        self.RiverCard = None
        self.CommunityCards = []
        self.Pot = 0
        self.Rounds = 0

        names = [
            'Josh',
            'Janae',
            'Michelle',
            'Tyson',
            'Chollin'
        ]

        self.Players = []
        for i in range(self.Bots):
            r = randint(0, len(names)-1)
            name = names[r]
            names.pop(r)
            self.AddPlayer(name=name)

        for i in range(self.Humans):
            r = randint(0, len(names)-1)
            name = names[r]
            names.pop(r)
            # self.AddPlayer(name=name, controlled=True)
            self.AddPlayer(name=name, controlled=True)

        self.PlayersOut = []

        if self.StatisticsMode:
            self.GameId = self.PymongoDB.games.insert_one({
                'players': len(self.Players)
            }).inserted_id

        self.Play()

    def CommunityCardsToJSON(self):
        json = {}
        json['flop'] = {}
        if self.FlopCards[0] and self.FlopCards[1] and self.FlopCards[2]:
            json['flop']['0'] = self.FlopCards[0].ToJSON()
            json['flop']['1'] = self.FlopCards[1].ToJSON()
            json['flop']['2'] = self.FlopCards[2].ToJSON()

        if self.TurnCard:
            json['turn'] = self.TurnCard.ToJSON()

        if self.RiverCard:
            json['river'] = self.RiverCard.ToJSON()

        return json

    def Wait(self):
        if(self.ReadTime < 1):
            input('')
        else:
            time.sleep(self.ReadTime)

    def Play(self):
        self.Rounds = 0

        while True:
            if(self.StatisticsMode):
                roundPlayers = []
                for p in range(len(self.Players)):
                    roundPlayers.append(self.Players[p])

                self.RoundId = self.PymongoDB.rounds.insert_one({
                    'players': len(self.Players),
                    'gameId': self.GameId
                }).inserted_id

            self.HumansInRound = 0
            for p in range(len(self.Players)):
                player = self.Players[p]
                if player.IsHuman():
                    self.HumansInRound += 1

            # self.AnteUp()

            self.RoundSection = DEAL
            self.Deal()
            self.TakeBets()
            if self.Verbose:
                print(self)
                if self.Readable:
                    self.Wait()

            if not self.EverybodyFolded():
                self.RoundSection = FLOP
                self.Flop()
                self.TakeBets()
                if self.Verbose:
                    print(self)
                    if(self.Readable):
                        self.Wait()

            if not self.EverybodyFolded():
                self.RoundSection = TURN
                self.Turn()
                self.TakeBets()
                if self.Verbose:
                    print(self)
                    if self.Readable:
                        self.Wait()

            if not self.EverybodyFolded():
                self.RoundSection = RIVER
                self.River()
                self.TakeBets()
                if self.Verbose:
                    print(self)
                    if self.Readable:
                        self.Wait()

            if not self.EverybodyFolded():
                self.RoundSection = SHOWDOWN
                roundWinners = self.Showdown()[:]
                if self.Verbose:
                    print(self)
                    if self.Readable:
                        self.Wait()

                numWinners = len(roundWinners)

                extraChips = self.Pot % numWinners
                self.Pot -= extraChips
                distributedChips = self.Pot / numWinners

                for p in range(len(roundWinners)):
                    player = roundWinners[p]
                    player.Chips += distributedChips

                if numWinners > 1:
                    for p in range(len(roundWinners)):
                        splitter = roundWinners[p]
                        if self.StatisticsMode:
                            self.PymongoDB.split_hands.insert_one({
                                'player': splitter.ToJSON(),
                                'community': self.CommunityCardsToJSON(),
                                'splitAmong': numWinners,
                                'playersPlayed': len(self.Players),
                                'everybodyFolded': False,
                                'gameId': self.GameId,
                                'roundId': self.RoundId
                        })
                else:
                    winner = roundWinners[0]
                    if self.StatisticsMode:
                        self.PymongoDB.winning_hands.insert_one({
                            'player': winner.ToJSON(),
                            'community': self.CommunityCardsToJSON(),
                            'playersPlayed': len(self.Players),
                            'everybodyFolded': False,
                            'gameId': self.GameId,
                            'roundId': self.RoundId
                        })

                    winner.Chips += self.Pot

                for p in range(len(self.Players)):
                    player = self.Players[p]

                    isWinner = False
                    for w in range(len(roundWinners)):
                        if player.PlayerNumber == roundWinners[w].PlayerNumber:
                            isWinner = True
                            break

                    if not isWinner and self.StatisticsMode:
                        self.PymongoDB.losing_hands.insert_one({
                            'player': player.ToJSON(),
                            'community': self.CommunityCardsToJSON(),
                            'playersPlayed': len(self.Players),
                            'everybodyFolded': False,
                            'gameId': self.GameId,
                            'roundId': self.RoundId
                        })
            else:
                for p in range(len(self.Players)):
                    if not self.Players[p].Folded:
                        roundWinner = self.Players[p]
                        break

                roundWinner.Chips += self.Pot

                if self.StatisticsMode:
                    print(self.EverybodyFolded())
                    self.PymongoDB.winning_hands.insert_one({
                        'player': roundWinner.ToJSON(),
                        'community': self.CommunityCardsToJSON(),
                        'playersPlayed': len(self.Players),
                        'everybodyFolded': True,
                        'gameId': self.GameId,
                        'roundId': self.RoundId
                    })

            # reset everything for the next round
            self.FlopCards = []
            self.TurnCard = None
            self.RiverCard = None
            self.CommunityCards = []
            self.Deck = TexasHoldemDeck()
            self.Pot = 0

            p = 0
            while p < len(self.Players):
                player = self.Players[p]
                if(player.Chips <= 0):
                    self.PlayersOut.append(player)
                    self.Players.pop(p)
                    if self.Verbose:
                        print(player.Name, ' is out')

                p += 1

            if len(self.Players) > 1:
                for p in range(len(self.Players)):
                    self.Players[p].ResetHand()
                    self.Players[p].Folded = False
                    self.Players[p].Checked = False
                    self.Players[p].SameHandValueAs = -1
            else:
                break

            self.Rounds += 1
            if self.Verbose:
                print(self)

        self.Winner = self.Players[0]
        if self.Verbose:
            print("------------------------------- GAME OVER -------------------------------------")
            print('Winner: ')
            print(self.Winner)
        if self.StatisticsMode:
            self.PymongoDB.games.update_one(
                {'_id': self.GameId},
                {
                    '$set': {
                        'winner': self.Winner.ToJSON()
                    }
                }
            )

# print("-------------------------------------------------------------------------------")

th = TexasHoldem(humans=1, bots=2, statisticsMode=False, autoStart=True, clearDB=False, verbose=True, readable=True, readTime=-1, debug=False)
# th = TexasHoldem(humans=0, bots=4, statisticsMode=True, clearDB=False, verbose=False, readable=False, readTime=-1, debug=False, autoStart=False)
# c = 0
# while c < 50000:
#     th.NewGame()
#     if c % 100 == 0:
#         print('game', c, 'rounds', th.Rounds, 'winner', th.Winner.Name)
#     c += 1


# -*- coding: utf-8 -*-
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import base64
import hashlib

def md5Hex(instr):
    return hashlib.md5(instr.encode(encoding='UTF-8')).hexdigest()

def md5HexJy(instr, keystr):
    return md5Hex(md5Hex(md5Hex(instr))+keystr)

class aes(object):
    def __init__(self,key,iv):
        self.key = key
        self.iv = iv
        key_b = bytes(self.key, 'utf-8')
        iv_b = bytes(self.iv, 'utf-8')
        self.cipher = Cipher(algorithms.AES(key_b), modes.CBC(iv_b), backend=default_backend())

    def encodeJson(self,line):
        byline = bytes(line, 'utf-8')
        encryptor = self.cipher.encryptor()
        padder = padding.PKCS7(128).padder()
        padded_data = padder.update(byline) + padder.finalize()
        enc_content = encryptor.update(padded_data) + encryptor.finalize()
        stren =base64.b64encode(enc_content)
        return stren.decode()

    def decodeJson(self,enStr):
        deStr = bytes(enStr,'utf-8')
        destrendd = base64.b64decode(deStr)
        depadder = padding.PKCS7(128).unpadder()
        decryptor = self.cipher.decryptor()
        padded_data = decryptor.update(destrendd) + decryptor.finalize()
        dec_content = depadder.update(padded_data) + depadder.finalize()
        return dec_content.decode()


import logging
import random

import matplotlib.pyplot as plt
import numpy as np
import sys

FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.propagate = True

class SGD_SVM(object):
    n = 0

    def __init__(self):
        self.w = None
        np.set_printoptions(precision=3)

    def calc_w(self, x, y, g=0.1, l=0.00001):
        return self._calc_w(self.w, x, y, g, l)

    def _calc_w(self, w, x_, y_, g=0.1, l=0.00001):
        v = y_ * np.dot(w, x_)
        return w - (g * l) * w + (0 if v > 1 else y_ * x_)

    def Qsvm(self, x_, y_, l=0.00001):
        return self._Qsvm(self.w, x_, y_, l)

    def _Qsvm(self, w, x_, y_, l=0.0001):
        v = y_ * np.dot(w, x_)
        loss = l * np.linalg.norm(w)**2 + max(0, 1 - v)
        grad = 0 if v > 1 else -y_ * x_
        return loss, grad

    def fw(self, x):
        return self._fw(self.w, x)[0]

    def _fw(self, w, x):
        value = np.dot(x, w)
        return np.sign(value), value

    def score(self, matrix, categories):
        n = 0; m = 0; v = []; s = []
        for x_, y_ in zip(matrix, categories):
            l, v_ = self._fw(self.w, x_)
            v.append(v_), s.append(y_)
            if l == y_:
                m += 1
            else:
                pass
                # logger.info("{} invece era {}".format(l, y_))
            n += 1

        return m / float(n), s, v

    def fit(self, matrix, categories):
        i = random.choice(range(matrix.shape[0]))
        self.w = self.calculate_w(matrix, categories, matrix[i].copy())
        return self.w

    def calculate_empirical_risk(self, x, y, w, g, l):
        loss = 0.0; n = len(y)
        for x_, y_ in zip(x, y):
            loss += l * np.linalg.norm(w) ** 2 + max(0, 1 - y_ * np.dot(w, x_))
        loss /= n
        return loss

    def calculate_w(self, x, y, w):

        l = 0.001
        g0 = 0.5; g = 0.0
        n = len(y); t = 1.0; i = 0

        old_p = int(100 * (t / n)); p = 0.9
        delta = np.inf; loss0 = np.inf; loss = 0

        # logger.info("{:>20}{:>20}{:>20}{:>20}".format("LOSS", "DELTA", "ACTUAL LOSS", "DELTA 2"))
        data = []
        while t < n:  # loss0 == np.inf or delta > 0.000001 or t < n:
            i = random.choice(range(n))
            x_, y_ = x[i], y[i]

            if (old_p != p and p % 10 == 0):
                logger.info("Completamento {}%".format(p))
                old_p = p
                #actual_q = self._Qsvm(w, x_, y_, l)[0]
                #loss = self.calculate_empirical_risk(x, y, w, g, l)
                #delta2 = np.abs(actual_q - loss)
                #delta = np.abs(loss0 - loss)
                #loss0 = loss
                #data.append( (loss, delta, actual_q, delta2) )
            p = int(100 * (t / n))

            g = g0 / (1 + l * g0 * t)
            # g = 1 / t
            grad = 0 if (y_ * np.dot(w, x_) > 1) else y_ * x_
            w = w - (g * l) * w + g * grad
            t += 1

            # v = y_ * np.dot(w, x_)
            # actual_q = self._Qsvm(w, x_, y_, l)[0]
            # loss = self.calculate_empirical_risk(x, y, w, g, l)
            # delta = np.abs(loss0 - loss)
            # delta2 = np.abs(actual_q - loss)
            # loss0 = loss
            # logger.info("{:>20}{:>20}{:>20}{:>20}".format(loss, delta, actual_q, delta2))

        #loss = self.calculate_empirical_risk(x, y, w, g, l)
        #delta2 = np.abs(actual_q - loss)
        #delta = np.abs(loss0 - loss)
        #logger.info("{:>20}{:>20}{:>20}{:>20}".format("LOSS", "DELTA", "ACTUAL LOSS", "DELTA 2"))
        #for d in data:
        #    logger.info("{:>20}{:>20}{:>20}{:>20}".format(d[0], d[1], d[2], d[3]))
        return w

if __name__ == '__main__':
    pass


# ------------------------------ #
#  1. IMPORTING MODULES
# ------------------------------ #

# ------------------------------ #
#  2. IMPORTING OTHER FILES
# ------------------------------ #

from A5_pageSpecificScrapeProcedure import scrapeFromThis

# ------------------------------ #
#  3. Functions
# ------------------------------ #

# page-specific scraping procedure
def scrapeForWebsite(df_jobs_forLang_init, dictOfLanguages, sourceWebsite):
    if sourceWebsite=='careerjet': # select specific lists for function calls
        # ------------------------------ #
        #  Limit the number of queries
        # ------------------------------ #
        # REDUCING THE NUMBER OF QUERIES (DEPENDING ON NUMBER OF SEARCH RESULTS PREVIOUSLY FOUND):
        # for each of those languages: Get again these results: 100 pages (i.e. 2000 results max.) is good

        # THIS WILL make 100 requests for 20 languages! i.e., about 200 requests.
        # ONLY DO THIS IF YOU KNOW WHAT YOU'RE DOING!
        # If previous searches have found most for SQL, search all 100 pages for SQL => and only a corresponding fraction + buffer correction (add some) for others
        for langName, numResults in dictOfLanguages.items():  # generally, do this: listOfLanguages[0:1] => uses first result as list
            print('\n')
            print(langName)

            # highest number of all jobs obtained in previous week
            maxNoResultsForALanguage = max(dictOfLanguages.values())

            # CONTROL HOW MANY PAGES ARE LOOKED AT: numResults *1.33 (sample) divided by 20 (results per page)
            if int(numResults) > 20:  # otherwise, just look at first page
                numPagesToLookAt = round(
                    int(numResults) / maxNoResultsForALanguage * 100)  # usual number: maxNoResultsForALanguage * 100  # careerjet.ch gives you max. 100 pages to look at (when searching for terms)
                    # 1.15 could be a good correction factor if results had been taken from last week - could maybe be that there are 15% more jobs than last week - but more than +15% for 1 week is unlikely
                print('numPagesToLookAt: ', int(numPagesToLookAt))
            else:
                numPagesToLookAt = 1

            numFirstRes = 1  # init
            listOfLinks_forLang = []
            # up to 2'000 => 100 requests per language (could get twice as many if i wanted)
            # usually, when one language doesn't yield more results: same result gets re-printed.

            # create list of URL's for this language:
            # by itself, numPagesToLookAt is "numpy.float64"
            for i in range(1, int(numPagesToLookAt)+1):  # i.e. if range(1,101), looking thru 100 pages! #+1 as buffer (avoid losing results)
                currentPageURL = "https://www.careerjet.ch/wsuchen/stellenangebote?s=" + str(
                    langName) + "&l=Schweiz&lid=38241&b=" + str(numFirstRes)
                numFirstRes += 20
                # print(numFirstRes)
                listOfLinks_forLang.append(currentPageURL)

            # ------------------------------ #
            #  For each language (still in the loop through langs: Actual scraping
            # ------------------------------ #
            # !!! The trick is that all the scrapes (should) append directly to the global arrays
            # see above (init): jobId = [] etc.
            # so, even though the first language will return its own array: arrays with the 2nd language will include the first, and so on!
            # so, at the end, we get arrays (e.g. jobId = []) that contain all the results - they won't get lost!
            # i.e. the last time we call this function, we will have all the results.
            df_jobs_CJ = scrapeFromThis(listOfLinks_forLang, langName, sourceWebsite)  # 2nd argument to pass the name of the language

            #break # for debugging purposes # break out of loop after 1 language
        # When all languages are done (looped through): we can finally return the resulting array back to the caller.
        return df_jobs_CJ # return to caller: checkAndScrapeIfNecessary

    elif sourceWebsite=='jobsCH': # select specific lists for function calls #
        # highest number of all jobs obtained in previous search
        maxNoResultsForALanguage = max(dictOfLanguages.values())
        # ------------------------------ #
        #  Limit the number of queries
        # ------------------------------ #
        # If previous searches have found most for SQL, search all 100 pages for SQL => and only a corresponding fraction + buffer correction (add some) for others
        for langName, numResults in dictOfLanguages.items():  # generally, do this: listOfLanguages[0:1] => uses first result as list
            print('\n')
            print('language Name:', langName)

            # CONTROL HOW MANY PAGES ARE LOOKED AT: numResults *1.33 (sample) divided by 20 (results per page)
            if int(numResults) > 20:  # otherwise, just look at first page
                numPagesToLookAt = round(
                    int(numResults) / maxNoResultsForALanguage * 58) # usual number: maxNoResultsForALanguage * 58   # jobs.ch gives you max. 23 pages to look at (when searching for terms)
                print('numPagesToLookAt: ', numPagesToLookAt)
                print('\n')
            else:
                numPagesToLookAt = 1

            pageNum = 1  # init
            listOfLinks_forLang = []
            # usually, when one language doesn't yield more results: same result gets re-printed.

            # create list of URL's for this language:
            # by itself, numPagesToLookAt is "numpy.float64"
            for i in range(1, int(numPagesToLookAt)):  # i.e. if range(1,101), looking thru 100 pages!
                currentPageURL = "https://www.jobs.ch/de/stellenangebote/?page=" + str(pageNum) + "&term=" + str(
                    langName)
                pageNum += 1
                # print(numFirstRes)
                listOfLinks_forLang.append(currentPageURL)

            df_jobs_JCH = scrapeFromThis(listOfLinks_forLang, langName, sourceWebsite)  # 2nd argument to pass the name of the language
        # When all languages are done (looped through): we can finally return the resulting array back to the caller (checkAndScrapeIfNecessary)
        return df_jobs_JCH

    elif sourceWebsite=='indeed': # select specific lists for function calls
        maxNoResultsForALanguage = max(dictOfLanguages.values())

        for langName, numResults in dictOfLanguages.items():  # generally, do this: listOfLanguages[0:1] => uses first result as list
            print('\n')
            print(langName)
            print('total no. of results', numResults)

            # CONTROL HOW MANY PAGES ARE LOOKED AT: numResults *0.33 (sample) divided by 20 (results per page)
            if numResults > 20:  # otherwise, just look at first page
                numPagesToLookAt = round(
                    int(numResults) / maxNoResultsForALanguage * 100)  # usual number: maxNoResultsForALanguage * 100  # indeed.ch gives you max. 100 pages to look at (when searching for terms)
                print('numPagesToLookAt: ', numPagesToLookAt)
                print('\n')
            else:
                numPagesToLookAt = 1

            startNumOfPage = 0  # init
            listOfLinks_forLang = []

            # create list of URL's for this language:
            for i in range(1, int(numPagesToLookAt)):  # i.e. if range(1,101), looking thru 100 pages!
                currentPageURL = "https://www.indeed.ch/Stellen?q=" + str(langName) + "&start=" + str(startNumOfPage)
                startNumOfPage += 10
                listOfLinks_forLang.append(currentPageURL)

            df_jobs_Ind = scrapeFromThis(listOfLinks_forLang, langName, sourceWebsite)  # 2nd argument to pass the name of the language
        # When all languages are done (looped through): we can finally return the resulting array back to the caller (checkAndScrapeIfNecessary)
        return df_jobs_Ind

    else: # if "sourceWebsite" has unknown name:
        print("Sorry, for the the page with variable sourceWebsite called: " + sourceWebsite + " does not appear to have a scrape procedure in the current ode")
        print('an empty dataframe will be returned: ')
        df_jobs_empty = scrapeFromThis(listOfLinks_forLang, langName, sourceWebsite) # calling the function with empty source website will just return an empty df
        return df_jobs_empty


# Bubble Sort
# It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped
# if they are not in order.
#
# Bubble Sort is one of the most straightforward sorting algorithms. Its name comes from the way the algorithm works:
# With every new pass, the largest element in the list “bubbles up” toward its correct position.
#
# Bubble sort consists of making multiple passes through a list, comparing elements one by one, and swapping adjacent
# items that are out of order.

def bubble_sort(list):
    # Swap the elements to arrange in order

    # Start looking at each item of the list one by one,
    # comparing it with its adjacent value. With each
    # iteration, the portion of the array that you look at
    # shrinks because the remaining items have already been
    # sorted.
    for iter_num in range(len(list) - 1, 0, -1):
        for idx in range(iter_num):
            if list[idx] > list[idx + 1]:
                # If the item you're looking at is greater than its
                # adjacent value, then swap them
                temp = list[idx]
                list[idx] = list[idx + 1]
                list[idx + 1] = temp

list = [19, 2, 31, 45, 6, 11, 121, 27]
print(f"Bubble sort: {list} -> ", end="")
bubble_sort(list)
print(f"{list}")
# When the above code is executed, it produces the following esult − [2, 6, 11, 19, 27, 31, 45, 121]

# Merge Sort Merge sort first divides the array into equal halves and then combines them in a sorted manner.
#
# Merge sort is a very efficient sorting algorithm. It’s based on the divide-and-conquer approach, a powerful algorithmic
# technique used to solve complex problems.
#
# To properly understand divide and conquer, you should first understand the concept of recursion. Recursion involves
# breaking a problem down into smaller subproblems until they’re small enough to manage. In programming, recursion is
# usually expressed by a function calling itself.
def merge_sort(unsorted_list):
    # If the input array contains fewer than two elements,
    # then return it as the result of the function
    if len(unsorted_list) <= 1:
        return unsorted_list
    # Find the middle point and devide it
    middle = len(unsorted_list) // 2

    # Sort the array by recursively splitting the input
    # into two equal halves, sorting each half and merging them
    # together into the final result
    left_list = unsorted_list[:middle]
    right_list = unsorted_list[middle:]

    left_list = merge_sort(left_list)
    right_list = merge_sort(right_list)
    return (merge(left_list, right_list))

# Merge the sorted halves
def merge(left_half, right_half):
    res = []

    # Now go through both arrays until all the elements
    # make it into the resultant array
    while len(left_half) != 0 and len(right_half) != 0:
        # The elements need to be sorted to add them to the
        # resultant array, so you need to decide whether to get
        # the next element from the first or the second array
        if left_half[0] < right_half[0]:
            res.append(left_half[0])
            left_half.remove(left_half[0])
        else:
            res.append(right_half[0])
            right_half.remove(right_half[0])

    # If you reach the end of either array, then you can
    # add the remaining elements from the other array to
    # the result and break the loop
    if len(left_half) == 0:
        res = res + right_half
    else:
        res = res + left_half
    return res

unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(f"Merge sort: {unsorted_list} -> {merge_sort(unsorted_list)}")
# When the above code is executed, it produces the following result − [11, 12, 22, 25, 34, 64, 90]

# Insertion Sort
# Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we compare the
# first two elements and sort them by comparing them. Then we pick the third element and find its proper position among
# the previous two sorted elements. This way we gradually go on adding more elements to the already sorted list by putting
# them in their proper position.
#
# Like bubble sort, the insertion sort algorithm is straightforward to implement and understand. But unlike bubble sort,
# it builds the sorted list one element at a time by comparing each item with the rest of the list and inserting it into
# its correct position. This “insertion” procedure gives the algorithm its name.
def insertion_sort(input_list):
    # Loop from the second element of the array until
    # the last element
    for i in range(1, len(input_list)):
        # Initialize the variable that will be used to
        # find the correct position of the element
        j = i - 1
        # This is the element we want to position in its
        # correct place
        nxt_element = input_list[i]
        # Compare the current element with next one

        # Run through the list of items (the left
        # portion of the array) and find the correct position
        # of the element referenced by `key_item`. Do this only
        # if `key_item` is smaller than its adjacent values.
        while (input_list[j] > nxt_element) and (j >= 0):
            # Shift the value one position to the left
            # and reposition j to point to the next element
            # (from right to left)
            input_list[j + 1] = input_list[j]
            j = j - 1

        # When you finish shifting the elements, you can position
        # `nxt_element` in its correct location
        input_list[j + 1] = nxt_element

list = [19, 2, 31, 45, 30, 11, 121, 27]
print(f"Insertion sort: {list} - > ", end="")
insertion_sort(list)
print(f"{list}")
# When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121]

# Shell Sort
# Shell Sort involves sorting elements which are away from each other. We sort a large sublist of a given list and go on
# reducing the size of the list until all elements are sorted. The below program finds the gap by equating it to half
# of the length of the list size and then starts sorting all elements in it. Then we keep resetting the gap until the
# entire list is sorted.

def shell_sort(input_list):
    # Start with a big gap, then reduce the gap
    gap = len(input_list) // 2

    # Do a gapped insertion sort for this gap size.
    # The first gap elements a[0..gap-1] are already in gapped
    # order keep adding one more element until the entire array
    # is gap sorted
    while gap > 0:

        for i in range(gap, len(input_list)):
            # add a[i] to the elements that have been gap sorted
            # save a[i] in temp and make a hole at position i
            temp = input_list[i]

            # shift earlier gap-sorted elements up until the correct
            # location for a[i] is found
            j = i
            # Sort the sub list for this gap

            while j >= gap and input_list[j - gap] > temp:
                input_list[j] = input_list[j - gap]
                j = j - gap

            # put temp (the original a[i]) in its correct location
            input_list[j] = temp

        # Reduce the gap for the next element
        gap = gap // 2

list = [19, 2, 31, 45, 30, 11, 121, 27]
print(f"Shell sort: {list} -> ", end="")
shell_sort(list)
print(f"{list}")
# When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121]

# Selection Sort
# In selection sort we start by finding the minimum value in a given list and move it to a sorted list. Then we repeat
# the process for each of the remaining elements in the unsorted list. The next element entering the sorted list is
# compared with the existing elements and placed at its correct position. So at the end all the elements from the
# unsorted list are sorted.
def selection_sort(input_list):
    for idx in range(len(input_list)):

        min_idx = idx
        for j in range(idx + 1, len(input_list)):
            if input_list[min_idx] > input_list[j]:
                min_idx = j
        # Swap the minimum value with the compared value

        input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]

l = [19, 2, 31, 45, 30, 11, 121, 27]
print(f"Selection sort: {l} -> ", end="")
selection_sort(l)
print(f"{l}")
# When the above code is executed, it produces the following result − [2, 11, 19, 27, 30, 31, 45, 121]


import functools

from flask import render_template, current_app, session as flask_session
from ..db import Player

def redirect_page(title, message, redirect_url, redirect_delay=0):
    message = message.format(delay=redirect_delay)
    return render_template('redirect.html', title=title, message=message,
                           url=redirect_url, delay=redirect_delay)

def inject_current_player(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        with current_app.db.session_scope() as session:
            if 'username' in flask_session:
                current_player = session.query(Player). \
                    filter_by(name=flask_session['username']).one_or_none()
            else:
                current_player = None
            return func(session, current_player, *args, **kwargs)
    return wrapped


''' Amer Abdelaziz
    U25449742
    This program demonstrates a BST in python along with
    several other functions

'''

''' From class  '''
def is_bintree(T):
    if type(T) is not tuple:
            return False
    if T == ():
            return True
    if len(T) != 3:
            return False
    if is_bintree(T[1]) and is_bintree(T[2]):
            return True
    return False

def bst_min(T):
    if T == ():
            return None
    if not T[1]:
            return T[0]
    return bst_min(T[1])
def bst_max(T):
    if T == ():
            return None
    if not T[2]:
            return T[0]
    return bst_max(T[2])
def is_bst(T):
    if not is_bintree(T):
        return False

    if T == ():
        return True

    if not is_bst(T[1]) or not is_bst(T[2]):
        return False

    if T[1] == () and T[2] == ():
        return True

    if T[2] == ():
        return bst_max(T[1]) < T[0]
    if T[1] == ():
        return T[0] < bst_min(T[2])
    return bst_max(T[1]) < T[0] < bst_min(T[2])

def bst_search(T,x):
    if T == ():
        return T
    if T[0] == x:
        return T
    if x < T[0]:
        return bst_search(T[1],x)
    return bst_search(T[2],x)

def bst_insert(T,x):
     if T == ():
            return (x,(),())
     elif x < T[0]:
            return (T[0],bst_insert(T[1],x),T[2])
     else:
            return (T[0],T[1],bst_insert(T[2],x))

def delete_min(T):
    if T == ():
        return T
    if not T[1]:
        return T[2]
    else:
        return (T[0],delete_min(T[1]),T[2])

def bst_delete(T,x):
    assert T, "deleting value not in tree"

    if x < T[0]:
        return (T[0],bst_delete(T[1],x),T[2])
    elif x > T[0]:
        return (T[0],T[1],bst_delete(T[2],x))
    else:
            if not T[1]:
                return T[2]
            elif not T[2]:
                return T[1]
            else:
                return (bst_min(T[2]),T[1],delete_min(T[2]))

def print_bintree(T,indent=0):
    if not T:
            print('*')
            return
    else:
            print(T[0])
            print(' '*(indent + len(T[0])-1)+'---', end = '')
            print_bintree(T[1],indent+3)
            print(' '*(indent + len(T[0])-1)+'---', end = '')
            print_bintree(T[2],indent+3)

def print_func_space(x):
    print(x, end=' ')

def inorder(T,f):
    if not is_bst(T):
        return
    if not T:
        return
    inorder(T[1],f)
    f(T[0])
    inorder(T[2],f)

def preorder(T,f):
    if not is_bst(T):
        return
    if not T:
        return
    f(T[0])
    preorder(T[1],f)
    preorder(T[2],f)

def postorder(T,f):
    if not is_bst(T):
        return
    if not T:
        return
    postorder(T[1],f)
    postorder(T[2],f)
    f(T[0])

    # Tree height function returns -1 if empty.... recursively
def tree_height(T):
    if not is_bst(T):
        return -1
    if not T:
        return -1
    if T == ():
        return -1
    else:
        return 1+max(tree_height(T[1]),tree_height(T[2]))

    # Balance ==> Difference between Left and Right trees
def balance(T):
    if not is_bst(T):
        return
    if not T:
        return
    return (tree_height(T[1]) - tree_height(T[2]))
    # min of the balances
def minBalance(T):
    if T == ():
        return 0
    else:
        return min(balance(T),minBalance(T[1]),minBalance(T[2]))

    #max of the bakances
def maxBalance(T):
    if T == ():
        return 0
    else:
        return max(balance(T),maxBalance(T[1]),maxBalance(T[2]))

    #is_avl based on the conditions
def is_avl(T):
    if T == ():
        return True
    return minBalance(T) >= -1 and maxBalance(T) <= 1

def subtree_count(T):
    if not T:
        return 0
    if T == ():
        return 0
    if T[1] or T[2]:
        return (1 + subtree_count(T[1]) + subtree_count(T[2]))

if __name__ == '__main__':
    K = ()
    for x in ('Joe','Bob', 'Phil', 'Paul', 'Marc', 'Jean', 'Jerry', 'Alice', 'Anne'):
        K = bst_insert(K,x)

    print()
    print('\nTree elements in sorted order\n')
    inorder(K,print_func_space)
    print()

    print('\n\nPrint full tree\n')
    print_bintree(K)

    print("\nDelete Bob and print tree\n")
    K = bst_delete(K,'Bob')
    print_bintree(K)
    print()

    print("\nPrint subtree at 'Phil'\n")
    print_bintree(bst_search(K,'Phil'))
    print()

    print("Height of the tree: ", tree_height(K))
    print("Balance: ", balance(K))
    print("Minimum Balance: ", minBalance(K))
    print("Maximum Balance: ", maxBalance(K))
    print("AVL: ", is_avl(K))
    print("Sub tree count:", subtree_count(K))


from snownlp import SnowNLP
import jieba
import jieba.analyse
import sqlite3
import re
jieba.load_userdict("mydict.txt")

conn = sqlite3.connect(r'C:\Users\I321338\PycharmProjects\Trendar\db.sqlite3')
cursor = conn.cursor()

f = open(r"C:\Users\I321338\PycharmProjects\Trendar\machine_learning\test500.txt",'r', encoding='utf-8')

text = f.readline()
sentiment = [0,0,0,0,0,0,0,0,0,0]
while text!="":
    ###############################
    #如果要把句子根据标点符号分开再来判断，把下面三句话解开注释
    #还要把Snownlp(text)的text改成i，r.write(text)的text改成i
    ###############################

    # file = re.split("\n|，|。|！|\ " ,text)
    # for i in file:
    #      if i != '':
            text_snow = SnowNLP(text)
            score = text_snow.sentiments
            sentiment[int(score*10)] = sentiment[int(score*10)]+1
            text = f.readline()

print(sentiment)
cursor.execute("delete from dashboard_sentiment")
cursor.execute("update sqlite_sequence SET seq = 0 where name ='dashboard_sentiment'")
for num in sentiment:
    # num = int(n)
    # print(num)
    cursor.execute(" insert into dashboard_sentiment (number) values(?)",(num,))
conn.commit()


import pyautogui, time #imports pyautogui and time modules
from time import sleep #imports sleep from time module

##########
count = 0#  #counter
##########

while True:
    time.sleep(10) #you can change the time if u want (second)
    count += 1 #Don't change this
    myScreenshot = pyautogui.screenshot() #Takes the screenshot
    myScreenshot.save(r'path here\screenshot{}.png'.format(count)) #saves the screenshot, change "path here".


import pytest
import arrays_5.sample_data as s

def test_sample_data():
    subset_length = 4
    input_set = [5, 10, 20, 4, 3, 5]
    result = s.sample_data(input_set, subset_length)

    if len(result) != subset_length:
        pytest.fail(f'sample_data() result length is {len(result)}, while expected {subset_length}')


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

from .layers import LayerOutput, mixed_layer, identity_projection, \
    slope_intercept_layer
from .attrs import is_compatible_with
from .default_decorators import *
import activations as act

__all__ = []

def register_unary_math_op(op_name, act):
    def op(input, name=None):
        return mixed_layer(input=[identity_projection(input=input)],
                           name=name,
                           act=act)
    op = wrap_name_default(op_name)(op)
    op.__doc__ = type(act).__doc__
    globals()[op_name] = op
    __all__.append(op_name)

register_unary_math_op('exp', act.ExpActivation())
register_unary_math_op('log', act.LogActivation())
register_unary_math_op('abs', act.AbsActivation())
register_unary_math_op('sigmoid', act.SigmoidActivation())
register_unary_math_op('tanh', act.TanhActivation())
register_unary_math_op('square', act.SquareActivation())

def add(layeroutput, other):
    if is_compatible_with(other, float):
        return slope_intercept_layer(input=layeroutput, intercept=other)
    assert isinstance(other, LayerOutput)
    return mixed_layer(input=[identity_projection(input=layeroutput),
                              identity_projection(input=other)])

LayerOutput.__radd__ = add
LayerOutput.__add__ = add

def sub(layeroutput, other):
    if is_compatible_with(other, float):
        return slope_intercept_layer(input=layeroutput, intercept=other)
    assert isinstance(other, LayerOutput)
    neg = slope_intercept_layer(input=other, slope=-1.0)
    return mixed_layer(input=[identity_projection(input=layeroutput),
                              identity_projection(input=neg)])

LayerOutput.__sub__ = sub

def rsub(layeroutput, other):
    neg = slope_intercept_layer(input=layeroutput, slope=-1.0)
    return add(neg, other)

LayerOutput.__rsub__ = rsub


# -*- coding: utf-8 -*-
import time
from odoo import api, models, _
from odoo.exceptions import UserError
from datetime import datetime

class ReportCostProfit(models.AbstractModel):

    _name = 'report.staffcommission_costprofit.report_cost_profit'

    def get_cost_profit_data(self, start_date, end_date, doctor, treatment_id):
        dom = [('date_invoice', '>=', start_date),
              ('date_invoice', '<=', end_date),
              ('is_patient', '=', True),
              ('type', '=', 'out_invoice'),
              ('state', 'in', ['open', 'paid'])]
        if doctor:
            dom.append(('dentist', '=', doctor[0]))
        history_ids = self.env['account.invoice'].search(dom)
        prod_dict = {}
        for invoice in history_ids:
            income = 0.0
            overhead_amt = 0.0
            material_cost = 0.0
            if invoice:
                for line in invoice.invoice_line_ids:
                    count = 0
                    if line.product_id.is_treatment:
                        if (treatment_id and line.product_id.id == treatment_id[0]) or not treatment_id:
                            income = line.price_subtotal
                            overhead_amt = line.product_id.lst_price * (line.product_id.overhead_cost/100)
                            material_cost = 0.0
                            for consumable in line.product_id.consumable_ids:
                                material_cost += consumable.consu_product_id.lst_price * consumable.quantity
                            if line.product_id.id in prod_dict:
                                count = prod_dict[line.product_id.id][1] + line.quantity
                                prod_dict[line.product_id.id][1] = count
                                overhead_final = overhead_amt * line.quantity
                                material_cost_final = material_cost * line.quantity
                                prod_dict[line.product_id.id][2] += income
                                prod_dict[line.product_id.id][3] += overhead_final
                                prod_dict[line.product_id.id][4] += material_cost_final
                                prod_dict[line.product_id.id][5] += income - material_cost_final - overhead_final
                            else:
                                overhead_final = overhead_amt * line.quantity
                                material_cost_final = material_cost * line.quantity
                                prod_dict[line.product_id.id] = [line.product_id.name, line.quantity,
                                                                 income, overhead_final, material_cost_final,
                                                                 income-material_cost_final -overhead_final]
        return [prod_dict]

    @api.multi
    def get_report_values(self, docids, data=None):
        if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
            raise UserError(_("Form content is missing, this report cannot be printed."))
        model = self.env.context.get('active_model')
        docs = self.env[model].browse(self.env.context.get('active_id'))
        start_date = data['form']['date_start']
        end_date = data['form']['date_end']
        treatment_id = data['treatment_id']
        doctor = data['doctor']
        final_records = self.get_cost_profit_data(start_date, end_date, doctor, treatment_id)
        period_start = datetime.strptime(start_date, '%Y-%m-%d')
        period_stop = datetime.strptime(end_date, '%Y-%m-%d')
        return {
            'period_start': period_start,
            'period_stop': period_stop,
            'doc_ids': self.ids,
            'doc_model': 'cost.profit.wizard',
            'data': data['form'],
            'docs': docs,
            'time': time,
            'get_cost_profit_data': final_records,
            'treatment_id': treatment_id,
            'doctor': doctor,
        }

    def formatLang(self, value, digits=None, date=False, date_time=False, grouping=True, monetary=False, dp=False,
                   currency_obj=False, lang=False):
        if lang:
            self.env.context['lang'] = lang
        return super(ReportCostProfit, self).formatLang(value, digits=digits, date=date, date_time=date_time,
                                                               grouping=grouping, monetary=monetary, dp=dp,
                                                               currency_obj=currency_obj)


import numpy as np
from collections import OrderedDict

import torch
import torch.nn as nn
import torch.nn.functional as F

from _Network.base_module import Network_Opts_base, Network_base,\
                                 disp_to_depth, ResnetEncoder_fromV2,\
                                 DepthDecoder

class Network_Opts(Network_Opts_base):
    def __init__(self):
        super().__init__()
        self.max_depth = 100
        self.min_depth = 0.1
        self.backbone = 18
        self.sample_mode = "nearest"

        self.use_depth = True

class BaseMonoDepthEstNetwork(Network_base):
    """The following parameters should be included in opts:
    min_depth, max_depth: min and max depth in predict
    """
    def __init__(self, opts, *args, **kargs):
        super().__init__(*args, **kargs)
        self.opts = opts

        self.networks["Encoder"] = ResnetEncoder_fromV2(self.opts.backbone,
                                                        True)
        if self.opts.backbone > 34:
            num_ch_enc = [64, 256, 512, 1024, 2048]
        else:
            num_ch_enc = [64, 64, 128, 256, 512]

        self.networks["Decoder"] = DepthDecoder(num_ch_enc,
                                                num_output_channels=1)

        self.all_net = nn.ModuleList(v for k, v in self.networks.items())

        if self.logger.is_train:
            self.logger.make_logdir("Disp")

    def forward(self, inputs, stage):
        image = inputs[("color_aug", "l")]
        features = self.networks["Encoder"](image)
        outputs = self.networks["Decoder"](features)

        if not self.opts.min_depth:
            K = inputs["K"]
            T = inputs["stereo_T"]
            w = image.size()[3]
            self.compute_min_depth(K, T, w)

        # compute depth from disp
        for scale in range(3, -1, -1):
            disp = outputs[("disp", scale)]
            if self.opts.use_depth:
                _, depth = disp_to_depth(disp, self.opts.min_depth,
                                        self.opts.max_depth)
            else:
                fx = inputs["K"][0, 0, 0]
                img_width = image.size()[-1]
                depth = fx/(img_width * 0.3 * disp + 1e-10)
            outputs[("depth", scale)] = depth

        if stage.is_visual and self.logger.is_train:
            self.logger.log_print(self.logger.step)
            v_dict = OrderedDict()
            v_modes = []
            v_size = [["img"]]

            v_dict["img"] = image.detach()
            v_modes.append("img")
            for scale in range(0, 4):
                show_disp = outputs[("disp", scale)].detach()
                self.logger.log_print(show_disp.mean())
                v_dict["disp_{}".format(scale)] = show_disp
                v_modes.append("disp")
                v_size.append(["disp_{}".format(scale)])

            self.logger.do_visualizion("Disp", v_dict, v_modes, v_size, "disp")
            self.logger.log_print("==========")

        return outputs

    def check_info(self):
        assert self.opts.height % 32 == 0, "'height' must be a multiple of 32"
        assert self.opts.width % 32 == 0, "'width' must be a multiple of 32"

    def get_trainable_params(self):
        names = ["Encoder", "Decoder"]
        muls = [1, 1]
        return self.get_module_params(names, muls)

    def compute_min_depth(self, K, T, w):
        fx = K[0, 0, 0]
        baseline = torch.abs(T[0, 0, 3])
        target_d = fx * baseline / (0.3 * w)
        disp_min = 1 / self.opts.max_depth
        disp_max = (1 - disp_min * 0.5 * target_d) / (0.5 * target_d)
        disp_max = disp_max.data
        self.opts.min_depth = 1 / disp_max
        print(self.opts.min_depth)


#!/usr/bin/python
import lutin.debug as debug
import lutin.tools as tools
import lutin.multiprocess as multiprocess
import os

def get_type():
	return "BINARY_SHARED"

def get_desc():
	return "WLD is wayland layer display to simplify display of graphic element"

def get_maintainer():
	return "authors.txt"

def get_version():
	return "version.txt"

def configure(target, my_module):
	my_module.add_extra_flags()
	# add the file to compile:
	my_module.add_src_file([
	    'screen.c',
	    'util.c',
	    'tag.c',
	    'window.c',
	    'config.c',
	    'layout.c',
	    'velox.c',
	    ])

	my_module.add_header_file([
	    'interface/*.h',
	    ],
	    destination_path="velox")

	# build in C mode
	my_module.compile_version("c", 1999)
	# add dependency of the generic C library:
	my_module.add_depend([
	    'c',
	    'wayland',
	    'wayland-layer-display',
	    'wayland-simple-compositor'
	    ])

	my_module.add_flag('c', [
	    "-D_GNU_SOURCE",
	    '-DVELOX_LIBEXEC="\\"out/Linux_x86_64/staging/clang/wayland-velox/wayland-velox.app/bin/\\""',
	    "-DENABLE_DEBUG=1",
	    "-Iprotocol",
	    "-DENABLE_LIBINPUT",
	    "-DENABLE_XWAYLAND",
	    "-I/usr/include",
	    "-I/usr/include/libdrm",
	    "-I/usr/include/libevdev-1.0/",
	    "-I/usr/include/pixman-1",
	    "-Wno-sign-compare",
	    "-Wno-macro-redefined",
	    "-Wno-missing-braces",
	    "-Wno-builtin-requires-header",
	    ])

	my_module.add_flag('link-lib', [
	    'drm_nouveau',
	    'drm_intel',
	    'drm',
	    'evdev',
	    'pixman-1',
	    'wayland-server',
	    'xkbcommon',
	    'input',
	    'udev',
	    'xcb',
	    'xcb-composite',
	    'xcb-ewmh',
	    'xcb',
	    'xcb-icccm',
	    'xcb',
	    'freetype',
	    'fontconfig',
	    'giomm-2.4',
	    ])

	multiprocess.run_command_direct("wayland-scanner server-header " + os.path.join(my_module.get_origin_path(), "protocol/velox.xml") + " out/tmpGeneratedData")
	ret1 = tools.file_read_data("out/tmpGeneratedData")
	debug.verbose("-----------------  protocol/velox-server-protocol.h  -----------------")
	debug.verbose("\n" + str(ret1))
	multiprocess.run_command_direct("wayland-scanner code " + os.path.join(my_module.get_origin_path(), "protocol/velox.xml") + " out/tmpGeneratedData")
	ret2 = tools.file_read_data("out/tmpGeneratedData")
	debug.verbose("-----------------  protocol/velox-protocol.c  -----------------")
	debug.verbose("\n" + str(ret2))

	my_module.add_generated_header_file(ret1, "protocol/velox-server-protocol.h", install_element=True)
	my_module.add_generated_src_file(ret2, "protocol/velox-protocol.c")

	return True


try:
    import ameba
    import time
    import uio as io
    import array
    import uctypes
    from utils import fast_copy
except:
    raise ImportError("ameba module import failed")

PERI_ON_BASE = const(0x40000000)
REG_CPU_PERIPHERAL_CTRL = const(0x02C0)
SPI_FLASH_BASE = const(0x98000000)
SPI_FLASH_CTRL_BASE = const(0x40006000)

REG_SPIC_CTRLR0 = const(0x0000)
REG_SPIC_CTRLR1 = const(0x0004)
REG_SPIC_SSIENR = const(0x0008)
REG_SPIC_SR = const(0x0028)
REG_SPIC_DR0 = const(0x0060)
REG_SPIC_ADDR_LENGTH = const(0x0118)

class FlashBdev:
    START_ADDR = 0x100000
    SEC_SIZE = 0x1000 # most flash sector is 4K
    START_SEC = START_ADDR // SEC_SIZE
    NUM_BLK = 252
    def __init__(self, blocks=NUM_BLK):
        self.blocks = blocks
        self.cache_buffer = bytearray(self.SEC_SIZE)

    def cmd(self, cmd, data=None, rxbuf=None):
        if len(cmd) != 1:
            raise ValueError('cmd length should be 1 byte')

        tmod = 1 if rxbuf is None else 3

        # enable CPU's spiflash pin
        ameba.mem32[PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL] |= (1<<0)
        ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_SSIENR] &= ~(1<<0)
        if tmod == 3:
            ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_CTRLR1] = len(rxbuf)
        if data is not None:
            ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_ADDR_LENGTH] = 0 if data is None else len(data)

        ctrlr0 = ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_CTRLR0]
        ctrlr0 &= 0xFFC0FCFF
        ctrlr0 |= ((tmod << 8) | (3 << 20))
        ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_CTRLR0] = ctrlr0

        ameba.mem8[SPI_FLASH_CTRL_BASE + REG_SPIC_DR0] = int.from_bytes(cmd, 1)

        if data is not None:
            for i in data:
                ameba.mem8[SPI_FLASH_CTRL_BASE + REG_SPIC_DR0] = i

        # activate this transfer
        ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_SSIENR] |= (1<<0)

        counter = 1000000
        while counter:
            reg_sr = ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_SR]
            busy = reg_sr & (1<<0)
            if busy == 0:
                break
            counter -= 1

        ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_SSIENR] &= ~(1<<0)

        if rxbuf is not None:
            for i in range(len(rxbuf)):
                rxbuf[i] = ameba.mem8[SPI_FLASH_CTRL_BASE + REG_SPIC_DR0]

        ameba.mem32[SPI_FLASH_CTRL_BASE + REG_SPIC_SSIENR] &= ~(1<<0)
        # disable CPU's spiflash pin
        ameba.mem32[PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL] &= ~(1<<0)

    def WREN(self):
        self.cmd(b'\x06')

    def WRDI(self):
        self.cmd(b'\x04')

    def WRSR(self, status):
        self.cmd(b'\x01', data=status)

    @property
    def RDSR(self):
        status = bytearray(1)
        self.cmd(b'\x05', rxbuf=status)
        return int.from_bytes(status, 1)

    @property
    def WIP(self):
        status = self.RDSR
        return status & (1<<0)

    @property
    def RDID(self):
        buffer = bytearray(3)
        self.cmd(b'\x9f', rxbuf=buffer)
        id = int.from_bytes(buffer, 3)
        manufactor_id = (id & 0xFF0000) >> 16
        device_id = id & 0xFFFF
        return (manufactor_id, device_id)

    def erasesector(self, addr):
        bytes_list = list(addr.to_bytes(3, 'little'))
        bytes_list.reverse()
        self.cmd(b'\x20', data = bytearray(bytes_list))

    def eraseblock(self, addr):
        bytes_list = list(addr.to_bytes(3, 'little'))
        bytes_list.reverse()
        self.cmd(b'\xd8', data = bytearray(bytes_list))

    def erasechip(self):
        self.cmd(b'\x60')

    def readblocks(self, n, buf):
        flash_cpu_ctrl_address = PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL
        ameba.mem32[flash_cpu_ctrl_address] |= (1<<0)
        dst_addr = uctypes.addressof(buf)
        src_addr = SPI_FLASH_BASE + (n + self.START_SEC) * self.SEC_SIZE
        fast_copy(dst_addr, src_addr, self.SEC_SIZE)
        ameba.mem32[flash_cpu_ctrl_address] &= ~(1<<0)

    def writeblocks(self, n, buf):
        address_base = SPI_FLASH_BASE + (n + self.START_SEC) * self.SEC_SIZE
        spi_status_address = SPI_FLASH_CTRL_BASE + REG_SPIC_SR
        flash_cpu_ctrl_address = PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL

        ameba.mem32[PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL] |= (1<<0)
        self.WREN()
        self.erasesector((n + self.START_SEC) * self.SEC_SIZE)
        while self.WIP != 0:
            pass

        arr = array.array("L", buf)

        for index, value in enumerate(arr):
            ameba.mem32[flash_cpu_ctrl_address] |= 0x01
            ameba.mem32[address_base + 4*index] = value

        ameba.mem32[PERI_ON_BASE + REG_CPU_PERIPHERAL_CTRL] &= ~(1<<0)

    def ioctl(self, op, arg):
        if op == 4: # BP_IOCTL_SEC_COUNT
            return self.blocks
        if op == 5: # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE


from django.db import models
from code_one.models import BankUser
import datetime

# Create your models here.
class DebitCard(models.Model):
    card_number = models.CharField(max_length=16, unique=True)
    date_created = models.DateTimeField(default=datetime.datetime.now())
    expiration_date = models.DateTimeField()
    bankUser = models.ForeignKey(BankUser)
    holder_first = models.CharField(max_length=20)
    holder_mid = models.CharField(max_length=1)
    holder_last = models.CharField(max_length=20)

    def __str__(self):
        return self.card_number

class Account(models.Model):
    balance = models.IntegerField(default=0)
    name = models.CharField(max_length=20)
    created_at = models.DateTimeField(default=datetime.datetime.now())
    last_deposit = models.DateTimeField(null=True, blank=True)
    last_withdraw = models.DateTimeField(null=True, blank=True)
    bankUser = models.ForeignKey(BankUser)
    debit_card = models.OneToOneField(DebitCard, on_delete=models.CASCADE, blank=True)

    def __str__(self):
        return self.name


import win32com.client as win32
import os
import re
import pythoncom
import sys
from collections import Counter
from datetime import datetime
iter=sys.argv[1]
start=datetime.now()
print("--------------------------------------------------------------------------------------------------------")
print("Document Name:", iter)
print("CheckList Rule - 22: Probable Acronyms in Document not defined in Acronym and Definition Table.")
print("Document Review Start Time:", start,"HH:MM:SS")
print("--------------------------------------------------------------------------------------------------------")
print("\n")
app=[]
if iter.endswith('.doc') or iter.endswith('.docx'):
 word1 = win32.Dispatch("Word.Application")
 word1.Visible = True
 p = os.path.abspath(iter)
 word1.Documents.Open(p)
 sheet_1 = word1.ActiveDocument
 for para in sheet_1.Paragraphs:
  a=para.Range.Text.encode('ascii','ignore').decode()
  pattern = r'(?:[A-Z]\.)+'
  t = re.findall('([A-Z]+)',a)
  for i in t:
   if len(i)>=2:     #discarding single capital letters
    app.append(i)
 def get_table_count():
  return sheet_1.Tables.Count

 def count_table_rows(table):
  return table.Rows.Count

 def count_table_columns(table):
  return table.Columns.Count

 def get_headers():
  headers = sheet_1.Sections(1).Headers(1)
  shape_count = headers.Shapes.Count
  for shape_num in range(1, shape_count + 1):
      t_range = headers.Shapes(shape_num).TextFrame.TextRange
      text = t_range.Text
      page_num = t_range.Information(3)  # 3 == wdActiveEndPageNumber
      yield text, page_num

 def get_table_text(table):
  col_count = count_table_columns(table)
  row_count = count_table_rows(table)

  for row in range(1, row_count + 1):
      row_data = []
      for col in range(1, col_count + 1):
          try:
              row_data.append(table.Cell(Row=row,Column=col).Range.Text.strip(chr(7) + chr(13)))

          except pythoncom.com_error as error:
              row_data.append("")

      yield row_data

 def get_all_table_text():
  for table in get_tables():
      table_data = []
      for row_data in get_table_text(table):
          #for col_data in .get_table_text(table):
              #table_data1.append(col_data)
              table_data.append(row_data)
      yield table_data
      #yield table_data1

 def get_tables():
  for table in sheet_1.Tables:
      yield table

 def __del__():
  word1.Quit()
 try:
  res=[]
  res1=[]
  pp={}
  jj=[]
  jjj=[]
  jjjj=[]

         #path = str(input())
         #count=0
         #open_doc = os.path.abspath(path)
  for table_num, table_text in enumerate(get_all_table_text()):
      #print("\n-------------- Table %s ----------------" % (table_num + 1))
      for row_data in table_text:
          b=", ".join(row_data)
          b=str(b).encode("utf-8")
          #print(b)
          k=b"Acronyms"
          l=b"Definition"
          if k in b:
              #print(table_text)
              k=table_text[0]
              #print(k)
              m=k.index('Acronyms')
              #print(m)
              for i in table_text:
               res.append(i[m])
  print("----------------------------------------------------------------------------------------------------------------------")
  print("Acronyms Defined:\n",res[1:])
  print("----------------------------------------------------------------------------------------------------------------------")
  res1=res[1:]
  print("Probable Acronyms not defined:\n",set(app)-set(res1))
  pp=set(app)-set(res1)
  #if len(pp)==0:
  # print("\nStatus:Pass")
  #else:
  # print("\nStatus:Fail")
 except:
  pass

end=datetime.now()
print("\nDocument Review End Time:", end)
print("\nTime taken For Document Review:", end-start,"HH:MM:SS")
sheet_1.Close()
word1.Quit()


import sys
from collections import defaultdict

my_dict = defaultdict(lambda:0)
my_dict["eric"] = 33
print(my_dict["eric"])
print(my_dict["fred"])
for foo, bar in sorted(my_dict.items()):
	print("%S --> %r % (foo, bar)")

print('hello world')

my_int = 4
my_float = 2.5
my_string = "hello"

print("string: %s\tfloat: %f\tint: %d" % (my_string, my_float, my_int))

my_variable = 5
if my_variable == 4:
	print("my_variable is 4")
else:
	print("my_variable is not 4")
for i in range(1, my_variable):
	print("i ==  %d" % (i))

sentence = "this is a pen"
words = sentence.split(" ")
for word in words:

	print(word)

print(" ||| ".join(words))

import sys
my_file = open(sys.argv[1], "r")
for line in my_file:
	line = line.strip()
if len(line) !=0:
	print(line)

my_file = open(sys.argv[1], "r")

for line in my_file:
	line = line.strip()
	if len(line) != 0:
		print(line)


from tipos.Bool import Bool
from tipos.Int import Int
from tipos.Fun import Fun
from tipos.Paren import Paren
from tipos.Var import Var

import sys

class Sustitucion:
  def __init__(self, pairs = None):
    "pairs = [(a, T1), (b, T2), ... , (z, Tn)]"

    if (pairs == None):
      self.pairs = []
    else:
      self.pairs = pairs

  def push(self, a, t):
    self.pairs.append((a, t))

  def pop(self):
    return self.pairs.pop()

  def contains(self, v):
    s = self.find(v)
    return s != None

  def find(self, v):
    s = filter(lambda e: (e[0].symbol == v.symbol), self.pairs)
    if (len(s) > 0):
      return s.pop()[1]
    else:
      return None

  def size(self):
    return len(self.pairs)

  def sustituir(self, t):
    if (isinstance(t, Fun)):
      t.domain = self.sustituir(t.domain)
      t.range = self.sustituir(t.range)
      return t
    elif(isinstance(t, Var)):
      e = self.find(t)
      if (e != None): return e
    elif(isinstance(t, Paren)):
      t.t = self.sustituir(t.t)

    return t

  def all(self):
    return self.pairs

  def compose(self, s):
    new_pairs = map(
      lambda e: (e[0], s.sustituir(e[1])),
      self.pairs
    )
    new_pairs.extend(filter(
      lambda e: (self.find(e[0]) == None),
      s.pairs
    ))

    return Sustitucion(new_pairs)


from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import generic

from .models import Article
from .forms import ArticleForm

class BlogHomeListView(generic.ListView):
    template_name = "blog/article_home.html"
    model = Article

def article_detail(request, pk):
    article = Article.objects.get(id=pk)
    return render(request, "blog/article.html", context={'article': article})

def article_create(request):
    if request.method == "POST":
        form = ArticleForm(request.POST, request.FILES)

        if form.is_valid():
            try:
                curr_user = User.objects.get(username=request.user.username)
            except User.DoesNotExist:
                curr_user = User.objects.get(username='admin')

            instance = form.save(commit=False)
            instance.author = curr_user
            instance.save()
            return HttpResponseRedirect(form.instance.get_absolute_url())
    else:
        form = ArticleForm()

    return render(request, "blog/article_create.html", context={'form': form})

def article_delete(request, pk):
    success_url = reverse_lazy('blog:blog-home')
    article = Article.objects.get(id=pk)

    if request.method == "POST" and "delete" in request.POST:
        article.delete()
        return HttpResponseRedirect(success_url)
    else:
        return HttpResponseRedirect(article.get_absolute_url())

def article_update(request, pk):
    article = Article.objects.get(id=pk)

    if request.method == "POST":
        form = ArticleForm(request.POST, request.FILES, instance=article)

        if form.is_valid():
            try:
                user = User.objects.get(username=request.user.username)
            except User.DoesNotExist:
                user = User.objects.get(username='admin')
            instance = form.save(commit=False)
            instance.author = user
            instance.save()
            return HttpResponseRedirect(instance.get_absolute_url())
    else:
        form = ArticleForm(instance=article)

    return render(request, "blog/article_update.html", context={'form': form})


# encoding: utf-8

from ckan import __version__ as ckan__version__
import ckan.plugins as p
import ckan.plugins.toolkit as tk
import json
from ckan.config.routing import SubMapper
import ckan.lib.jsonp as jsonp
from ckanext.digitalassetfields import util

ckan_version = util.version.parse(ckan__version__)

class DigitalassetfieldsPlugin(p.SingletonPlugin, tk.DefaultDatasetForm):
    p.implements(p.IDatasetForm)
    p.implements(p.IConfigurer)

    def _modify_package_schema(self, schema):
        schema.update({
            'custom_text': [tk.get_validator('ignore_missing'),
                            tk.get_converter('convert_to_extras')],
            'asset_type': [tk.get_validator('ignore_missing'),
                           tk.get_converter('convert_to_extras')],
            'related_projects': [tk.get_validator('ignore_missing'),
                                 tk.get_converter('convert_to_extras')],
            'related_publications': [tk.get_validator('ignore_missing'),
                                     tk.get_converter('convert_to_extras')],
            'asset_owner': [tk.get_validator('ignore_missing'),
                            tk.get_converter('convert_to_extras')],
            'asset_status': [tk.get_validator('ignore_missing'),
                             tk.get_converter('convert_to_extras')],
            'expl_notes': [tk.get_validator('ignore_missing'),
                           tk.get_converter('convert_to_extras')],
            'spatial': [tk.get_validator('ignore_missing'),
                           tk.get_converter('convert_to_extras')],
            'test': [tk.get_validator('ignore_missing'),
                           tk.get_converter('convert_to_extras')],
            'description': [tk.get_validator('ignore_missing'),
                            tk.get_converter('convert_to_extras')],
            'other_affiliates': [tk.get_validator('ignore_missing'),
                                 tk.get_converter('convert_to_extras')]
        })
        return schema

    def create_package_schema(self):
        schema = super(DigitalassetfieldsPlugin, self).create_package_schema()
        schema = self._modify_package_schema(schema)
        return schema

    def update_package_schema(self):
        schema = super(DigitalassetfieldsPlugin, self).update_package_schema()
        schema = self._modify_package_schema(schema)
        return schema

    def show_package_schema(self):
        schema = super(DigitalassetfieldsPlugin, self).show_package_schema()
        schema.update({
            'custom_text': [tk.get_converter('convert_from_extras'),
                            tk.get_validator('ignore_missing')],
            'asset_type': [tk.get_converter('convert_from_extras'),
                           tk.get_validator('ignore_missing')],
            'related_projects': [tk.get_converter('convert_from_extras'),
                                 tk.get_validator('ignore_missing')],
            'related_publications': [tk.get_converter('convert_from_extras'),
                                     tk.get_validator('ignore_missing')],
            'asset_owner': [tk.get_converter('convert_from_extras'),
                            tk.get_validator('ignore_missing')],
            'asset_status': [tk.get_converter('convert_from_extras'),
                             tk.get_validator('ignore_missing')],
            'expl_notes': [tk.get_converter('convert_from_extras'),
                           tk.get_validator('ignore_missing')],
            'test': [tk.get_converter('convert_from_extras'),
                           tk.get_validator('ignore_missing')],
            'spatial': [tk.get_converter('convert_from_extras'),
                            tk.get_validator('ignore_missing')],
            'description': [tk.get_converter('convert_from_extras'),
                            tk.get_validator('ignore_missing')],
            'other_affiliates': [tk.get_converter('convert_from_extras'),
                                 tk.get_validator('ignore_missing')]
        })
        return schema

    def is_fallback(self):
        # Return True to register this plugin as the default handler for
        # package types not handled by any other IDatasetForm plugin.
        return True

    def package_types(self):
        # This plugin doesn't handle any special package types, it just
        # registers itself as the default (above).
        return []

    def update_config(self, config):
        # Add this plugin's templates dir to CKAN's extra_template_paths, so
        # that CKAN will use this plugin's custom templates.

        # first defined templates are higher priority
        if ckan_version < util.version.parse("2.8.0"):
            # override some parts with bootstrap2 templates if needed
            tk.add_template_directory(config, 'bs2-templates')
        # fallback to Bootstrap3 templates.
        tk.add_template_directory(config, 'templates')
        tk.add_public_directory(config, 'public')
        tk.add_resource('fanstatic', 'digitalassetfields')
        tk.add_resource('resources', 'resources')


import numpy as np
#打开文件
file_snpdata = open('/node01/catg/lh/newport/out/core.vcf', mode = 'r')
file_seq_length = open('/node01/catg/lh/newport/ref/9.fasta', mode = 'r')
sorted_file = open('/node01/catg/lh/newport/out/sorted_file.log', mode = 'w')
space_std = 75
#space_std = input()
var_sum = 0
#设定过滤值
#获得reference的基因长度
seq_length_lines = file_seq_length.readlines()
length_cnt = 1 ; seq_length = 0
for line in seq_length_lines:
    if length_cnt> 1:
        for i in line.strip():
            seq_length = seq_length + 1
    length_cnt = length_cnt + 1

snpdata_lines = file_snpdata.readlines()
snp_line_cnt = 0 ; list_unsort = []

#对每行的第九个元素之后的所有元素进行方差计算
for line in snpdata_lines:
    if snp_line_cnt > 160:
        contig = line.split()[0]
        snp_site = int(line.split()[1])
        data = list(map(int, line.split()[9:]))
        var = np.var(data)
        var_sum = var_sum + var
        list_unsort.append([snp_site, var, contig])
    snp_line_cnt = snp_line_cnt + 1
#去除极低的数值
##var_ave = var_sum / len(list_unsort)
## for i in range(len(list_unsort), -1, -1):
##    if (list_unsort[i][1] < var_ave/10):
##        list_unsort.pop(i)

#计算每个snp上下的间距
prefix = 0 ; suffix = 0 ; spacing_list = []
num_strain = len (list_unsort)
for i in range(num_strain - 1):
    if i == 0:
        suffix = 1
        spacing = list_unsort[suffix][0]
        spacing_list.append(spacing)
        suffix =suffix + 1
    elif i == num_strain - 2:
        spacing = abs(list_unsort[suffix][0] - list_unsort[prefix][0])
        spacing_list.append(spacing)
        prefix = prefix + 1
    else:
        spacing = abs(list_unsort[suffix][0]- list_unsort[prefix][0])
        spacing_list.append(spacing)
        suffix = suffix + 1; prefix = prefix + 1
spacing_list.append(seq_length - list_unsort[prefix][0])

#合并并创建排序参考值
for i in range(num_strain):
    list_unsort[i].append(spacing_list[i])
    temp = (spacing_list[i] / space_std)
    if temp > 1:
        temp = 1
    temp = temp * temp * list_unsort[i][1]
    list_unsort[i].append(temp)

#对计算结果进行排序并输出前十位
list_sorted = sorted(list_unsort, reverse= True, key = lambda x : x[4])
sorted_file.write('position\tsd\tcontig\tspacing\tsort_value\n')
for i in list_sorted:
    sorted_file.write(str(i)[1:-1]+'\n')

#关闭文件
sorted_file.close()
file_seq_length.close()
file_snpdata.close()


from wtforms.validators import ValidationError

def validate(data, rules=None):
    if rules is None:
        assert type(data) is dict

        error_messages = None
        for name, field in data.items():
            validation = validate(field['data'], field['rules'])
            if not validation.validated:
                if error_messages is None:
                    error_messages = {name: validation.error_message}
                else:
                    error_messages[name] = validation.error_message

        return error_messages

    return Validator(data, rules)

class Validator(object):

    validated = False
    error_message = ''

    def __init__(self, data, rules):
        self.data = data
        self.rules = rules

        try:
            for rule in iter(self.rules):
                rule(self.data)
        except ValidationError as e:
            self.error_message = str(e)
        else:
            self.validated = True

class Rules(object):
    """验证规则"""
    class Required(object):
        def __init__(self, message='', data=None):
            self.message = message
            self.data = data

        def __call__(self, data):
            if self.data is None:
                rule = data is not None and data != str() and data != list()
            else:
                if type(data) is list:
                    rule = set(self.data) - set(data) != set(self.data)
                else:
                    rule = data in self.data

            if not rule:
                raise ValidationError(self.message)

    class Unique(object):
        def __init__(self, model, field, message='该内容已存在'):
            self.model = model
            self.field = field
            self.message = message

        def __call__(self, form, field):
            check = self.model.query.filter(self.field == field.data).first()
            if check:
                raise ValidationError(self.message)


from django.db import models
from django.conf import settings

models_yaml = settings.MODELS_YAML

models_dict = {}

types = {
    'date': models.DateField,
    'char': models.TextField,
    'int': models.IntegerField,
}

def model_name(title):
    def function(self):
        return title
    return function

for m in models_yaml:
    class_fields = {}
    class_fields['__module__'] = __name__
    class_fields['__unicode__'] = model_name(models_yaml[m]['title'])
    for f in models_yaml[m]['fields']:
        class_fields[f['id']] = types[f['type']](f['title'])

    models_dict[m] = type(m, (models.Model,), class_fields)


import os
import time
import shutil
import pickle

from common.entity.entities import Command, Node, Type
from common.network.utils import get_ip_address
from common.network.utils import changeIp
from sftp import download_from_ftp

class BBB():

    def __init__(self, path, rc_local_dest_path, sfp_server_addr, sftp_port: int = 22,
                 ftp_destination_folder: str = None):

        #  Parameters that define absolute locations inside the Beaglebone
        self.ftpDestinationFolder = ftp_destination_folder
        self.rcLocalDestPath = rc_local_dest_path
        self.configPath = path
        self.sfp_server_addr = sfp_server_addr
        self.sftp_port = sftp_port

        # The interface used (ethernet port on the Beaglebone).
        self.interfaceName = 'eth0'

        # My configs !
        self.node = Node()
        self.node.type = Type()
        self.node.ipAddress = get_ip_address(self.interfaceName)

        # Load the data from the cfg file.
        self.readParameters()

    def getInfo(self):
        info = "{}|{}|{}|{}|{}" \
            .format(Command.PING, self.node.name, self.node.type.name, self.node.ipAddress, self.node.type.sha)
        return info

    def reboot(self):
        os.system('reboot')

    def update_project(self):
        """
            Update the project, getting the current version available on the FTP server.
            The responsibility to keep it up to date is all on the server side.
            Always removing the old ones.
        :return: True or False
        """
        if type is None:
            return False
        try:
            repo_name = self.node.type.repoUrl.strip().split('/')[-1].split('.')[0]

            repo_dir = self.ftpDestinationFolder + repo_name + "/"
            if os.path.exists(repo_dir) and os.path.isdir(repo_dir):
                shutil.rmtree(repo_dir)
                time.sleep(1)

            if repo_dir.endswith('/') and self.node.rcLocalPath.startswith('/'):
                self.node.rcLocalPath = self.node.rcLocalPath[1:]

            download_from_ftp(sftp_server_addr=self.sfp_server_addr, sftp_port=self.sftp_port, path=repo_name,
                              destination=repo_dir)

            print("Downloaded Node repository from FTP server {} at {}".format(self.node.type.repoUrl, repo_name))

            if not os.path.isfile(repo_dir + self.node.rcLocalPath):
                shutil.rmtree(repo_dir)
                raise Exception("rc.local not found on path.")

            shutil.copy2((repo_dir + self.node.rcLocalPath), self.rcLocalDestPath)
            print("Copied file {} to {}".format(repo_dir + self.node.rcLocalPath, self.rcLocalDestPath))
            return True
        except Exception as e:
            print("{}".format(e))
            return False

    def update(self, desiredNode: Node = None):
        """
        @todo : NODE! Update Code !!!!
        Update the bbb with new data and refresh the project.
        :return:
        """
        if not desiredNode or not desiredNode.type:
            print('Node/Type is None !')
            return
        if not desiredNode.ipAddress:
            print('IP Address is None !')
            return
        try:
            self.node = desiredNode

            res, msg = changeIp(interface_name=self.interfaceName, desired_ip=desiredNode.ipAddress)
            if res:
                self.node.ipAddress = get_ip_address(self.interfaceName)
            print(msg)

            with open("/etc/hostname", "w") as hostnameFile:
                hostnameFile.write(desiredNode.name.replace(":", "-"))
                hostnameFile.close()

            self.update_project()

            self.writeNodeConfig(pickle.dumps(self.node))
        except Exception as e:
            print('Update Error ! {}'.format(e))

    def readParameters(self):
        self.readNodeConfig()
        try:
            name = os.popen("hostname", "r").readline()[:-1]
            indexes = [i for i, letter in enumerate(name) if letter == "-"]
            name = list(name)
            if len(indexes) > 2:
                name[indexes[1]] = ":"

            self.node.name = "".join(name)
        except FileNotFoundError:
            self.node.name = "error-hostname-not-found"

    def readNodeConfig(self):
        try:
            with open(self.configPath, 'rb') as file:
                self.node = pickle.load(file)
        except Exception as e:
            print('Read node config exception {}'.format(e))

    def writeNodeConfig(self, data):
        with open(self.configPath, 'wb+') as file:
            file.write(data)


a = int(input('\033[33mPrimeiro valor: '))
b = int(input('\033[33mSegundo valor: '))
c = int(input('\033[33mTerceiro valor: '))

# verificando quem é menor
menor = a
if b < a and b < c:
    menor = b
if c < a and c < b:
    menor = c

# verificando quem é maior
maior = a
if b > a and b > c:
    maior = b
if c > a and c > b:
    maior = c

print(f'\033[34mO menor valor digitado foi \033[32m{menor}')
print(f'\033[34mO maior valor digitado foi \033[32m{maior}')


from django import template
from parsifal.reviews.models import Review

register = template.Library()

@register.filter
def is_visitor(user, review):
    review = Review.objects.get(pk=review.id)
    if review.export_protocol and not user == review.author and not user in review.co_authors.all():
        return True

    for visitor in review.visitors.all():
        if user.id == visitor.id:
            return True
    return False