from app import app, db, login_manager
from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User, Preference, Gem, TypeGem, Requirement
from app.forms import LoginForm, RegistrationForm, EditProfileForm, RemoveProfileForm,\
    RestoreProfileForm, EditPasswordForm, AddGemsForm, ActionById, EditPrefForm, AddPrefForm,\
    ViewQueryForm, DistributionForm, RequirementsForm, GemTypesForm, AddTypeForm
from datetime import datetime, timedelta
from sqlalchemy import text, desc, or_, and_

@login_manager.user_loader# пользовательский загрузчик
def load_user(id):
    return db.session.query(User).get(int(id))

@app.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow() + timedelta(hours=5)
        db.session.commit()

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:# True, если юзер зареган
        return redirect(url_for('users'))

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        flash('You are logged in as a {}, {}'.format(user.name, user.character))
        if user.character == 'elf':
            return redirect(url_for('user', username=user.username))
        elif user.character == 'gnome':
            return redirect(url_for('add_gems'))
        elif user.character == 'master':
            return redirect(url_for('gems'))
        else:
            return redirect(url_for('users'))
    return render_template('login.html', title='Sign In', form=form)# form = form передает объект формы

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('users'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('users'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data, character=form.character.data, name=form.username.data.title())
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

@app.route('/edit_password', methods=['GET', 'POST'])
@login_required# защищает функцию просмотра: будет доступна только для зарегистрированных пользователей
def edit_password():

    form = EditPasswordForm()

    if form.validate_on_submit():
        user = current_user
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Your password has been changed.')
        return redirect(url_for('edit_password'))
    return render_template('edit_password.html', title='Edit password', form=form)

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():

    form_edit = EditProfileForm(current_user.username, current_user.email)
    form_remove = RemoveProfileForm()
    form_restore = RestoreProfileForm()

    if request.method == 'GET':
        form_edit.username.data = current_user.username
        form_edit.email.data = current_user.email
        form_edit.name.data = current_user.name
    if form_restore.is_submitted() and form_restore.submit_restore.data:
        current_user.status = True
        db.session.commit()
        flash('Profile has been restored.')
        return redirect(url_for('edit_profile'))
    elif form_remove.is_submitted() and form_remove.submit_remove.data:
        current_user.status = False
        current_user.deletion_date = datetime.utcnow()
        db.session.commit()
        flash('Profile has been deleted.')
        return redirect(url_for('edit_profile'))
    elif form_edit.validate_on_submit():
        current_user.username = form_edit.username.data
        current_user.name = form_edit.name.data
        current_user.email = form_edit.email.data
        db.session.commit()
        flash('Profile has been updated.')
        return redirect(url_for('edit_profile'))
    return render_template('edit_profile.html', title='Edit profile', user=user, form_edit=form_edit, form_remove=form_remove,\
        form_restore=form_restore)

@app.route('/add_gems', methods=['GET', 'POST'])
@login_required
def add_gems():

    form = AddGemsForm()
    temp_message = []

    if request.method == 'GET':
        form.amount_gem.data = 0
    elif form.validate_on_submit():
        for gem in range(int(form.amount_gem.data)):
            gem = Gem(type=str(form.type_gem.data.type), gnome_id=current_user.id)
            db.session.add(gem)
            db.session.commit()
            temp_message.append(gem.type)
        flash('Gem: {} - successfully added to the system.'.format(', '.join(temp_message)))
    return render_template('add_gems.html', title='Adding gems', form=form)

@app.route('/user/<username>', methods=['GET', 'POST'])
@login_required
def user(username):

    def get_prefs():# предпочтения эльфа
        return user.preferences.all()

    def get_types_pref():
        return [pref.gem_type for pref in get_prefs()]

    def get_gem_types():
        return [x.type for x in TypeGem.query.all()]

    def get_new_pref():
        return [(gem_type, gem_type) for gem_type in list(set(get_gem_types())-set(get_types_pref()))]

    def get_mined_gems():
        gems_gnome = Gem.query.filter_by(gnome_id=user.id).all()
        list_types = [gem.type for gem in gems_gnome]
        return {gem.type : list_types.count(gem.type) for gem in gems_gnome}

    def get_assigned_gems():
        return Gem.query.filter_by(elf_id=user.id).filter(Gem.status=='assigned').all()

    def get_confirmed_gems():
        gems_elf = Gem.query.filter_by(elf_id=user.id).filter(Gem.status=='confirmed').all()
        list_types = [gem.type for gem in gems_elf]
        return {gem.type : list_types.count(gem.type) for gem in gems_elf}

    user = User.query.filter_by(username=username).first_or_404()
    form_confirm = ActionById(prefix='confirm')
    form_add = AddPrefForm()
    form_del = ActionById(prefix='del')
    form_edit = EditPrefForm(prefix='edit')

    form_add.gem_type.choices = get_new_pref()

    form_edit.pref.label = ''
    form_edit.gem_rate.label = 'Rate'

    if form_confirm.is_submitted() and form_confirm.value.data:
        gem = Gem.query.get(form_confirm.value.data)
        gem.status = 'confirmed'
        gem.confirmation_date = datetime.utcnow()
        db.session.add(gem)
        db.session.commit()
        flash('The assigned {} was successfully confirmed by the {}.'.format(gem.type, user.name))
    elif form_del.is_submitted() and form_del.value.data:
        pref_del = Preference.query.get(form_del.value.data)
        db.session.delete(pref_del)
        db.session.commit()
        flash('Preference "{}" successfully deleted.'.format(pref_del))
    elif "gem_type" in request.form and form_add.gem_rate.validate(form_add):
        pref = Preference(gem_type=form_add.gem_type.data, gem_rate=form_add.gem_rate.data, elf_id=user.id)
        db.session.add(pref)
        db.session.commit()
        form_add.gem_type.choices = get_new_pref()
        flash('Preference "{}" successfully added.'.format(pref))
    elif "edit-submit_edit" in request.form and form_edit.gem_rate.validate(form_edit) and form_edit.pref.validate(form_edit):
        elf_pref = form_edit.pref.data
        elf_pref.gem_rate = form_edit.gem_rate.data
        db.session.commit()
        flash('Preference successfully edited.')

    return render_template('user.html',
                            title=user.name,
                            user=user,
                            prefs=get_prefs(),
                            mined_gems=get_mined_gems(),
                            assigned_gems=get_assigned_gems(),
                            confirmed_gems=get_confirmed_gems(),
                            form_confirm=form_confirm,
                            form_add=form_add,
                            form_del=form_del,
                            form_edit=form_edit)

@app.route('/')
@app.route('/users', methods=['GET', 'POST'])
def users():

    form = ActionById()

    form_view = ViewQueryForm()

    def get_elves():
        return User.query.filter(and_(User.character == 'elf', User.status == True)).all()

    def get_all_elves():
        return User.query.filter(User.character == 'elf').all()

    def get_gnomes():
        return User.query.filter(or_(User.character == 'gnome', User.character == 'master')).filter(User.status == True).all()

    def get_all_gnomes():
        return User.query.filter(or_(User.character == 'gnome', User.character == 'master')).all()

    if form_view.is_submitted():
        return render_template('users.html', title='Users', elves=get_all_elves(), gnomes=get_all_gnomes(), form=form, form_view=form_view)

    if form.is_submitted() and form.value.data:
        user = User.query.get(form.value.data)
        user.status = False
        db.session.add(user)
        db.session.commit()
        flash('User successfully removed from the system.')

    return render_template('users.html', title='Users', elves=get_elves(), gnomes=get_gnomes(), form=form, form_view=form_view)

@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():

    def get_requirements():
        return Requirement.query.all()

    def get_gem_types():
        return TypeGem.query.order_by(TypeGem.type).all()

    form_edit = RequirementsForm(prefix='edit')
    form_gem = GemTypesForm(prefix='gem')
    form_del = ActionById(prefix='del')
    form_add = AddTypeForm(prefix='add')

    if "edit-submit_edit" in request.form and form_edit.req_rate.validate(form_edit) and form_edit.req_type.validate(form_edit):
        req = form_edit.req_type.data
        req.req_rate = form_edit.req_rate.data
        db.session.add(req)
        db.session.commit()
        flash('{} coefficient successfully edited.'.format(req.req_type))
    elif "add-gem_type" in request.form and form_add.validate_on_submit():
        new_type = TypeGem(type=form_add.gem_type.data)
        db.session.add(new_type)
        db.session.commit()
        flash('Type "{}" successfully added to the system.'.format(new_type.type))
    elif form_del.is_submitted() and form_del.value.data:
        type_gem = TypeGem.query.get(form_del.value.data)
        db.session.delete(type_gem)
        db.session.commit()
        flash('Type "{}" has been deleted.'.format(type_gem.type))
    elif "gem-submit_type" in request.form and form_gem.validate_on_submit():
        type_edit = TypeGem.query.filter_by(type=form_gem.gem_type.data.type).first_or_404()
        type_edit.type = form_gem.edit_type.data
        db.session.add(type_edit)
        db.session.commit()
        flash('Type successfully changed to "{}".'.format(type_edit.type))

    return render_template('settings.html',
                           title='settings',
                           form_edit=form_edit,
                           form_del=form_del,
                           form_gem=form_gem,
                           form_add=form_add,
                           reqs=get_requirements(),
                           gem_types=get_gem_types())

@app.route('/gems', methods=['GET', 'POST'])
def gems():

    form = ActionById()
    form_view = ViewQueryForm()

    def get_all_gems():
        return Gem.query.order_by(desc(Gem.mined_date)).all()

    def get_gems():
        return Gem.query.order_by(desc(Gem.mined_date)).filter(Gem.status != 'deleted').all()

    def get_assigned_gems():
        return Gem.query.order_by(desc(Gem.mined_date)).filter(Gem.status == 'assigned').all()

    if form.is_submitted() and form.value.data:
        gem = Gem.query.get(form.value.data)
        gem.status = 'deleted'
        db.session.add(gem)
        db.session.commit()
        flash('Gem successfully removed from the system.')
    elif "view_all_gems" in request.form and form_view.is_submitted():
        return render_template('gems.html', title='Gems', gems=get_all_gems(), form=form, form_view=form_view)
    elif "view_assigned_gems" in request.form and form_view.is_submitted():
        return render_template('gems.html', title='Gems', gems=get_assigned_gems(), form=form, form_view=form_view)

    return render_template('gems.html', title='Gems', gems=get_gems(), form=form, form_view=form_view)

temp_assigned_gems = []

@app.route('/gems_distribution', methods=['GET', 'POST'])
@login_required
def gems_distribution():

    def count_assigned_elf(elf):
        return elf.elf_gems.filter_by(status='assigned').count()

    def count_confirmed_elf(elf):
        return elf.elf_gems.filter_by(status='confirmed').count()

    def get_mined_gems():
        return Gem.query.filter(Gem.status == 'mined').order_by(desc(Gem.mined_date)).all()

    def get_elves():
        return User.query.filter(and_(User.character == 'elf', User.status == True)).all()

    def count_gems_elf(elf):
        return count_assigned_elf(elf) + count_confirmed_elf(elf)

    def sum_gems_elves():
        query = text("SELECT COUNT (id) FROM gem WHERE status='assigned' OR status='confirmed'")
        response = db.engine.execute(query)
        return response.scalar() + num_temp_gems

    def get_weighted_choices():
        return {elf: (count_gems_elf(elf))/sum_gems_elves() for elf in get_elves()}

    def hungry_elf():
        return min(get_weighted_choices(), key=get_weighted_choices().get)

    form = DistributionForm()

    num_temp_gems = 0
    temp_message = []

    if request.method == 'GET':
        temp_assigned_gems.clear()
    elif form.is_submitted() and form.elf.data:
        gem = Gem.query.get(form.value.data)
        gem.elf = form.elf.data
        gem.status = 'assigned'
        gem.assigned_date = datetime.utcnow()
        gem.master = current_user
        gem.assignation_type = 'hand'
        db.session.add(gem)
        db.session.commit()
        flash('{} successfully assigned to the elf {}.'.format(gem.type, form.elf.data.name))
        return redirect(url_for('gems_distribution'))
    elif "submit_distrib" in request.form:
        if not get_mined_gems():
            flash('No gems for distribution')
        elif not temp_assigned_gems:
            for temp_gem in get_mined_gems():
                temp_gem.elf = hungry_elf()
                temp_gem.status = 'assigned'
                temp_assigned_gems.append(temp_gem)
                num_temp_gems += 1
        else:
            flash('Distribution already done')
        return render_template('gems_distribution.html', title='Gems distribution', gems=temp_assigned_gems, form=form)
    elif "submit_confirm" in request.form:
        if not temp_assigned_gems:
            flash('You first need to make a distribution!')
        else:
            for temp_gem in temp_assigned_gems:
                gem = Gem.query.get(temp_gem.id)
                gem.elf = temp_gem.elf
                gem.status = 'assigned'
                gem.assignation_type = 'algo'
                gem.assigned_date = datetime.utcnow()
                db.session.add(gem)
                db.session.commit()
                temp_message.append(gem.type)
            temp_assigned_gems.clear()
            flash('Distribution successfully completed. Gem: {} - assigned.'.format(', '.join(temp_message)))

    return render_template('gems_distribution.html', title='Gems distribution', gems=get_mined_gems(), form=form)


# -*- coding: utf-8 -*-

# Como funciona as burlações de votações online
# Material abaixo absorvido do curso Pythonicos, para estudos e conheicmento

import requests
import random
from pprint import pprint

def proxies(q,mode='json'):
	url = "http://proxy.tekbreak.com/%s/%s" %(q,mode)
	r = requests.get(url)

	# Escolho 1 dos n proxies. Passando o tamanho da minha lista no retorn r.json()
	x = random.randrange(0,len(r.json()))

	proxy = "%s://%s/%s" %(r.json()[x]["type"].lower(),r.json()[x]["ip"],r.json()[x]["port"])
	proxies = {r.json()[x]["type"].lower():proxy}
	return proxies

proxies = proxies(q=100)
# Passa um dicionário para o requests
r = requests.get("http://ipinfo.io",proxies=proxies)
pprint(r.content)


with open('series.csv','r',encoding='utf8') as file:
    for line in file:
        linha = line
        lista = linha.split(',')

nome = []
imdb = []
netflix = []
nota_imdb = 0
nota_netflix = 0

for i in range (0,lista):
    nome.append(lista[1])
    imdb.append(lista[5])
    netflix.append(lista[6])
for i in range (0,lista):
    print(nome,nota_imdb,nota_netflix)


def get_age ():
    age = int(input ("Plase enter your age: "))
    if age < 0:
        # Create a new instance of an exception
        my_error = ValueError ("{0} is not a valid age".format (age))
        raise my_error
    return age

get_age()

user_input = input ("Enter a floating point number: ")

try:
    #Try to do something that could fail
    input_as_float = float (user_input)
except ValueError:
    # This will be executed if a "ValueError" is raised
    print ("You did not enter a floating point number.", ValueError)
else:
    # This will be executed if not exception got raised in the try statement.
    print ("The square of number is: ", input_as_float**2)
finally:
    # This will be execute whether or not an exception is raised
    print ("Thank you!")


''' create a  mongodb client '''
from pymongo import MongoClient

MONGO_DB_HOST = 'localhost'
MONGO_DB_PORT = '27017'
DB_NAME = 'tap-news'

MONGO_CLIENT = MongoClient("%s:%s" % (MONGO_DB_HOST, MONGO_DB_PORT))

def get_db(database=DB_NAME):
    ''' return a mongodb client with name DB_NAME '''
    return MONGO_CLIENT[database]


# str=input()
# resoult={}
# for i in str:
#     resoult[i]=str.count(i)
# print(resoult)
# a = 'dasdasd'
# a = list(a)
# a.sort()
# print(a)
# A = 'dasdasd'
# A = list(A)
# A.pop(1)
# print(A)
# import numpy as np
# A = np.random.randn(5,5)
# for i in range(len(A)):
#     A[i].append(0)
# print(A)
def commonChars(A):
    ans = []
    for k in range(A[0]):

        for i in range(1, len(A)):
            if A[0][k] not in A[i]:
                break
            if i == len(A)-1:
                A[i] = A[i].replace(A[0][k], '', 1) # 通过用空格替换的方式来删除
    return ans


from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import numpy as np

gpu_model = np.array([580, 680, 780, 880, 980, 1080])
gpu_model = gpu_model.reshape(-1, 1)
fps = [ 40,  52,  67 , 85, 120 , 156]

line_fitter = LinearRegression()
line_fitter.fit(gpu_model, fps)
fps_predict=line_fitter.predict(gpu_model)
plt.plot(gpu_model, fps_predict)
plt.plot(gpu_model, fps, 'o')

ax=plt.subplot()
ax.set_xticks(gpu_model)
ax.set_yticks(fps)

next_gpu=np.array([1180])
next_gpu=next_gpu.reshape(-1,1)
print('Predicted FPS of the RTX 2080', line_fitter.predict(next_gpu))
plt.xlabel('NVIDIA GPUs by Model')
plt.ylabel('FPS')
plt.show()

#gpu_version = np.array([1, 2, 3, 4, 5, 6])
#gpu_version = gpu_version.reshape(-1, 1)
#fps = [ 40,  52,  67 , 85, 120 , 156]
#line_fitter = LinearRegression()
#line_fitter.fit(gpu_version, fps)
#fps_predict=line_fitter.predict(gpu_version)
#plt.plot(gpu_version, fps_predict)
#plt.plot(gpu_version, fps, 'o')
#ax=plt.subplot()
#ax.set_xticks(gpu_version)
#ax.set_yticks(fps)
#next_gpu=np.array([7])
#next_gpu=next_gpu.reshape(-1,1)
#print(line_fitter.predict(next_gpu))

plt.show()


'''
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7
'''

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def PreOrder(self):
        return [self.val,
                None if self.left is None else self.left.PreOrder(),
                None if self.left is None else self.right.PreOrder()]

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        return self.divide(preorder, inorder)

    def divide(self, preorder, inorder):
        if len(preorder) <= 0:
            return None
        split = preorder[0]
        newRoot = TreeNode(split)

        splitIndex = inorder.index(split)

        leftInorder = inorder[0: splitIndex]
        rightInorder = inorder[splitIndex + 1: len(inorder)]

        leftPreorder = preorder[1 : splitIndex+1]
        rightPreorder = preorder[splitIndex+1: len(preorder)]

        leftTree = self.divide(leftPreorder, leftInorder)
        rightTree = self.divide(rightPreorder, rightInorder)

        newRoot.left = leftTree
        newRoot.right = rightTree

        return newRoot

s = Solution()

root = s.buildTree([3,9,20,15,7],
[9,3,15,20,7])
print(root.PreOrder())


import requests
import time

url = "https://api2.1112.com/api/v1/otp/create"

def send(phone: str , times: int):

    payloads = {'phonenumber': f"{phone}", 'language': "th"}
    for i in range(times):
        r = requests.post(url, data=payloads)
        print(f"send to {phone} success")
        time.sleep(1)

phone_input = input("Phone : ")
times_input = int(input("Numbers : "))

send(phone=phone_input, times=times_input)


#!/usr/bin/env python3
import datetime
import os
try:
    now = datetime.datetime.now()
    print("Temperature Logger started at at {}".format(now))
    temp = os.popen("/opt/vc/bin/vcgencmd measure_temp").read()
    temp = float(temp.split("=")[1].split("'")[0])
    # print(u"    Temperature: {:.1f}\N{DEGREE SIGN}".format(temp))
    temppath = os.path.join(os.path.dirname(
             os.path.abspath(__file__)), "temp_log.txt")
    with open(temppath, "a") as log:
        log.write(u"{},  {:.1f}\n".format(now, temp))
    print("    Temperature is {:.1f}".format(temp))
except Exception as e:
    print(e)


from . import core as bknd_core
from ..static import cfg as ewcfg
from ..utils import core as ewutils

class EwBook:
    id_book = 0
    id_server = -1
    id_user = -1

    # The name of the book
    title = ""

    # The name of the author
    author = ""

    # If its been published or not
    book_state = 0

    # The in-game day it was published
    date_published = 0

    # Genre of zine (0-7)
    genre = -1

    # Length of the book after publishing
    length = 0

    # The total sales of the published book
    sales = 0

    # The average rating of the published book
    rating = 0

    # The number of people who have rated the book
    rates = 0

    # The number of pages in a book (between 5 and 20)
    pages = 10

    # The contents of the book
    book_pages = {}

    def __init__(
            self,
            id_book = None,
            member = None,
            book_state = None,
    ):
        self.book_pages = {}

        query_suffix = ""
        if id_book is not None:
            self.id_book = id_book
            query_suffix = " id_book = {}".format(self.id_book)

        elif member is not None:
            self.id_server = member.guild.id
            self.id_user = member.id
            query_suffix = " id_server = {} AND id_user = {}".format(self.id_server, self.id_user)
            if book_state is not None:
                self.book_state = book_state
                query_suffix += " AND book_state = {}".format(self.book_state)

        try:
            conn_info = bknd_core.databaseConnect()
            conn = conn_info.get('conn')
            cursor = conn.cursor()

            # Retrieve object
            cursor.execute("SELECT {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} FROM books WHERE{}".format(
                ewcfg.col_id_book,
                ewcfg.col_id_user,
                ewcfg.col_id_server,
                ewcfg.col_title,
                ewcfg.col_author,
                ewcfg.col_book_state,
                ewcfg.col_date_published,
                ewcfg.col_genre,
                ewcfg.col_length,
                ewcfg.col_sales,
                ewcfg.col_rating,
                ewcfg.col_rates,
                ewcfg.col_pages,
                query_suffix,
            ))
            result = cursor.fetchone()

            if result != None:
                # Record found: apply the data to this object.
                self.id_book = result[0]
                self.id_user = result[1]
                self.id_server = result[2]
                self.title = result[3]
                self.author = result[4]
                self.book_state = result[5]
                self.date_published = result[6]
                self.genre = result[7]
                self.length = result[8]
                self.sales = result[9]
                self.rating = result[10]
                self.rates = result[11]
                self.pages = result[12]

                # Retrieve additional properties
                cursor.execute("SELECT {}, {} FROM book_pages WHERE id_book = %s".format(
                    ewcfg.col_page,
                    ewcfg.col_contents
                ), (
                    self.id_book,
                ))

                for row in cursor:
                    # this try catch is only necessary as long as extraneous props exist in the table
                    try:
                        self.book_pages[row[0]] = row[1]
                    except:
                        ewutils.logMsg("extraneous book_pages row detected.")

        finally:
            # Clean up the database handles.
            cursor.close()
            bknd_core.databaseClose(conn_info)

    def persist(self):
        try:
            conn_info = bknd_core.databaseConnect()
            conn = conn_info.get('conn')
            cursor = conn.cursor()

            # Save the object.
            cursor.execute(
                "REPLACE INTO books({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)".format(
                    ewcfg.col_id_book,
                    ewcfg.col_id_server,
                    ewcfg.col_id_user,
                    ewcfg.col_title,
                    ewcfg.col_author,
                    ewcfg.col_book_state,
                    ewcfg.col_date_published,
                    ewcfg.col_genre,
                    ewcfg.col_length,
                    ewcfg.col_sales,
                    ewcfg.col_rating,
                    ewcfg.col_rates,
                    ewcfg.col_pages,
                ), (
                    self.id_book,
                    self.id_server,
                    self.id_user,
                    self.title,
                    self.author,
                    self.book_state,
                    self.date_published,
                    self.genre,
                    self.length,
                    self.sales,
                    self.rating,
                    self.rates,
                    self.pages,
                ))

            # Remove all existing property rows.
            cursor.execute("DELETE FROM book_pages WHERE {} = %s".format(
                ewcfg.col_id_book
            ), (
                self.id_book,
            ))

            # Write out all current property rows.
            for name in self.book_pages:
                cursor.execute("INSERT INTO book_pages({}, {}, {}) VALUES(%s, %s, %s)".format(
                    ewcfg.col_id_book,
                    ewcfg.col_page,
                    ewcfg.col_contents
                ), (
                    self.id_book,
                    name,
                    self.book_pages[name]
                ))

            conn.commit()
        finally:
            # Clean up the database handles.
            cursor.close()
            bknd_core.databaseClose(conn_info)

# The purpose of this is to make finding the average rating easier and to measure sales based on the amount of different people that buy them.
class EwBookSale:
    id_book = 0
    id_user = -1
    id_server = -1

    # If a user bought the book. 0 is not bought.
    bought = 0

    # A user's rating of a book. 0 is unrated.
    rating = 0

    def __init__(
            self,
            id_book = None,
            member = None,
    ):
        self.id_book = id_book
        self.id_user = member.id
        self.id_server = member.guild.id

        try:
            conn_info = bknd_core.databaseConnect()
            conn = conn_info.get('conn')
            cursor = conn.cursor()

            # Retrieve object
            cursor.execute("SELECT {}, {} FROM book_sales WHERE {} = %s AND {} = %s AND {} = %s".format(
                ewcfg.col_bought,
                ewcfg.col_rating,
                ewcfg.col_id_book,
                ewcfg.col_id_user,
                ewcfg.col_id_server,
            ), (
                self.id_book,
                self.id_user,
                self.id_server,
            ))
            result = cursor.fetchone()

            if result != None:
                # Record found: apply the data to this object.
                self.bought = result[0]
                self.rating = result[1]

        finally:
            # Clean up the database handles.
            cursor.close()
            bknd_core.databaseClose(conn_info)

    def persist(self):
        try:
            conn_info = bknd_core.databaseConnect()
            conn = conn_info.get('conn')
            cursor = conn.cursor()

            # Save the object.
            cursor.execute(
                "REPLACE INTO book_sales({}, {}, {}, {}, {}) VALUES(%s, %s, %s, %s, %s)".format(
                    ewcfg.col_id_book,
                    ewcfg.col_id_server,
                    ewcfg.col_id_user,
                    ewcfg.col_bought,
                    ewcfg.col_rating,
                ), (
                    self.id_book,
                    self.id_server,
                    self.id_user,
                    self.bought,
                    self.rating,
                ))

            conn.commit()
        finally:
            # Clean up the database handles.
            cursor.close()
            bknd_core.databaseClose(conn_info)


import django_filters
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated
from rest_framework import permissions
from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticatedOrReadOnly

from .models import Participant, ParticipantHistory, Subject
from .serializer import ParticipantSerializer, ParticipantHistorySerializer, SubjectSerializer

class SubjectViewSet(viewsets.ModelViewSet):
    """学科一覧を取得
    Returns:
        Object: 学科一覧データ
    """
    permission_classes = [AllowAny]
    queryset = Subject.objects.all()
    serializer_class = SubjectSerializer

class ParticipantViewSet(viewsets.ModelViewSet):
    """参加者テーブルからデータ取得
    """
    queryset = Participant.objects.all()
    serializer_class = ParticipantSerializer

    def get_queryset(self):
        """GETメソッド処理
        Returns:
            Object: 参加者情報
        """
        if self.request.query_params.get('phone_number') == None:
            queryset = Participant.objects.all()
            return queryset
        else:
            family_name = self.request.query_params.get('family_name')
            first_name = self.request.query_params.get('first_name')
            birthday = self.request.query_params.get('birthday')
            phone_number = self.request.query_params.get('phone_number')
            postal_code = self.request.query_params.get('postal_code')

            queryset = Participant.objects.filter(
                family_name=family_name,
                first_name=first_name,
                birthday=birthday,
                phone_number=phone_number,
                postal_code=postal_code)
            return queryset

    def get_permissions(self):
        if 'phone_number' in self.request.query_params:
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]

