# Import the dependencies.
import numpy as np
import pandas as pd
import datetime as dt

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify

#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///Resources/hawaii.sqlite")

# reflect an existing database into a new model
Base = automap_base()

# reflect the tables
Base.prepare(autoload_with=engine)

# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station

# Create our session (link) from Python to the DB
##session = Session(engine)

#################################################
# Flask Setup
#################################################

app = Flask(__name__)

#################################################
# Flask Routes
#################################################

@app.route("/")
def welcome():
    """List all available api routes."""
    return (
        f"
Climate Analysis Data of Honolulu, Hawaii for Trip Planning

"
        f"
Available Routes:

"

        f"1. One year (2016-08-23 -- 2017-08-23) precipitation data:
"
        f"/api/v1.0/precipitation

"

        f"2. List of stations:
"
        f"/api/v1.0/stations

"

        f"3. One year (2016-08-23 -- 2017-08-23) temperature data for the most active station:
"
        f"/api/v1.0/tobs

"

        f"4. To get the minimum, avarage and maximum temperatures for a specific date of your choice,\
            append  the following to the current URL:"
        f"
 /api/v1.0/yyyy-mm-dd
"
        f"where 2010/01/01 <= yyyy-mm-dd <= 2017-08-23.

"

        f"5. To get the minimum, avarage and maximum temperatures for a specific date range of your choice,\
            append  the following to the current URL:"
        f"
 /api/v1.0/yyyy-mm-dd/yyyy-mm-dd
"
        f"where first date < second date and 2010/01/01 <= yyyy-mm-dd <= 2017-08-23."
    )

# 2. Convert the query results from your precipitation analysis
# (i.e. retrieve only the last 12 months of data) to a dictionary using date as the key and prcp as the value.
# Return the JSON representation of your dictionary.

@app.route("/api/v1.0/precipitation")
def precipitation():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    # Find the most recent date in the data set.
    recent_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()

    # Calculate the date one year from the last date in data set.
    year_ago_date = dt.date(2017,8,23) - dt.timedelta(days=365)

    # Perform a query to retrieve the data and precipitation scores
    recent_year_data = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= year_ago_date).all()

    session.close()

    # Convert list of tuples into dictionary
    date_prcp_dict = {}
    for el in recent_year_data:
        date = el[0]
        prcp = el[1]
        date_prcp_dict[date] = prcp

    return jsonify(date_prcp_dict)

# 3. Return a JSON list of stations from the dataset.

@app.route("/api/v1.0/stations")
def stations():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    stations = session.query(Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all()

    session.close()

    stations_list = []
    for el in stations:
        station = el[0]
        name = el[1]
        latitude = el[2]
        longitude = el[3]
        elevation = el[4]
        stations_list.append({"station":station, "name":name, "latitude":latitude, "longitude":longitude, "elevation":elevation})

    return jsonify(stations_list)

# 4. Query the dates and temperature observations of the most-active station for the previous year of data.
#    Return a JSON list of temperature observations for the previous year.

@app.route("/api/v1.0/tobs")
def tobs():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    year_ago_date = dt.date(2017,8,23) - dt.timedelta(days=365)

    station_count = session.query(Measurement.station, func.count(Measurement.station)).group_by(Measurement.station).\
        order_by(func.count(Measurement.station).desc()).all()

    for row in station_count:
        print(row)

    active_st = session.query(Measurement.station, func.count(Measurement.station)).group_by(Measurement.station).\
        order_by(func.count(Measurement.station).desc()).first()
    most_active = active_st[0]

    one_year_temp_active_st = session.query(Measurement.date, Measurement.tobs).filter(Measurement.station==most_active).\
                            filter(Measurement.date >= year_ago_date).all()
    one_year_temp_df = pd.DataFrame(one_year_temp_active_st, columns = ['date', 'tobs'])
    one_year_temp_df.set_index('date', inplace = True)

    session.close()

    tobs_list = []
    for el in one_year_temp_active_st:
        tob_dict = {}
        date = el[0]
        tob = el[1]
        tob_dict[date] = tob
        tobs_list.append(tob_dict)

    return jsonify(tobs_list)

# 5. Return a JSON list of the minimum temperature, the average temperature,
#    and the maximum temperature for a specified start or start-end range.
#    For a specified start, calculate TMIN, TAVG, and TMAX for all the dates greater than or equal to the start date.
#    Accepts the start date as a parameter from the URL
#    Returns the min, max, and average temperatures calculated from the given start date to the end of the dataset
@app.route("/api/v1.0/<start>")
def start(start):
    # Create our session (link) from Python to the DB
    session = Session(engine)

    extreme_avg_temps = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs)).\
                        filter(Measurement.date >= start).all()
    TMIN = extreme_avg_temps[0][0]

    TAVG = extreme_avg_temps[0][1]
    TMAX = extreme_avg_temps[0][2]
    session.close()

    temp_list = []
    temp_dict = {}
    temp_dict["min_temp"] = TMIN
    temp_dict["avg_temp"] = TAVG
    temp_dict["max_temp"] = TMAX
    temp_list.append(temp_dict)

    return jsonify(temp_list)

# 6. Return a JSON list of the minimum temperature, the average temperature,
#    and the maximum temperature for a specified start or start-end range.
#    For a specified start date and end date, calculate TMIN, TAVG, and TMAX for the dates from the start date to the end date,
#    inclusive.
#    Accepts the start and end dates as parameters from the URL.
#    Returns the min, max, and average temperatures calculated from the given start date to the given end date.

@app.route("/api/v1.0/<start>/<end>")
def start_end(start, end):
    # Create our session (link) from Python to the DB
    session = Session(engine)

    extreme_avg_temps = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs)).\
                        filter(Measurement.date >= start).filter(Measurement.date <= end).all()
    TMIN = extreme_avg_temps[0][0]

    TAVG = extreme_avg_temps[0][1]
    TMAX = extreme_avg_temps[0][2]
    session.close()

    temp_list = []
    temp_dict = {}
    temp_dict["min_temp"] = TMIN
    temp_dict["avg_temp"] = TAVG
    temp_dict["max_temp"] = TMAX
    temp_list.append(temp_dict)

    return jsonify(temp_list)

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


from django.urls import path, include
from .views import ClientViewSet, TagViewSet, CodeOperatorViewSet
from rest_framework import routers

router = routers.SimpleRouter()
router.register(r'', ClientViewSet, basename='client')
router.register(r'tag', TagViewSet, basename='tag')
router.register(r'code', CodeOperatorViewSet, basename='code')

urlpatterns = [
    path('', include(router.urls)),
]


from xencio.account_classifier.classifier import AccountClassifier
from collections import defaultdict
import requests

