import platform
from getmac import get_mac_address as gma
import subprocess
import os
import re
import requests
import socket
from ipaddress import IPv4Network
import argparse
import sys

#Parser pour le choix des arguments
parser = argparse.ArgumentParser(description='Welcome to our Scanner, you can use this tools with multiple arguments. But if you want to perform FullScan, please type : -ps')
parser.add_argument("-d", "--subdom", help="Scan subdomains of a domain name", action='store_true')
parser.add_argument("-p", "--ping", help="Scan numbers of ip and chosen range of ports", action='store_true')
parser.add_argument("-s", "--soc", help="Scan ports for Ip address", action='store_true')
parser.add_argument("-o", "--out", help="Output results in .txt file", action='store_true')
parser.add_argument("-ps", "--full", help="Ports Scan of awaken hosts", action='store_true')
args = parser.parse_args()

# !!! Vous avez besoin d'installer la librairie getmac avant de lancer ce script : "pip install getmac"

# Début du script
# Trouver les informations commune à chaque système :
se = platform.system()
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
path = os.listdir('.')
print("Votre système d'exploitation est : ", se, "\nVotre adresse MAC est : ", gma(), "\nVotre adresse IP est : ", ip)

'''Création d'une fonction pour différencier la commande de récupération d'informations des interfaces
entre Windows et Linux/Mac (ifconfig/ipconfig)'''

def getinfo(se, path):
    if se == "Windows":
        ipconf = subprocess.check_output("ipconfig")

    elif se == "Darwin" or se == "Linux":
        ipconf = subprocess.check_output("ifconfig").decode("utf-8")

    else:
        print("Votre système n'est pas reconnu :/ !")
    # Création du fichier confIP.txt avec la variable ipconf qui différenciera le résultat en fonction du système d'exploitation.
    with open('confIP.txt', 'w+') as file:
        file.write(str(ipconf))

    # Récupération et affichage des adresses IP trouvées dans le fichier confIP.txt
    with open('confIP.txt', 'r') as f:
        pattern = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
        print('\nVoici le(s) Ip trouvée(s) sur votre machine :')
        for line in f:
            final_ip = re.findall(pattern, line)
            if final_ip:
                for i in final_ip:
                    print(i)

    # Liste fichiers du dossier actuel :
    #print("\nVoici les fichiers et dossiers présents dans votre répertoire actuel :")
    #for i in path:
        #print(i)

getinfo(se, path)

#Remove outdated file
if os.path.exists("IpUp.txt"):
    os.remove("IpUp.txt")

# Function FullScan (Host up + port scanner)
def fullScan(addr, ports):
    try:
# Test si host UP
# Changement de la commande ping en fonction de l'OS détécté
        if se == "Windows":
            res = subprocess.call(['ping', '/n', '2', '/l', '1', '-i', '0.2', '/W', "550", str(addr)])
        elif se == "Darwin" or "Linux":
            res = subprocess.call(['ping', '-c', '2', '-s', '1', '-i', '0.2', '-W', "550", str(addr)])
    except:
        None
# Si host up alors scan des ports
    if res == 0:
        print("#")
        print("ping to", addr, "OK")
        print("#")
        scan(addr, ports)
        if args.out:
            with open('IpUp.txt', 'a') as file:
                file.write(str(addr) + ' \n')
    elif res == 2:
        print("no response from", addr)
    else:
        print("ping to", addr, "failed!")

#Fonction de test Ping
def pingIp(addr, ports):
    try:
# Changement de la commande ping en fonction de l'OS détécté
        if se == "Windows":
            res = subprocess.call(['ping', '/n', '2', '/l', '1', '-i', '0.2', '/W', "550", str(addr)])
        elif se == "Darwin" or "Linux":
            res = subprocess.call(['ping', '-c', '2', '-s', '1', '-i', '0.2', '-W', "550", str(addr)])
    except:
        None
# Si host up
    if res == 0:
        print("#")
        print("ping to", addr, " OK")
        print("#")
#Si argument -o alors écriture dans le fichier IpUp.txt
        if args.out:
            with open('IpUp.txt', 'a') as file:
                file.write(str(addr) + ' \n')

    elif res == 2:
        print("no response from", addr)
    else:
        print("ping to", addr, "failed!")

#Fonction simple de scan de ports avec choix du nombre de ports
def scan(target, ports):
    print('\n' + ' Starting scan For ' + str(target))
    for port in range(1, ports):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(0.5)
            sock.connect((target, port))
            print("[+] Port Opened " + str(port))
        except :
            pass

# si args = -ps
if args.full:
    print("Enter in Full Scan Mode :")
    #targets = ""
    #if targets:
    targets = input("[*] Enter Targets To Scan(split them by , or add CIDR like /24 after ipaddress): ")
    ports = int(input("[*] Enter How Many Ports You Want To Scan: "))
    #else:
    if '/' in targets:
        print("[+] Scanning Range Multiple Targets")
        net = IPv4Network(targets, False)
        print("Net =>", net.hosts())
        for addr in net.hosts():
            print("Addr => ", str(addr))
            fullScan(str(addr), ports)
    if ',' in targets:
        print("[+] Scanning Multiple Targets")
        for ip_addr in targets.split(','):
            fullScan(ip_addr.strip(' '), ports)
    else:
        fullScan(targets, ports)

# si args = -p
if args.ping:
    targets = input("[*] Enter Targets To Scan(split them by , or add CIDR like /24 after ipaddress): ")
    ports = 0
    if '/' in targets:
        print("[+] Scanning Range Multiple Targets")
        net = IPv4Network(targets, False)
        for addr in net:
            pingIp(addr, ports)
    if ',' in targets:
        print("[+] Scanning Multiple Targets")
        for ip_addr in targets.split(','):
            pingIp(ip_addr.strip(' '), ports)
    else:
        pingIp(targets, ports)

# si args = -s
if args.soc:
    #targets = ""
    #if targets:
    targets = input("[*] Enter Targets To Scan(split them by , or add CIDR like /24 after ipaddress): ")
    ports = int(input("[*] Enter How Many Ports You Want To Scan: "))
    #else:
    if '/' in targets:
        print("[+] Scanning Range Multiple Targets")
        net = IPv4Network(targets, False)
        print("Net =>", net.hosts())
        for addr in net:
            print("Addr => ", str(addr))
            scan(str(addr), ports)
    if ',' in targets:
        print("[+] Scanning Multiple Targets")
        for ip_addr in targets.split(','):
            scan(ip_addr.strip(' '), ports)
    else:
        scan(targets, ports)

# Domains_Scanner
if args.subdom:
#Si le fichier out.txt existe, on le supprime
    if os.path.exists("out.txt"):
        os.remove("out.txt")
    def domain_scanner(domain_name, sub_domnames):
        print('-----------Scanner Started-----------')
        print('----URL after scanning subdomains----')

# Cette boucle permet de requeter chaque sous domaines identifier dans la wordlist
        for subdomain in sub_domnames:
#variable permettant de requeter dynamiquement
            url = f"https://{subdomain}.{domain_name}"
            try:
                requests.get(url)
#Affichage de la requete
                print(f'[+] {url}')
#Si argument -o placé, écriture dans le fichier out.txt
                if args.out:
                    with open('out.txt', 'a') as export:
                        export.write(str(url) + ' \n')
#except si la requete est fausse
            except requests.ConnectionError:
                pass
        print('\n')
        print('----Scanning Finished----')
        print('-----Scanner Stopped-----')

#Input du domaine choisi
    if __name__ == '__main__':
        dom_name = input("Enter the Domain Name:")
        print('\n')

    with open('grosse_wordlist.txt', 'r') as file:
        name = file.read()
        # appel de spilitlines() qui stocke la liste des chaînes de caractères scindées
        sub_dom = name.splitlines()

    dom_scan = domain_scanner(dom_name, sub_dom)


from flask import Blueprint

from invoice.api import BillCartApi, InvoiceAPI, CustomerInvoiceAPI, InvoiceCollectedAPI, InvoiceFailedAPI
from invoice.api import CouponCodeAPI

invoice_app = Blueprint('invoice_app', __name__)

bill_card_view = BillCartApi.as_view('bill_cart_api')
invoice_view = InvoiceAPI.as_view('invoice_api')
customer_invoice_view = CustomerInvoiceAPI.as_view('customer_invoice_api')
invoice_collected_view = InvoiceCollectedAPI.as_view('invoice_collected_api')
invoice_failed_view = InvoiceFailedAPI.as_view('invoice_failed_api')
coupon_code_view = CouponCodeAPI.as_view('coupon_api')

