from collections import defaultdict
import operator
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk

def classification(predicted_model, test_pairscore, test_bilinear_score, test_question, question, review):
    total_no = 0
    correct = 0
    incorrect = 0
    c , i = 0, 0
    relevant_reviews = defaultdict(lambda: defaultdict())
    for prod_key in test_bilinear_score:
        question_review_score = defaultdict(lambda: defaultdict())
        for each_question in test_bilinear_score[prod_key]:
            # total_no += 5
            review_score, dummy = defaultdict(), defaultdict()
            for each_review in test_bilinear_score[prod_key][each_question]:
                score = defaultdict()
                weight_list = predicted_model[prod_key][each_question]
                sum = weight_list[0] * test_pairscore[prod_key][each_question][each_review]['ROGUE'] + \
                      weight_list[1] * test_pairscore[prod_key][each_question][each_review]['BM25+'] + \
                      weight_list[2] * test_bilinear_score[prod_key][each_question][each_review]
                abs_sum = abs(sum)
                score['score'] = sum
                score['abs_score'] = abs_sum
                for x in review[prod_key]:
                    if x['ID'] == each_review:
                        score['actual_sen'] = x['actual_sen']
                        break
                review_score[each_review] = sum
                dummy[each_review] = score

            sorted_list = sorted(review_score.items(), key=lambda x: x[1], reverse=True)
            # sorted_list = list(reversed(sorted(review_score.iteritems(), key=operator.itemgetter(1))))
            i = 0
            # nltk.download()
            yes, no = 0, 0
            sid = SentimentIntensityAnalyzer()
            for x in sorted_list:
                sentence = dummy[x[0]]['actual_sen']
                #print sentence
                ss = sid.polarity_scores(sentence)
                if ss["compound"] < 0:
                    no += 1
                else:
                    yes += 1

                i += 1
                if i == 5:
                    break
            if yes >= no:
                if test_question[prod_key][0]['A'] == True:
                    c += 1
                else:
                    i += 1
            else:
                if test_question[prod_key][0]['A'] == False:
                    c += 1
                else:
                    i +=  1
    accuracy =  float(c) / float(c + i)
    print ("accuracy: %s" %accuracy)
    return c, i


import string

VARIABLE_NAME_START_CHARACTERS = string.ascii_letters + "_"
VARIABLE_NAME_CHARACTERS = VARIABLE_NAME_START_CHARACTERS + string.digits

NUMBER_START_CHARACTERS = string.digits
NUMBER_CHARACTERS = string.digits + "."

TUPLE_START_CHAR = '('
TUPLE_END_CHAR = ')'
BLOCK_START_CHAR = '{'
BLOCK_END_CHAR = '}'
TABLE_START_CHAR = '['
TABLE_END_CHAR = ']'

ENCLOSING_CHARACTERS =	TUPLE_START_CHAR +\
						TUPLE_END_CHAR +\
						BLOCK_START_CHAR +\
						BLOCK_END_CHAR +\
						TABLE_START_CHAR +\
						TABLE_END_CHAR

STRING_CHAR = '"'
COMMENT_CHAR = '#'
EOL_CHAR = ';'
SEPARATOR_CHAR = ','
NEWLINE_CHAR = '\n'

WHITESPACE = string.whitespace

TYPE_NULL = 0
TYPE_TERM = 1
TYPE_BOOLEAN = 2
TYPE_NUMBER = 3
TYPE_STRING = 4
TYPE_COMMENT = 5
TYPE_WHITESPACE = 6
TYPE_OPERATOR = 7
TYPE_FUNCTION = 8
TYPE_SUBROUTINE = 9
TYPE_ASSIGN = 10
TYPE_GOTO = 11
TYPE_GOSUB = 12
TYPE_EOL = 13
TYPE_SEPARATOR = 14
TYPE_ENCLOSED = 15
TYPE_BLOCK_START = 16
TYPE_BLOCK_END = 17
TYPE_OTHER = 18

LITERAL_TYPES = (
	TYPE_BOOLEAN,
	TYPE_NUMBER,
	TYPE_STRING
)

TYPE_NAMES = (
	"NULL",
	"TERM",
	"BOOLEAN",
	"NUMBER",
	"STRING",
	"COMMENT",
	"WHITESPACE",
	"OPERATOR",
	"FUNCTION",
	"SUBROUTINE",
	"CALL",
	"GOTO",
	"GOSUB",
	"EOL",
	"SEPARATOR",
	"ENCLOSED",
	"BLOCK START",
	"BLOCK END",
	"OTHER"
)

LEFT_TO_RIGHT = 0
RIGHT_TO_LEFT = 1


from app import app
from flask_restful import Api
from app.resources.resources_typon import NS, profile,Statstypon
from app.resources.resources_typon import SpeciesListAPItypon, SpeciesAPItypon
from app.resources.resources_typon import SchemaListAPItypon, SchemaLociAPItypon, SchemaAPItypon, SchemaZipAPItypon
from app.resources.resources_typon import LociListAPItypon, LociAPItypon, LociFastaAPItypon, LociSequencesAPItypon, LociUniprotAPItypon
from app.resources.resources_typon import AlleleListAPItypon, AlleleAPItypon, SequencesAPItypon, SequencesListAPItypon
from app.resources.resources_typon import IsolatesAPItypon, IsolatesAllelesAPItypon, IsolatesListAPItypon, IsolatesProfileAPItypon,IsolatesLociAPItypon,IsolatesUserListAPItypon

#version="/v1"
version="/"+app.config['API_VERSION']

## API Setup ##
api = Api(app)

# NOTE: maybe use 'url_for(...)' + concatenation instead of hard coding URIs

api.add_resource(NS,
				version+'/NS',
				endpoint='NS')

api.add_resource(Statstypon,
				version+'/NS/stats',
				endpoint='NStats')

api.add_resource(profile,
				version+'/NS/species/<int:spec_id>/profiles',
				endpoint='profile')

api.add_resource(SpeciesListAPItypon,
				version+'/NS/species',
				endpoint='speciesList')

api.add_resource(SpeciesAPItypon,
				version+'/NS/species/<int:spec_id>',
				endpoint='species')

api.add_resource(SchemaListAPItypon,
				version+'/NS/species/<int:spec_id>/schemas',
				endpoint='schemaList')

api.add_resource(SchemaAPItypon,
				version+'/NS/species/<int:spec_id>/schemas/<int:id>',
				endpoint='schema')

api.add_resource(SchemaZipAPItypon,
				version+'/NS/species/<int:spec_id>/schemas/<int:id>/compressed',
				endpoint='schemaZip')

api.add_resource(SchemaLociAPItypon,
				version+'/NS/species/<int:spec_id>/schemas/<int:id>/loci',
				endpoint='schemaLoci')

api.add_resource(LociListAPItypon,
				version+'/NS/species/<int:spec_id>/loci',
				endpoint='lociList')

api.add_resource(LociAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:id>',
				endpoint='loci')

api.add_resource(LociFastaAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:id>/fasta',
				endpoint='lociFasta')

api.add_resource(LociUniprotAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:id>/uniprot',
				endpoint='lociUniprot')

api.add_resource(AlleleListAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:loci_id>/alleles',
				endpoint='alleleList')

api.add_resource(AlleleAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:loci_id>/alleles/<int:allele_id>',
				endpoint='allele')

api.add_resource(SequencesAPItypon,
				version+'/NS/sequences/<string:seq_id>',
				endpoint='sequences')

api.add_resource(SequencesListAPItypon,
				version+'/NS/sequences',
				endpoint='sequencesNumber')

api.add_resource(IsolatesListAPItypon,
				version+'/NS/species/<int:spec_id>/isolates',
				endpoint='isolatesList')