class ParticipantHistoryViewSet(viewsets.ModelViewSet):
    queryset = ParticipantHistory.objects.all()
    serializer_class = ParticipantHistorySerializer

    def get_queryset(self):
        """GETメソッド処理
        Returns:
            Object: 参加者情報
        """
        if self.request.query_params.get('join_day') == None:
            queryset = ParticipantHistory.objects.all()
            return queryset
        else:
            join_day = self.request.query_params.get('join_day')
            queryset = ParticipantHistory.objects.filter(
                join_day=join_day)
            return queryset

    def get_permissions(self):
        if self.request.method == 'POST':
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]


import pathlib
import requests
import os
import sqlite3
import time

class Data:

    def __init__(self, filename="settings/chats.db"):

        #only checks whether the file exists if default path is used
        self.con = sqlite3.connect(filename)
        cur = self.con.cursor()
        cur.execute('''CREATE TABLE IF NOT EXISTS Users(userId INT PRIMARY KEY)''')
        cur.execute('''CREATE TABLE IF NOT EXISTS RSS_News(title TEXT PRIMARY KEY, Timestamp TEXT)''')
        self.con.commit()
        cur.close()

    def get_chats(self):
        cur = self.con.cursor()
        cur.execute('''SELECT * FROM Users''')
        users = [x[0] for x in cur.fetchall()]
        cur.close()
        return users

    def add_chats(self, chat_ids):
        cur = self.con.cursor()
        for id in chat_ids:
            cur.execute('''INSERT INTO Users VALUES (''' + str(id) + ')')
        self.con.commit()
        cur.close()

    def remove_chats(self, chat_ids):
        cur = self.con.cursor()
        for id in chat_ids:
            cur.execute('''DELETE FROM Users WHERE userId=''' + str(id))
        self.con.commit()
        cur.close()

    def get_rss_news(self):
        cur = self.con.cursor()
        cur.execute('SELECT title FROM RSS_News')
        news = [x[0] for x in cur.fetchall()]
        cur.close()
        return news

    def add_rss_news(self, title):
        timestamp = time.time()
        cur = self.con.cursor()
        cur.execute("INSERT INTO RSS_News VALUES('" + title + "','" + str(timestamp) + "')")
        self.con.commit()
        cur.close()