invoice_app.add_url_rule('/customer/<customer_id>/cart/billcart', view_func=bill_card_view, methods=['POST', ])
invoice_app.add_url_rule('/invoice/<invoice_id>', view_func=invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/invoice/', view_func=invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/customer/<customer_id>/invoices', view_func=customer_invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/invoice/<invoice_id>/collected', view_func=invoice_collected_view, methods=['POST', ])
invoice_app.add_url_rule('/invoice/<invoice_id>/failed', view_func=invoice_failed_view, methods=['PUT', ])

invoice_app.add_url_rule('/coupon_code/', view_func=coupon_code_view, methods=['POST', ])
invoice_app.add_url_rule('/coupon_code/<code>/is_valid', view_func=coupon_code_view, methods=['GET', ])
invoice_app.add_url_rule('/coupon_code/<code>', view_func=coupon_code_view, methods=['DELETE', ])


from . import base
from . import bots
from . import messages
from . import memberships
from . import user
from groupy import utils
from groupy import pagers
from groupy import exceptions

class Groups(base.Manager):
    """A group manager."""

    def __init__(self, session):
        super().__init__(session, path='groups')

    def _raw_list(self, **params):
        response = self.session.get(self.url, params=params)
        if response.status_code == 304:
            return []
        return [Group(self, **group) for group in response.data]

    def list(self, page=1, per_page=10, omit=None):
        """List groups by page.

        The API allows certain fields to be excluded from the results so that
        very large groups can be fetched without exceeding the maximum
        response size. At the time of this writing, only 'memberships' is
        supported.

        :param int page: page number
        :param int per_page: number of groups per page
        :param int omit: a comma-separated list of fields to exclude
        :return: a list of groups
        :rtype: :class:`~groupy.pagers.GroupList`
        """
        return pagers.GroupList(self, self._raw_list, page=page,
                                per_page=per_page, omit=omit)

    def list_all(self, per_page=10, omit=None):
        """List all groups.

        Since the order of groups is determined by recent activity, this is the
        recommended way to obtain a list of all groups. See
        :func:`~groupy.api.groups.Groups.list` for details about ``omit``.

        :param int per_page: number of groups per page
        :param int omit: a comma-separated list of fields to exclude
        :return: a list of groups
        :rtype: :class:`~groupy.pagers.GroupList`
        """
        return self.list(per_page=per_page, omit=omit).autopage()

    def list_former(self):
        """List all former groups.

        :return: a list of groups
        :rtype: :class:`list`
        """
        url = utils.urljoin(self.url, 'former')
        response = self.session.get(url)
        return [Group(self, **group) for group in response.data]

    def get(self, id):
        """Get a single group by ID.

        :param str id: a group ID
        :return: a group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        url = utils.urljoin(self.url, id)
        response = self.session.get(url)
        return Group(self, **response.data)

    def create(self, name, description=None, image_url=None, share=None, **kwargs):
        """Create a new group.

        Note that, although possible, there may be issues when not using an
        image URL from GroupMe's image service.

        :param str name: group name (140 characters maximum)
        :param str description: short description (255 characters maximum)
        :param str image_url: GroupMe image service URL
        :param bool share: whether to generate a share URL
        :return: a new group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        payload = {
            'name': name,
            'description': description,
            'image_url': image_url,
            'share': share,
        }
        payload.update(kwargs)
        response = self.session.post(self.url, json=payload)
        return Group(self, **response.data)

    def update(self, id, name=None, description=None, image_url=None,
               office_mode=None, share=None, **kwargs):
        """Update the details of a group.

        .. note::

            There are significant bugs in this endpoint!
            1. not providing ``name`` produces 400: "Topic can't be blank"
            2. not providing ``office_mode`` produces 500: "sql: Scan error on
            column index 14: sql/driver: couldn't convert <nil> (<nil>) into
            type bool"

            Note that these issues are "handled" automatically when calling
            update on a :class:`~groupy.api.groups.Group` object.

        :param str id: group ID
        :param str name: group name (140 characters maximum)
        :param str description: short description (255 characters maximum)
        :param str image_url: GroupMe image service URL
        :param bool office_mode: (undocumented)
        :param bool share: whether to generate a share URL
        :return: an updated group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        path = '{}/update'.format(id)
        url = utils.urljoin(self.url, path)
        payload = {
            'name': name,
            'description': description,
            'image_url': image_url,
            'office_mode': office_mode,
            'share': share,
        }
        payload.update(kwargs)
        response = self.session.post(url, json=payload)
        return Group(self, **response.data)

    def destroy(self, id):
        """Destroy a group.

        :param str id: a group ID
        :return: ``True`` if successful
        :rtype: bool
        """
        path = '{}/destroy'.format(id)
        url = utils.urljoin(self.url, path)
        response = self.session.post(url)
        return response.ok

    def join(self, group_id, share_token):
        """Join a group using a share token.

        :param str group_id: the group_id of a group
        :param str share_token: the share token
        :return: the group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        path = '{}/join/{}'.format(group_id, share_token)
        url = utils.urljoin(self.url, path)
        response = self.session.post(url)
        group = response.data['group']
        return Group(self, **group)

    def rejoin(self, group_id):
        """Rejoin a former group.

        :param str group_id: the group_id of a group
        :return: the group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        url = utils.urljoin(self.url, 'join')
        payload = {'group_id': group_id}
        response = self.session.post(url, json=payload)
        return Group(self, **response.data)

    def change_owners(self, group_id, owner_id):
        """Change the owner of a group.

        .. note:: you must be the owner to change owners

        :param str group_id: the group_id of a group
        :param str owner_id: the ID of the new owner
        :return: the result
        :rtype: :class:`~groupy.api.groups.ChangeOwnersResult`
        """
        url = utils.urljoin(self.url, 'change_owners')
        payload = {
            'requests': [{
                'group_id': group_id,
                'owner_id': owner_id,
            }],
        }
        response = self.session.post(url, json=payload)
        result, = response.data['results']  # should be exactly one
        return ChangeOwnersResult(**result)

class ChangeOwnersResult:
    """The result of requesting a group owner change.

    :param str group_id: group_id of the group
    :param str owner_id: the ID of the new owner
    :param str status: the status of the request
    """

    #: the status that represents success
    success_code = '200'

    #: a map of statuses to meanings
    status_texts = {
        '200': 'everything checked out',
        '400': 'the group is already owned by that user',
        '403': 'you must own a group to change its owner',
        '404': 'either the new owner is not a member of the group, or the '
               'new owner or the group were not found',
        '405': 'request object is missing required field or any of the '
               'required fields is not an ID',
    }

    def __init__(self, group_id, owner_id, status):
        self.group_id = group_id
        self.owner_id = owner_id
        self.status = status
        self.reason = self.status_texts.get(status, 'unknown')

    @property
    def is_success(self):
        """Return ``True`` if the request was successful."""
        return self.status == self.success_code

    def __bool__(self):
        return self.is_success

class Group(base.ManagedResource):
    """A group."""

    def __init__(self, manager, **data):
        super().__init__(manager, **data)
        self.messages = messages.Messages(self.manager.session, self.id)
        self.gallery = messages.Gallery(self.manager.session, self.group_id)
        self.leaderboard = messages.Leaderboard(self.manager.session, self.id)
        self.memberships = memberships.Memberships(self.manager.session, self.id)
        self._bots = bots.Bots(self.manager.session)
        self._user = user.User(self.manager.session)

        members = self.data.get('members') or []
        self.members = [memberships.Member(self.manager, self.id, **m) for m in members]
        self.created_at = utils.get_datetime(self.data['created_at'])
        self.updated_at = utils.get_datetime(self.data['updated_at'])

    def __repr__(self):
        klass = self.__class__.__name__
        return '<{}(name={!r})>'.format(klass, self.name)

    def __eq__(self, other):
        return self.group_id == other.group_id

    @property
    def is_mine(self):
        membership = self.get_membership()
        return 'owner' in membership.roles

    def post(self, text=None, attachments=None):
        """Post a new message to the group.

        :param str text: the text of the message
        :param attachments: a list of attachments
        :type attachments: :class:`list`
        :return: the message
        :rtype: :class:`~groupy.api.messages.Message`
        """
        return self.messages.create(text=text, attachments=attachments)

    def update(self, name=None, description=None, image_url=None,
               office_mode=None, share=None, **kwargs):
        """Update the details of the group.

        :param str name: group name (140 characters maximum)
        :param str description: short description (255 characters maximum)
        :param str image_url: GroupMe image service URL
        :param bool office_mode: (undocumented)
        :param bool share: whether to generate a share URL
        :return: an updated group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        # note we default to the current values for name and office_mode as a
        # work-around for issues with the group update endpoint
        if name is None:
            name = self.name
        if office_mode is None:
            office_mode = self.office_mode
        return self.manager.update(id=self.id, name=name, description=description,
                                   image_url=image_url, office_mode=office_mode,
                                   share=share, **kwargs)

    def destroy(self):
        """Destroy the group.

        Note that you must be the owner.

        :return: ``True`` if successful
        :rtype: bool
        """
        return self.manager.destroy(id=self.id)

    def rejoin(self):
        """Rejoin the group.

        Note that this must be a former group.

        :return: a current (not former) group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        return self.manager.rejoin(group_id=self.group_id)

    def refresh_from_server(self):
        """Refresh the group from the server in place."""
        group = self.manager.get(id=self.id)
        self.__init__(self.manager, **group.data)

    def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None,
                   **kwargs):
        """Create a new bot in a particular group.

        :param str name: bot name
        :param str avatar_url: the URL of an image to use as an avatar
        :param str callback_url: a POST-back URL for each new message
        :param bool dm_notification: whether to POST-back for direct messages?
        :return: the new bot
        :rtype: :class:`~groupy.api.bots.Bot`
        """
        return self._bots.create(name=name, group_id=self.group_id,
                                 avatar_url=avatar_url, callback_url=callback_url,
                                 dm_notification=dm_notification)

    def change_owners(self, user_id):
        """Change the owner of the group.

        Note that the user must be a member of the group.

        :param str user_id: the user_id of the new owner
        :return: the result
        :rtype: :class:`~groupy.api.groups.ChangeOwnersResult`
        """
        return self.manager.change_owners(self.group_id, user_id)

    def get_membership(self):
        """Get your membership.

        Note that your membership may not exist. For example, you do not have
        a membership in a former group. Also, the group returned by the API
        when rejoining a former group does not contain your membership. You
        must call :func:`refresh_from_server` to update the list of members.

        :return: your membership in the group
        :rtype: :class:`~groupy.api.memberships.Member`
        :raises groupy.exceptions.MissingMembershipError: if your membership is
                not in the group data
        """
        user_id = self._user.me['user_id']
        for member in self.members:
            if member.user_id == user_id:
                return member
        raise exceptions.MissingMembershipError(self.group_id, user_id)

    def update_membership(self, nickname=None, **kwargs):
        """Update your own membership.

        Note that this fails on former groups.

        :param str nickname: new nickname
        :return: updated membership
        :rtype: :class:`~groupy.api.members.Member`
        """
        return self.memberships.update(nickname=nickname, **kwargs)

    def leave(self):
        """Leave the group.

        :return: ``True`` if successful
        :rtype: bool
        """
        membership = self.get_membership()
        return membership.remove()


import os
import argparse

# args option
parser = argparse.ArgumentParser()
parser.add_argument('--project_name',type=str,default='My_Project',help='The name of project')
args = parser.parse_args()

# Create Folder

folder_list = ['models','checkpoints','data','datasets','docs','options','result','scripts','test_out','util']
file_list = ['train.py','test.py']

if not os.path.isdir('./'+args.project_name):
	os.mkdir(args.project_name)
os.chdir(args.project_name)
print('Starting create folders....')
for folder_name in folder_list:
	path = './' + folder_name
	if not os.path.isdir(path):
		os.mkdir(path)
print('Successfully creating folders !')
print('Starting create files....')
for file_name in file_list:
	path = './' + file_name
	if not os.path.isfile(path):
		fd = open(path,mode='w',encoding='utf-8')
		fd.close()

print('Successfully creating files !')


from main.loadFile import load_file
from main.writeFile import write_file
__author__ = 'vdthoang'

def twitter_seperate_file(path, name, number):
    list_load = load_file(path, name)
    chunks = [list_load[x:x+number] for x in xrange(0, len(list_load), number)]

    for index in range(0, len(chunks)):
        write_file(path, name.replace('.csv', '') + '_' + str(index + 1), chunks[index])

if __name__ == '__main__':
    path = 'D:/Project/Transportation_SMU-NEC_collaboration/Data/twitter'
    name = 'tweet_2015_filtering.csv'
    number = 32000 # total size of tweets is: 156971, we separate in to 5 different files
    twitter_seperate_file(path, name, number)


from django.test import TestCase
from django.urls import resolve
from lists.views import home_page
from django.http import HttpRequest
from django.template.loader import render_to_string
from lists.models import Item, List

# Create your tests here.
class HomePageTest(TestCase):
    # def test_root_url_resolves_to_home_page_view(self):
    #     found = resolve('/')
    #     self.assertEqual(found.func, home_page)

    def test_uses_home_template(self):
        #request = HttpRequest() #创建了一个HttpRequest对象。用户请求网页，django中看到的就是这个对象
        #response = home_page(request)#把这个httprequest对象传给home_page视图，得到响应。
        #用test client代替httpresponse对象，也不再直接调用视图函数，用self,client.get
        response = self.client.get('/')
        html = response.content.decode('utf8')#提取响应的.content，得到的结果是原始字节，即0和1。
        #expected_html = render_to_string('home.html') #用render_to_String手动渲染
        #self.assertEqual(html,expected_html)
        # decode用来把原始字节转换成发给用户的html字符串
        # self.assertTrue(html.startswith('')) #希望响应以标签开头，并在结尾处关闭该标签
        # self.assertIn('<title>To-Do lists</title>', html)#希望响应中有一个<title>标签，内容包含单词To-Do Lists
        # self.assertTrue(html.endswith(''))#希望响应以标签结尾
        self.assertTemplateUsed(response,'home.html') #assertTemplateUsed用于检查响应是哪个模板渲染的

    def test_only_saves_items_when_necessary(self):
        self.client.get('/')
        self.assertEqual(Item.objects.count(),0)

    # def test_displays_all_list_item(self):
    #     Item.objects.create(text = 'itemey 1')
    #     Item.objects.create(text = 'itemey 2')
    #     response = self.client.get('/')
    #     self.assertIn('itemey 1',response.content.decode())
    #     self.assertIn('itemey 2',response.content.decode())

class NewListTest(TestCase):
    def test_can_save_a_POST_request(self):
        #发送post请求，data指定想发送的表单数据
        self.client.post('/',data= {'item_text':'A new list item'})
        #检查视图是否把新添加的待办事项存入数据库
        # self.assertEqual(Item.objects.count(),1)
        #objects.all()[0]
        new_item = Item.objects.first()
        #检查待办事项的文本是否正确
        # self.assertEqual(new_item.text,'A new list item')
        #检查post请求渲染得到的html中是否有指定的文本
        #self.assertIn('A new list item',response.content.decode())
        #self.assertTemplateUsed(response, 'home.html')  # 检查是否依然使用这个模板

        # self.assertEqual(response.status_code,302)
        # self.assertEqual(response['location'],'/')

    def test_redirects_after_POST(self):
        # 不再拿响应中的content属性值和渲染模板的值比较
        # 现在比较重新定向
        response = self.client.post('/lists/new',data= {'item_text':'A new list item'})
        new_list = List.objects.first()
        # self.assertEqual(response.status_code, 302)
        # self.assertEqual(response['location'], '/')
        # self.assertEqual(response['location'], '/lists/the-only-list-in-the-world/')
        self.assertRedirects(response,f'/lists/{new_list.id}/')

class ListAndItemModelTest(TestCase):
    def test_saving_and_retrieving_items(self):
        list_ = List()
        list_.save()
        #	3. 在数据库中创建新纪录：创建一个对象；为一些属性赋值；调用.save()函数
        first_item = Item()
        first_item.text = 'The first (ever) list item'
        first_item.list = list_
        first_item.save()

        second_item = Item()
        second_item.text = 'Item the second'
        second_item.list = list_
        second_item.save()

        saved_list = List.objects.first()
        self.assertEqual(saved_list,list_)

        #django提供了一个查询数据库的API,即类.objects，.all()是查询方法，返回类似列表的对象，叫QuerySet
        saved_items = Item.objects.all()
        self.assertEqual(saved_items.count(),2)
        first_saved_item = saved_items[0]
        second_saved_item = saved_items[1]

        self.assertEqual(first_saved_item.text,'The first (ever) list item')
        self.assertEqual(first_saved_item.list, list_)
        self.assertEqual(second_saved_item.text,'Item the second')
        self.assertEqual(second_saved_item.list,list_)

class ListViewTest(TestCase):
    def test_uses_list_template(self):
        list_ = List.objects.create()
        response = self.client.get(f'/lists/{list_.id}/')
        self.assertTemplateUsed(response,'list.html')

    def test_displays_only_items_for_that_list(self):
        correct_list = List.objects.create()
        Item.objects.create(text = 'itemey 1', list = correct_list)
        Item.objects.create(text = 'itemey 2',list = correct_list)

        other_list = List.objects.create()
        Item.objects.create(text='other list item 1', list=other_list)
        Item.objects.create(text='other list item 2', list=other_list)

        response = self.client.get(f'/lists/{correct_list.id}/')
        # self.assertContains(response,'itemey 1') #判断响应里面包含这个字符串，assertContains会处理字节，不用额外的decode
        # self.assertContains(response,'itemey 2')
        self.assertNotContains(response, 'other list item 1')
        self.assertNotContains(response, 'other list item 2')

    def test_passes_correct_list_to_template(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        response = self.client.get(f'/lists/{correct_list.id}/')
        #response.context表示要传入render函数的上下文
        self.assertEqual(response.context['list'],correct_list)

class NewItemTest(TestCase):
    def test_can_save_a_POST_request_to_an_existing_list(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        self.client.post(f'/lists/{correct_list.id}/add_item',
                         data = {'item_text':'A new item for an existing list'})

        self.assertEqual(Item.objects.count(),1)
        new_item = Item.objects.first()

        self.assertEqual(new_item.text,'A new item for an existing list')
        self.assertEqual(new_item.list,correct_list)

    def test_redirects_to_list_view(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        response = self.client.post(f'/lists/{correct_list.id}/add_item',
                                    data = {'item_text':'A new item for an existing list'})

        self.assertRedirects(response,f'/lists/{correct_list.id}/')


import random
import sys

def result(op1, op2):
    if op1 == op2:
        print("There is a draw ({})".format(op1))
        return 50
    else:
        index1 = options.index(op1)
        index2 = options.index(op2)
        half = len(options) // 2
        if index2 > index1 and index2 - index1 <= half or \
                index2 < index1 and index1 - index2 > half:
            print(f"Well done. The computer chose {op1} and failed")
            return 100
        else:
            print(f"Sorry, but the computer chose {op1}")
            return 0

name = input("Enter your name: ")
print(f"Hello, {name}")
file = open("rating.txt", "r", encoding="utf-8")
lines = file.readlines()
lines = [line.rstrip() for line in lines]
lines = [line.split() for line in lines]
scores = {player: int(score) for player, score in lines}
file.close()

options = input()
if options:
    options = options.split(",")
    options = [option.strip().lower() for option in options]
else:
    options = ["scissors", "rock", "paper"]

print("Okay, let's start")
while True:
    user = input()
    if user == "!exit":
        print("Bye!")
        sys.exit()
    elif user == "!rating":
        print(f"Your rating: {scores[name]}")
    elif user not in options:
        print("Invalid input")
    else:
        points = result(random.choice(options), user)
        score = scores.setdefault(name, 0)
        scores.update({name: score + points})


import cv2

cap = cv2.VideoCapture(0)
while (cap.isOpened()):
  ret,img = cap.read()
  cv2.imshow('my win',img)
  img_canny = cv2.Canny(img, 30, 70)
  cv2.imshow('canny',img_canny)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()


a = int(input('PRIMEIRO VALOR:'))
b = int(input('SEGUNDO VALOR:'))
c = int(input('tERCEIRO VALOR:'))
# Verificando quem é menor
menor = a
if b < a and b < c:
    menor = b
if c < a and c < b:
    menor = c
print('O menor valor digitado foi {}'.format(menor))
# Verificando quem é o maio
maio = a
if b > a and b > c:
    maio = b
if c > a and c > b:
    maio = c
print('O maior valor digitado foi {}'.format(maio))


#
# @lc app=leetcode.cn id=55 lang=python3
#
# [55] 跳跃游戏
#
# https://leetcode-cn.com/problems/jump-game/description/
#
# algorithms
# Medium (37.00%)
# Likes:    411
# Dislikes: 0
# Total Accepted:    49.7K
# Total Submissions: 133.2K
# Testcase Example:  '[2,3,1,1,4]'
#
# 给定一个非负整数数组，你最初位于数组的第一个位置。
#
# 数组中的每个元素代表你在该位置可以跳跃的最大长度。
#
# 判断你是否能够到达最后一个位置。
#
# 示例 1:
#
# 输入: [2,3,1,1,4]
# 输出: true
# 解释: 我们可以先跳 1 步，从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
#
#
# 示例 2:
#
# 输入: [3,2,1,0,4]
# 输出: false
# 解释: 无论怎样，你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 ， 所以你永远不可能到达最后一个位置。
#
#
#

# @lc code=start

from typing import List

class Solution:
    def canJump(self, nums: List[int]) -> bool:

        # # 2019-12-28 19:50:33
        # # Time Limit Exceeded
        # # 72/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i): return True
        #     return False

        # return dfs(0)

        # # # 2019-12-28 20:39:04
        # # Time Limit Exceeded
        # # 74/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)
        # is_location_valid = [None for _ in range(len_nums)]

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     if is_location_valid[location] is False: return False
        #     if is_location_valid[location] is True: return True

        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i):
        #             is_location_valid[location] = True
        #             return True

        #     is_location_valid[location] = False
        #     return False

        # return dfs(0)

        # # # 2019-12-28 20:39:04
        # # Time Limit Exceeded
        # # 74/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)
        # is_location_valid = [None for _ in range(len_nums)]

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     if is_location_valid[location] is False: return False
        #     if is_location_valid[location] is True: return True

        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i):
        #             is_location_valid[location] = True
        #             return True

        #     is_location_valid[location] = False
        #     return False

        # return dfs(0)

        # # 2019-12-28 21:03:32
        # # 找到关键位置
        # len_nums = len(nums)
        # end_reachable = len_nums - 1
        # for i in range(len_nums - 1, -1, -1):
        #     if i + nums[i] >= end_reachable:
        #         end_reachable = i

        # return end_reachable == 0

        # 2019-12-28 21:03:40
        # 要点: 如果i可以到达, 那么所有{j|j<i}也可以到达
        max_reachable = 0
        for i, n in enumerate(nums):
            if i > max_reachable: return False
            max_reachable = max(i + n, max_reachable)
            # if max_reachable >= len(nums) - 1: return True  # shortcut, 注意len(nums)本身也是O(N)

        return True

# def main():
#     s = Solution()
#     assert s.canJump([2, 0])
#     assert s.canJump([2, 0, 0])
#     assert s.canJump([3, 2, 1, 0, 4]) is False
#     assert s.canJump([2, 3, 1, 1, 4]) is True
#     assert s.canJump([2, 0, 6, 9, 8, 4, 5, 0, 8, 9, 1, 2, 9, 6, 8, 8, 0, 6, 3, 1, 2, 2, 1, 2, 6, 5, 3, 1, 2, 2, 6, 4, 2, 4, 3, 0, 0, 0, 3, 8, 2, 4, 0, 1, 2, 0, 1, 4, 6, 5, 8, 0, 7, 9, 3, 4, 6, 6, 5, 8, 9, 3, 4, 3, 7, 0, 4, 9, 0, 9, 8, 4, 3, 0, 7, 7, 1, 9, 1, 9, 4, 9, 0, 1, 9, 5, 7, 7, 1, 5, 8, 2, 8, 2, 6, 8, 2, 2, 7, 5, 1, 7, 9, 6]) is False

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

# @lc code=end


#!/usr/bin/python
# encoding: utf-8

import torch
import torch.nn as nn
from torch.autograd import Variable
import collections
import Levenshtein
import tensorflow as tf
import numpy as np
from PIL import Image
from torchvision.transforms import ToTensor, Normalize

mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]

class BeamSearchDecoder():
    def __init__(self, lib, corpus, chars, word_chars, beam_width=20, lm_type='Words', lm_smoothing=0.01, tfsess=None):
        word_beam_search_module = tf.load_op_library(lib)
        self.mat = tf.placeholder(tf.float32)
        corpus = open(corpus).read()
        chars = open(chars).read()
        word_chars = open(word_chars).read()

        self.beamsearch_decoder = word_beam_search_module.word_beam_search(self.mat, beam_width, lm_type, lm_smoothing, corpus, chars, word_chars)
        self.tfsess = tfsess or tf.Session()
        self.idx2char = dict(zip(range(0, len(chars)), chars))

    def beamsearch(self, mat):

        mat = np.concatenate((mat[:,:, 1:], mat[:,:,:1]), axis=-1)
        results=self.tfsess.run(self.beamsearch_decoder, {self.mat:mat})
        return results

    def decode(self, preds_idx):
        return [''.join([self.idx2char[idx] for idx in row if idx < len(self.idx2char)]) for row in preds_idx]

def resizePadding(img, width, height):
    desired_w, desired_h = width, height #(width, height)
    img_w, img_h = img.size  # old_size[0] is in (width, height) format
    ratio = 1.0*img_w/img_h
    new_w = int(desired_h*ratio)
    new_w = new_w if desired_w == None else min(desired_w, new_w)
    img = img.resize((new_w, desired_h), Image.ANTIALIAS)

    # padding image
    if desired_w != None and desired_w > new_w:
        new_img = Image.new("RGB", (desired_w, desired_h), color=255)
        new_img.paste(img, (0, 0))
        img = new_img

    img = ToTensor()(img)
    img = Normalize(mean, std)(img)

    return img

def maxWidth(sizes, height):
    ws = [int(height*(1.0*size[0]/size[1])) for size in sizes]
    maxw = max(ws)

    return maxw

class strLabelConverter(object):
    """Convert between str and label.

    NOTE:
        Insert `blank` to the alphabet for CTC.

    Args:
        alphabet (str): set of the possible characters.
        ignore_case (bool, default=True): whether or not to ignore all of the case.
    """

    def __init__(self, alphabet, ignore_case=True):
        self._ignore_case = ignore_case
        if self._ignore_case:
            alphabet = alphabet.lower()
        self.alphabet = alphabet + '-'  # for `-1` index

        self.dict = {}
        for i, char in enumerate(alphabet):
            # NOTE: 0 is reserved for 'blank' required by wrap_ctc
            self.dict[char] = i + 1

    def encode(self, text):
        """Support batch or single str.

        Args:
            text (str or list of str): texts to convert.

        Returns:
            torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
            torch.IntTensor [n]: length of each text.
        """
        if isinstance(text, str):
            text = [
                self.dict[char.lower() if self._ignore_case else char]
                for char in text
            ]
            length = [len(text)]
        elif isinstance(text, collections.Iterable):
            length = [len(s) for s in text]
            text = ''.join(text)
            text, _ = self.encode(text)

        return (torch.IntTensor(text), torch.IntTensor(length))

    def decode(self, t, length, raw=False):
        """Decode encoded texts back into strs.

        Args:
            torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
            torch.IntTensor [n]: length of each text.

        Raises:
            AssertionError: when the texts and its length does not match.

        Returns:
            text (str or list of str): texts to convert.
        """
        if length.numel() == 1:
            length = length[0]
            assert t.numel() == length, "text with length: {} does not match declared length: {}".format(t.numel(), length)
            if raw:
                return ''.join([self.alphabet[i - 1] for i in t])
            else:
                char_list = []
                for i in range(length):
                    if t[i] != 0 and (not (i > 0 and t[i - 1] == t[i])):
                        char_list.append(self.alphabet[t[i] - 1])
                return ''.join(char_list)
        else:
            # batch mode
            assert t.numel() == length.sum(), "texts with length: {} does not match declared length: {}".format(t.numel(), length.sum())
            texts = []
            index = 0
            for i in range(length.numel()):
                l = length[i]
                texts.append(
                    self.decode(
                        t[index:index + l], torch.IntTensor([l]), raw=raw))
                index += l
            return texts

class averager(object):
    """Compute average for `torch.Variable` and `torch.Tensor`. """

    def __init__(self):
        self.reset()

    def add(self, v):
        if type(v) is list:
            self.n_count += len(v)
            self.sum += sum(v)
        else:
            self.n_count += 1
            self.sum += v

    def reset(self):
        self.n_count = 0
        self.sum = 0

    def val(self):
        res = 0
        if self.n_count != 0:
            res = self.sum / float(self.n_count)
        return res

def oneHot(v, v_length, nc):
    batchSize = v_length.size(0)
    maxLength = v_length.max()
    v_onehot = torch.FloatTensor(batchSize, maxLength, nc).fill_(0)
    acc = 0
    for i in range(batchSize):
        length = v_length[i]
        label = v[acc:acc + length].view(-1, 1).long()
        v_onehot[i, :length].scatter_(1, label, 1.0)
        acc += length
    return v_onehot

def loadData(v, data):
    v.resize_(data.size()).copy_(data)

def prettyPrint(v):
    print('Size {0}, Type: {1}'.format(str(v.size()), v.data.type()))
    print('| Max: %f | Min: %f | Mean: %f' % (v.max().data[0], v.min().data[0],
                                              v.mean().data[0]))

def assureRatio(img):
    """Ensure imgH <= imgW."""
    b, c, h, w = img.size()
    if h > w:
        main = nn.UpsamplingBilinear2d(size=(h, h), scale_factor=None)
        img = main(img)
    return img

def cer_loss_one_image(sim_pred, label):
    loss = Levenshtein.distance(sim_pred, label) * 1.0 / max(len(sim_pred), len(label))
    return loss

def cer_loss(sim_preds, labels):
    losses = []
    for i in range(len(sim_preds)):
        pred = sim_preds[i]
        text = labels[i]

        loss = cer_loss_one_image(pred, text)
        losses.append(loss)
    return losses


grades = ['B', 'B' , 'F', 'C', 'B', 'A', 'A', 'D', 'C', 'D', 'A', 'A', 'B']

grades.sort()
x = []
y = []
for i in grades:
    if(i not in y):
        y.append(i)
        z = grades.count(i)
        x.append(int(z))

print(x)

for i in range(7):
    for j in range(3):
        if((i >= 1 or i <= 5) and (i != 3 and i != 0)):
            if(j == 1):
                print( end="   ")
            else: print("*", end="")
        elif(i == 3): print("***", end="\b\b")
        else: print("*", end=" ")
    print(end="\n")

for i in range(9):
    for j in range(3):
        if(i == 0):
            if(j == 0):
                print("   * ", end="")
            else: print("* * *", end="\b")
        elif((i >= 1 or i <= 5) and (i != 4 and i != 0)):
            if(j == 1):
                print(end="\t")
            else: print("*", end="\t")
        elif(i == 4): print("* * * ", end="")
        else: print("*", end="\t")
    print(end="\n")

for i in range(9):
    for j in range(i+1):
        print(i+1, end="")
    print(end="\n")

for i in range (3,0,-1):
    for j in range(i):
        print(j+1, end="")
    print(end="\n")

for i in range(10):
    for j in range(i):
        print("*", end="")
    print(end="\n")

for i in range (20, 10, -3):
    for j in range(2):
        if(j==1 and i == 11): break
        print(i, end = " ")

def xmult(a, b):
    c = []
    for i in a:
        for j in b:
            c.append(i*j)
    return c

print(xmult([2,3], [3,4]))

list_1 = []
list_2 = []

input_1 = input("Enter the first list(use space as separator) ")
input_2 = input("Enter second list(use space as separator) ")

list_1 = input_1.split()
list_2 = input_2.split()

for i in range(len(list_1)):
    list_1[i] = int(list_1[i])

for i in range(len(list_2)):
    list_2[i] = int(list_2[i])

def digitSplitter(a):
    firstDigit = (a//1000)
    secondDigit = (a//100 - (firstDigit)*10)
    thirdDigit = (a//10 - (a//100)*10)
    fourthDigit = (a - (a//10)*10)

    print(f"{firstDigit}\n{secondDigit}\n{thirdDigit}\n{fourthDigit}")

numbers = input("Enter Four digit number (e.g 1234) ")

if(len(numbers) != 4 or numbers[0] == '0'): print("Error")
else: digitSplitter(int(numbers))

print(1234//1000)
print(1234//100 - (1234//1000)*10)
print(1234//10 - (1234//100)*10)
print(1234-(1234//10)*10)

for i in range(11, 42, 5):
    print(i, end=" ")

print()

for j in range(3, 34, 5):
    print(j, end=" ")

print()

for k in range(20, 10, -3):
    if(k >= 12):
        print(k, k, end=" ")
    else: print(k)

print()

def acronym(phrase):
    phrase = phrase.title()
    for i in phrase:
        if(i.isupper()):
            print(i, end="")

input_phrase = input("Enter the phrase you want to get acronym of ")

acronym(input_phrase)

students_list = (input("Enter the names of students separated by spaces")).split()

for i in students_list:
    for j in i[0]:
        if(ord(j) >=97 and ord(j) <= 109):
            print(i)

month = int(input("Enter the month "))
date = int(input("Enter the date of month"))

if(month == 1 or month == 2 or month == 12):
    print("season is Winter")
elif(month == 3 or month == 4 or month == 5):
    print()

#quadratic equation roots calculator

from cmath import sqrt

a = int(input("Enter value of a "))
b = int(input("Enter value of b "))
c = int(input("Enter value of c "))

if(a == 0): print("The roots cannot be calculated because of divison with 0")
else:
    x1 = (-b + sqrt((pow(b, 2)) - 4*a*c))/(2*a)
    x2 = (-b - sqrt((pow(b, 2)) - 4*a*c))/(2*a)
    print(f"The roots of the given quadratic eqation are {x1} and {x2}")

for i in range (1,6):
    if(i == 1):
        print("\t", end="")
    elif(i == 2):
        print("       *", end="")
    elif(i == 3):
        print("      **", end="")
    elif(i == 4):
        print("     ***", end="")
    elif(i == 5):
        print("    ****", end="")
    for j in range(i):
        print("*", end="")
    print()

for i in range (1,6):
    if(i == 1):
        print("\t", end="")
    else: print("\t"+("\b"*(i-1))+("*"*(i-1)),end="")
    for j in range(i):
        print("*", end="")
    print()

x = [9,2,4,1,5,6]

for _ in range(len(x)-1):
    for i in range(len(x)-1):
        if x[i] > x[i+1]:
            x[i] , x[i+1] = x[i+1], x[i]
print(x)

n = 4
x = 1
for i in range(4,0,-1):
    if(i == 4): continue
    x = x*i

print(x)

print(round(1.2312312, 3))
print(1//2)

print(isinstance(123, int))

print("ß".lower())

x="AbC"

x.lower()
print(x)

print("as\"asd\"da")

a = 1
print(a, id(a))
a = 2
print(a, id(a))

a = [1,2,3]

print(a*3)

words = ['bat', 'ball', 'barn', 'basket', 'badminton']

for _ in range(len(words) - 1):
    for i in range(len(words)-1):
        if(words[i] > words[i+1]):
            words[i] , words[i+1] = words[i+1], words[i]

print(words)

words = ['bat', 'ball', 'barn', 'basket', 'badminton']
words.sort()

print(words)

l1 = [22,33,44,55,66,77,88,99,11,12,23]
print(l1[-1:5:-3])

print(max(l1))

a=3
b=4

print(a*a+b*b)

a = "sd"
b = 23
c = 2.0

print("%s %i %0.1f" %(a,b,c))

print(list("123 123 123"))

for i in range(20,0,-1):
    print(i)

a = 9
b = 11
while True:
    if a == 0: break
    print(b, end=" ")
    if(b != 11): a -= 1
    b = a+b

a = [11,22,33,44,55,66,77,88,99,100]
print(a[-1:1:-3])
x = 11
print(x, end=" ")

for i in range(9,0,-1):
    x += i
    print(x, end=' ')

print(3//2)

print()

import datetime
print(datetime._is_leap(2000))

print(-10>>1)


import os
from setuptools import find_packages, setup
from esi import __version__

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='adarnauth-esi',
    version=__version__,
    install_requires=[
        'requests>=2.9.1,<3.0',
        'requests_oauthlib>=0.8.0,<1.0',
        'django>=1.10',
        'bravado>=8.4.0,<10.0',
        'celery>=4.0.2',
    ],
    packages=find_packages(),
    include_package_data=True,
    license='GNU General Public License v3 (GPLv3)',
    description='Django app for accessing the EVE Swagger Interface.',
    long_description=README,
    url='https://github.com/adarnof/adarnauth-esi',
    author='Adarnof',
    author_email='adarnof@gmail.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.10',
        'Framework :: Django :: 1.11',
        'Framework :: Django :: 2.0',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


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

from threading import Thread
import socket

server_ip = input('Enter server IP: ')
server_port = int(input('Enter server port: '))

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    sock.connect((server_ip, server_port))
    print(f'Connected to server {server_ip}:{server_port}')
except:
    print('Error!')

class ReplyHandler(Thread):
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        while True:
            reply = sock.recv(1024)
            print(reply)

thread = ReplyHandler()
thread.daemon = True
thread.start()

try:
    while True:
        message = bytes(input('Message: '), 'utf8')
        sock.sendall(message)
except KeyboardInterrupt:
    print('Closing connection..')
    sock.close()
    print('Goodbye!'); exit()


#Biblotecas
import curses
import psutil
import threading
import time
import platform

#variables
global numerosHilos
global conta
global mutex
global barrera
#Variables para la sincronizar hilos
numerosHilos = 4
conta = 0
mutex = threading.Semaphore(1)
barrera= threading.Semaphore(0)

#Conversion de bytes
def convesion(num, sufijo='B'):
    for unit in ['','K','M','G','T','P','E','Z']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, sufijo)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', sufijo)

#procesos en ejecucion
def procesos(tamanio):
	lstproc = psutil.pids()
	lstproc.reverse()

	for x in xrange(0,tamanio):
		pantalla.addstr(10+x, 2,"%d "%lstproc[x])
		pantalla.addstr(10+x, 8,psutil.Process(lstproc[x]).name()+"         ")
		pantalla.addstr(10+x, 22,psutil.Process(lstproc[x]).status()+"  ")
		pantalla.addstr(10+x, 35,"%d   "%psutil.Process(lstproc[x]).num_threads())
		pantalla.addstr(10+x, 43,psutil.Process(lstproc[x]).username()+"      ")
		pantalla.addstr(10+x, 53,"%.2f"%psutil.Process(lstproc[x]).cpu_percent(interval=0))
		pantalla.addstr(10+x, 63,convesion(psutil.Process(lstproc[x]).memory_info().rss)+"    ")

#inicalizacion de la barrera
def inbarre():
	global conta
	mutex.acquire()
	conta=conta+1
	mutex.release()

	if conta == numerosHilos:
		barrera.release()
	barrera.acquire()
	barrera.release()

# porcentaje
def porcentaje (fuente,y):
	tamanio = 50
	percent = int(round(fuente/2))
	for i in range(0,percent):
		pantalla.addstr(y,i+18," ",curses.A_STANDOUT)
	for i in range(percent,tamanio):
		pantalla.addstr(y,i+18," ")
	if fuente<10:
		pantalla.addstr(y,18+tamanio,"| 0%d %%"%fuente)
	else:
		pantalla.addstr(y,18+tamanio,"| %d %%"%fuente)
	pantalla.refresh()

	inbarre()

# la memoria usada y disponible
def memoriaUsada():
	pantalla.addstr(7,45,convesion(psutil.virtual_memory().available))
	pantalla.addstr(7,71,convesion(psutil.virtual_memory().used))

	inbarre()

# inicia los hilos de las funciones
def hilos():
	threading.Thread(target=memoriaUsada, args=[]).start()
	threading.Thread(target=procesos, args=[13]).start()
	threading.Thread(target=porcentaje, args=[psutil.cpu_percent(interval=1),2]).start()
	threading.Thread(target=porcentaje, args=[psutil.virtual_memory().percent,4]).start()

#Funcion que dibuja toda la interfaz
def interfaz(args):
	global pantalla
	global conta
	global numerosHilos

	while True:

		pantalla = curses.initscr()

		pantalla.addstr(0, 45, "Monitor de Procesos",curses.A_BOLD)
		pantalla.addstr(2, 1, "Uso de CPU:")
		pantalla.addstr(4, 1, "Uso de MEMORIA:")
		pantalla.addstr(6, 28, platform.system())
		pantalla.addstr(6, 34, platform.processor())
		pantalla.addstr(6, 43,"%d Nucleos"%psutil.cpu_count())
		pantalla.addstr(7, 3,"Memoria Total: "+convesion(psutil.virtual_memory().total))
		pantalla.addstr(7, 30,"Memoria Libre:")
		pantalla.addstr(7, 55,"Memoria en Uso:")

		for j in xrange(1,79):
			pantalla.addstr(9, j, " ")
		pantalla.addstr(9, 2,"PID",curses.A_REVERSE)
		pantalla.addstr(9,8,"Nombre",curses.A_REVERSE)
		pantalla.addstr(9,23,"Estado",curses.A_REVERSE)
		pantalla.addstr(9,34,"Hilos",curses.A_REVERSE)
		pantalla.addstr(9,42,"Usuario",curses.A_REVERSE)
		pantalla.addstr(9,53,"% CPU",curses.A_REVERSE)
		pantalla.addstr(9,63,"Memoria",curses.A_REVERSE)

		hilos()
		mutex.acquire()
		conta-=numerosHilos
		mutex.release()

		pantalla.refresh()

		curses.endwin()

curses.wrapper(interfaz)


import pytest
from typing import *
import logging
import pandas as pd
from pandas import errors as pde
from ml_training import train_model as tm

@pytest.fixture(name='input_dataframe', scope='session')
def input_dataframe_() -> pd.DataFrame:
    """Use fixtures to define the dataframe"""
    try:
        test_data = tm.read_data('data/census_clean_v1.csv')
        logging.info("Fixture: Test data imported successfully: SUCCESS")
    except pde.EmptyDataError as err:
        logging.error("Fixture: Testing import_data: Your data file is empty")
        raise err
    except FileNotFoundError as err:
        logging.error("Fixture: Testing import_data: The file wasn't found")
        raise err
    return test_data

@pytest.fixture(name='train_test_split', scope='session')
def train_test_split_(input_dataframe) -> Tuple[List[Any], List[Any]]:
    """

    Parameters
    ----------
    input_dataframe

    Returns
    -------

    """
    try:
        train, test = tm.split_data(input_dataframe)
        assert len(train) > 0
        assert len(test) > 0
        logging.info(
            "Fixture: Test data_split: SUCCESS"
        )
    except AssertionError as err:
        logging.error(
            "Fixture: Test data_split does not produce the expected lists: ERROR"
        )
        raise err

    return train, test

@pytest.fixture(name='train_test_gen', scope='session')
def train_test_gen_(train_test_split):
    """

    Parameters
    ----------
    train_test_split

    Returns
    -------

    """
    try:
        train, test = train_test_split
        X_train, y_train, encoder_in, lb = tm.train_gen(train)
        X_test, y_test, encoder_test, lb_ = tm.test_gen(test, encoder_in, lb)

        assert len(X_train) > 0
        assert len(y_train) > 0
        assert len(X_test) > 0
        assert len(y_test) > 0
        logging.info(
            "Fixture: Generate train, test split with tm.train_gen: SUCCESS"
        )
    except AssertionError as err:
        logging.error(
            "Fixture: Test train_gen, test_gen does not produce the expected lists: ERROR"
        )
    return X_train, y_train, X_test, y_test, encoder_in, lb

@pytest.fixture(name='test_xgb_pipe', scope='session')
def test_xgb_pipe_(train_test_gen):
    """

    Parameters
    ----------
    train_test_gen

    Returns
    -------

    """
    X_train, y_train, X_test, y_test, encoder, lb = train_test_gen
    try:
        xgb_model = tm.train_xgb_pipe(X_train, y_train, X_test, y_test)
        assert len(xgb_model.predict(X_test)) > 0
        logging.info(
            "Testing train_xgb_pipe: The model delivers predictions: SUCCESS"
        )
    except AssertionError as err:
        logging.error(
            "Testing train_xgb_pipe: The model doesn't deliver predictions: ERROR"
        )
        raise err

    return xgb_model, encoder, lb

@pytest.fixture(name="negative_ex", scope='session')
def negative_ex_():
    """

    Returns
    -------

    """
    test_input = {
        "age": 39,
        "workclass": "State-gov",
        "education": "Bachelors",
        "marital-status": "Never-married",
        "occupation": "Adm-clerical",
        "relationship": "Not-in-family",
        "race": "White",
        "sex": "Male",
        "hours-per-week": 40,
        "native-country": "United-States"
    }

    return test_input

@pytest.fixture(name="positive_ex", scope='session')
def positive_ex_():
    """

    Returns
    -------

    """
    test_input = {
        "age": 40,
        "workclass": "Private",
        "education": "Doctorate",
        "marital-status": "Married-civ-spouse",
        "occupation": "Prof-specialty",
        "relationship": "Husband",
        "race": "White",
        "sex": "Male",
        "hours-per-week": 60,
        "native-country": "United-States"
    }
    return test_input


from typing import Any, Dict, Union

from pydantic import BaseModel

class HttpExceptionModel(BaseModel):
    detail: str

def add_to_openapi_doc(code_pair: Dict[int, str]) -> Dict[int, Dict[str, Any]]:
    return {
        code: {
            "description": detail,
            "model": HttpExceptionModel,
        }
        for code, detail in code_pair.items()
    }


import numpy as np
from numpy.core.defchararray import translate
from numpy.lib.function_base import append
import pandas as pd
import glob
import re
from shutil import move
from pandas.core.frame import DataFrame
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, AveragePooling2D, Dense, Flatten, InputLayer
from tensorflow.keras.utils import to_categorical
from tensorflow.python import keras
from tensorflow.python.keras.backend import conv2d
from tensorflow.python.keras.layers.core import Activation
from tensorflow.python.keras.layers.pooling import MaxPooling2D
from sklearn.model_selection import train_test_split
from tensorflow.python.ops.gen_array_ops import empty

from tensorflow.python.keras import backend as K

# data generator

def dataGenerator(fileList, batchSize=10):

    i = 0
    while True:
        if i*batchSize >= len(fileList):
            i = 0
            np.random.shuffle(fileList)
        else:
            fileChunk = fileList[i * batchSize: (i + 1) * batchSize]
            data = []
            labels = []
            for file in fileChunk:
                temp = pd.read_csv(open(file, 'r'))

                data.append(temp.values.reshape(128, 35, 1))

                accel = temp['Acceleration Norm Max']
                decel = temp['Acceleration Norm Min']
                turn1 = temp['Angular Speed Max']
                turn2 = temp['Angular Speed Min']
                riskOccurence = 0

                # counts number of instances of acceleration or deceleration above 4.5 m/s^2 or below -4.5 m/s^2
                for j in range(len(accel)):
                    if accel[j] >= 4.5:
                        riskOccurence += 1

                    if decel[j] <= -4.5:
                        riskOccurence += 1

                emptyLabel = [0 for n in range(50)]
                if riskOccurence < 50:
                    emptyLabel[riskOccurence] = 1
                else:
                    emptyLabel[49] = 1

                labels.append(emptyLabel)

                # labels.append(temp2)

            data = np.asarray(data).reshape(-1, 128, 35, 1)
            labels = np.asarray(labels)
            yield data, labels

            i += 1

# main

driverFiles = glob.glob("data/Stat Matricies/**/*t[0][0-2][0-9].csv")

# creates the data sets
train, test = train_test_split(driverFiles, test_size=1000, random_state=0)

trainDataSet = tf.data.Dataset.from_generator(dataGenerator, args=[train, 100], output_shapes=(
    (None, 128, 35, 1), (100, 50)), output_types=(tf.float64, tf.float64))

testDataSet = tf.data.Dataset.from_generator(dataGenerator, args=[test, 100], output_shapes=(
    (None, 128, 35, 1), (100, 50)), output_types=(tf.float64, tf.float64))

poolSize = (3, 1)

# creates the model
model = Sequential([
    Conv2D(32, [5, 35], input_shape=(128, 35, 1)),
    tf.keras.layers.MaxPool2D(poolSize),
    tf.keras.layers.Conv2D(64, [3, 1]),
    tf.keras.layers.MaxPool2D(poolSize),
    tf.keras.layers.Conv2D(64, [3, 1]),
    tf.keras.layers.MaxPool2D(poolSize),
    Dense(128, activation='relu'),
    Flatten(),
    Dense(50, activation='softmax')
])

model.compile(
    optimizer='adam',
    loss='SquaredHinge',
    metrics=['Accuracy', tf.keras.metrics.TopKCategoricalAccuracy(k=5)],
)

epochs = 9
stepsPerEpoch = 200
steps = 100

# model = keras.models.load_model('cnn4.h5')

print(model.fit(trainDataSet, steps_per_epoch=stepsPerEpoch, epochs=epochs))

model.save('cnn4.h5')

testLoss, testAcc, topKAcc = model.evaluate(testDataSet, steps=steps)
print("test loss: ", testLoss, "\naccuracy: ",
      testAcc, "\ntop-5 accuracy: ", topKAcc)


"""
Monte Carlo dart-throwing simulation
"""

import math as m
import numpy as np
import matplotlib.pyplot as plt

def draw_board(r=1, pts=100):
    plt.plot([-r, r, r, -r, -r], [-r, -r, r, r, -r], 'k-')
    theta = np.linspace(0, 2*m.pi, pts)
    x = r*np.cos(theta)
    y = r*np.sin(theta)
    plt.plot(x, y, 'r-')
    plt.axis('equal')

def throw_darts(r=1):
    xpos = np.random.uniform(-r, r)
    ypos = np.random.uniform(-r, r)
    return (xpos, ypos)

def plot_darts(x, y, color='b'):
    plt.figure(1)
    plt.plot(x, y, '.', mfc=color, mec=color)
    plt.draw()
    plt.pause(0.01)

def plot_est(nums, ests):
    plt.figure(2)
    plt.plot(nums, ests, 'ko')
    plt.plot(nums, m.pi*np.ones(len(nums)), 'g.')
    plt.draw()
    plt.pause(0.01)

if __name__ == '__main__':
    darts_to_throw = 10000
    darts_thrown = 0
    board_rad = 1
    do_plot = 0
    inside = 0
    pi_est = []
    x_i_vec = []
    y_i_vec = []
    x_o_vec = []
    y_o_vec = []

    plt.figure(1)
    plt.clf()
    draw_board(r=board_rad)

    plt.figure(2)
    plt.clf()

    while darts_thrown < darts_to_throw:
        darts_thrown += 1
        x_d, y_d = throw_darts(board_rad)
        r_d = m.sqrt(x_d**2 + y_d**2)
        color='m'
        if r_d < board_rad:
            inside += 1
            x_i_vec += [x_d]
            y_i_vec += [y_d]
            color='g'
        else:
            x_o_vec += [x_d]
            y_o_vec += [y_d]

        pi_est += [4*inside/darts_thrown]
        print('{:5d}'.format(darts_thrown) +
               ' {:5d}'.format(inside) +
               ' {:0.3e}'.format(pi_est[-1]))

        if do_plot:
            plot_darts(x_d, y_d, color)
            plot_est(darts_thrown, pi_est[-1])

    if not do_plot:
        plot_darts(x_i_vec, y_i_vec, 'g')
        plot_darts(x_o_vec, y_o_vec, 'm')
        plot_est(np.linspace(1, darts_thrown, darts_thrown), pi_est)

    plt.figure(1)
    draw_board(board_rad)


import numpy as np
import scipy
from scipy.linalg import eigvalsh
from numpy.core.numerictypes import typecodes

# Functions borrowed from alexandrebarachant/pyRiemann github repository
# https://github.com/alexandrebarachant/pyRiemann

def matrix_operator(Ci, operator):
    """matrix equivalent of an operator."""
    if Ci.dtype.char in typecodes["AllFloat"] and not np.isfinite(Ci).all():
        raise ValueError(
            "Covariance matrices must be positive definite. Add regularization to avoid this error."
        )
    eigvals, eigvects = scipy.linalg.eigh(Ci, check_finite=False)
    eigvals = np.diag(operator(eigvals))
    Out = np.dot(np.dot(eigvects, eigvals), eigvects.T)
    return Out

def logm(Ci):
    return matrix_operator(Ci, np.log)

def expm(Ci):
    return matrix_operator(Ci, np.exp)

def sqrtm(Ci):
    return matrix_operator(Ci, np.sqrt)

def invsqrtm(Ci):
    isqrt = lambda x: 1.0 / np.sqrt(x)
    return matrix_operator(Ci, isqrt)

def get_sample_weight(sample_weight, data):
    if sample_weight is None:
        sample_weight = np.ones(data.shape[0])
    if len(sample_weight) != data.shape[0]:
        raise ValueError("len of sample_weight must be equal to len of data.")
    sample_weight /= np.sum(sample_weight)
    return sample_weight

def mean_riemann(covmats, tol=10e-9, maxiter=50, init=None, sample_weight=None):
    sample_weight = get_sample_weight(sample_weight, covmats)
    Nt, Ne, Ne = covmats.shape
    if init is None:
        C = np.mean(covmats, axis=0)
    else:
        C = init
    k = 0
    nu = 1.0
    tau = np.finfo(np.float64).max
    crit = np.finfo(np.float64).max
    # stop when J<10^-9 or max iteration = 50
    while (crit > tol) and (k < maxiter) and (nu > tol):
        k = k + 1
        C12 = sqrtm(C)
        Cm12 = invsqrtm(C)
        J = np.zeros((Ne, Ne))

        for index in range(Nt):
            tmp = np.dot(np.dot(Cm12, covmats[index, :, :]), Cm12)
            J += sample_weight[index] * logm(tmp)

        crit = np.linalg.norm(J, ord="fro")
        h = nu * crit
        C = np.dot(np.dot(C12, expm(nu * J)), C12)
        if h < tau:
            nu = 0.95 * nu
            tau = h
        else:
            nu = 0.5 * nu

    return C

def distance_riemann(A, B):
    return np.sqrt((np.log(eigvalsh(A, B)) ** 2).sum())

def dist_riem(A, B):
    return np.linalg.norm(scipy.linalg.logm(np.dot(np.linalg.inv(A), B)))

# Proper code

class Base(object):
    #   Accepts 4 dimensional array:
    #   (x,y,z,s) - let it be the dimension
    #       x - how many gestures are to be classified
    #       y - number of repetitions for each gesture (equal for every gesture)
    #       z - number of channels
    #       s - number of samples in each gesture
    #   Returns 3 dimensional array with gestures classified based on riemann geometry
    #   which is necessary for classifying gestures with online signal
    def __init__(self, arr):
        self.__gestures = arr
        self.__number_of_gestures = arr.shape[0]
        self.__repetitions = arr.shape[1]
        self.__ch = arr.shape[2]
        self.__SPD_matrices = np.zeros(
            (self.__number_of_gestures, self.__ch, self.__ch)
        )

    #   matrix with matrices classified (one gesture - one 2 dimensional matrix)
    def Make_SPDBase(self):
        corr_package = np.zeros(
            (self.__number_of_gestures, self.__repetitions, self.__ch, self.__ch)
        )
        #       matrix where correlation coefficient matrices of each gesture repetition
        #       will be placed.
        for index in np.ndindex(self.__number_of_gestures, self.__repetitions):
            # loop for computing correlation coefficient matrices
            corr_package[index[0], index[1], :, :] = np.corrcoef(
                self.__gestures[index[0], index[1], :, :]
            )
        for gesture in range(self.__number_of_gestures):
            # loop for computing mean distances for matrices describing one gesture
            mean = mean_riemann(
                corr_package[gesture, :, :, :],
                tol=1e-08,
                maxiter=50,
                init=None,
                sample_weight=None,
            )
            self.__SPD_matrices[gesture, :, :] = mean[:, :]
        return self.__SPD_matrices

    def __str__(self):
        print("number of gestures in base: " + str(self.__number_of_gestures))
        print("number of repetitions for gesture: " + str(self.__repetitions))
        print("number of channels: " + str(self.__ch))
        return "number of samples for each gesture: " + str(self.__gestures.shape[3])

    def __getitem__(self, n):
        try:
            return self.__SPD_matrices[n, :, :]
        except IndexError:
            return (
                "please choose index from range [0,"
                + str(self.__number_of_gestures - 1)
                + "]"
            )

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

    def add(self, other):
        if (
            self.__number_of_gestures != other.__number_of_gestures
            or self.__ch != other.__ch
            or self.__gestures.shape[3] != other.__gestures.shape[3]
        ):
            return ValueError(
                "Bases must have same number of gestures, channels and samples"
            )
        base_new = np.zeros(
            (
                self.__number_of_gestures,
                self.__repetitions + other.__repetitions,
                self.__ch,
                self.__gestures.shape[3],
            )
        )
        for i in range(self.__number_of_gestures):
            base_new[i, : self.__repetitions, :, :] = self.__gestures[i, :, :, :]
            base_new[i, self.__repetitions :, :, :] = other.__gestures[i, :, :]
        return base_new

class MDM(object):
    #   Accepts base made with class above and 2D matrix of gesture signals
    #   Returns index of gesture classified based on riemann geometry
    def __init__(self, base, gesture):  # base - 3d , gesture = 2D
        self.__base = base
        self.__gesture = gesture
        self.__number_of_gestures = base.shape[0]
        self.__distances = {}

    def classify(self):
        # computes distances between online gesture and each gesture from base
        corr_gesture = np.corrcoef(self.__gesture)
        for gesture in range(self.__number_of_gestures):
            self.__distances[gesture] = distance_riemann(
                self.__base[gesture, :, :], corr_gesture
            )
        return self.__distances

    def getmin(self, threshold=1):
        # chooses minimal distance (if bigger than threshold returns None)
        if 0 > threshold or threshold > 1:
            raise ValueError("Values between 0 and 1 only")
        elif min(self.__distances.values()) < threshold:
            return min(self.__distances, key=self.__distances.get)
        else:
            return None

    @property
    def number_of_gestures(self):
        return self.__number_of_gestures

    def __str__(self):
        for gesture, distance in self.__distances.items():
            print(
                "number of gesture: ",
                str(gesture),
                "         distance: ",
                str(distance),
            )
        return "  "

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

    def __getitem__(self, n):
        return self.__distances[n]