api.add_resource(IsolatesAPItypon,
				version+'/NS/species/<int:spec_id>/isolates/<string:isol_id>',
				endpoint='isolates')

api.add_resource(IsolatesAllelesAPItypon,
				version+'/NS/species/<int:spec_id>/isolates/<string:isol_id>/alleles',
				endpoint='isolatesAlleles')

api.add_resource(IsolatesUserListAPItypon,
				version+'/NS/species/<int:spec_id>/user/isolates',
				endpoint='isolatesUser')

api.add_resource(IsolatesLociAPItypon,
				version+'/NS/species/<int:spec_id>/isolates/<string:isol_id>/loci/<int:locus_id>',
				endpoint='isolatesLoci')

api.add_resource(IsolatesProfileAPItypon,
				version+'/NS/species/<int:spec_id>/isolates/<string:isol_id>/schemas/<int:id>',
				endpoint='isolatesProfiles')

api.add_resource(LociSequencesAPItypon,
				version+'/NS/species/<int:spec_id>/loci/<int:loci_id>/sequences',
				endpoint='lociSequences')


#!/usr/bin/python

def ruler_fun():
    prompt = "Enter size of ruler : "
    sizeRuler = int(input(prompt))

    tmp1 = sizeRuler
    ruler = "|"

    while tmp1 > 0:
        ruler = ruler + "." * 3 + "|"
        tmp1 = tmp1 - 1

    ruler = ruler + "\n" + "0"

    tmp2 = 1
    while tmp2 < sizeRuler + 1:
        if tmp2 < 10:
            ruler = ruler + " " * 3 + str(tmp2)
        else:
            ruler = ruler + " " * 2 + str(tmp2)
        tmp2 = tmp2 + 1
    return ruler

def rectangle_fun():
    prompt = "Enter width of rectangle : "
    widthRectangle = int(input(prompt))
    tmp1 = widthRectangle
    tmp2 = widthRectangle

    prompt = "Enter height of rectangle : "
    heightRectangle = int(input(prompt))

    rectangle = "+"

    while heightRectangle > 0:
        while tmp1 > 0:
            rectangle = rectangle + "-" * 3 + "+"
            tmp1 = tmp1 - 1

        rectangle = rectangle + "\n" + "|"
        while tmp2 > 0:
            rectangle = rectangle + " " * 3 + "|"
            tmp2 = tmp2 - 1

        rectangle = rectangle + "\n" + "+"

        tmp2 = widthRectangle
        tmp1 = widthRectangle
        heightRectangle = heightRectangle - 1

        if heightRectangle == 0:
            while tmp2 > 0:
                rectangle = rectangle + "-" * 3 + "+"
                tmp2 = tmp2 - 1

    return rectangle

rectangle = rectangle_fun()
ruler = ruler_fun()

print(ruler)
print(rectangle)


# 最小路径和
# https://leetcode-cn.com/problems/minimum-path-sum/submissions/
class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        dp = [ [0] * (n+1) ] * (m+1)

        for i in range(m-1, -1 , -1):
            for j in range(n-1, -1, -1):
                if j == n-1:
                    dp[i][j] = grid[i][j] + dp[i+1][j]
                    continue
                if i == m-1:
                    dp[i][j] = grid[i][j] + dp[i][j+1]
                    continue
                else:
                    dp[i][j] = grid[i][j] + min(dp[i+1][j], dp[i][j+1])
        # print(dp)
        return dp[0][0]


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

import logging
from datetime import datetime

from sqlalchemy import ForeignKey
from sqlalchemy.dialects import mysql
from sqlalchemy.schema import Column
from sqlalchemy.sql import text
from sqlalchemy.types import TIMESTAMP

from flood.models import db_session, Base, get_id, to_dict
from flood.models.group import Group

logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger(__name__)

dateformat = '%Y-%m-%dT%H:%M:%S'

class User(Base):
    __tablename__ = 'users'

    id = Column(
        mysql.VARCHAR(length=64), default=get_id, primary_key=True
    )
    name = Column(
        mysql.VARCHAR(length=128), nullable=False
    )
    email = Column(
        mysql.VARCHAR(length=128), nullable=False
    )
    pswd = Column(
        mysql.VARCHAR(length=128), nullable=False
    )
    adm = Column(
        mysql.BOOLEAN, nullable=True
    )
    created_at = Column(
        TIMESTAMP, server_default=text('CURRENT_TIMESTAMP'), nullable=False, index=True
    )

    def __repr__(self):
        return f"<User(id={self.id}, name={self.name})>"

    def to_dict(self):
        result = {
            "id": self.id,
            "name": self.name,
            "email": self.email,
            "adm": self.adm,
            "created_at": None
        }
        if self.created_at is not None:
            result['created_at'] = self.created_at.isoformat()

        return result

def buid_object_from_row(row):
    user = User(
        name=row.get("name", None),
        id=row.get("id", None),
        email=row.get("email", None),
        pswd=row.get("pswd", None),
        adm=row.get("adm", None),
    )
    if "created_at" in row.keys():
        user.created_at = datetime.strptime(row["created_at"], dateformat)

    return user

@db_session
def create(session, user):
    _logger.info(
        "CREATING_USER_MODEL: {}".format(user),
    )
    result = User(
        name=user.get("name"),
        email=user.get("email"),
        pswd=user.get("pswd"),
        adm=user.get("adm", False)
    )
    session.add(result)

    session.flush()
    r = to_dict(result)
    session.commit()
    return buid_object_from_row(r)

@db_session
def list(session):
    _logger.info(
        "LISNTING_USER_MODEL",
    )

    data = []

    result = session.query(User).all()

    if result is None:
        return data
    else:
        for row in result:
            r = to_dict(row)
            data.append(buid_object_from_row(r))
        return data

@db_session
def get(session, id):
    _logger.info(
        "GETTING_USER_MODEL: {}".format(id),
    )
    result = session.query(User).get(id)
    if result is None:
        return None
    else:
        r = to_dict(result)
        return buid_object_from_row(r)

@db_session
def get_by_email(session, email):
    _logger.info(
        "GETTING_USER_MODELBY_EMAIL: {}".format(id),
    )
    result = session.query(User).filter(User.email == email).first()
    if result is None:
        return None
    else:
        r = to_dict(result)
        return buid_object_from_row(r)

@db_session
def delete(session, user_id):
    _logger.info(
        "DELETING_USER_MODEL: {}".format(user_id),
    )
    x = session.query(User).get(user_id)
    r = to_dict(x)
    session.delete(x)
    session.commit()
    return buid_object_from_row(r)


from Decoding import decode

def parseLayout(layout):
    crosswordSize = len(layout)
    crossword = [[] for x in range(crosswordSize)]
    for i in range(crosswordSize):
        cleanLayoutLine = layout[i].replace(';','')
        for k in range(len(cleanLayoutLine)):
            if (cleanLayoutLine[k] is '#'):
                crossword[i].append(cleanLayoutLine[k])
            else:
                crossword[i].append(None)
    print('Parsed layout: ', crossword)
    return crossword

def checkColumnsValidity(words):
    crossword = [['#', 'a', 'b'], ['c', 'a', 'b'], ['a', '#', 'a']]
    crosswordSize = len(crossword)
    columnStrings = []
    for i in range(crosswordSize):
        columnValues = []
        for k in range(crosswordSize):
            cellValue = crossword[k][i]
            if (cellValue is not None):
                columnValues.append(cellValue)
        separateStrings = (''.join(columnValues)).split('#')
        columnStrings.append(separateStrings)
    print('Column strings', columnStrings)
    for i in range(len(columnStrings)):
        for k in range(len(columnStrings[i])):
            if (columnStrings[i][k] is '' or columnStrings[i][k] in words):
                print(columnStrings[i][k])
            else:
                return False
    return True