def oneAway(s1,s2):
    #checking for insertion and deletion
    if len(s1) == len(s2):
        checkReplace(s1,s2)
    elif len(s1)-1 == len(s2):
        checkID(s1,s2)
    elif len(s1) == len(s2)-1:
        checkID(s1,s2)
    else:
        return False

def checkReplace(s1,s2):
    count = 0
    for i in range(len(s1)):
        if s2[i] != s1[i]:
            count += 0
    if count <= 1:
        return True
    else:
        return False

def CheckID(s1,s2):
    count = 0
    if len(s1) > len(s2):
        for i in range(len(s1)):
            if s1[i] not in s2:
                count += 1
    if len(s2) > len(s1):
        for i in range(len(s2)):
            if s2[i] not in s1:
                count += 1
    if count <= 1:
        return True
    else:
        return False


import sys
from bs4 import BeautifulSoup
from xml.sax import saxutils
import re

if __name__ == '__main__':

    mode = sys.argv[1]

    if mode == 'escape_title':

        path = sys.argv[2]

        out_path = sys.argv[3]

        in_file = open(path, 'r')

        def match_function(match):
            group = match.group(1)
            return '<title>' + group.replace('&', '&').replace('<', '<').replace('>', '>') + '</title>'
        content = in_file.read()
        content = re.sub(r'<title>(.+)</title>', match_function, content)

        out_file = open(out_path, 'w')

        out_file.write(content)

        # soup = BeautifulSoup(in_file.read(), features="xml")
        #
        # # print(soup)
        #
        # out_file = open(out_path, 'w')
        #
        # content = soup.findAll('title')
        # for i, element in enumerate(content):
        #     print(element.name)
        #     if element.name == 'title':
        #         print(element)
        #         element.stringsax = saxutils.escape(element.text)
        #         print(element)

        # out_file.write(content)


# -*- coding: utf-8 -*-
"""
Created on Fri Nov  6 12:56:13 2020

@author: USER
"""

import pandas as pd
import datetime as dt

df_tr = pd.read_excel (r'KPMG_VI_New_raw_data_update_final.xlsx', sheet_name='Transactions')
df_nc = pd.read_excel (r'KPMG_VI_New_raw_data_update_final.xlsx', sheet_name='NewCustomerList')
df_cd = pd.read_excel (r'KPMG_VI_New_raw_data_update_final.xlsx', sheet_name='CustomerDemographic')
df_ca = pd.read_excel (r'KPMG_VI_New_raw_data_update_final.xlsx', sheet_name='CustomerAddress')