if __name__ == "__main__":
    classifier = AccountClassifier()

    banks = {'工商银行', '建设银行', '中国银行',
             '农业银行', '交通银行', '邮储银行',
             '兴业银行', '广发银行', '民生银行',
             '招商银行', '光大银行', '浦发银行',
             '中信银行'}
    total_dict = defaultdict(int)
    right_dict = defaultdict(int)
    total = 0
    right = 0
    error = 0
    with open('account_data', 'r') as file:
        for line in file.readlines():
            mylist = line.strip().split()
            try:
                if mylist[1] in banks:
                    # result = classifier.check(mylist[0])
                    # result=requests.get("http://ymo.wiki/xencio/account/"+mylist[0])
                    total += 1
                    total_dict[mylist[1]] += 1
                    if result.bank == mylist[1]:
                        right += 1
                        right_dict[result.bank] += 1
            except Exception as E:
                print(E)
                error += 1
    print('Error: ', error)
    print(total_dict)
    print(right_dict)
    print(total)
    print(right)


import struct
import select
import socket
import time
import os
from scapy.arch import get_if_addr
import concurrent.futures
import itertools
import random
from concurrent.futures import ThreadPoolExecutor

MAGIC_COOKIE = 0xabcddcba
MESSAGE_TYPE = 0X2
VIRTUAL_NETWORK = 'eth1'
NUM_OF_TEAMS = 2
SERVER_TCP_PORT = 2075
TIME_LIMIT = 10
BROADCAST_PORT = 13117
BROADCAST_INTERVAL = 1

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def Broadcast(time_limit=TIME_LIMIT, interval=BROADCAST_INTERVAL):
    # create udp socket and send message in Brodcast_port (13117)
    x = socket.gethostbyname(socket.gethostname()) #get ip
    ip = x if os.name == 'nt' else get_if_addr(VIRTUAL_NETWORK)
    print(bcolors.HEADER+"Server started, listening on ip address", bcolors.BOLD+ip+bcolors.ENDC)
    # start_time = time.time()
    ipex =".255.255"
    y = ip.split(".")
    fix_ip=y[0]+"."+y[1]+ipex
    # Open new udp socket
    udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    # Set a timeout
    udp_server.settimeout(0.3)
    # Set broadcasting mode
    udp_server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    # constants vars to determent the Packet Formats
    brodcast_message = struct.pack('IbH', MAGIC_COOKIE, MESSAGE_TYPE, SERVER_TCP_PORT)
    while flag1: #while there is no 2 clinets connected..
        try:
            #send the broadcast message to all..
            udp_server.sendto(brodcast_message, (fix_ip, BROADCAST_PORT))
        except Exception as e:
            print(bcolors.FAIL+"Broadcasting error!"+bcolors.ENDC)
            return False
        time.sleep(interval)
    # the broadcast transmmit is over, close the UDP socket and return to main
    print("end brodcast")
    udp_server.close()
    return True

def listen_for_clients( time_limit=TIME_LIMIT):
    # global var used to stop the broadcast when 2 clients connect.
    global flag1
    flag1 = True
    #Open server socket in SERVER_TCP_PORT and wait for client to connect
    start_time = time.time()
    #Open server socket
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.setblocking(0) # dont block input messeges
    #try to create tcp server to connect the clients.
    while time.time() - start_time < time_limit:
        try:
            serverSocket.bind(('', SERVER_TCP_PORT ))
            break
        except Exception as massage:
            print(bcolors.FAIL+'Bind error. Message:'+bcolors.ENDC, massage)
            time.sleep(1)
    # queue for the amount of client I'm ready to hold..
    serverSocket.listen(5)
    #list of all the open and running sockets
    socketsList = [serverSocket]
    teamIpNameDict = {}  # team_ip : team_name
    i = 0
    flag1 = True
    while socketsList and flag1: #and time.time() - start_time < time_limit:
        readable, writable, exceptional = select.select(socketsList, [], socketsList, 0)
        for sock in readable:
            if sock is serverSocket:
                connection, client_address = sock.accept() # connection 1 socket
                connection.setblocking(0)
                socketsList.append(connection)
                teamIpNameDict[connection] = (None, client_address[0])

            else:  # The client should sent team's name
                data = sock.recv(1024) # Recive data from client
                i += 1
                if i == 2:
                    flag1 = False
                if teamIpNameDict[sock][0] == None:
                    if data:
                        teamIpNameDict[sock] = (str(data, "utf-8")[0:-1], teamIpNameDict[sock][1]) #name
                    else:
                        socketsList.remove(sock) #if there is no data, remove and close socket
                        sock.close()
                else:
                    if data:
                        print("Unexpected data from client")

        # for sock in exceptional:
        #     socketsList.remove(sock)
        #     sock.close()
        time.sleep(0.1)
    serverSocket.setblocking(1)
    return teamIpNameDict, socketsList, serverSocket

def randomQuestion():
    while True:
        x = random.randint(0,9)
        y = random.randint(0,9)

        allops = ['+','-','*']
        op = allops[random.randint(0,2)]
        z = 0
        if op == "+":
          z = x + y
          q = str(x) + "+" + str(y) + "?"
        if op == "-":
          z = max(x,y)-min(x,y)
          q = str(max(x,y)) + "-" + str(min(x,y)) + "?"
        if op == "*":
          z = x*y
          q = str(x) + "*" + str(y) + "?"

        if z > -1 and z < 10:
            tup = (q,z)
            return tup
    print("problem randomQuestion")
    return