def putWordsInRows(crossword, words):
    wordsCopy = [x for x in words]
    rowsWords = [[] for x in range(len(crossword))]
    for i in range(len(crossword)):
        words = []
        for k in range(len(crossword)):
            if (crossword[i][k] is not '#'):
                words.append(crossword[i][k])
            else:
                rowsWords[i].append(words)
                words = []
        rowsWords[i].append(words)

    filledCrossword = [[] for x in range(len(crossword))]
    for i in range(len(rowsWords)):
        for k in range(len(rowsWords[i])):
            worldLength = len(rowsWords[i][k])
            if worldLength > 0:
                for x in range(len(wordsCopy)):
                    if (len(wordsCopy[x]) is worldLength):
                        pickedWord = wordsCopy.pop(x)
                        filledCrossword[i].append(pickedWord)
                        break
    print('Filled', filledCrossword)

if __name__ == '__main__':
    print('Starting CrosswordCreator')
    (words, layout) = decode()
    print('\nLayout: ', layout)
    print('Words: ', words)
    crossword = parseLayout(layout)
    columnsValid = checkColumnsValidity(words)
    putWordsInRows(crossword, words)
    print('Are columns valid?', columnsValid)


from typing import List
from collections import defaultdict

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:

        stop2route = defaultdict(list, [])

        for i, r in enumerate(routes):
            for stop in r:
                stop2route[stop].append(i)

        stop2remove = []
        for stop, route in stop2route.items():
            if len(route) == 1 and stop != S and stop != T:
                stop2remove.append( (stop, route[0]) )
        for s, r in stop2remove:
            stop2route.pop(s)
            routes[r].remove(s)

        del stop2remove

        print(stop2route)

        # initialize the queue with all possible stops from the bus originated from the stop S
        queue = []
#        queue = [ stop for stop in routes[r] for r in stop2route[S] ]
        for r in stop2route[S]:
            queue.extend([ (1, stop) for stop in routes[r] if stop != S])
        # keep a record of buses taken
        #taken = set(stop2route[S])
        #
        visited = set([S])

        while queue:
            print(queue)
            k, curr = queue.pop(0)
            if curr == T:
                return k
            #visited.add(curr)
            for r in stop2route[curr]:
                #if r not in taken:
                #    queue.extend([(k+1, stop) for stop in routes[r] if stop != curr and stop not in visited])
                queue.extend([(k+1, stop) for stop in routes[r] if stop != curr and stop not in visited])

        return -1

if __name__ == '__main__':
    sol = Solution()

    input_list = [
        {"routes": [[1, 2, 7], [3, 6, 7]], 'S': 1, 'T': 6},
    ]

    for inp in input_list:
        result = sol.numBusesToDestination(**inp)
        print(result)


# 文本词频统计 -- Hamlet