df_tr.Profit = df_tr.list_price - df_tr.standard_cost

age = pd.to_datetime(df_nc.DOB)

def from_dob_to_age(born):
    today = dt.date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
#age column for new customers
age = age.apply(lambda x: from_dob_to_age(x))
df_nc.insert(5, "Age", age, True)

age = pd.to_datetime(df_cd.DOB)

#age column for old customers
age = age.apply(lambda x: from_dob_to_age(x))
df_cd.insert(6, "Age", age, True)

bins= [0,10,20,30,40,50,60,70,80,90]
labels = ['0-10','10-20','20-30','30-40','40-50','50-60','60-70','70-80','80+']
df_nc['AgeGroup'] = pd.cut(df_nc['Age'], bins=bins, labels=labels, right=False)
df_cd['AgeGroup'] = pd.cut(df_cd['Age'], bins=bins, labels=labels, right=False)

with pd.ExcelWriter('Updated_dataset.xlsx') as writer:
    df_tr.to_excel(writer, sheet_name='Transactions')
    df_nc.to_excel(writer, sheet_name='NewCustomerList')
    df_cd.to_excel(writer, sheet_name='CustomerDemographic')
    df_ca.to_excel(writer, sheet_name='CustomerAddress')


from __future__ import print_function
import sys
from . import getmac

def main():
    try:
        import argparse
    except ImportError:
        print("You must install argparse on Python 2.6 and below ('pip install argparse')")
        sys.exit(1)

    description = 'Get the MAC address of system network ' \
                  'interfaces or remote hosts on the LAN'
    parser = argparse.ArgumentParser('getmac', description=description)
    parser.add_argument('--version', action='version',
                        version='getmac %s' % getmac.__version__)
    parser.add_argument('-d', '--debug', action='count',
                        help='Enable debugging output. Add characters to '
                             'increase verbosity of output, e.g. \'-dd\'.')
    parser.add_argument('--no-network-requests', action='store_true',
                        help='Do not send a UDP packet to refresh the ARP table')

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-i', '--interface', type=str, default=None,
                       help='Name of a network interface on the system')
    group.add_argument('-4', '--ip', type=str, default=None,
                       help='IPv4 address of a remote host')
    group.add_argument('-6', '--ip6', type=str, default=None,
                       help='IPv6 address of a remote host')
    group.add_argument('-n', '--hostname', type=str, default=None,
                       help='Hostname of a remote host')

    args = parser.parse_args()

    if args.debug:
        getmac.DEBUG = args.debug

    mac = getmac.get_mac_address(
        interface=args.interface, ip=args.ip,
        ip6=args.ip6, hostname=args.hostname,
        network_request=not args.no_network_requests)

    if mac is not None:
        print(mac)
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == '__main__':
    main()


import keyboard
while True:
    print("_____________________________Tamrin #4 _________________________________\n\n")
    MySentence = "farshad,nematpour,25,Ahvaz,Mashhad,Azad-University,Data-Minning"
    print("Our words are: ",MySentence)
    input("enter for Spliting: ")

    MySentence_Splited = MySentence.split(",")
    print("Word after packaging : ", MySentence_Splited)

    print("\n___________________________Farshad NematPour ___________________________\n\n")
    keyboard.wait('q')
    keyboard.send('ctrl+6')


import datetime as dt
from typing import List

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import relationship

from scrum.db.base_class import Base
from scrum.db_models.accessible_project import AccessibleProject, Roles

class Project(Base):
    __tablename__ = 'projects'

    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, index=True)
    description = Column(String(2000))
    color = Column(String, default='#3F51B5')
    created_at = Column(DateTime, default=dt.datetime.utcnow())
    users: List[AccessibleProject] = relationship('AccessibleProject', cascade='save-update, delete')
    sprint_length = Column(Integer, nullable=False, default=2)
    tags = relationship('Tag', cascade='save-update, delete')
    tasks = relationship('Task', cascade='save-update, delete')
    sprints = relationship('Sprint', cascade='save-update, delete')

    def __init__(self, creator_id: int, **kwargs):
        super().__init__(**kwargs)
        ap = AccessibleProject(user_id=creator_id, role=Roles.owner)
        self.users.append(ap)


#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# -*- Mode: python -*-

from lib.common import DataStore
from lib.logger import logger
import shlex
import random
import os
import sys
import time
import string
import ntpath

try:
    from impacket.dcerpc.v5 import atsvc
    from impacket.dcerpc.v5.dtypes import NULL
    from impacket.dcerpc.v5 import tsch
except ImportError:
    sys.stderr.write('atexec: Impacket import error')
    sys.stderr.write('atexec: Impacket by SecureAuth Corporation is required for this tool to work. Please download it using:'
                     '\npip: pip install -r requirements.txt\nOr through your package manager:\npython-impacket.')
    sys.exit(255)

###############################################################
# Code borrowed and adapted from Impacket's atexec.py example #
###############################################################
class AtSvc(object):
    def __init__(self):
        pass

    def atexec(self, command):
        def output_callback(data):
            print(data.decode('utf-8'))

        if DataStore.version_major < 6:
            logger.warn('This command only works on Windows >= Vista')
            return

        self.__tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp'
        self.__at_command = command
        self.__atsvc_connect()

        xml = """<?xml version="1.0" encoding="UTF-16"?>
        <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
          <Triggers>
            <CalendarTrigger>
              <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary>
              <Enabled>true</Enabled>
              <ScheduleByDay>
                <DaysInterval>1</DaysInterval>
              </ScheduleByDay>
            </CalendarTrigger>
          </Triggers>
          <Principals>
            <Principal id="LocalSystem">
              <UserId>S-1-5-18</UserId>
              <RunLevel>HighestAvailable</RunLevel>
            </Principal>
          </Principals>
          <Settings>
            <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
            <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
            <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
            <AllowHardTerminate>true</AllowHardTerminate>
            <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
            <IdleSettings>
              <StopOnIdleEnd>true</StopOnIdleEnd>
              <RestartOnIdle>false</RestartOnIdle>
            </IdleSettings>
            <AllowStartOnDemand>true</AllowStartOnDemand>
            <Enabled>true</Enabled>
            <Hidden>true</Hidden>
            <RunOnlyIfIdle>false</RunOnlyIfIdle>
            <WakeToRun>false</WakeToRun>
            <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
            <Priority>7</Priority>
          </Settings>
          <Actions Context="LocalSystem">
            <Exec>
              <Command>cmd.exe</Command>
              <Arguments>/C %s > %%windir%%\\Temp\\%s 2>&1</Arguments>
            </Exec>
          </Actions>
        </Task>
                """ % (self.__at_command, self.__tmpFileName)

        taskCreated = False
        try:
            logger.info('Creating task \\%s' % self.__tmpFileName)
            tsch.hSchRpcRegisterTask(self.__dce, '\\%s' % self.__tmpFileName, xml,
                                     tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE)
            taskCreated = True

            logger.info('Running task \\%s' % self.__tmpFileName)
            tsch.hSchRpcRun(self.__dce, '\\%s' % self.__tmpFileName)

            done = False
            while not done:
                logger.debug('Calling SchRpcGetLastRunInfo for \\%s' % self.__tmpFileName)
                resp = tsch.hSchRpcGetLastRunInfo(self.__dce, '\\%s' % self.__tmpFileName)
                if resp['pLastRuntime']['wYear'] != 0:
                    done = True
                else:
                    time.sleep(2)

            logger.info('Deleting task \\%s' % self.__tmpFileName)
            tsch.hSchRpcDelete(self.__dce, '\\%s' % self.__tmpFileName)
            taskCreated = False
        except tsch.DCERPCSessionError as e:
            logger.error(e)
            e.get_packet().dump()
        finally:
            if taskCreated is True:
                tsch.hSchRpcDelete(self.__dce, '\\%s' % self.__tmpFileName)

        self.transferClient = self.trans.get_smb_connection()
        waitOnce = True
        while True:
            try:
                logger.info('Attempting to read ADMIN$\\Temp\\%s' % self.__tmpFileName)
                self.transferClient.getFile('ADMIN$', 'Temp\\%s' % self.__tmpFileName, output_callback)
                break
            except Exception as e:
                if str(e).find('SHARING') > 0:
                    time.sleep(3)
                elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0:
                    if waitOnce is True:
                        # We're giving it the chance to flush the file before giving up
                        time.sleep(3)
                        waitOnce = False
                    else:
                        raise
                else:
                    raise
        logger.debug('Deleting file ADMIN$\\Temp\\%s' % self.__tmpFileName)
        self.transferClient.deleteFile('ADMIN$', 'Temp\\%s' % self.__tmpFileName)
        self.__atsvc_disconnect()

    def __atsvc_connect(self):
        '''
        Connect to atsvc named pipe
        '''
        self.check_share(DataStore.writable_share)

        logger.debug('Connecting to the ATSVC named pipe')
        self.smb_transport('atsvc')

        logger.debug('Binding on Task Manager (ATSVC) interface')
        self.__dce = self.trans.get_dce_rpc()
        self.__dce.set_credentials(*self.trans.get_credentials())
        self.__dce.connect()
        self.__dce.bind(tsch.MSRPC_UUID_TSCHS)

    def __atsvc_disconnect(self):
        '''
        Disconnect from samr named pipe
        '''
        logger.debug('Disconnecting from the ATSVC named pipe')
        self.__dce.disconnect()


# coding=utf-8

'''
Author: Amos.Li
Email: hpu120623@126.com

date: 2020/4/5 15:49
'''
"""柱状图bar"""
import numpy as np
from matplotlib import pyplot as plt

x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
plt.bar(x, y1, width, color='r')
plt.bar(x + width, y2, width, color='g')
plt.xticks(x + width, ['a', 'b', 'c', 'd', 'e'])
plt.show()


from numpy import linalg as LA

with open("../dataset/py/data_2d2cxn.txt", "r") as f:
  data = f.read()
  points = data.split()
x_pos = list(map(float, points[::2]))
y_pos = list(map(float, points[1::2]))
x_bar = sum(x_pos)/len(x_pos)
y_bar = sum(y_pos)/len(y_pos)
ri = [((i-x_bar)**2 + (j-y_bar)**2) ** (1/2) for i,j in zip(x_pos, y_pos)]
R = sum(ri)
x = sum((i*j) for i,j in zip(ri, x_pos)) / R
y = sum((i*j) for i,j in zip(ri, y_pos)) / R
print("x  = {}, y  = {}".format(x_bar, y_bar))
print("x' = {}, y' = {}".format(x, y))
boundary = [-(y_bar-y), (x_bar-x)]
norm = LA.norm(boundary)
boundary = [boundary[0]/norm, boundary[1]/norm]
print(boundary)