def game(teamIpNameDict, sockets, server, time_limit=TIME_LIMIT):
    print('in game')
    time.sleep(10) # wait 10 sec before start the game.
    #print("start game")
    player1 = []
    player2 = []
    teamName1 = ""
    teamName2 = ""
    i = 0
    for player in teamIpNameDict.values():
        if i == 0:
            player1.append(player)
            teamName1 = player[0]
        else:
            player2.append(player)
            teamName2 = player[0]
        i += 1
    #print("player 1 ",player1," player 2 ",player2)
    teams_dictionary = {}
    for player in player1 + player2:
        # {ip1 : (name,gameID), ip2 : (name,gameID)}
        teams_dictionary[player[1]] = (player[0], 1 if player in player1 else 2)

    message = "Welcome to Quick Maths. \nPlayer 1:"
    for player in player1:
        if not player:
            player ="adi" ##################################rmove
        message += player[0]+'\n'
    message += "Player 2:"
    for player in player2:
        if not player:
            player ="ohad" #################################remove
        message += player[0]+'\n==\n'
    message += "Please answer the following question as fast as you can:\nHow much is "

    tup = randomQuestion()
    qusestuin = tup[0]
    realAns = tup[1]
    message += qusestuin
    clinetAddresses = []  # Save clients addresses to send end messages through
    for running_socket in sockets:
        try:
            if running_socket != server:
                # send the end message
                running_socket.sendall(bytes(message, "utf-8"))
                running_socket.setblocking(1)
                # keep the address of the socket(of the client)
                clinetAddresses.append(running_socket.getpeername())
                #close the socket.
                running_socket.close()
        except Exception as e:
            print(bcolors.FAIL+"Error occurred while try to send message to client."+bcolors.ENDC)

    nowTime = time.time()
    finalMessage = ''
    listSockets = [server]
    socket_ips = {}
    flag = False

    # while there is socekts in the list of socktes.
    while listSockets and time.time() - nowTime < time_limit and not flag :
        readable, writable, exceptional = select.select(listSockets, [], listSockets, 0)
        for sock in readable:
            if sock is server:
                connection, client_address = sock.accept() # return who is connect
                connection.setblocking(0)
                listSockets.append(connection)
                socket_ips[connection] = client_address[0]
            else:  # Client send answer
                data = sock.recv(1) # reading anser from client->1 digit
                flag = True # stop the loop
                userAns = data.decode('utf-8')

                # figure who is connected right now
                curP = teams_dictionary[socket_ips[connection]][0]
                if curP == teamName1:
                    secP = teamName2
                else:
                    secP = teamName1
                # print("current player is ,", curP, " and anwser is ", userAns)
                # print("sec player is ,", secP)
                # begin check the answer we got. follow by announced who win the game.
                try :
                    print(realAns)
                    if int(userAns) == realAns: # check if right answer
                        finalMessage= whoWon(curP,realAns)
                        listSockets.remove(sock)
                        sock.close()
                        flag = True
                        print(finalMessage)
                        break
                    else: # the second team will win
                        finalMessage = whoWon(secP,realAns)
                        print(finalMessage)
                        listSockets.remove(sock)
                        sock.close()
                        flag = True
                        break
                except: # if the client didn't send a digit -> auto lose..
                    finalMessage = whoWon(secP,realAns)
                    print(finalMessage)
                    listSockets.remove(sock)
                    sock.close()
                    flag = True
                    break
        time.sleep(0.01)
        for sock in exceptional:
            listSockets.remove(sock)
            sock.close()
    # send the end message to all
    for address in clinetAddresses:
        try:
            if finalMessage == '': # if no one cliams the winning..
                finalMessage = "its a Draw!"
            running_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            running_socket.connect(address)
            running_socket.sendall(bytes(finalMessage, "utf-8"))  # TODO
            #open_socket.setblocking(1)
            running_socket.close()
        except Exception as e:
            print(bcolors.FAIL+"Error while sending end messages!"+bcolors.ENDC)
    # server.setblocking(1)
    server.close()
    # make the UDP server run and transmit again
    flag1=True
    print("game end")

def whoWon(name,ans):
    msg = "\nGame over!\nThe correct answer was " + str(ans) + "!\n"
    msg += "Congratulations to the winner: " + name +"\n"
    return msg

if __name__ == "__main__":
    with concurrent.futures.ThreadPoolExecutor() as executor:
        while 1:
            broadcast1 = executor.submit(Broadcast)

            teams_future = executor.submit(listen_for_clients)
            team_names, sockets, server = teams_future.result()
            if len(sockets)-1 >= NUM_OF_TEAMS:
                match = executor.submit(game(team_names, sockets, server))
                flag1 = True
            else:
                i = 0
                # print("in main, else on len >=2")
                for open_socket in sockets:
                    open_socket.close()
                    print("close socket..")
    executor.shutdown()


#!/usr/bin/python
# coding=utf-8

# File Name: questionMapping.py
# Author   : john
# company  : foxconn
# Mail     : john.y.ke@mail.foxconn.com
# Created Time: 2018/12/25 10:51
# Describe :

from refo import finditer, Predicate, Star, Any, Disjunction    # 正则表达式库
import re

# TODO SPARQL前缀和模板
SPARQL_PREXIX = u"""
    PREFIX : <http://www.poem.com#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX vocab: <http://localhost:2020/resource/vocab/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX map: <http://localhost:2020/resource/#>
    PREFIX db: <http://localhost:2020/resource/>
"""

SPARQL_SELECT_TEM = u"{prefix}\n" + \
             u"SELECT DISTINCT {select} WHERE {{\n" + \
             u"{expression}\n" + \
             u"}}\n"

SPARQL_COUNT_TEM = u"{prefix}\n" + \
             u"SELECT COUNT({select}) WHERE {{\n" + \
             u"{expression}\n" + \
             u"}}\n"

SPARQL_ASK_TEM = u"{prefix}\n" + \
             u"ASK {{\n" + \
             u"{expression}\n" + \
             u"}}\n"

class W(Predicate):
    def __init__(self, token=".*", pos=".*"):
        self.token = re.compile(token + "$")
        self.pos = re.compile(pos + "$")
        super(W, self).__init__(self.match)

    def match(self, word):
        m1 = self.token.match(word.token)
        m2 = self.pos.match(word.pos)
        return m1 and m2

class Rule(object):
    def __init__(self, condition_num, condition=None, action=None):
        assert condition and action
        self.condition = condition
        self.action = action
        self.condition_num = condition_num

    def apply(self, sentence):
        matches = []
        for m in finditer(self.condition, sentence):
            i, j = m.span()
            matches.extend(sentence[i:j])

        return self.action(matches), self.condition_num

# TODO 定义关键词
pos_poet = "nr"   # 诗人名
pos_poem = "nz"  # 诗词名
pos_dynasty = "nt"    # 朝代
pos_verse = "x" # 诗句

poet_entity = (W(pos=pos_poet))
poem_entity = (W(pos=pos_poem))
dynasty_entity = (W(pos=pos_dynasty))
verse_entity = (W(pos=pos_verse))

poem = (W("诗") | W("词") | W("古诗") | W("诗词") | W("文章") | W("作品") | W("诗歌"))
poet = (W("诗人") | W("作者") | W("谁"))
dynasty = (W("朝代") | W("年代") | W("时候") | W("时间") | W("时代"))
content = (W("内容"))
born = (W("出自"))
next_verse = (W("下一句") | W("下句"))
prev_verse = (W("上一句") | W("上句"))