def getText():
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_’‘“”{|}~`':
        txt = txt.replace(ch,' ')
    return txt

hamletText=getText()
words = hamletText.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)

for i in range(10):
    print(items[i][0])


import sublime
import sublime_plugin

prnt = lambda x: window.run_command('my',{'a':x})

class My(sublime_plugin.TextCommand):
	def run(self, edit, **args):
		print('Hello, World!',args['a'])
		#sublime.message_dialog('Hello')
		sublime.status_message('Hello')
		#self.view.insert(edit, 0, "Hello, World!")

		window = sublime.active_window()
		nnn=window.create_output_panel('nnn')
		window.run_command('show_panel',dict(panel='nnn'))
		#sublime.active_window().run_command('show_panel',dict(panel='find_in_files'))


import streamlit as st
import numpy as np
import pandas as pd
import altair as alt
from scipy import stats
import plotly.express as px
from plotly import tools
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import StandardScaler

hide_streamlit_style = """
					<style>
					#MainMenu {visibility: hidden;}
					footer {visibility: hidden;}
					</style>
					"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

Games_url = ('s3://nbabdata/games.csv')
Games_details_url = ('s3://nbabdata/games_details.csv')
players_url = ('s3://nbabdata/players.csv')
rankings_url = ('s3://nbabdata/ranking.csv')
teams_url = ('s3://nbabdata/teams.csv')

@st.cache(allow_output_mutation=True)
def load_data4():
    df = pd.read_csv(Games_url)
    return df

@st.cache(allow_output_mutation=True)
def load_data5():
    df = pd.read_csv(Games_details_url)
    return df

@st.cache(allow_output_mutation=True)
def load_data6():
    df = pd.read_csv(players_url)
    return df

@st.cache(allow_output_mutation=True)
def load_data7():
    df = pd.read_csv(rankings_url)
    return df

@st.cache(allow_output_mutation=True)
def load_data8():
    df = pd.read_csv(teams_url)
    return df

games_df = load_data4()
games_details_df = load_data5()
players_df = load_data6()
rankings_df = load_data7()
teams_df = load_data8()

def main():

	analysis = ['Match analysis','Match Details analysis','Top attributes players']
	play_type = ['Attacking', 'Defending']
	options = ['Single Player Analysis','Players Comparision']
	teams = rankings_df['TEAM'].unique()
	unique = games_details_df['PLAYER_NAME'].unique()
	equiv = {12020:202021, 12019:201920, 22019:201920, 12018:201819, 22018:201819, 12017:201718, 22017:201718, 12016:201617, 22016:201617, 12015:201516, 22015:201516, 12014:201415, 22014:201415, 12013:201314, 22013:201314, 12012:201213, 22012:201213, 12011:201112, 22011:201112, 12010:201011, 22010:201011, 12009:200910, 22009:200910, 12008:200809, 22008:200809, 12007:200708, 22007:200708, 12006:200607, 22006:200607, 12005:200506, 22005:200506, 12004:200405, 22004:200405, 12003:200304, 22003:200304, 12002:200203, 22002:200203}
	rankings_df["Season"] = rankings_df["SEASON_ID"].map(equiv).astype(int)
	seasons = rankings_df['Season'].unique()
	teams_eq = {1610612737:'Hawks',1610612738:'Celtics',1610612740:'Pelicans',1610612741:'Bulls',1610612742:'Mavericks',1610612743:'Nuggets',1610612745:'Rockets',1610612746:'Clippers',1610612747:'Lakers',1610612748:'Heat',1610612749:'Bucks',1610612750:'Timberwolves',1610612751:'Nets',1610612752:'Knicks',1610612753:'Magic',1610612754:'Pacers',1610612755:'76ers',1610612756:'Suns',1610612757:'Trail Blazers',1610612758:'Kings',1610612759:'Spurs',1610612760:'Thunder',1610612761:'Raptors',1610612762:'Jazz',1610612763:'Grizzlies',1610612764:'Wizards',1610612765:'Pistons',1610612766:'Hornets',1610612739:'Cavaliers',1610612744:'Warriors'}
	games_df["HomeTeam"] = games_df["HOME_TEAM_ID"].map(teams_eq).astype(str)
	games_df["VisitingTeam"] = games_df["VISITOR_TEAM_ID"].map(teams_eq).astype(str)
	games_df['Match'] = games_df['HomeTeam'] + ' '+'vs' + ' '+ games_df['VisitingTeam']
	stats_cols = {
    'FGM':'Field Goals Made',
    'FGA':'Field Goals Attempted',
    'FG_PCT':'Field Goal Percentage',
    'FG3M':'Three Pointers Made',
    'FG3A':'Three Pointers Attempted',
    'FG3_PCT':'Three Point Percentage',
    'FTM':'Free Throws Made',
    'FTA':'Free Throws Attempted',
    'FT_PCT':'Free Throw Percentage',
    'OREB':'Offensive Rebounds',
    'DREB':'Defensive Rebounds',
    'REB':'Rebounds',
    'AST':'Assists',
    'TO':'Turnovers',
    'STL':'Steals',
    'BLK':'Blocked Shots',
    'PF':'Personal Foul',
    'PTS':'Points',
    'PLUS_MINUS':'Plus-Minus'
	}
	stat_col = {
	'PTS_home': 'Points made HomeTeam',
	'PTS_away': 'Points made AwayTeam',
	'FG_PCT_home':'Field Goal Percentage HomeTeam',
	'FT_PCT_home':'Free Throw Percentage HomeTeam',
	'FG3_PCT_home': 'Three Point Percentage HomeTeam',
	'AST_home': 'Assists HomeTeam',
	'REB_home': 'Rebounds HomeTeam',
	'FG_PCT_away':'Field Goal Percentage AwayTeam',
	'FT_PCT_away':'Free Throw Percentage AwayTeam',
	'FG3_PCT_away': 'Three Point Percentage AwayTeam',
	'AST_away': 'Assists AwayTeam',
	'REB_away': 'Rebounds AwayTeam'
	}
	attributes = ['Field Goal Percentage HomeTeam','Free Throw Percentage HomeTeam','Three Point Percentage HomeTeam','Assists HomeTeam','Rebounds HomeTeam','Field Goal Percentage AwayTeam','Free Throw Percentage AwayTeam','Three Point Percentage AwayTeam','Assists AwayTeam','Rebounds AwayTeam']
	attributes_players = ['Three Pointers Made','Free Throws Made','Offensive Rebounds','Defensive Rebounds','Rebounds','Assists','Turnovers','Steals','Blocked Shots','Personal Foul']
	games_details_df_new = rename_df(games_details_df, stats_cols)
	games_df_new = rename_df(games_df, stat_col)
	page = st.sidebar.selectbox("Choose a page", ["Homepage", "Stats Exploration", "Players Comparision", "Scout Watch"])
	if page == "Homepage":
		st.header("This is an advance basketball data explorer.")
		st.write("Please select a page on the left for different analysis.")
		st.markdown("![Alt Text](https://media.tenor.com/images/07002ec173d710cf8309cc1a91e0f7d9/tenor.gif)")
	elif page == "Stats Exploration":
		st.title("Advanced Match Stats Exploration")
		option = st.selectbox('Choose the type of analysis', analysis )
		if option == 'Match analysis':
			col1,col2,col3= st.beta_columns(3)
			col4,col5,col6 = st.beta_columns(3)
			with col1:
				match= st.selectbox("Choose a Match", games_df_new['Match'].unique())
			with col3:
				season = st.selectbox("Choose a season", games_df_new['SEASON'].unique())
			with col5:
				submit = st.button('Submit')
			if submit:
				visualize_matches(games_df_new,season,match)
		elif option == 'Match Details analysis':
			st.header('Choose the player for his stats in a match')
			col1,col2,col3= st.beta_columns(3)
			col4,col5,col6 = st.beta_columns(3)
			with col1:
				player = st.selectbox("Type in to choose a player", unique)
			with col2:
				match = st.selectbox('Type in to choose the match', games_df_new['Match'].unique())
			with col3:
				season = st.selectbox("Choose the season", games_df_new['SEASON'].unique())
			with col5:
				submit = st.button('Submit')
			if submit:
				visualize_players(games_details_df_new, games_df_new, season, player, match)
		elif option == 'Top attributes players':
			st.header('Choose the attribute for top players of the season')
			col1,col2,col3= st.beta_columns(3)
			col4,col5,col6 = st.beta_columns(3)
			with col1:
				att = st.selectbox("Type in to choose the attribute", attributes_players)
			with col3:
				season = st.selectbox("Choose the season", games_df_new['SEASON'].unique())
			with col5:
				submit = st.button('Submit')
			if submit:
				visualize_top_players(games_details_df_new, games_df_new, season, att)

	elif page == "Players Comparision":
		st.title("Players comparision and player analysis")
		sub = st.selectbox("Choose the option of comparision or single player analysis", options)
		col7,col8,col9 = st.beta_columns(3)
		col10,col11 = st.beta_columns(2)
		if sub == 'Players Comparision':
			with col7:
				player_1 = st.selectbox("Choose the first player", unique)
			with col8:
				player_2 = st.selectbox("Choose the second player", unique)
			with col9:
				player_season = st.selectbox("Choose the season", games_df_new['SEASON'].unique())
			visualize_two_players(games_details_df_new, games_df_new, player_1, player_2, player_season)
		elif sub == 'Single Player Analysis':
			with col10:
				player_1 = st.selectbox("Choose the player for analysis", unique)
			with col11:
				player_season = st.selectbox("Choose the season", games_df_new['SEASON'].unique())
			visualize_single_player(games_details_df_new,games_df_new, player_1, player_season)

	elif page == "Scout Watch":
		st.title('Top players of NBA and their ratings of the season')
		season = st.selectbox("Choose the season",games_df_new['SEASON'].unique())
		submit = st.button('Submit')
		if submit:
			show_top_players(games_details_df_new,games_df_new,season)

def visualize_matches(df,season,match):
	season_df = df[df['SEASON'] == season]
	match_df = season_df[season_df['Match'] == match]
	match_df = match_df.drop(['GAME_ID','HOME_TEAM_ID','VISITOR_TEAM_ID','TEAM_ID_home','SEASON','TEAM_ID_away'],axis=1)
	st.subheader('Detailed Stats')
	st.write(match_df)
	attributes = ['Points made HomeTeam','Points made AwayTeam','Assists HomeTeam','Rebounds HomeTeam','Assists AwayTeam','Rebounds AwayTeam']
	col1,col2,col3 = st.beta_columns(3)
	rel_df = match_df[attributes]
	sums = rel_df.sum()
	colors = ['red','orange']*5
	with col1:
		fig = go.Figure(data=[go.Bar(
					name = match,
					x = attributes,
					y = sums,
					marker_color = colors
					)
					])
		fig.update_layout(height=500,width=800)
		fig.update_layout(
    				title={
        			'text': 'Summary stats of all the' + ' ' + ' ' + str(match) + ' ' +'played in '+' '+ str(season),
        			'y':0.98,
        			'x':0.40,
        			'xanchor': 'center',
        			'yanchor': 'top'})
		st.plotly_chart(fig)

def visualize_players(games_details_df_new, games_df_new, season, player, match):
	player_df = games_details_df_new[games_details_df_new['PLAYER_NAME'] == player]
	merged_df = player_df.merge(games_df_new, on='GAME_ID')
	merged_match_df = merged_df[merged_df['Match'] == match]
	merge_df = merged_match_df[merged_match_df['SEASON'] == season]
	if merge_df.empty:
		st.write('No data available')
		return None
	st.subheader('Detailed Stats')
	st.write(merge_df.drop(['GAME_ID','TEAM_ID','PLAYER_ID','HOME_TEAM_ID','VISITOR_TEAM_ID','TEAM_ID_home','TEAM_ID_away'],axis=1))
	attributes = ['Points made HomeTeam','Points made AwayTeam','Assists HomeTeam','Rebounds HomeTeam','Assists AwayTeam','Rebounds AwayTeam','Field Goals Made','Field Goals Attempted','Three Pointers Made','Three Pointers Attempted','Free Throws Made','Free Throws Attempted','Offensive Rebounds','Defensive Rebounds','Rebounds','Assists','Turnovers','Steals','Blocked Shots','Personal Foul','Points',]
	col1,col2,col3 = st.beta_columns(3)
	rel_df = merge_df[attributes]
	sums = rel_df.sum()
	colors = ['red','orange']*10
	with col1:
		fig = go.Figure(data=[go.Bar(
					name = match,
					x = attributes,
					y = sums,
					marker_color = colors
					)
					])
		fig.update_layout(height=500,width=800)
		fig.update_layout(
    				title={
        			'text': 'Summary of all the' + ' '+ str(player) + ' '+'stats' +' '+ str(match) + ' ' +'played in '+' '+ str(season),
        			'y':0.98,
        			'x':0.40,
        			'xanchor': 'center',
        			'yanchor': 'top'})
		st.plotly_chart(fig)
	ppg = rel_df['Points'].sum() / len(rel_df)
	ppg_ht = rel_df['Points made HomeTeam'].sum() / len(rel_df)
	ppg_at = rel_df['Points made AwayTeam'].sum() / len(rel_df)
	apg = rel_df['Assists'].sum() / len(rel_df)
	apg_ht = rel_df['Assists HomeTeam'].sum() / len(rel_df)
	apg_at = rel_df['Assists AwayTeam'].sum() / len(rel_df)
	col4,col5,col6,col7,col8,col9 =st.beta_columns(6)
	with col4:
		st.write('Points per game by player {}'.format(str(ppg)))
	with col5:
		st.write('Points per game by HT {}'.format(str(ppg_ht)))
	with col6:
		st.write('Points per game by AT {}'.format(str(ppg_at)))
	with col7:
		st.write('Assists per game by player {}'.format(str(apg)))
	with col8:
		st.write('Assists per game by HT {}'.format(str(apg_ht)))
	with col9:
		st.write('Assists per game by AT {}'.format(str(apg_at)))

def rename_df(df, col_dict):
    cols = df.columns
    new_cols = [(col_dict[c] if c in col_dict else c) for c in cols]
    df.columns = new_cols
    return df

def visualize_two_players(games_details_df_new, games_df_new, player_1, player_2, player_season):
	player1_df = games_details_df_new[games_details_df_new['PLAYER_NAME'] == player_1]
	merged1_df = player1_df.merge(games_df_new, on='GAME_ID')
	merge1_df = merged1_df[merged1_df['SEASON'] == player_season]
	player2_df = games_details_df_new[games_details_df_new['PLAYER_NAME'] == player_2]
	merged2_df = player2_df.merge(games_df_new, on='GAME_ID')
	merge2_df = merged2_df[merged2_df['SEASON'] == player_season]
	if merge1_df.empty:
		st.write('No data available')
		return None
	if merged2_df.empty:
		st.write('No data available')
		return None
	attributes = ['Three Pointers Made','Free Throws Made','Offensive Rebounds','Defensive Rebounds','Rebounds','Assists','Turnovers','Steals','Blocked Shots','Personal Foul']
	col1,col2,col3,col4 = st.beta_columns(4)
	rel1_df = merge1_df[attributes]
	sums1 = rel1_df.sum()
	rel2_df = merge2_df[attributes]
	sums2 = rel2_df.sum()

	with col1:
		data = [go.Scatterpolar(
  					r = sums1,
  					theta = attributes,
  					fill = 'toself',
  					name= str(player_1),
     				line =  dict(
            		color = 'orange'
        				)
					),
					go.Scatterpolar(
  					r = sums2,
  					theta = attributes,
  					fill = 'toself',
  					name= str(player_2),
     				line =  dict(
            		color = 'red'
        				)
					)]

		layout = go.Layout(
  					polar = dict(
    				radialaxis = dict(
      				visible = True,
      				range = [0, 1000]
    				)
  				),
  					showlegend = True,
  					title = "{} vs {} Summary Stats Comparison of {}".format(str(player_1), str(player_2), player_season)
				)
		fig = go.Figure(data=data, layout=layout)
		st.plotly_chart(fig)
		merge1_df = merge1_df.drop(['GAME_ID','TEAM_ID','PLAYER_ID','HOME_TEAM_ID','VISITOR_TEAM_ID','TEAM_ID_home','TEAM_ID_away'],axis=1)
		merge2_df = merge2_df.drop(['GAME_ID','TEAM_ID','PLAYER_ID','HOME_TEAM_ID','VISITOR_TEAM_ID','TEAM_ID_home','TEAM_ID_away'],axis=1)
		horizontal_df = pd.concat([merge1_df.T, merge2_df.T],axis =1)
	with col4:
		colors = ['red','orange']*10
		attributes = ['Field Goals Made','Field Goals Attempted','Three Pointers Made','Three Pointers Attempted','Free Throws Made','Free Throws Attempted','Points']
		rel1_df = merge1_df[attributes]
		sums1 = rel1_df.sum()
		rel2_df = merge2_df[attributes]
		sums2 = rel2_df.sum()
		fig = go.Figure(data=[go.Bar(
					name = player_1,
					x = attributes,
					y = sums1
					),
					go.Bar(
							name = player_2,
							x = attributes,
							y = sums2
							)
					])
		fig.update_layout(yaxis={'categoryorder':'total ascending'})
		fig.update_layout(barmode='stack')
		fig.update_layout(height=500,width=550)
		fig.update_layout(
    				title={
        			'text': 'Additional summary stats of the' + ' ' + str(player_1) + ' '+'and'+' '+str(player_2)+' '+'in ' +' '+ str(player_season),
        			'y':0.98,
        			'x':0.40,
        			'xanchor': 'center',
        			'yanchor': 'top'})
		st.plotly_chart(fig)
	st.subheader('Match by match details')
	st.write(horizontal_df)

def visualize_single_player(games_details_df_new,games_df_new, player_1, player_season):
	player_df = games_details_df_new[games_details_df_new['PLAYER_NAME'] == player_1]
	merged_df = player_df.merge(games_df_new, on='GAME_ID')
	merge_df = merged_df[merged_df['SEASON'] == player_season]
	if merge_df.empty:
		st.write('No data available')
		return None
	attributes = ['Three Pointers Made','Free Throws Made','Offensive Rebounds','Defensive Rebounds','Rebounds','Assists','Turnovers','Steals','Blocked Shots','Personal Foul']
	attributes_name = ['PLAYER_NAME','Three Pointers Made','Free Throws Made','Offensive Rebounds','Defensive Rebounds','Rebounds','Assists','Turnovers','Steals','Blocked Shots','Personal Foul']
	col1,col2,col3,col4 = st.beta_columns(4)
	col5,col6 = st.beta_columns(2)
	all_merged_df = games_details_df_new.merge(games_df_new, on='GAME_ID')
	all_merge_df = all_merged_df[all_merged_df['SEASON'] == player_season]
	all_rel_df = all_merge_df[attributes_name]
	group_df = all_rel_df.groupby('PLAYER_NAME').sum().reset_index()
	nn_data = group_df.drop('PLAYER_NAME',axis=1)
	model = NearestNeighbors(algorithm = 'ball_tree', n_neighbors=12)
	model.fit(nn_data)
	ind = group_df[group_df['PLAYER_NAME']==player_1].index.tolist()[0]
	indices = model.kneighbors(nn_data)[1]
	df = pd.DataFrame(columns=['Recommended players'])
	def recommend_me(ind,df):
		for i in indices[ind][1:]:
			df = df.append({'Recommended players': (group_df.iloc[i]['PLAYER_NAME'])},ignore_index=True)
		return df
	with col6:
		st.write('Recommended players list of the season')
		st.write(recommend_me(ind,df))

	rel_df = merge_df[attributes]
	sums = rel_df.sum()
	with col1:
		data = [go.Scatterpolar(
  				r = sums,
  				theta = attributes,
  				fill = 'toself',
  				name= str(player_1),
     			line =  dict(
            	color = 'orange'
        		)
			)]

		layout = go.Layout(
  				polar = dict(
    			radialaxis = dict(
      			visible = True,
      			range = [0, 1000]
    			)
  			),
  				showlegend = True,
  				title = "{} stats distribution in {}".format(player_1,player_season)
			)
		fig = go.Figure(data=data, layout=layout)
		st.plotly_chart(fig)
	with col4:
		colors = ['red','orange']*10
		attributes = ['Field Goals Made','Field Goals Attempted','Three Pointers Made','Three Pointers Attempted','Free Throws Made','Free Throws Attempted','Points']
		rel_df = merge_df[attributes]
		sums = rel_df.sum()
		fig = go.Figure(data=[go.Bar(
					name = player_1,
					x = attributes,
					marker_color = colors,
					y = sums
					)
					])
		fig.update_layout(yaxis={'categoryorder':'total ascending'})
		fig.update_layout(height=500,width=550)
		fig.update_layout(
    				title={
        			'text': 'Additional summary stats of the' + ' ' + str(player_1) + ' '+'in ' +' '+ str(player_season),
        			'y':0.98,
        			'x':0.40,
        			'xanchor': 'center',
        			'yanchor': 'top'})
		st.plotly_chart(fig)
	st.subheader('Detailed match by match stats')
	st.write(merge_df)

def show_top_players(games_details_df_new,games_df_new,season):
	merged_df = games_details_df_new.merge(games_df_new, on='GAME_ID')
	season_data = merged_df[merged_df['SEASON'] == season]
	group_df = season_data.groupby('PLAYER_NAME').sum().reset_index()
	group_df['performance_index'] = group_df['Points'] + group_df['Field Goal Percentage'] + group_df['Three Point Percentage'] + group_df['Free Throw Percentage'] + group_df['Offensive Rebounds'] + group_df['Defensive Rebounds'] + group_df['Rebounds'] + group_df['Steals'] + group_df['Assists'] + group_df['Turnovers'] - group_df['Personal Foul']
	group_df.sort_values(by=['performance_index'], ascending=False,inplace=True)
	group_df['performance_index'] = (group_df['performance_index'] - group_df['performance_index'].min()) / (group_df['performance_index'].max() - group_df['performance_index'].min()) * 9 + 0.46
	df1 = group_df[['PLAYER_NAME', 'performance_index']]
	df1.reset_index(drop=True,inplace=True)
	st.write(df1)

def visualize_top_players(games_details_df_new, games_df_new, season, att):
	merged_df = games_details_df_new.merge(games_df_new, on='GAME_ID')
	season_data = merged_df[merged_df['SEASON'] == season]
	group_df = season_data.groupby('PLAYER_NAME').sum().reset_index()
	df = group_df.sort_values(by=[att])
	df.fillna(0,inplace = True)
	fig = px.scatter(df, x='Points' ,y=att, color = "Points", size = att , hover_data=['PLAYER_NAME'])
	fig.update_layout(height=500,width=800)
	fig.update_layout(
    				title={
        			'text': 'Top players of the NBA' + ' ' +' '+'having' +' '+ str(att) +' ' + 'in' +' '+ str(season),
        			'y':0.98,
        			'x':0.40,
        			'xanchor': 'center',
        			'yanchor': 'top'})
	st.plotly_chart(fig)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import pandas as pd
import numpy as np
import bs4
import nltk
import urllib
import requests

request = "books.txt"

columns = ['title', 'author', 'rating']

with open(request) as f:
    #read and load books
    text = f.read()
    books = [s for s in text.splitlines()]

url = "https://www.commonsensemedia.org/book-reviews/pride-and-prejudice"

url_get = requests.get(url)
soup = bs4.BeautifulSoup(url_get.content, 'html.parser')

ed_value = soup.find("div", id="content-grid-item-educational")

result = re.sub('[^0-9]','', a)

pos_msg = None
pos_RM = None
violence = None
sex = None
language = None
consumerism = None
Drinking_drug_smoke = None

print(soup.contents)


# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# 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
#
#     https://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.

"""Wrappers for protocol buffer enum types."""

import enum

class CompressionType(enum.IntEnum):
    """
    The ways in which threat entry sets can be compressed.

    Attributes:
      COMPRESSION_TYPE_UNSPECIFIED (int): Unknown.
      RAW (int): Raw, uncompressed data.
      RICE (int): Rice-Golomb encoded data.
    """

    COMPRESSION_TYPE_UNSPECIFIED = 0
    RAW = 1
    RICE = 2

class ThreatType(enum.IntEnum):
    """
    The type of threat. This maps dirrectly to the threat list a threat may
    belong to.

    Attributes:
      THREAT_TYPE_UNSPECIFIED (int): Unknown.
      MALWARE (int): Malware targeting any platform.
      SOCIAL_ENGINEERING (int): Social engineering targeting any platform.
      UNWANTED_SOFTWARE (int): Unwanted software targeting any platform.
    """

    THREAT_TYPE_UNSPECIFIED = 0
    MALWARE = 1
    SOCIAL_ENGINEERING = 2
    UNWANTED_SOFTWARE = 3

class ComputeThreatListDiffResponse(object):
    class ResponseType(enum.IntEnum):
        """
        The type of response sent to the client.

        Attributes:
          RESPONSE_TYPE_UNSPECIFIED (int): Unknown.
          DIFF (int): Partial updates are applied to the client's existing local database.
          RESET (int): Full updates resets the client's entire local database. This means
          that either the client had no state, was seriously out-of-date,
          or the client is believed to be corrupt.
        """

        RESPONSE_TYPE_UNSPECIFIED = 0
        DIFF = 1
        RESET = 2


# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Leonardo Donelli @ Creativi Quadrati
#    Copyright 2014 Leonardo Donelli
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields

class sale_order(orm.Model):
    _inherit = 'sale.order'

    _columns = {
        'allowed_users_ids': fields.many2many(
            'res.users',
            string='Allowed Users',
            groups='base.group_sale_secret_orders',
            help=('Users that can see this order. If left empty, normal rules'
                  ' apply. If you want to make it invisible to everyone, add'
                  ' only yourself as allowed.'),
        ),
    }


from doit.tools import title_with_actions

from doitcmd import BaseCommand

class Copy(BaseCommand):
    cmd_template = 'install {opts} {source} {dest}'
    base_options = {'D': True} # -D / create all leading folders

    def __call__(self, source, dest, **kwargs):
        """return task dict"""
        opts = self.opt_str(self.options, kwargs)

        cmd = self.cmd_template.format(opts=opts, source=source, dest=dest)
        return {
            'name': '{}'.format(dest),
            'actions': [self.action(cmd)],
            'file_dep': [source],
            'targets': [dest],
            'title': title_with_actions,
            }


import datetime
from django.db.transaction import atomic

from SocialApp.models import Slide, Friend
from UserApp.models import User
from UserApp.models import Profile
from common import keys
from common import errors
from libs.cache import rds
from Tantan import config

def rcmd_from_queue(uid):
    '''从推荐列表进行推荐'''
    # 结果是2进制列表,取20个
    uid_list = rds.lrange(keys.FIRST_RCMD_Q % uid, 0, 19)
    # 转换成int类型
    uid_list = [int(uid) for uid in uid_list]

    users = User.objects.filter(id__in=uid_list)
    return users

def rcmd_from_db(uid, num=20):
    '''从数据库中推荐用户'''
    profile = Profile.objects.get(id=uid)

    # 计算出生日期范围
    today = datetime.date.today()
    earliest_birth = today - datetime.timedelta(days=profile.max_dating_age * 365)
    latest_birth = today - datetime.timedelta(days=profile.min_dating_age * 365)

    # 仅仅获取已经划过的人的sid
    sid_list = Slide.objects.filter(uid=uid).values_list('sid', flat=True)

    users = User.objects.filter(
        location=profile.dating_location,
        gender=profile.dating_gender,
        birthday__range=[earliest_birth, latest_birth]
    ).exclude(id__in=sid_list)[:num]

    return users

def rcmd(uid):
    '''推荐用户'''
    first_users = rcmd_from_queue(uid)
    remain = 20 - len(first_users)
    if remain > 0:
        second_users = rcmd_from_db(uid, num=remain)
        return set(first_users) | set(second_users)
    else:
        return first_users

# 将函数放在事务中执行，出错会自动回滚，成功自动提交

@atomic
def like_someone(uid, sid):
    '''喜欢的人'''
    # 1.添加滑动记录
    Slide.slide(uid=uid, sid=sid, slide_type='like')

    # 2.强制删除优先推荐队列里的id
    rds.lrem(keys.FIRST_RCMD_Q % uid, count=0, value=sid)

    # 给被滑动者添加积分
    rds.zincrby(keys.HOT_RANK, config.SLIDE_SCORE['like'], sid)

    # 3.检查对方是否喜欢自己，如果喜欢那么建立好友关系
    is_like = Slide.is_liked(uid=sid, sid=uid)
    if is_like is True:
        Friend.make_friend(uid, sid)
        return True
    else:
        return False

@atomic
def superlike_someone(uid, sid):
    '''超级喜欢'''
    # 1.添加滑动记录
    Slide.slide(uid=uid, sid=sid, slide_type='superlike')

    # 2.强制删除优先推荐队列里的id
    rds.lrem(keys.FIRST_RCMD_Q % uid, count=0, value=sid)

    # 给被滑动者添加积分
    rds.zincrby(keys.HOT_RANK, config.SLIDE_SCORE['superlike'], sid)

    # 3.检查对方是否喜欢自己，如果喜欢那么建立好友关系
    is_like = Slide.is_liked(uid=sid, sid=uid)
    if is_like is True:
        Friend.make_friend(uid, sid)
        return True
    elif is_like is False:
        return False
    else:
        # 对方没有滑到自己，将自己添加到对方的优先推荐队列
        rds.lpush(keys.FIRST_RCMD_Q % sid, uid)
        return False

def dislike_someone(uid, sid):
    '''不喜欢'''
    # 1.添加滑动记录
    Slide.slide(uid=uid, sid=sid, slide_type='dislike')

    # 2.强制删除优先推荐队列里的id
    rds.lrem(keys.FIRST_RCMD_Q % uid, count=0, value=sid)

    # 给被滑动者添加积分
    rds.zincrby(keys.HOT_RANK, config.SLIDE_SCORE['dislike'], sid)

def rewind_slide(uid):
    '''反悔(每天3次，5分钟内)'''
    now_time = datetime.datetime.now()
    today = now_time.date()
    rewind_key = keys.REWIND_K % (today, uid)

    # 检查是否已经3次
    rewind_num = rds.get(rewind_key, 0)
    if rewind_num >= config.REWIND_TIMES:
        raise errors.RewindLimit

    # 检查最后一次滑动是否在5分钟内
    last_slide = Slide.objects.filter(uid=uid).latest('slide_time')

    if now_time > last_slide.slide_time + datetime.timedelta(minutes=config.REWIND_TIMEOUT):
        raise errors.RewindTimeout

    # 将多次数据修改在事务中执行
    with atomic():

        # 检查是否是好友
        if last_slide.slide_type in ['like', 'superlike']:
            Friend.broken(uid, last_slide.sid)

            if last_slide.slide_type == 'superlike':
                # 从对方的推荐列表里删除我的id
                rds.lrem(keys.FIRST_RCMD_Q % last_slide.sid, count=0, value=uid)

        # 撤回被滑动者的积分
        score = config.SLIDE_SCORE[last_slide.slide_type]
        rds.zincrby(keys.HOT_RANK, -score, last_slide.sid)

        # 删除最后一次滑动
        last_slide.delete()

        # 设置缓存，反悔次数加一
        rds.set(rewind_key, rewind_num + 1, 86400)

def get_top_n(RANK_NUM):
    '''获取排行榜前n名的用户数据'''
    # 从redis里取出原始数据
    origin_data = rds.zrevrange(keys.HOT_RANK, 0, RANK_NUM - 1, withscores=True)
    # 原始数据转换成int类型
    cleaned_data = [[int(uid), int(score)] for uid, score in origin_data]

    # 用户的id列表
    uid_list = [item[0] for item in cleaned_data]

    # 数据库取数据
    users = User.objects.filter(id__in=uid_list)
    users = sorted(users, key=lambda user: uid_list.index(user.id))

    # 整理数据
    rank_data = []
    for index, (uid, score) in enumerate(cleaned_data):
        rank = index + 1
        user = users[index]
        user_data = user.to_dict(exclude=['phonenum', 'birthday', 'location',
                                          'vip_id', 'vip_end'])
        user_data['rank'] = rank
        user_data['score'] = score
        rank_data.append(user_data)

    return rank_data


import bpy
from bpy.types import Operator

# Set the pivot point of the active object
# to the center and add a mirror modifier
class FC_MirrorOperator(Operator):
    bl_idname = "object.mirror"
    bl_label = "Center Origin & Mirror"
    bl_description = "Mirror selected object"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):

        mode = context.active_object.mode
        return len(context.selected_objects) == 1 and mode == "OBJECT"

    def execute(self, context):

        cursor_location = bpy.context.space_data.cursor_location.copy()

        bpy.context.scene.cursor_location = (0.0, 0.0, 0.0)
        bpy.ops.object.origin_set(type='ORIGIN_CURSOR')

        bpy.ops.object.modifier_add(type='MIRROR')

        bpy.context.scene.cursor_location = cursor_location

        return {'FINISHED'}


import math

def convert_image_to_ascii(img, compress_var=0, det=0):

    img_in_ascii = []

    compress_img = []

    x = 0

    main_img = compress_img if compress_var != 0 else img

    main_width = int(img.shape[0] / compress_var) if compress_var != 0 else img.shape[0]
    main_height = int(img.shape[1] / compress_var) if compress_var != 0 else img.shape[1]

    if compress_var != 0:

        for i in range(0, img.shape[0]):

            if i % compress_var == 0:

                compress_img.append([])

                for e in range(0, img.shape[1]):

                    if e % compress_var == 0:

                        compress_img[x].append(img[i][e])

                x += 1

    x = 0

    if det != 0:

        arr = [chr(i) for i in range(34, 48)]

        save_pixels = dict()

        counter = 0

        save_pixels[0] = {arr[counter]: [main_img[0][0][0], main_img[0][0][1], main_img[0][0][2]]}

        for i in range(0, main_width):

            img_in_ascii.append([])

            for e in range(0, main_height):

                counter_second = 0
                pos = 0

                for z in range(0, len(save_pixels)):

                    for q in range(0, 3):

                        number = int(math.fabs(int(main_img[i][e][q]) - int(save_pixels[z][arr[z]][q])))

                        if number > det:
                            counter_second += 1

                            break

                        pos = z

                if counter_second == len(save_pixels):

                    counter += 1

                    if counter < len(arr):

                        save_pixels[len(save_pixels)] = {
                            arr[counter]: [main_img[i][e][0], main_img[i][e][1], main_img[i][e][2]]}

                        img_in_ascii[x].append(arr[counter])

                    elif counter >= len(arr):

                        is_found = True

                        det_second = 10

                        while is_found:

                            for u in range(0, len(save_pixels)):

                                for g in range(0, 3):

                                    second_number = int(
                                        math.fabs(int(main_img[i][e][g]) - int(save_pixels[u][arr[u]][g])))

                                    if second_number < det_second:
                                        img_in_ascii[x].append(arr[u])

                                        is_found = False

                            det_second += 20

                elif counter_second != len(save_pixels):

                    img_in_ascii[x].append(arr[pos])

            x += 1

    elif det == 0:

        for i in range(0, main_width):

            img_in_ascii.append([])

            for e in range(0, main_height):

                number = ((int(main_img[i][e][0]) + int(main_img[i][e][1]) + int(main_img[i][e][2])) / int(12)) + 33

                img_in_ascii[x].append(chr(int(number)))

            x += 1

    file = open("converted_pict.txt", "w")

    for i in range(0, main_width):

        for e in range(0, main_height):

            file.write(img_in_ascii[i][e])

        file.write('\n')

    pass


import sys
from datetime import datetime
from datetime import timedelta

fp_in = open(sys.argv[1], 'r')
fp_out = open(sys.argv[2], 'w')

upper_time = datetime.strptime('20000101 00:00:03', '%Y%m%d %H:%M:%S')
now_max = -1
for line in fp_in:
    record = line.split(',')
    if record[0]!='EUR/USD':
        print('Data inconsistent')
        exit(1)

    now_time = datetime.strptime(record[1].split('.')[0], '%Y%m%d %H:%M:%S')
    if now_time > upper_time:
        if now_max > 0:
            print(now_max, file=fp_out)
        now_max = float(record[2])
        upper_time = now_time + timedelta(seconds=3)
    now_max = max(now_max, float(record[2]))

fp_in.close()
fp_out.close()


"""
Linearithmic algorithm for building suffix array.
"""
#import ipdb; ipdb.set_trace()

class SuffixArray:
    """
    Test case from 'http://www.allisons.org/ll/AlgDS/Strings/Suffix/'
    >>> suffix_array = SuffixArray('mississippi')
    >>> suffix_array.suffix
    [10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2]
    """

    def __init__(self, s):
        self.s = s
        self.suffix = None
        self.inverse = None
        self._build_suffix_array()  # generate suffix and inverse array

    def _build_suffix_array(self):
        s = self.s
        n = len(s)
        suffix = list(range(n))
        inverse = list(range(n))
        flag = [False] * n  # check if row is sorted
        suffix.sort(key=lambda x: s[x])
        for i, v in enumerate(suffix):
            inverse[v] = i
        k = 2
        while k < n:
            l = 0
            m = k // 2 - 1  # index of last sorted char
            while l < n:
                if flag[l]:
                    l += 1
                    continue
                r = l + 1
                while r < n and suffix[l]+m<n and suffix[r]+m<n and s[suffix[l]+m]==s[suffix[r]+m]:
                    r += 1
                if r - l == 1:
                    flag[l] = True
                    l += 1
                else:
                    suffix[l:r] = sorted(suffix[l:r], key=lambda x: inverse[x+k//2] if x+k//2<n else -1)
                    l = r
            for i, v in enumerate(suffix):
                inverse[v] = i
            k *= 2
        self.suffix = suffix
        self.inverse = inverse


from typing import Optional, Iterable

from .base import BaseFunction, SyncFunctionMixin
from .request import Request

__all__ = (
    'BaseKeyPair',
    'KeyPair',
)

class BaseKeyPair(BaseFunction):

    @classmethod
    def _create(cls, user_id: int,
                is_active: bool=True,
                is_admin: bool=False,
                resource_policy: Optional[str]=None,
                rate_limit: Optional[int]=None,
                concurrency_limit: Optional[int]=None,
                fields: Optional[Iterable[str]]=None):
        if fields is None:
            fields = ('access_key', 'secret_key')
        q = 'mutation($user_id: Int!, $input: KeyPairInput!) {' \
            '  create_keypair(user_id: $user_id, props: $input) {' \
            '    ok msg keypair { $fields }' \
            '  }' \
            '}'
        q = q.replace('$fields', ' '.join(fields))
        vars = {
            'user_id': user_id,
            'input': {
                'is_active': is_active,
                'is_admin': is_admin,
                'resource_policy': resource_policy,
                'rate_limit': rate_limit,
                'concurrency_limit': concurrency_limit,
            },
        }
        resp = yield Request('POST', '/admin/graphql', {
            'query': q,
            'variables': vars,
        })
        data = resp.json()
        return data['create_keypair']

    @classmethod
    def _list(cls, user_id: int,
              is_active: Optional[bool]=None,
              fields: Optional[Iterable[str]]=None):
        if fields is None:
            fields = (
                'access_key', 'secret_key',
                'is_active', 'is_admin',
            )
        q = 'query($user_id: Int!, $is_active: Boolean) {' \
            '  keypairs(user_id: $user_id, is_active: $is_active) {' \
            '    $fields' \
            '  }' \
            '}'
        q = q.replace('$fields', ' '.join(fields))
        vars = {
            'user_id': user_id,
            'is_active': is_active,
        }
        resp = yield Request('POST', '/admin/graphql', {
            'query': q,
            'variables': vars,
        })
        data = resp.json()
        return data['keypairs']

    @classmethod
    def activate(cls, access_key: str):
        raise NotImplementedError

    @classmethod
    def deactivate(cls, access_key: str):
        raise NotImplementedError

    def __init_subclass__(cls):
        cls.create = cls._call_base_clsmethod(cls._create)
        cls.list = cls._call_base_clsmethod(cls._list)

class KeyPair(SyncFunctionMixin, BaseKeyPair):
    pass


# -*- coding: utf-8 -*-
"""
Éditeur de Spyder

Ceci est un script temporaire.
"""

from pyDatalog import pyDatalog
pyDatalog.clear()
pyDatalog.create_terms('X, eatFiles, green, yellow, croakes, chirps, sings, canary, frog, P')

load("""
""")

frog(X) <= croakes(X) & eatFiles(X)
canary(X) <= chirps(X) & sings(X)
green(X) <= frog(X)
yellow(X) <= canary(X)

pyDatalog.assert_fact('croakes', 'fritz')
pyDatalog.assert_fact('eatFiles', 'fritz')

query = 'frog(X)'
answers = pyDatalog.ask(query).answers
print(answers)


# coding=utf-8
'日志，全局统一用logger'

from logging.handlers import TimedRotatingFileHandler

__author__ = 'Jiateng Liang'
from bootstrap import app

import logging

logger = logging.getLogger(app.config['LOG_NAME'])

fh = TimedRotatingFileHandler(filename=app.config['LOG_PATH'], when="D", interval=1)

if app.config['LOG_LEVEL'] == 'DEBUG':
    logger.setLevel(logging.DEBUG)
    fh.setLevel(logging.DEBUG)
elif app.config['LOG_LEVEL'] == 'INFO':
    logger.setLevel(logging.INFO)
    fh.setLevel(logging.INFO)
elif app.config['LOG_LEVEL'] == 'WARN':
    logger.setLevel(logging.WARN)
    fh.setLevel(logging.WARN)
elif app.config['LOG_LEVEL'] == 'ERROR':
    logger.setLevel(logging.ERROR)
    fh.setLevel(logging.ERROR)

formatter = logging.Formatter(app.config['LOG_FORMAT'], app.config['LOG_DATE_FORMAT'])

fh.setFormatter(formatter)
logger.addHandler(fh)

if app.config['LOG_CONSOLE']:
    console = logging.StreamHandler()
    console.setLevel(app.config['LOG_LEVEL'])
    console.setFormatter(formatter)
    logger.addHandler(console)