num1 = int(input("Enter a number \n"))
s = len(str(num1))
str1 = str(num1 * num1)
#print("Square of the number is",str1)
while (len(str1) / 2) != s:
    str1 = "0" + str1

num2 = ""
num3 = ""
for eq1 in range(int(len(str1) / 2)):
    num2 += str1[eq1]
#print(num2)
for eq2 in range(int(len(str1) / 2), len(str1)):
    num3 += str1[eq2]
#print(num3)
add = int(num2) + int(num3)

if add == num1:
    #print(num1,"is equal to", add)
    print("It is kaprekar number")
else:
    #print(num1,"is not equal to ",add)
    print("It is not a kaprekar number")


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authentication import BasicAuthentication
from rest_framework.authentication import TokenAuthentication
from rest_framework import permissions
from rest_framework import parsers
import json
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q

from categories.models      import Category
from direct_messages.models import DirectMessage
from direct_messages.models import DirectMessageContent
from favorite.models        import Favorite
from items.models           import Item
from item_contacts.models   import ItemContact
from profiles.models        import Profile
from solicitudes.models     import Solicitud

from api.constants import SerializerContextKey
from api.constants import BtnChoice
from api.constants import CategoryValue

from api.serializers import ItemSerializer
from api.serializers import ProfileSerializer
from api.serializers import SolicitudSerializer
from api.serializers import ItemContactSerializer
from api.serializers import SolicitudSerializer

from api.utils import getTokenFromHeader
from api.utils import getUserByToken, getItemDetailUrl

class ItemListAPIView(APIView):
    """
    endpoint: 'items/list/'
    name: 'api:item_list'
    #dar,venderを一覧するView
    """

    def get(self, request, *args, **kwargs):
        serializerContext = {}
        item_objects = Item.objects.all().exclude(active=False).order_by("-created_at")
        serializer = ItemSerializer(item_objects, many=True)
        serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data

        return Response(serializerContext)

class ItemHomeListAPIView(APIView):
    """
    endpoint: 'api/items/home/list'
    name: "api:item_home_list"
    """
    def get(self, request, *args, **kwargs):
        serializerContext = {}
        #las cosas
        #item_objects_cosas = Item.objects.filter(category__number="1").filter(category__number="2").filter(category__number="3").order_by("-created_at")
        item_objects_cosas = Item.objects.filter(Q(category__number="1")|Q(category__number="2")|Q(category__number="3")).exclude(active=False).order_by("-id")
        serializer_cosas = ItemSerializer(item_objects_cosas, many=True)

        item_objects_habitacion = Item.objects.filter(Q(category__number="4")|Q(category__number="5")|Q(category__number="6")|Q(category__number="7")).exclude(active=False).order_by("-id")
        serializer_habitacion = ItemSerializer(item_objects_habitacion, many=True)

        item_objects_trabajo = Item.objects.filter(Q(category__number="8")|Q(category__number="9")).exclude(active=False).order_by("-id")
        serializer_trabajo = ItemSerializer(item_objects_trabajo, many=True)

        item_objects_tienda = Item.objects.filter(category__number="10").exclude(active=False).order_by("-id")
        serializer_tienda = ItemSerializer(item_objects_tienda, many=True)

        serializerContext[SerializerContextKey.ITEM_OBJECTS_COSAS]      = serializer_cosas.data
        serializerContext[SerializerContextKey.ITEM_OBJECTS_HABITACION] = serializer_habitacion.data
        serializerContext[SerializerContextKey.ITEM_OBJECTS_TRABAJO]    = serializer_trabajo.data
        serializerContext[SerializerContextKey.ITEM_OBJECTS_TIENDA]     = serializer_tienda.data
        return Response(serializerContext)

class ItemCategoryListAPIView(APIView):

    def get(self, request, *args, **kwargs):
        """機能

        endpoint: 'api/items/category/<int:pk>/items/list/'
        name: -
        """
        """テスト項目
        """
        category_number = self.kwargs["pk"]

        if category_number == 999:
            return redirect('api:item_home_list')
        elif category_number == 500:
            #500 --- Las Cosas...(1,2,3) dar o donar, busca donante, quiere avisarのカテゴリを一括にしたもの / categories.models.py 参照すること
            itemObjects = Item.objects.filter(Q(category__number="1")|Q(category__number="2")|Q(category__number="3")).exclude(active=False).order_by("-id")
            serializer  = ItemSerializer(itemObjects, many=True)
            serializerContext = {}
            serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data
            return Response(serializerContext)

        elif category_number == 600:
            #600 --- Habitacion...(4,5,6,7) buscar habitacion, alquilar habitacion, dar pencionado, busco pencionista
            itemObjects = Item.objects.filter(Q(category__number="4")|Q(category__number="5")|Q(category__number="6")|Q(category__number="7")).exclude(active=False).order_by("-id")
            serializer = ItemSerializer(itemObjects, many=True)
            serializerContext = {}
            serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data
            return Response(serializerContext)

        elif category_number == 700:
            #700 --- trabajo ...(8,9) buscar empleo, buscar trabajador
            itemObjects = Item.objects.filter(Q(category__number="8")|Q(category__number="9")).exclude(active=False).order_by("-id")
            serializer = ItemSerializer(itemObjects, many=True)
            serializerContext = {}
            serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data
            return Response(serializerContext)

        elif category_number == 800:
            #800 ___ Empresas y Servicios ...(10) publicidad de Enpresas y Servicios
            itemObjects = Item.objects.filter(category__number="10").exclude(active=False).order_by("-id")
            serializer = ItemSerializer(itemObjects, many=True)
            serializerContext = {}
            serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data
            return Response(serializerContext)

        #print(category_number)
        categoryObj = Category.objects.get(number=category_number)
        itemObjects = Item.objects.filter(category=categoryObj).exclude(active=False).exclude(active=False).order_by("-created_at")
        serializer  = ItemSerializer(itemObjects, many=True)
        serializerContext = {}
        serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data

        return Response(serializerContext)

class ItemCategoryLocalListAPIView(APIView):
    #dar,venderを一覧するView
    # このAPIViewを発行するときはクライアントは必ずユーザー認証が終わっているので、ユーザー認証等は考える必要ない。

    def get(self, request, *args, **kwargs):
        """機能

        endpoint: 'api/items/category/<int:pk>/items/list/local/'
        name: -
        """
        """テスト項目
        """

        token = getTokenFromHeader(self)
        userObj = getUserByToken(token)
        profileObj  = Profile.objects.get(user=userObj)

        category_number = self.kwargs["pk"]
        #print(category_number)
        categoryObj = Category.objects.get(number=category_number)
        itemObjects = Item.objects.filter(category=categoryObj).filter(adm1=profileObj.adm1).exclude(active=False).order_by("-created_at")
        serializer  = ItemSerializer(itemObjects, many=True)
        serializerContext = {}
        serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data

        return Response(serializerContext)

class ItemFavoriteListAPIVIiew(APIView):
    """
    requestUserがのfav記事リスト一覧を表示する
    endpoint: 'items/user/item_favorite_list/'
    name: -s
    """

    def get(self, request, *args, **kwargs):

        #アクセスユーザーの制限
        token = getTokenFromHeader(self)
        requestUser = getUserByToken(token)
        if requestUser == None:
            return Response({"result": "fail"})

        favItemObjects = Item.objects.filter(favorite_users=requestUser).exclude(active=False)
        serializer = ItemSerializer(favItemObjects, many=True)

        #serializerContextに表示するデータを格納
        serializerContext={}
        serializerContext[SerializerContextKey.ITEM_OBJECTS] = serializer.data

        #成功した場合のレスポンスを返す
        return Response(serializerContext)

class ItemDetailSerializerAPIView(APIView):

    authentication_classes = ()
    #permission_classes = (permissions.IsAuthenticated,)

    def get_object(self):

        try:
            pk = self.kwargs["pk"]
            return Item.objects.get(pk=pk)
        except Item.DoesNotExist:
            raise Response({"result":"fail", "detail":"no exists"})

    def isChangedCategoryValue(self, item_obj, jsonData):
        """機能
        patchのみで使うメソッド
        patchで送信されたデータと変更対象となるデータの比較を行い、categoryだけ変更があった場合にはTrueを返す
        """

        if item_obj.category.number != jsonData["category"]["number"]:
            return True
        return False

    def get(self, request, *args, **kwargs):

        """機能
        endpointに対応する記事データを返す

        endpoint: "api/items/<int:pk>/"
        name: "item_detail"

        必要なオブジェクト
        item_obj, profile_obj, solicitudes_objects, direct_messages_objects
        ItemContactに関しては最新の５コメントしか表示しない仕様である。

        """
        """テスト項目
        済 ItemオブジェクトがResponseとして返される
        済 endpoint内のintに対応するidの記事データが返される
        済 ItemContactオブジェクトがItemオブジェクトのプロパティとしてResponseで返される
        済 UserオブジェクトがItemオブジェクトのプロパティとしてResponseで返される
        済 SolicitudオブジェクトがItemオブジェクトのプロパティとしてResponseで返される
        """

        pk = self.kwargs["pk"]
        item_obj = Item.objects.get(id=pk)
        item_obj_serializer = ItemSerializer(item_obj)
        user_obj = item_obj.user
        profile_obj = Profile.objects.get(user=item_obj.user)
        profile_obj_serializer  = ProfileSerializer(profile_obj)
        solicitudes_objects     = item_obj.solicitudes.all()
        solicitudSerializer     = SolicitudSerializer(solicitudes_objects, many=True)
        item_contact_objects    = item_obj.item_contacts.all().order_by("-timestamp")[:5]
        item_contact_objects_serializer = ItemContactSerializer(item_contact_objects, many=True)
        direct_messages_objects = DirectMessage.objects.filter(item=item_obj)

        # 共通のデータをserializer_contextに格納する
        serializer_context = {}
        serializer_context["item_obj_serializer"] = item_obj_serializer.data
        serializer_context["profile_obj_serializer"] = profile_obj_serializer.data

        token = getTokenFromHeader(self)
        accessUser = getUserByToken(token)

        # serializer_context[SerializerContextKey.BTN_CHOICE]を設定
        if accessUser == None:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.ANONYMOUS_USER_ACCESS

        elif accessUser == user_obj and solicitudes_objects.count() == 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.NO_SOLICITUDES

        elif accessUser == user_obj and solicitudes_objects.count() != 0 and direct_messages_objects.count() == 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.SELECT_SOLICITUDES

        elif accessUser == user_obj and direct_messages_objects.count() != 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.GO_TRANSACTION

        elif accessUser != user_obj and solicitudes_objects.filter(applicant=Profile.objects.get(user=accessUser)).count() == 0 and direct_messages_objects.filter(item=item_obj).count() == 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.SOLICITAR

        elif accessUser != user_obj and solicitudes_objects.filter(applicant=Profile.objects.get(user=accessUser)).count() != 0 and direct_messages_objects.count() == 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.SOLICITADO

        elif accessUser != user_obj and direct_messages_objects.filter(participant=Profile.objects.get(user=accessUser)).count() == 1:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.GO_TRANSACTION

        elif accessUser != user_obj and direct_messages_objects.filter(participant=Profile.objects.get(user=accessUser)).count() == 0:
            serializer_context[SerializerContextKey.BTN_CHOICE] = BtnChoice.CANNOT_TRANSACTION

        #データを送信
        return Response(serializer_context)

    def patch(self, request, *args, **kwargs):
        """
        endpoint: /api/items/<int:pk>/
        name: -
        """
        """テスト項目
        タイトルのみの変更の場合にはタイトルが変更される。
        カテゴリーだけの変更の場合にはカテゴリーの変更が反映される。

        """
        pk = self.kwargs["pk"]
        item_obj = Item.objects.get(id=pk)

        print("ここ通っている？？？")
        print(request.data)

        strJsonData = request.data["jsonData"]
        jsonData = json.loads(strJsonData)

        #categoryName = jsonData.pop("category")["name"]
        #print("CATEGORY_NAME" + categoryName)
        #category_obj = Category.objects.get(name=categoryName)

        imagesData = request.FILES
        #print("IMAGES_DATA    :   ", imagesData)

        isChanged = self.isChangedCategoryValue(item_obj, jsonData)
        if isChanged == True:
            category_obj = Category.objects.get(number=jsonData["category"]["number"])
            item_obj.category = category_obj
            item_obj.save()

        serializer = ItemSerializer(item_obj, data=jsonData, partial=True)
        print("is_valid? : ",serializer.is_valid())
        if serializer.is_valid():
            serializer.save()

            itemId = serializer.instance.id
            url = getItemDetailUrl(itemId)

            if len(request.FILES.keys()) == 0:
                return Response({"result":"success", "detail":url })

            #if len(request.FILES.keys()) > 0:
            print("TRUEが🐸")
            #item_objに画像データを追加修正する。
            try:
                serializer.instance.image1 = imagesData[SerializerContextKey.IMAGE1]
                #item_obj.image1 = imagesData[SerializerContextKey.IMAGE1]
            except:
                pass
            try:
                serializer.instance.image2 = imagesData[SerializerContextKey.IMAGE2]
                #item_obj.image2 = imagesData[SerializerContextKey.IMAGE2]
            except:
                pass
            try:
                serializer.instance.image3 = imagesData[SerializerContextKey.IMAGE3]
                #item_obj.image3 = imagesData[SerializerContextKey.IMAGE3]
            except:
                pass

            serializer.instance.save()
            return Response({"result":"success", "detail":url })

        return Response({"result":"success", "detail":url })