'''1. 某个诗人写了哪些诗
2.某首诗是谁写的
3.哪个诗人是哪个朝代的
4.哪首诗是哪个朝代的
5.哪个朝代有哪些诗
6.哪个朝代有哪些诗人
8.诗歌具体内容
9.诗句是哪个诗人写的
10.诗句出自哪首诗
11.上一句
12.下一句'''
class Question:
    def __init__(self):
        pass

    @staticmethod
    def has_poem_question(word_objects):  # 某个诗人写了哪些诗
        select = u"?x"

        sparql = None
        for w in word_objects:
            if w.pos == pos_poet:
                e = u"?s :poetName '{poet}'." \
                    u"?s :poetProduction  ?m." \
                    u"?m :poemName ?x".format(poet=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def has_poet_question(word_objects):    # 某首诗是谁写的
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_poem:
                e = u"?s :poemName '{poem}'." \
                    u"?a :poetProduction ?s." \
                    u"?a :poetName ?n".format(poem=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def born_poet_question(word_objects):  # 哪个诗人是哪个朝代的
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_poet:
                e = u"?s :poetName '{poet}'." \
                    u"?s :poetDynasty ?n.".format(poet=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def born_poem_question(word_objects):  # 诗歌是哪个朝代的
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_poem:
                e = u"?s :poemName '{poem}'." \
                    u"?m :poetProduction ?s." \
                    u"?m :poetDynasty ?n.".format(poem=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def born_poets_question(word_objects):  # 哪个朝代有哪些诗人
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_dynasty:
                e = u"?s :poetDynasty '{dynasty}'." \
                    u"?s :poetName ?n.".format(dynasty=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def born_poems_question(word_objects):  # 哪个朝代有哪些诗歌
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_dynasty:
                e = u"?s :poetDynasty '{dynasty}'." \
                    u"?s :poetProduction ?m." \
                    u"?m :poemName ?n.".format(dynasty=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def poets_content_question(word_objects):  # 诗歌内容
        select = u"?n"

        sparql = None
        for w in word_objects:
            if w.pos == pos_poem:
                e = u"?s :poemName '{poem}'." \
                    u"?s :poemContent ?n.".format(poem=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def poet_verse_question(word_objects):  # 按句找作者
        select = u"?o"

        sparql = None
        for w in word_objects:
            if w.pos == pos_verse:
                e = u"?s :verseContent '{verse}'." \
                    u"?s :verseIn ?m." \
                    u"?n :poetProduction ?m."\
                    u"?n :poetName ?o.".format(verse=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def poem_verse_question(word_objects):  # 按句查诗
        select = u"?o"

        sparql = None
        for w in word_objects:
            if w.pos == pos_verse:
                e = u"?s :verseContent '{verse}'." \
                    u"?s :verseIn ?m." \
                    u"?m :poemName ?o.".format(verse=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def next_verse_question(word_objects):  # 下一句
        select = u"?o"

        sparql = None
        for w in word_objects:
            if w.pos == pos_verse:
                e = u"?s :verseContent '{verse}'." \
                    u"?s :verseId ?m." \
                    u"?s :sentenceId ?n." \
                    u"?s :verseLen ?l." \
                    u"?k :verseId ?x." \
                    u"?k :sentenceId ?y." \
                    u"?k :verseContent ?o." \
                    u"filter ((?x = ?m) && (?y = ?n +1) && (?y <= ?l))".format(verse=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

    @staticmethod
    def prev_verse_question(word_objects):  # 上一句
        select = u"?o"

        sparql = None
        for w in word_objects:
            if w.pos == pos_verse:
                e = u"?s :verseContent'{verse}'." \
                    u"?s :verseId ?m." \
                    u"?s :sentenceId ?n." \
                    u"?k :verseId ?x." \
                    u"?k :sentenceId ?y." \
                    u"?k :verseContent ?o." \
                    u"FILTER ((?x = ?m) && (?y = ?n - 1) && (?n > 1))".format(verse=w.token)

                sparql = SPARQL_SELECT_TEM.format(prefix=SPARQL_PREXIX,
                                                  select=select,
                                                  expression=e)
                break
        return sparql

rules = [
    Rule(condition_num=2, condition=((poet_entity + Star(Any(), greedy=False) + poem + Star(Any(), greedy=False)) | (poem + Star(Any(), greedy=False) + poet_entity + Star(Any(), greedy=False))), action=Question.has_poem_question),
    Rule(condition_num=2, condition=((poem_entity + Star(Any(), greedy=False) + poet + Star(Any(), greedy=False)) | (poet + Star(Any(), greedy=False) + poem_entity + Star(Any(), greedy=False))), action=Question.has_poet_question),
    Rule(condition_num=2, condition=(poet_entity + Star(Any(), greedy=False) + dynasty + Star(Any(), greedy=False)), action=Question.born_poet_question),
    Rule(condition_num=2, condition=(poem_entity + Star(Any(), greedy=False) + dynasty + Star(Any(), greedy=False)), action=Question.born_poem_question),
    Rule(condition_num=2, condition=((dynasty_entity + Star(Any(), greedy=False) + poem + Star(Any(), greedy=False)) | (poem + Star(Any(), greedy=False) + dynasty_entity + Star(Any(), greedy=False))), action=Question.born_poems_question),
    Rule(condition_num=2, condition=((dynasty_entity + Star(Any(), greedy=False) + poet + Star(Any(), greedy=False)) | (poet + Star(Any(), greedy=False) + dynasty_entity + Star(Any(), greedy=False))), action=Question.born_poets_question),
    Rule(condition_num=1, condition=(poem_entity + Star(Any(), greedy=False)), action=Question.poets_content_question),
    Rule(condition_num=2, condition=((verse_entity + Star(Any(), greedy=False) + poet + Star(Any(), greedy=False)) | (poet + Star(Any(), greedy=False) + verse_entity + Star(Any(), greedy=False))), action=Question.poet_verse_question),
    Rule(condition_num=2, condition=((verse_entity + Star(Any(), greedy=False) + poem + Star(Any(), greedy=False)) | (poem + Star(Any(), greedy=False) + verse_entity + Star(Any(), greedy=False))), action=Question.poem_verse_question),
    Rule(condition_num=2, condition=(verse_entity + Star(Any(), greedy=False) + next_verse + Star(Any(), greedy=False)), action=Question.next_verse_question),
    Rule(condition_num=2, condition=(verse_entity + Star(Any(), greedy=False) + prev_verse + Star(Any(), greedy=False)), action=Question.prev_verse_question)
]


import pandas as pd

# VALEURS
suppliers = ['Supplier1', 'Supplier2', 'Supplier3', 'Supplier4']
countries = ['China', 'USA', 'France', 'France']
target = [0, 0, 1, 0]

# NOMS COLONNES
cols = ["supplier_name", "country_name", "target"]

# CREATION DATAFRAME
df = pd.DataFrame(list(zip(suppliers, countries, target)),
                  columns=cols)
print(df)

# TRANSFORMATION AVEC LE ONE HOT ENCODING
one_hot_df = pd.get_dummies(df, columns=["country_name"])
print(f"\n {one_hot_df.to_string()}")


first, second = map(int, input().split())
big = max(first, second)
small = min(first, second)
# 유클리드 호제법
def GCD(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def LCM(a, b):
    return a*b // GCD(a,b)
print(GCD(big, small))
print(LCM(big, small))

baekjoon/16_정수론_및_조합론/03_2609_최대공약수와 최소공배수.py

03_2609_최대공약수와 최소공배수.py


from collections.abc import Sequence
from itertools import zip_longest
from collections.abc import Mapping

from streamsort import mob_eq
from streamsort.types import Mob

from .constants import SINGLE_MAX_MS, SINGLE_MAX_TRACKS

def categorize_projects(
    projects: Sequence[Mapping],
) -> tuple[list[dict], list[dict], list[dict]]:
    project_list = list[dict]()
    singles, albums = list[dict](), list[dict]()
    for project in projects:
        if (
            len(project["objects"]) <= SINGLE_MAX_TRACKS
            and sum(t["duration_ms"] for t in project["objects"])
            <= SINGLE_MAX_MS
        ):
            project = {**project, "length_class": "single"}
            singles.append(project)
        else:
            project = {**project, "length_class": "album"}
            albums.append(project)
        project_list.append(project)
    if len(project_list) and len(albums):
        assert albums[0] is project_list[0] or singles[0] is project_list[0]
    elif len(project_list):
        assert singles[0] is project_list[0]
    return project_list, singles, albums

def song_presumed_eq(song1: Mob, song2: Mob) -> bool:
    return song1["name"] == song2["name"] and all(
        mob_eq(*artists)
        for artists in zip_longest(
            song1["artists"], song2["artists"], fillvalue={"uri": ""}
        )
    )

def single_in_album(single: Mob, album: Mob) -> bool:
    album_tracks = {t["name"]: t["artists"] for t in album["objects"]}
    for track in single["objects"]:
        if not all(
            mob_eq(*artists)
            for artists in zip_longest(
                track["artists"],
                album_tracks.get(track["name"], []),
                fillvalue={"uri": ""},
            )
        ):
            return False
    return True


import os
from multiprocessing import Queue

from zdl.utils.media.image import ImageCV

from zdl.projects.BoxingAI.boxingai import BoxingAI

class BoxingAIImage(BoxingAI):
    def __init__(self, path):
        assert os.path.isfile(path)
        super().__init__()
        self.media = ImageCV(path)
        self.queue_name_img_tuple = Queue(maxsize=2)

    def _startProducingImgs(self):
        img = self.media.org()
        base_name = os.path.basename(self.media.fname)
        # self.require_show(img,title=f'{base_name}:org')
        img = self._execPrepHooks(img, base_name)
        # ImageCV(img,'testing').show()
        self.queue_name_img_tuple.put((base_name, img))
        self.queue_name_img_tuple.put('DONE')

    def _connectAndSmoothPoses(self, all_poses, smooth):
        return all_poses


from typing import Callable, List, Literal, Tuple, Optional, Any, overload
import asyncio

from . import compat, utils
from .types import BytesLike, Coro, Address
from .errors import PartialRead

__all__ = (
    'StreamWriter',
    'StreamReader',
    'StreamProtocol',
    'get_address',
    'open_connection',
    'start_server',
    'start_unix_server'
)

class StreamWriter:
    """
    Parameters
    -----------
    transport: :class:`asyncio.Transport`
        The transport to use.
    """
    def __init__(self, transport: asyncio.Transport, close_waiter: asyncio.Future[None]) -> None:
        self._transport = transport
        self._close_waiter = close_waiter
        self._waiter: Optional[asyncio.Future[None]] = None
        self._loop = compat.get_running_loop()

    async def __aenter__(self):
        return self

    async def __aexit__(self, *args: Any):
        self.close()
        await self.wait_closed()

    @property
    def transport(self) -> asyncio.Transport:
        """
        The transport used by this writer
        """
        return self._transport

    async def _wait_for_drain(self, timeout: Optional[float] = None) -> None:
        if self._waiter is None:
            return

        try:
            await asyncio.wait_for(self._waiter, timeout)
        finally:
            self._waiter = None

    def pause_writing(self):
        """
        Creates a future that is resolved when :meth:~`.StreamWriter.resume_writing` is called.
        This is supposed to be called when :meth:`asyncio.Protocol.pause_writing` is called.
        """
        if not self._waiter:
            self._waiter = self._loop.create_future()

    def resume_writing(self):
        """
        Sets the future that was created by :meth:~`.StreamWriter.pause_writing` to be resolved.
        This is supposed to be called when :meth:`asyncio.Protocol.resume_writing` is called.
        """
        if self._waiter:
            self._waiter.set_result(None)

    @overload
    def write(self, data: BytesLike) -> None:
        ...
    @overload
    def write(self, data: BytesLike, *, drain: Literal[True]) -> Coro[None]:
        ...
    @overload
    def write(self, data: BytesLike, *, drain: Literal[False]) -> None:
        ...
    def write(self, data: BytesLike, *, drain: bool = False) -> Any:
        """
        Writes data to the transport.

        Parameters
        ----------
        data: Union[:class:`bytearray`, :class:`bytes`]
            data to write.
        drain: :class:`bool`
            Whether to wait until all data has been written.
        """
        self._transport.write(data)
        if drain:
            return self.drain()

    @overload
    def writelines(self, data: List[BytesLike]) -> None:
        ...
    @overload
    def writelines(self, data: List[BytesLike], *, drain: Literal[True]) -> Coro[None]:
        ...
    @overload
    def writelines(self, data: List[BytesLike], *, drain: Literal[False]) -> None:
        ...
    def writelines(self, data: List[BytesLike], *, drain: bool = False) -> Any:
        """
        Writes a list of data to the transport.

        Parameters
        ----------
        data: List[Union[:class:`bytearray`, :class:`bytes`]]
            list of data to write.
        drain: :class:`bool`
            Whether to wait until all data has been written.
        """
        self._transport.writelines(data)
        if drain:
            return self.drain()

    def write_eof(self):
        """
        Writes EOF to the transport.
        """
        self._transport.write_eof()

    def set_write_buffer_limits(self, high: Optional[int] = None, low: Optional[int] = None) -> None:
        """
        Sets the high-water and low-water limits for write flow control.

        Parameters
        ------------
        high: Optional[:class:`int`]
            The high-water limit.
        low: Optional[:class:`int`]
            The low-water limit.
        """
        self._transport.set_write_buffer_limits(high, low)

    def get_write_buffer_size(self) -> int:
        """
        Gets the size of the write buffer.
        """
        return self._transport.get_write_buffer_size()

    async def drain(self, *, timeout: Optional[float] = None):
        """
        Waits until all data has been written.
        """
        if self.transport.is_closing():
            await asyncio.sleep(0)

        await self._wait_for_drain(timeout)

    def get_extra_info(self, name: str) -> Any:
        """
        Gets extra info about the transport.

        Parameters
        ----------
        name: :class:`str`
            The name of the extra info.
        """
        return self._transport.get_extra_info(name)

    def set_protocol(self, protocol: asyncio.BaseProtocol) -> None:
        """
        Sets the protocol used by the transport.

        Parameters
        ----------
        protocol: :class:`asyncio.BaseProtocol`
            The protocol to use.
        """
        self._transport.set_protocol(protocol)

    def get_protocol(self) -> asyncio.BaseProtocol:
        """
        Gets the protocol used by the transport.
        """
        return self._transport.get_protocol()

    def close(self):
        """
        Closes the transport.
        """
        self._transport.close()

    async def wait_closed(self) -> None:
        """
        Waits until the transport is closed.
        """
        await self._close_waiter

class StreamReader:
    """
    Attributes
    ----------
    buffer: :class:`bytearray`
        A bytearray containing the data.
    loop: :class:`asyncio.AbstractEventLoop`
        A reference to the event loop.
    """
    def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
        self.buffer: bytearray = bytearray()
        self.loop = loop or compat.get_running_loop()

        self._waiter: Optional[asyncio.Future[None]] = None
        self._eof = False

    def __aiter__(self):
        return self

    async def __anext__(self):
        data = await self.readline(wait=False)
        if not data:
            raise StopAsyncIteration

        return data

    async def _wait_for_data(self, timeout: Optional[float] = None):
        if self.at_eof():
            raise RuntimeError('Cannot wait for data after EOF')

        if self._waiter is not None:
            raise RuntimeError('Already waiting for data')

        self._waiter = self.loop.create_future()

        try:
            await asyncio.wait_for(self._waiter, timeout)
        finally:
            self._waiter = None

    def at_eof(self) -> bool:
        """
        Returns whether the reader has reached EOF.
        """
        return self._eof

    def reset(self) -> bytes:
        """
        Resets the reader's buffer.
        """
        data = self.buffer
        self.buffer = bytearray()

        return bytes(data)

    def feed_data(self, data: BytesLike) -> None:
        """
        Feeds the data to the reader.

        Parameters
        ----------
        data: Union[:class:`bytearray`, :class:`bytes`]
            data to be fed.
        """
        if self._eof:
            raise RuntimeError('Cannot feed data after EOF')

        self.buffer.extend(data)

        if self._waiter:
            try:
                self._waiter.set_result(None)
            except asyncio.InvalidStateError:
                pass

    def feed_eof(self):
        """
        Feeds EOF to the reader.
        """
        if self._waiter:
            try:
                self._waiter.set_result(None)
            except asyncio.InvalidStateError:
                pass

        self._eof = True

    async def read(
        self,
        nbytes: Optional[int] = None,
        *,
        timeout: Optional[float] = None,
        wait: bool = True
    ) -> bytes:
        """
        Reads ``nbytes`` off the stream. If ``nbytes`` is not provided, reads the whole stream.

        Parameters
        ----------
        nbytes: :class:`int`
            Number of bytes to read.
        timeout: Optional[:class:`float`]
            Timeout to wait for the read to complete.
        wait: :class:`bool`
            Whether to wait for data to be available.

        Raises
        ------
        asyncio.TimeoutError: If the timeout expires.
        """
        if not self.buffer:
            if wait:
                await self._wait_for_data(timeout=timeout)
            else:
                return b''

        if not nbytes:
            return self.reset()

        while nbytes > len(self.buffer):
            if self.at_eof():
                buffer = self.reset()
                raise PartialRead(buffer, nbytes)

            await self._wait_for_data(timeout=timeout)

        data = self.buffer[:nbytes]
        self.buffer = self.buffer[nbytes:]

        return bytes(data)

    async def readuntil(
        self,
        delimiter: BytesLike,
        *,
        timeout: Optional[float] = None,
        wait: bool = True,
        include: bool = False
    ) -> bytes:
        """
        Reads until the delimiter is found.

        Parameters
        ----------
        delimiter: Union[:class:`bytearray`, :class:`bytes`]
            The delimiter to read until.
        timeout: Optional[:class:`float`]
            Timeout to wait for the read to complete.
        wait: :class:`bool`
            Whether to wait for data to be available.
        include: :class:`bool`
            Whether to include the delimiter in the returned data.

        Raises
        ------
        asyncio.TimeoutError: If the timeout expires.
        """
        if not self.buffer:
            if wait:
                await self._wait_for_data(timeout=timeout)
            else:
                return b''

        pos = self.buffer.find(delimiter)
        while pos == -1:
            if self.at_eof():
                buffer = self.reset()
                raise PartialRead(buffer, None)

            await self._wait_for_data(timeout=timeout)
            pos = self.buffer.find(delimiter)

        if include:
            data = self.buffer[:pos + len(delimiter)]
        else:
            data = self.buffer[:pos]

        self.buffer = self.buffer[pos + len(delimiter):]
        return bytes(data)

    async def readline(
        self,
        *,
        timeout: Optional[float] = None,
        wait: bool = True,
        include: bool = False
    ) -> bytes:
        """
        Reads a line off the stream.

        Parameters
        ----------
        timeout: Optional[:class:`float`]
            Timeout to wait for the read to complete.
        wait: :class:`bool`
            Whether to wait for data to be available.
        include: :class:`bool`
            Whether to include the delimiter in the returned data.

        Raises
        ------
        asyncio.TimeoutError: If the timeout expires.
        """
        try:
            return await self.readuntil(b'\n', timeout=timeout, wait=wait, include=include)
        except PartialRead as e:
            return e.partial

    async def readlines(
        self,
        hint: Optional[int] = None,
        *,
        timeout: Optional[float] = None,
        wait: bool = False
    ) -> List[bytes]:
        """
        Reads all lines off the stream.

        Parameters
        ----------
        hint: Optional[:class:`int`]
            Hint to the number of lines to read.
        timeout: Optional[:class:`float`]
            Timeout to wait for the read to complete.
        wait: :class:`bool`
            Whether to wait for data to be available.

        Raises
        ------
        asyncio.TimeoutError: If the timeout expires.
        """
        lines = []

        while True:
            try:
                line = await self.readline(timeout=timeout, wait=wait)
            except asyncio.TimeoutError:
                break

            if (hint is not None and len(lines) >= hint) or not line:
                break

            lines.append(line)

        return lines

class StreamProtocol(asyncio.Protocol):
    def __init__(
        self,
        loop: asyncio.AbstractEventLoop,
        connection_callback: Callable[[StreamReader, StreamWriter], Any],
    ) -> None:
        self.loop = loop
        self.connection_callback = connection_callback
        self.reader = StreamReader(loop)
        self.writer: Optional[StreamWriter] = None
        self.paused = False
        self.waiter = loop.create_future()

    def __call__(self) -> Any:
        return self.__class__(self.loop, self.connection_callback)

    def connection_made(self, transport: Any) -> None:
        self.writer = writer = StreamWriter(transport, self.waiter)

        if utils.iscoroutinefunction(self.connection_callback):
            self.loop.create_task(self.connection_callback(self.reader, writer))
        else:
            self.connection_callback(self.reader, writer)

    def connection_lost(self, exc: Optional[BaseException]) -> None:
        if exc:
            self.waiter.set_exception(exc)
        else:
            self.waiter.set_result(None)

        self.writer = None
        self.reader.reset()

    def data_received(self, data: bytes) -> None:
        self.reader.feed_data(data)

    def eof_received(self) -> None:
        self.reader.feed_eof()

    def resume_writing(self) -> None:
        if not self.writer or not self.paused:
            return

        self.paused = False
        self.writer.resume_writing()

    def pause_writing(self) -> None:
        if not self.writer or self.paused:
            return

        self.paused = True
        self.writer.pause_writing()

def get_address(writer: StreamWriter, type: str) -> Address:
    if type not in ('sockname', 'peername'):
        raise ValueError(f'Invalid address type {type!r}. Must be either sockname or perrname.')

    addr = writer.get_extra_info('sockname')
    if len(addr) == 4:
        host, port, flowinfo, scope_id = addr
    else:
        host, port = addr
        flowinfo, scope_id = None, None

    return Address(host, port, flowinfo, scope_id)

async def open_connection(
    host: Optional[str] = None, port: Optional[int] = None, **kwargs: Any
) -> Tuple[StreamReader, StreamWriter]:
    """
    Opens a connection to a remote host.

    Parameters
    -----------
    host: Optional[:class:`str`]
        The host to connect to.
    port: Optional[:class:`int`]
        The port to connect to.
    **kwargs: Any
        Additional keyword arguments to pass to :meth:`asyncio.loop.create_connection`.
    """
    loop = kwargs.pop('loop', None) or compat.get_running_loop()
    protocol = StreamProtocol(loop, lambda w, r: None)

    _, proto = await loop.create_connection(protocol, host=host, port=port, **kwargs) # type: ignore
    return proto.reader, proto.writer

async def start_server(
    connection_callback: Callable[[StreamReader, StreamWriter], Any],
    host: Optional[str] = None,
    port: Optional[int] = None,
    **kwargs: Any
) -> asyncio.AbstractServer:
    """
    Starts a server.

    Parameters
    -----------
    connection_callback: Callable[[:class:`~StreamReader`, :class:`~StreamWriter`], Any]
        The callback to call when a connection is made.
    host: Optional[:class:`str`]
        The host to listen on.
    port: Optional[:class:`int`]
        The port to listen on.
    **kwargs: Any
        Additional keyword arguments to pass to :meth:`asyncio.loop.create_server`.
    """
    loop = kwargs.pop('loop', None) or compat.get_running_loop()
    protocol = StreamProtocol(loop, connection_callback)

    server = await loop.create_server(protocol, host=host, port=port, **kwargs)  # type: ignore
    return server

async def start_unix_server(
    connection_callback: Callable[[StreamReader, StreamWriter], Any],
    path: Optional[str] = None,
    **kwargs: Any
) -> asyncio.AbstractServer:
    """
    Starts a Unix server.

    Note
    ----
    This only works on unix based systems (duh).

    Parameters
    -----------
    connection_callback: Callable[[:class:`~StreamReader`, :class:`~StreamWriter`], Any]
        The callback to call when a connection is made.
    path: Optional[:class:`str`]
        The path of the unix domain socket.
    **kwargs: Any
        Additional keyword arguments to pass to :meth:`asyncio.loop.create_unix_server`.

    """
    loop = kwargs.pop('loop', None) or compat.get_running_loop()
    protocol = StreamProtocol(loop, connection_callback)

    server = await loop.create_unix_server(protocol, path=path, **kwargs)  # type: ignore
    return server


def cargar_voto(diccionario, partido, votos):
    if partido in votacion.keys():
        votacion[partido]+=votos
    else:
         votacion[partido]=votos

votacion = {}
seguir = 's'
partido = input('Ingrese el partido a sumarle votos: ')
votos = int(input('Ingrese la cantidad de votos a sumarle: '))
cargar_voto(votacion, partido, votos)
seguir = input('Desea seguir ingresando?(s/n): ')
while seguir != 'n':
    partido = input('Ingrese el partido a sumarle votos: ')
    votos = int(input('Ingrese la cantidad de votos a sumarle: '))
    cargar_voto(votacion, partido, votos)
    seguir = input('Desea seguir ingresando?(s/n): ')

lista_votos = list(votacion.items())
lista_votos.sort(reverse = True)
for item in lista_votos:
    print(f'El partido {item[0]} obtuvo {item[1]} votos.')


from rest_framework import serializers

from music.models import Music, Comment, Genre
from accounts.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            'username',
        )

class CommentSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Comment
        fields = (
            'user',
            'comment_text',
        )

class GenreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Genre
        fields = (
            'name',
        )

class CompletedMusicSerializer(serializers.ModelSerializer):
    owner = UserSerializer()
    genre = GenreSerializer()
    comment = CommentSerializer(many=True)
    # contributor = UserSrializer()
    total_like_user = serializers.IntegerField(source='total_likes_user')

    class Meta:
        model = Music
        fields = (
            'genre',
            'title',
            'seed_file',
            'completed_music',
            'album_jacket',
            'owner',
            'create_date',
            'total_like_user',
            'comment',
            'music_option',
        )

class LikeMusicSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = (
            'liked_music'
        )


import math
import random
import unittest

from transposition import columnar_transposition, crack_columnar_transposition, brute_force

class TranspositionTests(unittest.TestCase):

    def test_book_example_encryption(self):
        plaintext = "Common sense is not so common."
        key = 8
        ciphertext = columnar_transposition(plaintext, key)
        expected = "Cenoonommstmme oo snnio. s s c"
        self.assertEqual(ciphertext, expected)

    def test_book_example_decryption(self):
        plaintext  = "Common sense is not so common."
        ciphertext = "Cenoonommstmme oo snnio. s s c"
        cracked = brute_force(ciphertext)
        found = False

        for string in cracked:
            if string == plaintext:
                found = True
                break

        self.assertTrue(found)

    def test_random_examples(self):
        random.seed(42)
        plaintext = ''

        for n in range(100):
            for n in range(50):
                integer = math.floor(random.random() * 10)
                plaintext += str(integer)
            key = random.randrange(1, len(plaintext) // 2)
            ciphertext = columnar_transposition(plaintext, key)
            plaintext_2 = crack_columnar_transposition(ciphertext, key)
            self.assertEqual(plaintext, plaintext_2)
            plaintext = ''

unittest.main()


# URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.)

def urlify(s, trueLen):
    """ Keep two pointers - the current index and the current "true index"
        Whenever we encounter a space, the next three slots become ['%', '2', '0']
        For example:
            "Mr John Smith    "
                         ^ true index
                             ^ current index
        Time Complexity:
            O(N)
    """
    s = list(s)
    i = len(s) - 1
    t = trueLen - 1
    while i >= 0:
        if s[t] == " ":
            s[i] = "0"
            s[i - 1] = "2"
            s[i - 2] = "%"
            i -= 3
        else:
            s[i] = s[t]
            i -= 1
        t -= 1
    return "".join(s)

if __name__ == "__main__":
    print(urlify("Mr John Smith    ", 13))
    print(urlify("Hello world how are you        ", 23))


import json
import csv
import sys
import operator
import urllib.request
from datetime import datetime
from os import listdir,remove
from os.path import isfile,join,dirname,realpath

#Chargement de la configuration du script
with open("{}/config.json".format(dirname(realpath(__file__)))) as f:
    data = json.load(f)

#Liste des fichiers à traiter
chemin_chargement = data['formulaire.app.chemin.chargement.fichiers']
clef_api = data['formulaire.app.clef.api']
url_api = data['formulaire.app.url.api']

def lister_fichiers(chemin_chargement):
    fichiers = [f for f in listdir(chemin_chargement) if isfile(join(chemin_chargement, f))]
    return fichiers

#Analyse le fichier pour extraire les informations
def analyser_fichier(chemin_chargement, fichier):
    departement={}
    compte_population=0
    compte_nombre_hotels=0
    communes={}
    with open('{}/{}'.format(chemin_chargement, fichier), encoding='utf-8') as csvfile:
        csvreader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
        for ligne in csvreader:
            departement['code']=ligne['DEP']
            compte_population = compte_population + int(ligne['Population'])
            compte_nombre_hotels = compte_nombre_hotels + int(ligne['Nb Hotel'])
            communes[ligne['LIBGEO']] = int(ligne['Population'])

    departement['population'] = compte_population
    departement['nombreHotel'] = compte_nombre_hotels
    departement['communePlusGrande'] = max(communes.items(), key=operator.itemgetter(1))[0]
    departement['communePlusPetite'] = min(communes.items(), key=operator.itemgetter(1))[0]

    return departement

#Appelle l'API pour mettre a jour la base de données
def insere_departement(fichier, url, departement):
    response = None
    try:
        req = urllib.request.Request(url)
        req.add_header('Content-Type', 'application/json; charset=utf-8')
        jsondata = json.dumps(departement)
        jsondataasbytes = jsondata.encode('utf-8')
        req.add_header('Content-Length', len(jsondataasbytes))
        response=urllib.request.urlopen(req, jsondataasbytes)
    except urllib.error.URLError as err:
        print("Erreur inattendue:", err.reason)
        return False
    if response.status == 200:
        return True
    else:
        println(response.reason)
        return False

liste_fichiers=lister_fichiers(chemin_chargement)
if len(liste_fichiers) == 0:
    print(u"{} - Aucun fichier trouvé".format(datetime.now()))
    exit(1)

for fichier in liste_fichiers:
    departement = analyser_fichier(chemin_chargement, fichier)
    remove(chemin_chargement+"/"+fichier)
    if not insere_departement(fichier, url_api + "/" + fichier + "/" +clef_api, departement):
        print(u"{} - Impossible de poster le fichier {}".format(datetime.now(), fichier))
    else:
        print(u"{} - Fichier {} posté avec succès".format(datetime.now(), fichier))


from datetime import datetime

import pytz
from django.test import TestCase

from casexml.apps.case.cleanup import rebuild_case_from_forms
from casexml.apps.case.mock import CaseFactory, CaseStructure
from casexml.apps.case.tests.util import delete_all_cases, delete_all_xforms
from casexml.apps.case.util import (
    get_datetime_case_property_changed,
    get_paged_changes_to_case_property,
)
from corehq.form_processor.models import CommCareCase, RebuildWithReason

class TestCasePropertyChanged(TestCase):
    def setUp(self):
        self.domain = "isildur"
        self.factory = CaseFactory(self.domain)
        self.case = self.factory.create_case(owner_id='owner', case_name="Aragorn", update={"sword": "Narsil"})
        self.other_case = self.factory.create_case()

    def tearDown(self):
        delete_all_xforms()
        delete_all_cases()

    def test_date_case_property_changed(self):
        updated_on = datetime(2015, 5, 3, 12, 11)
        # submit 2 updates
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'abc': "updated"
                    },
                    "date_modified": updated_on
                }),
        )
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'bcd': "updated"
                    },
                }),
        )
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)

        self.assertEqual(
            updated_on.replace(tzinfo=pytz.UTC),
            get_datetime_case_property_changed(case, "abc", "updated")
        )

    def test_multiple_cases_in_update(self):
        day_1 = datetime(2015, 5, 1, 12, 11)
        day_2 = datetime(2015, 5, 2, 12, 11)

        # Submit two updates TOGETHER, one for this case, but irrelevant,
        # and one for another case, but touching the same property
        self.factory.create_or_update_cases([
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'not_relevant': "updated"
                    },
                    "date_modified": day_1,
                }),
            CaseStructure(
                self.other_case.case_id,
                attrs={
                    "update": {
                        'relevant_property': "updated"
                    },
                    "date_modified": day_1,
                }),
        ])

        # Submit an update that DOES modify the relevant property
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'relevant_property': "updated"
                    },
                    "date_modified": day_2,
                }),
        )
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)

        self.assertEqual(
            day_2.replace(tzinfo=pytz.UTC),
            get_datetime_case_property_changed(case, "relevant_property", "updated")
        )

    def test_owner_id_changed(self):
        changes, _ = get_paged_changes_to_case_property(self.case, 'owner_id')
        self.assertEqual(len(changes), 1)
        self.assertEqual(changes[0].new_value, 'owner')

        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'owner_id': 'new_owner'
                    },
                }),
        )
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)

        changes, _ = get_paged_changes_to_case_property(case, 'owner_id')
        self.assertEqual(len(changes), 2)
        self.assertEqual(changes[0].new_value, 'new_owner')
        self.assertEqual(changes[1].new_value, 'owner')

    def test_name_changed(self):
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'name': 'Strider'
                    },
                }),
        )
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)
        changes, _ = get_paged_changes_to_case_property(case, 'name')
        self.assertEqual(len(changes), 2)
        self.assertEqual(changes[0].new_value, 'Strider')
        self.assertEqual(changes[1].new_value, 'Aragorn')

    def test_blank_change(self):
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'sword': ''
                    },
                }),
        )
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)
        changes, _ = get_paged_changes_to_case_property(case, 'sword')
        self.assertEqual(len(changes), 2)
        self.assertEqual(changes[0].new_value, '')
        self.assertEqual(changes[1].new_value, 'Narsil')

    def test_case_rebuild(self):
        # Cases with rebuild actions were failing because rebuild actions have no form
        # https://manage.dimagi.com/default.asp?276216#1494409
        self.factory.create_or_update_case(
            CaseStructure(
                self.case.case_id,
                attrs={
                    "update": {
                        'sword': ''
                    },
                }),
        )
        rebuild_case_from_forms(self.domain, self.case.case_id, RebuildWithReason())
        case = CommCareCase.objects.get_case(self.case.case_id, self.domain)
        changes, _ = get_paged_changes_to_case_property(case, 'sword')
        self.assertEqual(len(changes), 2)
        self.assertEqual(changes[0].new_value, '')
        self.assertEqual(changes[1].new_value, 'Narsil')