#mypages/views.MyItemListViewに対応
class MyItemListSerializerAPIView(APIView):
    """
    endpoint: api/mylist/
    name:
    """

    def get(self, request, *args, **kwargs):
        serializerContext = {}
        #ユーザー認証されていないときは、ログインページにつなぐ
        if request.auth == None:
            return Response({"result":"fail"})
            # Android端末では"ログインして下さい"を表示させる。

        #自分が作成した記事を表示する
        item_objects = Item.objects.filter(user=request.user).order_by("-created_at")
        if item_objects.count() > 0:

            item_objects_serializer = ItemSerializer(item_objects, many=True)

            print("maji??")
            #print(item_objects_serializer.data)
            return Response({"itemSerializer":item_objects_serializer.data})
        else:
            print("koko??")
            return Response({"itemSerializer":"jeje"})

class ItemFavoriteAPIView(APIView):

    def patch(self, request, *args, **kwargs):
        """
        endpoint: 'api/item/<int:pk>/favorite/'
        name: 'api:item_favorite'

        #機能：Item.favorite_users(ManyToManyField)にFavoriteオブジェクトを追加する。または削除する。
        機能：Item.favorite_users(ManyToManyField)にUserオブジェクトを追加する。または削除する。

        補足:
        このViewを通るのはすべて認証ユーザーである。
        未認証ユーザーがFavボタンを押しても、端末に”ログインしてください”と表示されるのみで通信が行われないから。

        """

        fav_status = None
        users   = []

        token       = getTokenFromHeader(self)
        requestUser = getUserByToken(token)
        itemObjId = self.kwargs["pk"]
        item_obj  = Item.objects.get(id=itemObjId)

        #item_obj.favorite_users.all()を使ってFavoriteオブジェクトに結びついたUserオブジェクトをリスト化する
        for user_obj in item_obj.favorite_users.all():
            users.append(user_obj)
            #if user_obj == requestUser:
            #    fav_status = "Favを既に押している"

        if requestUser in users:
            item_obj.favorite_users.remove(requestUser)

        elif requestUser not in users:
            item_obj.favorite_users.add(requestUser)

        return Response({"result":"success"})

class ItemCreateAPIViewMulti(APIView):

    """
    Itemオブジェクトを生成するために、
    user_obj, title, description, category_obj, adm0, adm1, adm2, image1, image2, image3を取得する。
    段階に分けて
    ① user_obj,
    ② category_obj,
    ③ title, description, adm0, adm1, adm2,
    ④ image1, image2, image3
    でItemオブジェクトを生成する。

    """

    authentication_classes = (TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    parser_classes = (parsers.MultiPartParser,)

    def post(self, request, *args, **kwargs):

        #① user_objを取得
        token = getTokenFromHeader(self)
        user_obj = getUserByToken(token)
        #print(token)

        #② category_objを取得
        #print("REQUEST_DATA")
        #print(request.data)
        strJsonData = request.data["jsonData"]
        jsonData = json.loads(strJsonData)
        #print(jsonData)

        categoryNumber = jsonData.pop("category")["number"]
        #print("CATEGORY_NAME" + categoryNumber)
        category_obj = Category.objects.get(number=categoryNumber)
        jsonData["category"] = category_obj.id

        #③ title, description, adm0, adm1, adm2を取得
        #serializer.is_valid()がTrueのとき各要素を取得する

        imagesData = request.FILES
        #print("IMAGES_DATA    :   ", imagesData)

        serializer = ItemSerializer(data=jsonData)

        if serializer.is_valid():
            print("SERIALIZER.IS_VALID : TRUE")

            item_obj = Item.objects.create(
                title = jsonData["title"],
                user = user_obj,
                description = jsonData["description"],
                price = jsonData["price"],
                category = category_obj,
                adm0 = jsonData["adm0"],
                adm1 = jsonData["adm1"],
                adm2 = serializer.validated_data["adm2"]
                )

            try:
                point = jsonData["point"]
                item_obj.point = point
                item_obj.save()
            except:
                pass
            try:
                radius = jsonData["radius"]
                item_obj.radius = radius
                item_obj.save()
            except:
                pass

            url = getItemDetailUrl(item_obj.id)

            #print("ItemObject生成成功")

            if len(request.FILES.keys()) > 0:
                print("TRUEが🐸")
                #item_objに画像データを追加修正する。
                try:
                    item_obj.image1 = imagesData[SerializerContextKey.IMAGE1]
                except:
                    pass
                try:
                    item_obj.image2 = imagesData[SerializerContextKey.IMAGE2]
                except:
                    pass
                try:
                    item_obj.image3 = imagesData[SerializerContextKey.IMAGE3]
                except:
                    pass

                item_obj.save()
                return Response({"result":"success", "detail":url })

            return Response({"result":"success", "detail":url})

        elif serializer.is_valid() == False:
            print("SERIALIZER.IS_VALID : False")
            for ele in serializer:
                print(ele)

            return  Response({"result":"fail"})

'''
# items/views.py ItemCreateView(View)に対応
class ItemCreateAPIView(APIView):

    """
    endpoint: 'api/item_create/'
    name: -

    """

    authentication_classes = (TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    #parser_classes = (parsers.MultiPartParser,)

    def post(self, request, *args, **kwargs):

        print("REQUEST.DATA   :   ")
        print(request.data)

        print(type(request.data))

        token = getTokenFromHeader(self)
        user_obj = getUserByToken(token)

        data = request.data
        categoryName = data.pop("category")["name"]
        category_obj = Category.objects.get(name=categoryName)

        serializer = ItemSerializer(data=request.data)
        if serializer.is_valid():
            print("SERIALIZER.IS_VALID : TRUE")
            #serializer.validated_data["user"] = user_obj

            item_obj = Item.objects.create(
                title = request.data["title"],
                user = user_obj,
                description = request.data["description"],
                category = category_obj,
                adm0 = request.data["adm0"],
                adm1 = request.data["adm1"],
                #adm2 = request.data["adm2"]
                adm2 = serializer.validated_data["adm2"]
                )

            print("ItemObject生成成功")
            #item_obj.user = user_obj
            #item_obj.category = category_obj

            return Response({"result":"success"})

        elif serializer.is_valid() == False:
            print("SERIALIZER.IS_VALID : False")
            #print(serializer.error_messages)

            #print(serializer.user.error_messages)
            for ele in serializer:
                print(ele)

            #print(serializer.errors())

            return  Response({"result":"fail"})

'''


__author__ = 'Muneer'
import  pygame, random,math, pygame.gfxdraw, Sound
import game_objects

class Item(pygame.sprite.Sprite):
    # something that is collected by the player
    # when collected the player is changed
    # depending on the item type
    inner_colour = (0,69,178)
    outer_colour = (0,99,255)
    def __init__(self, position):
        pygame.sprite.Sprite.__init__(self)
        self.type = random.randint(1,1)
        self.position = position
        self.direction = random.randint(0, 360)
        self.speed = 200
        self.size = self.radius = 16
        self.needs_removing = False

    def update(self,deltaT):
        # driiiffffttt
        x,y = self.position
        x += int(self.speed*math.cos(math.radians(self.direction))*deltaT)
        y += int(self.speed*math.sin(math.radians(self.direction))*deltaT)
        self.position = x,y

    def draw(self, screen):
        # draw outer
        pygame.gfxdraw.aacircle(screen,int(self.position[0]), int(self.position[1]), self.radius, self.outer_colour)
        pygame.gfxdraw.filled_circle(screen,int(self.position[0]), int(self.position[1]), self.radius, self.outer_colour)
        # draw inner
        pygame.gfxdraw.aacircle(screen,int(self.position[0]), int(self.position[1]), self.radius-2, self.inner_colour)
        pygame.gfxdraw.filled_circle(screen,int(self.position[0]), int(self.position[1]), self.radius-2, self.inner_colour)

    def NoType(self, player):
        pass

    def HealthUp(self,player):
        player.lives += 1

    def on_collect(self, player):
        if self.type == ItemType.HealthUp:
            self.HealthUp(player)
        elif self.type == ItemType.NoType:
            self.NoType(player)

    def collision_response(self, other):
        # if we collided with player kill ourselves
        if isinstance(other,game_objects.Ship.Ship):
            self.on_collect(other)
            self.needs_removing = True
            Sound.sound_manager.play_sound(Sound.sounds.item_pickup)

class ItemType:
    # enum for ItemTypes
    NoType, HealthUp = range(2)


from Agregar import *

class Modificar(object):
	def cambiarC(self):
		while True:
			print("Presione '5' para salir")
			CorreoM = input("Ingrese el correo que desea modificar ")
			if CorreoM in Registros:
				Usuario1 = IngresoVerificacion(correo, email)
				P = Usuario1.contraseña()
				Registros[CorreoM]=P
				break
			elif CorreoM == "5":
				break
			else:
				print("El correo no existe, vuelva a intentarlo")


'''
AI기초통계
13장 빅데이터 분석 과제
교안 234페이지~235페이지 상단

20. 5. 17.

차재관 작성
'''

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import pandas as pd
from scipy.spatial import distance
# scipy에서 spatial 패키지 중 distance 모듈을 가져오기

proj = ccrs.Mercator()
plt.figure(figsize=(10, 10))
ax = plt.axes(projection = proj)
ax.set_extent((-25.0, 20.0, 52.0, 10.0))
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS, linestyle=':')

def euc(a, b):
    return distance.euclidean(a, b) # 유클리드 거리: 두 점을 계산할 때 사용

birddata = pd.read_csv('bird_tracking.csv')
bird_names = pd.unique(birddata.bird_name)

sindex = 2500 # 시작 인덱스
eindex = 7500 # 끝 인덱스

ix = birddata['bird_name'] == 'Eric'
x, y = birddata.longitude[ix], birddata.latitude[ix]

i = [x[sindex], y[sindex]]
j = [x[eindex], y[eindex]]

ax.plot(x[sindex:eindex], y[sindex:eindex], '.', transform=ccrs.Geodetic())
print('Eric', euc(i, j))

ix = birddata['bird_name'] == 'Nico'
x, y = birddata.longitude[ix], birddata.latitude[ix]

start = len(x)
dest = len(y)

i = [x[start+sindex], y[start+sindex]]
j = [x[dest+eindex], y[dest+eindex]]

ax.plot(x[sindex:eindex], y[sindex:eindex], '.', transform=ccrs.Geodetic())
print('Nico', euc(i, j))

ix = birddata['bird_name'] == 'Sanne'
x, y = birddata.longitude[ix], birddata.latitude[ix]

start = start + len(x)
dest = dest + len(y)

i = [x[start+sindex], y[start+sindex]]
j = [x[dest+eindex], y[dest+eindex]]

ax.plot(x[sindex:eindex], y[sindex:eindex], '.', transform=ccrs.Geodetic())
print('Sanne', euc(i, j))
plt.show()


from mpl_toolkits.mplot3d import Axes3D
import re
import folium
from folium.plugins import HeatMap
import pandas as pd
import numpy as np
import geohash2
import matplotlib.pyplot as plt

df = pd.read_csv(
    'D:\\Program_file\\python_file\\python.con\\mobike_train_data.csv')

df['starttime'] = pd.to_datetime(df.starttime)
df = df.sort_values(by='starttime', ascending=True)
df.index = df['starttime']
#df = df['2017-05-15 06:00:00' : '2017-05-15 06:30:00']

dayTimeIndex = [x for x in range(0, 24)]
dayTime = [[0]*24, [0]*24]
Count = []
for a in range(10, 25):
    One = []
    for b in range(23):
        dx = df["2017-05-{:0>2d} {:0>2d}:00:00".format(
            a, dayTimeIndex[b]): "2017-05-{:0>2d} {:0>2d}:00:00".format(a, dayTimeIndex[b+1])]
        One.append(dx.shape[0])
        dayTime[0][b] += dx.shape[0]
        if dx.shape[0] != 0:
            dayTime[1][b] += 1
    dx = df["2017-05-{:0>2d} {:0>2d}:00:00".format(
            a, 23): "2017-05-{:0>2d} {:0>2d}:00:00".format(a + 1, 0)]
    One.append(dx.shape[0])
    dayTime[0][23] += dx.shape[0]
    if dx.shape[0] != 0:
        dayTime[1][23] += 1
    Count.append(One)

df = pd.read_csv(
    'D:\\Program_file\\python_file\\python.con\\mobike_train_data.csv', usecols=['starttime', 'geohashed_start_loc', 'geohashed_end_loc'])
fig = plt.figure(figsize=(18, 10))

for hour_one in range(8, 10):
    df7_start = pd.DataFrame(columns=['j1', 'w1', 'xx'])
    df7_end = pd.DataFrame(columns=['j2', 'w2'])
    df14_start = pd.DataFrame(columns=['j1', 'w1', 'xx'])
    df14_end = pd.DataFrame(columns=['j2', 'w2'])

    for i in range(df.shape[0]):
        # 2017-05-(10|11|12|15|16|17|18|19|22|23)\s(06|07|08):\d\d:\d\d
        an = re.search(
            '2017-05-(13|14)\s{:0>2d}:1\d:\d\d'.format(hour_one), df.iloc[i, 0])
        if(an):
            df7_start = df7_start.append(
                [{'j1': geohash2.decode(df.iloc[i][1])[0], 'w1': geohash2.decode(df.iloc[i][1])[1], 'xx':1}], ignore_index=True)
            df7_end = df7_end.append(
                [{'j2': geohash2.decode(df.iloc[i][2])[0], 'w2':geohash2.decode(df.iloc[i][2])[1], 'xx':1}], ignore_index=True)

        # 2017-05-(10|11|12|15|16|17|18|19|22|23)\s(06|07|08):\d\d:\d\d
        an = re.search(
            '2017-05-(13|14)\s{:0>2d}:1\d:\d\d'.format(hour_one), df.iloc[i, 0])
        if(an):
            df14_start = df14_start.append(
                [{'j1': geohash2.decode(df.iloc[i][1])[0], 'w1': geohash2.decode(df.iloc[i][1])[1], 'xx':1}], ignore_index=True)
            df14_end = df14_end.append(
                [{'j2': geohash2.decode(df.iloc[i][2])[0], 'w2':geohash2.decode(df.iloc[i][2])[1], 'xx':1}], ignore_index=True)

    dx = df7_start.groupby(by=[df7_start["j1"], df7_start["w1"]])
    di = dx.count()['xx']
    start_count_1 = di.sort_values()
    dx = df7_end.groupby(by=[df7_end["j2"], df7_end["w2"]])
    di = dx.count()['xx']
    end_count_1 = di.sort_values()
    d = {"start": start_count_1, "end": end_count_1}
    count_1 = pd.DataFrame(d)
    count_1 = count_1.fillna(0)

    count_1["E-S_7"] = np.nan
    count_1 = count_1.copy()
    for i in range(count_1.shape[0]):
        count_1.iloc[i][2] = count_1.iloc[i][0] - count_1.iloc[i][1]

    # count_1.to_csv('D:/data_count1.csv')

    # ---------------------------------------
    dx = df14_start.groupby(by=[df14_start["j1"], df14_start["w1"]])
    di = dx.count()['xx']
    start_count_2 = di.sort_values()
    dx = df14_end.groupby(by=[df14_end["j2"], df14_end["w2"]])
    di = dx.count()['xx']
    end_count_2 = di.sort_values()
    d = {"start": start_count_2, "end": end_count_2}
    count_2 = pd.DataFrame(d)
    count_2 = count_2.fillna(0)

    count_2["E-S_14"] = np.nan
    count_2 = count_2.copy()
    for i in range(count_2.shape[0]):
        count_2.iloc[i][2] = count_2.iloc[i][0] - count_2.iloc[i][1]

    # count_2.to_csv('D:/data_count2.csv')

    count_1.drop(['start'], axis=1, inplace=True)
    count_1.drop(['end'], axis=1, inplace=True)
    count_2.drop(['start'], axis=1, inplace=True)
    count_2.drop(['end'], axis=1, inplace=True)
    count = pd.merge(count_1, count_2, left_index=True,
                     right_index=True, how='outer')
    count = count.fillna(0)

    count["14-7"] = np.nan
    count = count.copy()
    for i in range(count.shape[0]):
        count.iloc[i][2] = count.iloc[i][1] - \
            count.iloc[i][0]*((Count[10][hour_one]+Count[11]
                               [hour_one])/(Count[3][hour_one]+Count[4][hour_one]))

    # count.to_csv('D:/data_count_count_14-7.csv')
    # -----------------------------------------------------

    x = []
    y = []
    z = []
    for i, j in zip(count_2.index, count_2["E-S_14"]):
        if j != 0 and 39 <= float(i[0]) <= 41 and 116 <= float(i[1]) <= 118:
            x.append(float(i[0]))
            y.append(float(i[1]))
            z.append(j)

    C = []
    for a in z:
        if a < -16:
            C.append('C0')
        elif a < -8:
            C.append('C2')
        elif a < 0:
            C.append('C9')
        elif a < 8:
            C.append('C6')
        elif a < 16:
            C.append('C1')
        elif a > 15:
            C.append('C3')
    plt.subplot(2, 2, (hour_one-7)*2-1)
    ax = fig.add_subplot(111, projection='3d')
    ax.set_zlim(-30, 25)
    ax.bar3d(x, y, 0, dx=0.005, dy=0.005, dz=z, alpha=0.5, color=C)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    ax.set_xlabel('纬度')
    ax.set_ylabel('经度')
    ax.set_zlabel('自行车改变量')

    # -------------------------------------------

    x = []
    y = []
    z = []
    for i, j in zip(count.index, count["14-7"]):
        if j != 0 and 39 <= float(i[0]) <= 41 and 116 <= float(i[1]) <= 118:
            x.append(float(i[0]))
            y.append(float(i[1]))
            z.append(j)

    C = []
    for a in z:
        if a < -16:
            C.append('C0')
        elif a < -8:
            C.append('C2')
        elif a < 0:
            C.append('C9')
        elif a < 8:
            C.append('C6')
        elif a < 16:
            C.append('C1')
        elif a > 15:
            C.append('C3')

    plt.subplot(2, 2, (hour_one-7)*2)
    ax = fig.add_subplot(111, projection='3d')
    ax.set_zlim(-30, 25)
    ax.bar3d(x, y, 0, dx=0.005, dy=0.005, dz=z, alpha=0.5, color=C)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    ax.set_xlabel('纬度')
    ax.set_ylabel('经度')
    ax.set_zlabel('自行车改变量')
fig.show()
fig.savefig("xxx.png", dpi=1000)


# -** coding: utf-8 -*-
from NameCommand import RemoveSeason, RemoveShowName, RemoveGarbage, RemovePoints, BeEpisodePrefix, RemoveWhitespace, RemoveBracketsStrings
from OSCommand import RenameFile, MoveFile, DeleteNFO
from IMDBApi import IMDBLogic
from EpisodeFacotry import EpisodeFacotry
from Episode import Episode
import os

"""
BCD stands for Beautify, Create, Destroy
This is the core of the application.
Depending on the passed bash flag, it opens different
patterns.
"""
class BCD:
    def makeDecision(self, path, key = ''):
        if not path.endswith('/'):
            path = path + '/'

        decideTable = {
            'do' : self.__do,
            'look' : self.__look,
            'imdblook' : IMDBLogic.IMDBLogic().imdbLook,
            'imdbdo' : self.__imdbDo
        }

        episodes = []
        episodes.extend(EpisodeFacotry().decide(path))
        decideTable[key](episodes)

    """
    Do uses the BCD algorithm to generate names, but does not shows any input to the shell
    """
    def __do(self, episodes):
        for e in episodes:
            self.__doOne(e)

    """
    Look uses the BCD algorithm to generate names, but does not change them only shows
    them in the shell.
    """
    def __look(self, episodes):
        for e in episodes:
            self.__lookOne(e)

    def __doOne(self, e):
        DeleteNFO().execute(e)
        RemoveSeason().execute(e)
        RemoveShowName().execute(e)
        RemoveGarbage().execute(e)
        RemovePoints().execute(e)
        BeEpisodePrefix().execute(e)
        RemoveBracketsStrings().execute(e)
        RemoveWhitespace().execute(e)
        RenameFile().execute(e)
        MoveFile().execute(e)

    def __lookOne(self, e):
        RemoveSeason().execute(e)
        RemoveShowName().execute(e)
        RemoveGarbage().execute(e)
        RemovePoints().execute(e)
        BeEpisodePrefix().execute(e)
        RemoveBracketsStrings().execute(e)
        RemoveWhitespace().execute(e)
        print('BCD: ' + e.getName())

    """
    Creates a imbdLogic obj and changes the names of the objects
    to the imdb data, after that it calls all commands through __do()
    """
    def __imdbDo(self, episodes):
        IMDBLogic.IMDBLogic().imdbDo(episodes)
        self.__do(episodes)


from django.utils import timezone

from rafflie.models import User

class UpdateLastActivityMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user'), 'The UpdateLastActivityMiddleware requires authentication middleware to be installed.'
        if request.user.is_authenticated():
            User.objects.filter(user__id=request.user.id) \
                           .update(last_activity=timezone.now())


# _*_ coding:utf-8 _*_
# @time: 2020/10/8 下午6:53
# @author: 张新新
# @email: 1262981714@qq.com

from auto import init_handeye
from auto import score
from auto import simple_campose
from auto import select_simple_pose
from auto import auto_calibration

from Vrep import vrep_connect
from Vrep import UR5
from Vrep import Kinect
from Vrep import Kinect_test

from board import apriltagboard

from handineye import motion
from handineye import rx
from handineye import rz

from method import dual
from method import li
from method import tsai

import cv2
import transforms3d
import numpy as np
import time

import random
import os
import string
import matplotlib.pyplot as plt
fs2 = cv2.FileStorage("../config/intrinsic_gt.yml",cv2.FileStorage_READ)
intrinsic = fs2.getNode("intrinsic").mat()
dist = fs2.getNode("dist").mat()
fs2.release()

fs = cv2.FileStorage("../config/handineye_gt.yml", cv2.FileStorage_READ)
Hcamera2end = fs.getNode("Hcamera2end").mat()
Hobj2base = fs.getNode("Hobj2base").mat()
fs.release()
board = apriltagboard.AprilTagBoard("../config/apriltag.yml", "../config/tagId.csv")
fs = cv2.FileStorage("../config/init_sample.yml",cv2.FileStorage_READ)
init_pose = fs.getNode("initpose").mat()

q = init_pose[:4].flatten()
pose_r = transforms3d.quaternions.quat2mat(q)

pose = np.identity(4)

pose[:3,:3]= pose_r[:,:]
pose[0, 3] = init_pose[4]
pose[1, 3] = init_pose[5]
pose[2, 3] = init_pose[6]
imgsize = (640,480)
fs.release()

cliend = vrep_connect.getVrep_connect()
camera = Kinect.Camera(cliend)
camera2 = Kinect_test.Camera(cliend)
robot = UR5.Robot(cliend)
while (True):
    flag = robot.move(pose)
    if flag:
        break
    robot.go_home()
    robot.go_guodudian()

rgb_image = camera.get_rgb_image()
flag,objpoint,imgpoint = board.getObjImgPointList(rgb_image,verbose=0)
campose = board.extrinsic(imgpoint,objpoint,intrinsic,dist)

candidate_camera_pose = simple_campose.generate_simple_pose("../config/auto_sample.yml", board,
                                                                campose[:3, :3], 0 )
board_max_x = board.marker_X * (board.markerSeparation + board.tag_size)
board_max_y = board.marker_Y * (board.markerSeparation + board.tag_size)
mid_x = board_max_x / 2
mid_y = board_max_y / 2
#board_max_y = board_max_y / 2
mid_points = np.array([[0, mid_x, mid_x, board_max_x],
                       [mid_y, 0, board_max_y, mid_y],
                       [0, 0, 0, 0],
                       [1, 1, 1, 1]])
select_pose = []
all = 0
camera_intrinsic = np.append(intrinsic, np.zeros([3, 1]), 1)

for pose in candidate_camera_pose:

    points = np.dot(camera_intrinsic, np.dot(pose, mid_points))
    folder = ""
    if (points[2, 0] < 0):
        folder = "/home/zhangxinxin/data/campose_test/False"
        print("False")
    else:
        points[:, :] = points[:, :] / points[2, :]
        t = 0
        for j in range(4):
            if points[0, j] > 0 and points[0, j] < imgsize[0] and points[1, j] > 0 and points[1, j] < imgsize[1]:
                t = t + 1
        if t >= 3:
            folder = "/home/zhangxinxin/data/campose_test/True"
            print("True")
        else:
            folder = "/home/zhangxinxin/data/campose_test/False"
            print("false")
        if t == 4:
            all = all + 1
        x = points[0,:]
        y = points[1,:]

    Hcam2base = np.dot(Hobj2base, np.linalg.inv(pose))
    camera2.move(Hcam2base)
    image = camera2.get_rgb_image()
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    cv2.imwrite(os.path.join(folder,ran_str+".png"),image)


#Function to convert integer to binary string
def int2bin(num):
    binString = ''

    while num > 0:
        mod = num % 2
        binString = str(mod)+binString
        num //= 2

    return binString

#Function to calculate fast power
def fastPower(g, x, p):
	result = 1
	while x > 0:
		if x%2 == 1:
			result = result*g %p
		g = g**2 %p
		x //= 2
	return result

#Function to read file
def readFile():
	file = open('input.txt', 'r')
	p = int(file.readline()) #prime number
	g = int(file.readline()) #number who's inverse modulo is to be found
	b = int(file.readline())
	A = int(file.readline())
	cipher = int(file.readline(),2)

	# Calculate shared key as A**b %p
	key = fastPower(A, b, p)

	# Find the secret message
	plain = diffieHelman(cipher, key, p)
	print(plain)

	file.close()

#Decrypt a cipher text using the shared key
def diffieHelman(cipher, key, p):
	#print(cipher)
	#print(key)

	inverseKey = fastPower(key, p-2, p)
	#print(inverseKey)

	plain = int2bin((cipher*inverseKey) %p)

	#print(plain)
	#Return the plain text
	return ''.join(chr(int(plain[(i*8):(i*8 + 8)],2)) for i in range(len(plain)//8))

readFile()


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

# Strict Isolation (SI)
# ms tbs 10000 -t tbs -r tbs tbs -I 2 tbs tbs 0 -n 1 tbs -n 2 tbs -ej tbs 2 1 -eN tbs tbs

from numpy.random import uniform
from numpy.random import binomial
from random import shuffle

nMultilocus = 10000

N_bound = [0, 30]
T_bound = [0, 30]

# read bpfile
infile = open("bpfile", "r")
tmp = infile.readline()
L = infile.readline().strip().split("\t")
nsamA = infile.readline().strip().split("\t")
nsamB = infile.readline().strip().split("\t")
theta = infile.readline().strip().split("\t")
rho = infile.readline().strip().split("\t")
infile.close()

# number of loci
nLoci = len(L)

# sum of nsamA + nsamB
nsam_tot = [ int(nsamA[i]) + int(nsamB[i]) for i in range(nLoci) ]

# param multilocus: values that will be printed in priorfile.txt
## N = N_pop_i / Nref
N1 = uniform(low = N_bound[0], high = N_bound[1], size = nMultilocus)
N2 = uniform(low = N_bound[0], high = N_bound[1], size = nMultilocus)
Na = uniform(low = N_bound[0], high = N_bound[1], size = nMultilocus)

## times
Tsplit = uniform(low = T_bound[0], high = T_bound[1], size = nMultilocus)

# param monolocus: values that will be read by ms
priorfile = "N1\tN2\tNa\tTsplit\n"
for sim in range(nMultilocus):
	priorfile += "{0:.5f}\t{1:.5f}\t{2:.5f}\t{3:.5f}\n".format(N1[sim], N2[sim], Na[sim], Tsplit[sim])

	for locus in range(nLoci):
		print("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6:.5f}\t{7:.5f}\t{8:.5f}\t{9:.5f}\t{10:.5f}".format(nsam_tot[locus], theta[locus], rho[locus], L[locus], nsamA[locus], nsamB[locus], N1[sim], N2[sim], Tsplit[sim], Tsplit[sim], Na[sim]))

outfile = open("priorfile.txt", "w")
outfile.write(priorfile)
outfile.close()


'''
Define crossover operation over two equal-length strings A and B as follows:

the result of that operation is a string of the same length as the input strings
result[i] is either A[i] or B[i], chosen at random
Given array of strings inputArray and a string result, find for how many pairs of strings from inputArray the result of the crossover operation over them may be equal to result.

Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair).

Example

For inputArray = ["abc", "aaa", "aba", "bab"] and result = "bbb", the output should be
stringsCrossover(inputArray, result) = 2.

Input/Output

[execution time limit] 4 seconds (py3)

[input] array.string inputArray

A non-empty array of equal-length strings.

Guaranteed constraints:
2 ≤ inputArray.length ≤ 10,
1 ≤ inputArray[i].length ≤ 10.

[input] string result

A string of the same length as each of the inputArray elements.

Guaranteed constraints:
result.length = inputArray[i].length.

[output] integer
'''

from itertools import combinations

def stringsCrossover(inputArray, result):
    combs = list(combinations(inputArray, 2))
    count = 0
    for combination in combs:
        found = True
        for i, char in enumerate(result):
            if char != combination[0][i] and char != combination[1][i]:
                found = False
                break
        if found:
            count += 1
    return count

inputArray = ["aa", "ab", "ba"]
result = "bb"

print(stringsCrossover(inputArray, result))