from crm.capsule_crm import util
from crm.capsule_crm.entities.capsulecrm_contact import CapsulecrmContact
from crm.capsule_crm.entities.capsulecrm_deal import CapsulecrmDeal
from crm.capsule_crm.entities.capsulecrm_case import CapsulecrmCase
from crm.capsule_crm.entities.capsulecrm_tag import CapsulecrmTag
from crm.capsule_crm.entities.capsulecrm_task import CapsulecrmTask
import json

class CapsulecrmApi:
    def contacts(self, context, params):
        '''List of contacts'''

        return self.parties(context, params)

    def parties(self, context, params):
        '''List of parties'''

        access_token = util.get_access_token(context['headers'])
        url = "parties"
        respose_obj = util.rest("GET", url, access_token)
        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def party_mappings(self, parties_list):
        # Unifies party response

        parties = []
        for party in parties_list:
            party_obj = CapsulecrmContact(
                party_id=party['id'],
                account_id=party.get('organisation').get(
                    'id') if party.get('organisation') else None,
                first_name=party.get('firstName'),
                last_name=party.get('lastName'),
                email=party.get('emailAddresses')[0].get(
                    'address') if party.get('emailAddresses') else None,
                business_phone=party.get('phoneNumbers')[0].get(
                    'phoneNumbers') if party.get('phoneNumbers') else None,
                owner_id=party.get('owner'),
                mailing_city=party.get('addresses')[0].get(
                    'city') if party.get('addresses') else None,
                mailing_country=party.get('addresses')[0].get(
                    'country') if party.get('addresses') else None,
                mailing_state=party.get('addresses')[0].get(
                    'state') if party.get('addresses') else None,
                mailing_street=party.get('addresses')[0].get(
                    'street') if party.get('addresses') else None,
                mailing_zip=party.get('addresses')[0].get(
                    'zip') if party.get('addresses') else None,
                title=party.get('title'),
                job_title=party.get('jobTitle'),
                website=party.get('websites')
            )
            parties.append(party_obj.__dict__)
        return json.dumps(parties)

    def contact(self, context, params):
        '''get details of contact'''

        return self.party(context, params)

    def party(self, context, params):
        '''get details of pary'''

        access_token = util.get_access_token(context['headers'])

        if params.get('id') is None or params.get('party_id') == '':
            raise Exception('Provide party id')

        url = f"parties/{int(params.get('id'))}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied party id')

        party = json.loads(respose_obj.text)['party']
        party_obj = CapsulecrmContact(
            party_id=party['id'],
            account_id=party.get('organisation').get(
                'id') if party.get('organisation') else None,
            first_name=party.get('firstName'),
            last_name=party.get('lastName'),
            email=party.get('emailAddresses')[0].get(
                'address') if party.get('emailAddresses') else None,
            business_phone=party.get('phoneNumbers')[0].get(
                'phoneNumbers') if party.get('phoneNumbers') else None,
            owner_id=party.get('owner'),
            mailing_city=party.get('addresses')[0].get(
                'city') if party.get('addresses') else None,
            mailing_country=party.get('addresses')[0].get(
                'country') if party.get('addresses') else None,
            mailing_state=party.get('addresses')[0].get(
                'state') if party.get('addresses') else None,
            mailing_street=party.get('addresses')[0].get(
                'street') if party.get('addresses') else None,
            mailing_zip=party.get('addresses')[0].get(
                'zip') if party.get('addresses') else None,
            title=party.get('title'),
            job_title=party.get('jobTitle'),
            website=party.get('websites')
        )

        return party_obj.__dict__, respose_obj.status_code

    def party_by_name(self, context, params):
        '''get details of party by name'''

        access_token = util.get_access_token(context['headers'])

        if params.get('name') is None or params.get('name') == '':
            raise Exception('Provide name')

        url = f"parties/search?q={params.get('name')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied name')

        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def party_by_email(self, context, params):
        '''get details of party by Email'''

        access_token = util.get_access_token(context['headers'])

        if params.get('email') is None or params.get('email') == '':
            raise Exception('Provide email')

        url = f"parties/search?q={params.get('email')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied Email')

        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def cases(self, context, params):
        '''List of cases'''

        access_token = util.get_access_token(context['headers'])
        activity = "kases"
        respose_obj = util.rest("GET", activity, access_token)
        cases_list = json.loads(respose_obj.text)['kases']
        return self.case_mapping(cases_list), respose_obj.status_code

    def case(self, context, params):
        '''get details of case'''

        access_token = util.get_access_token(context['headers'])

        if params.get('id') is None or params.get('id') == '':
            raise Exception('Provide case id')

        activity = f"kases/{params.get('id')}"
        respose_obj = util.rest("GET", activity, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied case id')

        case = []
        case.append(json.loads(respose_obj.text)['kase'])
        return self.case_mapping(case), respose_obj.status_code

    def case_mapping(self, case_list):
        # unifies case response'''

        cases = []
        for case in case_list:
            case_obj = CapsulecrmCase(
                case_id=case['id'],
                contact_id=case['party'].get(
                    'id') if case.get('party') else None,
                name=case.get('name'),
                description=case.get('description'),
                status=case.get('status'),
                owner_id=case['owner']['id']
            )
            cases.append(case_obj.__dict__)
        return json.dumps(cases)

    def opportunities(self, context, params):
        '''list of opportunities'''

        access_token = util.get_access_token(context['headers'])
        url = "opportunities"
        respose_obj = util.rest("GET", url, access_token)
        parties_list = json.loads(respose_obj.text)['opportunities']

        return self.opportunity_mappings(parties_list), respose_obj.status_code

    def opportunity(self, context, params):
        '''get opportunities details'''

        access_token = util.get_access_token(context['headers'])

        if params.get('opportunity_id') is None or params.get('opportunity_id') == '':
            raise Exception('Provide case id')

        url = f"opportunities/{params.get('opportunity_id')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied opportunity id')

        data = []
        data.append(json.loads(respose_obj.text)['opportunity'])

        return self.opportunity_mappings(data), respose_obj.status_code

    def opportunity_mappings(self, opportunities_list):
        # unifies opportunities response

        opportunities = []
        for opportunity in opportunities_list:
            opportunity_obj = CapsulecrmDeal(
                deal_id=opportunity['id'],
                name=opportunity.get('name'),
                close_date=opportunity.get('expectedCloseOn'),
                description=opportunity.get('description'),
                stage_id=opportunity.get('milestone').get(
                    'id') if opportunity.get('milestone') else None,
                value=opportunity.get('value').get(
                    'amount') if opportunity.get('value') else None,
                probability=opportunity.get('probability'),
                owner_id=opportunity['owner'].get('id'),
                contact_id=opportunity['party'].get('id'),
                currency_id=opportunity['value'].get(
                    'currency') if opportunity.get('value') else None
            )
            opportunities.append(opportunity_obj.__dict__)
        return json.dumps(opportunities)

    def tags(self, context, params):
        '''list of tags in parties, opportunities and kases'''

        access_token = util.get_access_token(context['headers'])

        if params.get('entity') is None or params.get('entity') == '':
            raise Exception(
                'Provide required entity. Supported entites are parties, opportunities and kases')

        url = f"{params.get('entity')}/tags"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied entites')

        tag_list = json.loads(respose_obj.text)['tags']
        tags = []
        for tag in tag_list:
            tag_obj = CapsulecrmTag(
                tag_id=tag['id'],
                tag=tag.get('name'),
                description=tag.get('description')
            )
            tags.append(tag_obj.__dict__)

        return json.dumps(tags), respose_obj.status_code

    def tasks(self, context, params):
        '''list of tasks'''

        access_token = util.get_access_token(context['headers'])
        activity = "tasks"
        respose_obj = util.rest("GET", activity, access_token)
        task_list = json.loads(respose_obj.text)['tasks']

        return self.task_mapping(task_list), respose_obj.status_code

    def task_mapping(self, task_list):
        # unifies task response

        tasks = []
        for task in task_list:
            task_obj = CapsulecrmTask(
                name=task.get('description'),
                description=task.get('detail'),
                category_id=task['category'].get(
                    'id') if task.get('category') else None,
                owner_id=task['owner'].get(
                    'id') if task.get('owner') else None,
                due_date=task.get('dueOn')
            )
            tasks.append(task_obj.__dict__)

        return json.dumps(tasks)

    def profile(self, context, payload):
        '''Details of authenticated user'''

        access_token = util.get_access_token(context['headers'])
        url = "users/current"
        response = util.rest("GET", url, access_token).json()['user']
        profile = {
            'id':response['id'],
            'name':response['username']
        }

        # party is contact
        party = response.get('party')
        if party:
            params = {
                "id":party.get('id')
            }
            email_obj = self.party(context, params)
            profile['email']=email_obj[0]['email']

        return profile


'''manifest.py'''
import json
from datetime import datetime
from typing import List, Union

from fonty.models.font import FontFamily, InstalledFont
from fonty.lib.constants import APP_DIR, MANIFEST_PATH, JSON_DUMP_OPTS
from fonty.lib.list_fonts import get_user_fonts, get_user_fonts_count
from fonty.lib.json_encoder import FontyJSONEncoder
from fonty.lib.variants import FontAttribute
from fonty.lib import utils

class Manifest:
    '''Manifest is a class to manage a manifest list of installed fonts on the user's system.'''

    # Class Attributes

    schema_version: str = "0.1.0"
    families: List[FontFamily]
    last_modified: datetime
    font_count: int

    # Constructor

    def __init__(
        self,
        families: List[FontFamily],
        last_modified: Union[str, datetime] = None,
        font_count: int = 0
    ) -> None:
        self.families = families
        self.last_modified = utils.parse_date(last_modified)
        self.font_count = font_count

    # Class Methods

    def add(self, font: InstalledFont) -> int:
        '''Add a font to the manifest.'''

        family_name = font.get_family_name()

        # Load existing or create a FontFamily object
        family = self.get(family_name)
        family_idx = self.get_index(family_name)
        if family is None:
            family = FontFamily(name=family_name, fonts=[])

        # Check if font is already in manifest
        existing_variants = [str(variant) for variant in family.get_variants()]
        variant = str(font.get_variant())
        if variant in existing_variants:
            return 0

        # Add font to FontFamily object
        family.fonts.append(font)

        # Update manifest instance
        if family_idx is None:
            self.families.append(family)
        else:
            self.families[family_idx] = family

        self.font_count += 1
        return 1

    def remove(self, font: InstalledFont) -> int:
        '''Remove a font from the manifest.'''

        # Load FontFamily
        family = self.get(font.family)
        family_idx = self.get_index(font.family)
        if family is None:
            return 0

        # Remove font from FontFamily
        font_idx = next((
            i for i, val in enumerate(family.fonts) if val.variant == font.variant
        ), None)
        if font_idx is None:
            return 0
        family.fonts.pop(font_idx)

        # Update the instance with the updated FontFamily
        if family.fonts:
            self.families[family_idx] = family
        else:
            del self.families[family_idx]

        self.font_count -= 1
        return 1

    def get(self, name: str) -> FontFamily:
        '''Load a font family from the manifest.'''
        return next((val for val in self.families if val.name.lower() == name.lower()), None)

    def get_index(self, name: str) -> int:
        '''Get the index position of the font family in the manifest.'''
        return next((idx for idx, val in enumerate(self.families) if val.name.lower() == name.lower()), None)

    def save(self, path: str = None) -> None:
        '''Save the manifest list to disk.'''
        utils.check_dirs(APP_DIR)
        path = path if path else MANIFEST_PATH

        data = {
            'schema_version': self.schema_version,
            'last_modified': datetime.now().isoformat(),
            'font_count': self.font_count,
            'font_families': self.families
        }

        # Write to file (manifest.json)
        with open(path, 'w') as f:
            json.dump(data, f, cls=FontyJSONEncoder, **JSON_DUMP_OPTS)

    def is_stale(self) -> bool:
        '''Returns `true` if the total number of fonts in the manifest does not
           match the total number of fonts in the system.
        '''
        return get_user_fonts_count() != self.font_count

    # Static Methods

    @staticmethod
    def load(path: str = None) -> 'Manifest':
        '''Load the manifest file from disk.'''
        path = path if path else MANIFEST_PATH

        with open(path, encoding='utf-8') as f:
            data = json.loads(f.read())

        # Create FontFamily instances
        families = []
        for family in data['font_families']:
            fonts: List[InstalledFont] = [InstalledFont(
                installed_path=font.get('local_path'),
                registry_name=font.get('registryName', None),
                family=family.get('name'),
                variant=FontAttribute.parse(font.get('variant'))
            ) for font in family['fonts']]
            families.append(FontFamily(name=family.get('name'), fonts=fonts))

        return Manifest(
            families=families,
            font_count=data['font_count'],
            last_modified=data['last_modified']
        )

    @staticmethod
    def generate() -> 'Manifest':
        '''Generate a manifest list from the user's installed fonts.'''
        return Manifest(
            families=get_user_fonts(),
            font_count=get_user_fonts_count(),
            last_modified=datetime.now()
        )


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

This is a temporary script file.
"""
import requests
from collections import defaultdict

# import BeautifulSoup

def download(url="https://www.google.com/search", params={}, retries=3):

    resp = None
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"
    header = {"user-agent": user_agent}
    try:
        resp = requests.get(url, params=params, headers=header)
        resp.raise_for_status()  # error/event 발생하면 except로 가게해라
    except requests.exceptions.HTTPError as e:
        if e.response.status_code // 100 == 5 and retries > 0:
            print(retries)
            resp = download(url, params, retries - 1)
        else:
            print(e.response.status_code)
            print(e.response.reason)
            print(e.response.headers)
    return resp

threshold = 3

def urlExtractor(seed, limit):
    if limit > threshold:
        return []
    html = download(seed)
    dom = BeautifulSoup(html.text, "lxml")
    links = [_["href"] for _ in dom.select("a") if _.has_attr("href")]
    unseen = list()
    for link in links:
        if len(link) > 1 and link[0] == "/":
            newLink = requests.compat.urljoin(seed, link)
            if newLink not in unseen:
                unseen.append((newLink, limit + 1))
        elif link.startswith("http"):
            unseen.append((link, limit + 1))
    return unseen


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

import random
import logging

from flask import Flask
from flask import request

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

logging.basicConfig(filename='bob.log', level=logging.DEBUG)

app = Flask(__name__, static_url_path="/static")
epithets = []
names = {}

def get_epithets():
    with open("epithets.txt") as f:
        global epithets
        epithets = f.readlines()

@app.route(u'/')
def name():
    return app.send_static_file('form.html')

@app.route(u'/welcome')
def welcome():
    name = request.args.get("name")
    logging.info(name)
    epithet = names.get(name, epithets[random.randint(0, len(epithets))])
    names[name] = epithet
    return 'Рад тебя видеть снова, {} {}!'.format(epithet, name)

if __name__ == '__main__':
    get_epithets()
    app.run(debug=True, port=8080)


from game import GameOfChess
import pygame
import sys
from pygame.constants import QUIT
from pygame.draw import rect
from pieces import *
import LegalMove
import ai
import Engine

pygame.init()
pygame.font.init()

WIN = pygame.display.set_mode([830, 870])

pygame.display.set_caption("Quin's Chess Game!")
myfont = pygame.font.SysFont('Cambria', 30)
smallfont = pygame.font.SysFont('Times', 20)
bigTitle = pygame.font.SysFont('Times', 70, bold=True, italic=False)
clock = pygame.time
colorWhite = (255, 255, 255)
colorBlack = (0, 0, 0)
colorRed = (255, 0, 0)
colorSalmon = (255, 160, 122)
colorDarkRed  = (215, 51, 51)
colorBrown = (110, 38, 14)

#   SPRITES     #
wKing = pygame.image.load("Images/WhiteKing.png")
wQueen = pygame.image.load("Images/WhiteQueen.png")
wBishop = pygame.image.load("Images/WhiteBishop.png")
wKnight = pygame.image.load("Images/WhiteKnight.png")
wRook = pygame.image.load("Images/WhiteRook.png")
wPawn = pygame.image.load("Images/WhitePawn.png")
bKing = pygame.image.load("Images/BlackKing.png")
bQueen = pygame.image.load("Images/BlackQueen.png")
bBishop = pygame.image.load("Images/BlackBishop.png")
bKnight = pygame.image.load("Images/BlackKnight.png")
bRook = pygame.image.load("Images/BlackRook.png")
bPawn = pygame.image.load("Images/BlackPawn.png")
# ALL SPRITES #
# SCALING
wKing = pygame.transform.scale(wKing, (75, 75))
wQueen = pygame.transform.scale(wQueen, (75, 75))
wBishop = pygame.transform.scale(wBishop, (75, 75))
wKnight = pygame.transform.scale(wKnight, (75, 75))
wRook = pygame.transform.scale(wRook, (75, 75))
wPawn = pygame.transform.scale(wPawn, (75, 75))
bKing = pygame.transform.scale(bKing, (75, 75))
bQueen = pygame.transform.scale(bQueen, (75, 75))
bBishop = pygame.transform.scale(bBishop, (75, 75))
bKnight = pygame.transform.scale(bKnight, (75, 75))
bRook = pygame.transform.scale(bRook, (75, 75))
bPawn = pygame.transform.scale(bPawn, (75, 75))
# SCALING TINY
swKing = pygame.transform.scale(wKing, (15, 15))
swQueen = pygame.transform.scale(wQueen, (15, 15))
swBishop = pygame.transform.scale(wBishop, (15, 15))
swKnight = pygame.transform.scale(wKnight, (15, 15))
swRook = pygame.transform.scale(wRook, (15, 15))
swPawn = pygame.transform.scale(wPawn, (15, 15))
sbKing = pygame.transform.scale(bKing, (15, 15))
sbQueen = pygame.transform.scale(bQueen, (15, 15))
sbBishop = pygame.transform.scale(bBishop, (15, 15))
sbKnight = pygame.transform.scale(bKnight, (15, 15))
sbRook = pygame.transform.scale(bRook, (15, 15))
sbPawn = pygame.transform.scale(bPawn, (15, 15))

def drawChessBoard(game):
    colorTan = (210, 180, 140)
    for x in range(8): # Number of rows on a chessboard
        for y in range(8): # Number of columns on a chessboard
            if(x % 2 == 0):
                if(y % 2 == 0):
                    #Tan
                    pygame.draw.rect(WIN, colorTan, pygame.Rect((x*100), (y*100), 100, 100))
                else:
                    # Green
                    pygame.draw.rect(WIN, colorBrown, pygame.Rect((x*100), (y*100), 100, 100))
            else:
                if(y % 2 == 0):
                    #Green
                    pygame.draw.rect(WIN, colorBrown, pygame.Rect((x*100), (y*100), 100, 100))
                else:
                    #Tan
                    pygame.draw.rect(WIN, colorTan, pygame.Rect((x*100), (y*100), 100, 100))

    if(game.CurrentlySelected != None):
        selectedX = (game.CurrentlySelected.letter * 100) - 100 # 1 Indexed
        selectedY = 800 - (game.CurrentlySelected.number * 100)
        pygame.draw.rect(WIN, colorRed, pygame.Rect(selectedX, selectedY, 100, 100))
        # valid moves too
        ValidMoveSet = game.CurrentlySelected.returnLegalMoves()
        for x in range(len(ValidMoveSet)):
            if(LegalMove.isValid(ValidMoveSet[x][0], ValidMoveSet[x][1], game.CurrentlySelected, game.Black, game.White, game.PreviouslyMovingPiece) and not LegalMove.isCheckAfterMove(ValidMoveSet[x][0], ValidMoveSet[x][1], game.CurrentlySelected, game.Black, game.White)):
                validmovX = (ValidMoveSet[x][0] * 100) - 100
                validmovY = 800 - (ValidMoveSet[x][1] * 100)
                if((validmovX //100) % 2 == 0):
                    if((validmovY//100) % 2 == 0):
                        pygame.draw.rect(WIN, colorSalmon, pygame.Rect(validmovX, validmovY, 100, 100))
                    else:
                        pygame.draw.rect(WIN, colorDarkRed, pygame.Rect(validmovX, validmovY, 100, 100))
                else:
                    if((validmovY//100) % 2 == 0):
                        pygame.draw.rect(WIN, colorDarkRed, pygame.Rect(validmovX, validmovY, 100, 100))
                    else:
                        pygame.draw.rect(WIN, colorSalmon, pygame.Rect(validmovX, validmovY, 100, 100))

    for x in range(8):
        rownumber = myfont.render((x+1).__str__(), False, (0, 0, 0))
        WIN.blit(rownumber,(802,(840-100*(x+1))))
        columnletter = myfont.render(chr(97+x).capitalize(), False, (0, 0, 0))
        WIN.blit(columnletter,((100*x +40),800))
        pygame.draw.line(WIN, colorBlack, (0, 100*x) , (830, 100*x))
        pygame.draw.line(WIN, colorBlack, (100*x, 0) , (100*x, 830))
    pygame.draw.line(WIN, colorBlack, (0, 800) , (830, 800))
    pygame.draw.line(WIN, colorBlack, (800, 0) , (800, 830))

def drawWhite(game):
    for  something in game.White:
        x = (something.letter * 100) - 100
        y = 800 - (something.number * 100)# 1 is first index
        rectangle = pygame.Surface((100, 100), pygame.SRCALPHA)
        #rectangle.fill((255, 255, 255, 0))
        if(something.__class__.__name__ == "Pawn"):
            rectangle.blit(wPawn, (10,10))
        elif(something.__class__.__name__ == "King"):
           rectangle.blit(wKing, (10,10))
        elif(something.__class__.__name__ == "Queen"):
            rectangle.blit(wQueen, (10,10))
        elif(something.__class__.__name__ == "Bishop"):
            rectangle.blit(wBishop, (10,10))
        elif(something.__class__.__name__ == "Knight"):
            rectangle.blit(wKnight, (10,10))
        elif(something.__class__.__name__ == "Rook"):
            rectangle.blit(wRook, (10,10))
        #All_PIECES.append(rectangle)
        WIN.blit(rectangle, (x, y))

def drawBlack(game):
    for  something in game.Black:
        x = (something.letter * 100) - 100
        y = 800 - (something.number * 100)# 1 is first index
        rectangle = pygame.Surface((100, 100), pygame.SRCALPHA)
        #rectangle.fill((255, 255, 255, 0))
        if(something.__class__.__name__ == "Pawn"):
            rectangle.blit(bPawn, (10,10))
        elif(something.__class__.__name__ == "King"):
           rectangle.blit(bKing, (10,10))
        elif(something.__class__.__name__ == "Queen"):
            rectangle.blit(bQueen, (10,10))
        elif(something.__class__.__name__ == "Bishop"):
            rectangle.blit(bBishop, (10,10))
        elif(something.__class__.__name__ == "Knight"):
            rectangle.blit(bKnight, (10,10))
        elif(something.__class__.__name__ == "Rook"):
            rectangle.blit(bRook, (10,10))
        #All_PIECES.append(rectangle)
        WIN.blit(rectangle, (x, y))

def drawSelectedPiece(game):
    if(game.CurrentlySelected != None):
        pygame.draw.rect(WIN, colorRed, (100, 100, game.CurrentlySelected.letter, game.CurrentlySelected.number))

def drawChessPieces(game):
    drawWhite(game)
    drawBlack(game)
    drawSelectedPiece(game)

def drawBottomBar(game):
    pygame.draw.rect(WIN, (76, 76, 76), pygame.Rect(0, 830, 830, 40))
    white = smallfont.render("White", False, colorWhite)
    black = smallfont.render("Black", False, colorWhite)
    #WIN.blit(turn,(625,760))
    WIN.blit(white,(700, 840))
    WIN.blit(black,(50, 840))
    if(game.WhiteTurn):
        x = 760
    else:
        x = 30
    pygame.draw.rect(WIN, (212, 175, 55), pygame.Rect(x, 847, 10, 10))
    for x in range(len(game.CapturedWhite)):
        surf = pygame.Surface((20, 20), pygame.SRCALPHA)
        if(game.CapturedWhite[x].__class__.__name__ == "Pawn"):
            surf.blit(swPawn, (0,0))
        elif(game.CapturedWhite[x].__class__.__name__ == "King"):
           surf.blit(swKing, (0,0))
        elif(game.CapturedWhite[x].__class__.__name__ == "Queen"):
            surf.blit(swQueen, (0,0))
        elif(game.CapturedWhite[x].__class__.__name__ == "Bishop"):
            surf.blit(swBishop, (0,0))
        elif(game.CapturedWhite[x].__class__.__name__ == "Knight"):
            surf.blit(swKnight, (0,0))
        elif(game.CapturedWhite[x].__class__.__name__ == "Rook"):
            surf.blit(swRook, (0,0))
        WIN.blit(surf, ((100 + (20*x)), 845))

    for x in range(len(game.CapturedBlack)):
        surf = pygame.Surface((20, 20), pygame.SRCALPHA)
        if(game.CapturedBlack[x].__class__.__name__ == "Pawn"):
            surf.blit(sbPawn, (0,0))
        elif(game.CapturedBlack[x].__class__.__name__ == "King"):
           surf.blit(sbKing, (0,0))
        elif(game.CapturedBlack[x].__class__.__name__ == "Queen"):
            surf.blit(sbQueen, (0,0))
        elif(game.CapturedBlack[x].__class__.__name__ == "Bishop"):
            surf.blit(sbBishop, (0,0))
        elif(game.CapturedBlack[x].__class__.__name__ == "Knight"):
            surf.blit(sbKnight, (0,0))
        elif(game.CapturedBlack[x].__class__.__name__ == "Rook"):
            surf.blit(sbRook, (0,0))
        WIN.blit(surf, ((680 - (20*x)), 845))

def drawWindow(game):
    WIN.fill(colorWhite)
    drawChessBoard(game)
    drawChessPieces(game)
    drawBottomBar(game)
    pygame.display.update()

def squareInLegalMoves(attemptedMove, allowedMoves):
    #is attempted move in allowed moves?
    for x in range(len(allowedMoves)):
        if(attemptedMove == allowedMoves[x]):
            return True
    return False

def printEngineEval(WHITE_PIECES, BLACK_PIECES):
    values = Engine.Eval(WHITE_PIECES, BLACK_PIECES)
    print("White Material :"+str(values[0]))
    print("Black Material :"+str(values[1]))
    print("White/Black Controlled Squares :"+str(values[2]))
    print("White King Safety :"+str(values[3]))
    print("Black King Safety :"+str(values[4]))

def drawLoadScreen():
    WIN.fill(colorBlack)
    Title = bigTitle.render("Chess", True, colorWhite)
    PlayGame = smallfont.render("Vs. Computer", True, colorWhite)
    PlayOnline = smallfont.render("Online", True, colorWhite)
    Quit = smallfont.render("Quit", True, colorWhite)
    pygame.draw.rect(WIN, colorRed, pygame.Rect(300, 450, 200, 50))
    pygame.draw.rect(WIN, colorRed, pygame.Rect(300, 520, 200, 50))
    pygame.draw.rect(WIN, colorRed, pygame.Rect(300, 590, 200, 50))
    WIN.blit(Title,(305, 305))
    WIN.blit(PlayGame,(340, 460))
    WIN.blit(PlayOnline,(340, 530))
    WIN.blit(Quit,(340, 600))
    pygame.display.update()

def main():
    loadScreen = True
    while loadScreen:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                click = pygame.mouse.get_pos()
                if(click[0] >= 300 and click[0] <= 500):
                    if(click[1] >= 450 and click[1] <= 500): # VS AI
                        loadScreen = False
                    elif(click[1] >= 520 and click[1] <= 570): # NETWORKING
                        print("Nope.")
                    elif(click[1] >= 590 and click[1] <= 640): #NO PLAY
                        pygame.quit()
                        sys.exit()
        drawLoadScreen()

    Running = True
    clock = pygame.time.Clock()
    game = GameOfChess()
    Opponent = ai.ComputerOpponent()
    while Running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if(game.WhiteTurn): # The players turn
                    selected = game.SelectPiece(pygame.mouse.get_pos())
                    # Okay maybe trying to move
                    if(game.CurrentlySelected != None and not selected): # We didnt select a piece with that mousedown, and we have a piece selected
                        game.MovePiece(pygame.mouse.get_pos(), False)

        clock.tick(30)
        drawWindow(game)
        if(not game.WhiteTurn):
            move = Opponent.move(game.White, game.Black, True, game.PreviouslyMovingPiece, game.BlackCheck, game.WhiteCheck, game.MoveNumber)
            tmp = LegalMove.getPieceAtSquare(move[0].letter, move[0].number, game.Black)
            if(tmp != None):
                game.CurrentlySelected = tmp
                game.MovePiece((move[1], move[2]), True)

    pygame.quit()

if __name__ == "__main__":
    main()


"""Main script.

When launched, it guides the user from choosing a classification method and its parameters to plotting and saving the data.
"""

from modules.helpers import (
    choose_classification_method,
    choose_split_factor,
    plot_and_save_fig,
)
from modules.knn import evaluate_knn, evaluate_knn_optimized
from modules.mlp import run_mlp_training
from modules.read_cifar import read_cifar, split_dataset

chosen_method = choose_classification_method()
split_factor = choose_split_factor()
k_max = 20

dict = read_cifar("data")
(data, labels) = dict

data_train, labels_train, data_test, labels_test = split_dataset(
    data, labels, split_factor
)

if chosen_method == 0:
    accuracies = []
    list_k = list(range(1, 21, 1))
    for k in list_k:
        print("Evaluating KNN for k = ", k)
        k_accuracy = evaluate_knn(data_train, labels_train, data_test, labels_test, k)
        accuracies.append(k_accuracy)

    plot_and_save_fig(k_max, accuracies, split_factor, "knn")

elif chosen_method == 1:

    accuracy_for_all_k = evaluate_knn_optimized(
        data_train, labels_train, data_test, labels_test, k_max
    )

    plot_and_save_fig(k_max, accuracy_for_all_k, split_factor, "knn")

elif chosen_method == 2:
    num_epoch = 100
    (train_accuracies, train_losses, final_accuracy) = run_mlp_training(
        data_train, labels_train, data_test, labels_test, 64, 0.1, num_epoch
    )

    print("Final accuracy for test data is :", final_accuracy)

    plot_and_save_fig(num_epoch, train_accuracies, split_factor, "mlp")
    plot_and_save_fig(num_epoch, train_losses, split_factor, "mlp loss")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/8/21 11:51
# @Site    :
# @File    : selection_sort.py
# @Software: PyCharm
# 选择排序 O(n^2) 不稳定
def selection_sort(nums):
    for i in range(len(nums)):
        min_i = i
        for j in range(i+1, len(nums)):
            if nums[j] < nums[min_i]:
                min_i = j
        nums[i], nums[min_i] = nums[min_i], nums[i]
    return nums

print(selection_sort([54,26,93,15,77,3,44,55,20]))


class Group:
    number: str
    moodle_id: int
    moodle_name: str

    def __init__(self, subject, number, moodle_id, moodle_name):
        self.__subject = subject
        self.number = number
        self.moodle_id = moodle_id
        self.moodle_name = moodle_name

    def get_students(self):
        if self.moodle_id is None:
            return

        for student in self.__subject.students:
            if student.moodle_group_id == self.moodle_id:
                yield student


# standard library imports
import logging, os, md5, sys
import hashlib, json
import simplejson
import time
from datetime import datetime
from HTMLParser import HTMLParser

# google
from google.appengine.ext import ndb
from google.appengine.api import urlfetch
from google.appengine.api import channel

# related webapp2 imports
import webapp2
from webapp2_extras import security
from webapp2_extras.auth import InvalidAuthIdError, InvalidPasswordError
from webapp2_extras.appengine.auth.models import Unique

# local application/library specific imports
import config
from lib.utils import generate_token
from lib.apishims import InstanceApiShim
from web.basehandler import BaseHandler

# note User is not used except to send to channel
from web.models.models import User, Appliance, Wisp, Cloud, Instance, Project, InstanceBid, Image, Flavor, LogTracking

from utter_libs.schemas import schemas
from utter_libs.schemas.helpers import ApiSchemaHelper

# easy button for error response
def error_response(handler, message, code, params):
	params['response'] = "error"
	params['message'] = message
	handler.response.set_status(code)
	return handler.render_template('api/response.json', **params)

# appliance token validation
# http://0.0.0.0/api/v1/authorization/ via POST
class TokenValidate(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self):
		# paramters, assume failure, response type
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"

		# get appliance variables
		try:
			packet = json.loads(self.request.body)
			apitoken = packet['appliance']['apitoken']
		except:
			params['message'] = "You must submit a valid JSON object with a token."
			self.response.set_status(401)
			return self.render_template('api/response.json', **params)

		# load the appliance
		appliance = Appliance.get_by_token(apitoken)

		if not appliance:
			params['message'] = "Token is not valid."
			self.response.set_status(401)
			return self.render_template('api/response.json', **params)

		if appliance.activated == False:
			# appliance not activated
			params['message'] = "Appliance has been disabled by pool controller. Please contact support."
			self.response.set_status(409)
			return self.render_template('api/response.json', **params)

		# update appliance info
		latitude = float(packet['appliance']['location']['latitude'])
		longitude = float(packet['appliance']['location']['longitude'])
		appliance.location = ndb.GeoPt(latitude, longitude)
		appliance.dynamicimages = bool(packet['appliance']['dynamicimages'])
		appliance.put()

		# respond with success
		params['response'] = "success"
		params['message'] = "Appliance token authenticated."
		return self.render_template('api/response.json', **params)

	def get(self):
		return self.post()

# bids creation
# http://0.0.0.0/api/v1/bids/
class BidsHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	# creation of a bid
	def post(self):
		# request basics
		ip = self.request.remote_addr

		# response, type, cross posting
		params = {}
		self.response.headers['Content-Type'] = "application/json"
		self.response.headers['Access-Control-Allow-Origin'] = '*'

		# check if this IP has any other bids open
		instancebid = InstanceBid.get_incomplete_by_ip(ip)

		# check we have an instancebid already
		if instancebid:
			# validate wisp
			if instancebid.wisp == None:
				instancebid.key.delete()
				return error_response(self, "Deleting bid because no wisp was associated.", 403, params)

			# load the payment address
			if instancebid.instance:
				instancebid.address = instancebid.instance.get().address
				instancebid.ask = instancebid.instance.get().ask
			else:
				# we should have an instance assosciated, so bail on this one
				instancebid.key.delete()
				return error_response(self, "Deleting bid because no instance was associated.", 403, params)

			params['response'] = "error"
			params['message'] = "The calling IP address already has an instance reservation in progress."
			params['instancebid'] = instancebid
			self.response.set_status(403)
			return self.render_template('api/bid.json', **params)

		# load POSTed JSON
		try:
			request = json.loads(self.request.body)
		except Exception as ex:
			return error_response(self, "Failure in parsing request JSON.", 403, params)

		# load optional values or defaults
		# ipv4 (allow default)
		if 'requires_ipv4' in request:
			requires_ipv4 = request['requires_ipv4']
		else:
			requires_ipv4 = 0

		# ipv6 (allow default)
		if 'requires_ipv6' in request:
			requires_ipv6 = request['requires_ipv6']
		else:
			requires_ipv6 = 0

		# providers (allow default)
		if 'providers' in request:
			providers = request['providers']
		else:
			providers = [{u'id': 1, u'name': u'All Providers'}]

		# flavors (required)
		if 'flavor' in request:
			flavor_name = request['flavor']
			flavor = Flavor.get_by_name(flavor_name)

			# check if flavor was found
			if not flavor:
				return error_response(self, "Flavor not found.", 403, params)

		else:
			return error_response(self, "Flavor name is required.", 403, params)

		# cloud (optional)
		if 'cloud_id' in request:
			cloud_id = request['cloud_id']
			cloud = Cloud.get_by_id(long(cloud_id))

			# check if cloud was found
			if not cloud:
				return error_response(self, "Cloud ID not found.", 403, params)
		else:
			cloud = None

		# disallow both a wisp and a callback_url
		if 'wisp_id' in request and 'callback_url' in request:
			return error_response(self, "A wisp and a callback URL may not be used together.", 403, params)

		# require either a wisp or a callback_url
		if 'wisp_id' not in request and 'callback_url' not in request:
			return error_response(self, "A valid wisp or a callback URL is required.", 403, params)

		# load the wisp, if there is one
		if 'wisp_id' in request:
			wisp_id = request['wisp_id']
			wisp = Wisp.get_by_id(long(wisp_id))
		else:
			wisp = None

		# load the callback URL, if there is one
		if 'callback_url' in request:
			callback_url = request['callback_url']
		elif wisp:
			callback_url = wisp.callback_url
		else:
			callback_url = ""

		# test we have a callback_url or a valid image in the wisp
		if callback_url > "":
			try:
				result = urlfetch.fetch(callback_url, deadline=5)
				if result.status_code > 399:
					return error_response(self, "The callback URL is unreachable.", 403, params)
				# test result's image URL
			except Exception as ex:
				return error_response(self, "The callback URL is unreachable.", 403, params)
		elif wisp:
			if wisp.image == None and wisp.dynamic_image_url == None and wisp.project == None:
				return error_response(self, "A valid wisp or a callback URL is required.", 403, params)

		# grab a new bid hash to use for the new bid
		token = generate_token(size=16)
		name = "smr-%s" % generate_token(size=8)

		# create a new bid
		instancebid = InstanceBid()
		instancebid.token = token
		instancebid.name = name
		instancebid.need_ipv4_address = bool(requires_ipv4)
		instancebid.need_ipv6_address = bool(requires_ipv6)
		instancebid.flavor = flavor.key
		instancebid.remote_ip = ip
		instancebid.appliances = providers # providers is already JSON
		instancebid.status = 0
		instancebid.callback_url = callback_url

		# expires in 5 minutes
		epoch_time = int(time.time())
		instancebid.expires = datetime.fromtimestamp(epoch_time+300)

		# add wisp, if present
		if wisp:
			instancebid.wisp = wisp.key

		# add cloud, if present
		if cloud:
			instancebid.cloud = cloud.key

		# update
		instancebid.put()

		# sleep for dev
		if config.debug:
			time.sleep(2)

		# reserve the instance
		InstanceBid.reserve_instance_by_token(instancebid.token)

		# get the address, if you got an instance
		if instancebid.instance:
			address = instancebid.instance.get().address
			ask = instancebid.instance.get().ask
		else:
			# no instance was reserved
			instancebid.key.delete()
			return error_response(self, "No valid instances were returned.", 403, params)

		# hack address and ask into instancebid object for template (not stored)
		instancebid.address = address
		instancebid.ask = ask

		# build out the response
		params['response'] = "success"
		params['message'] = "A new instance bid has been created."
		params['instancebid'] = instancebid

		# return response and include cross site POST headers
		self.response.set_status(201)

		return self.render_template('api/bid.json', **params)

	def get(self):
		return self.post()

	def options(self):
		self.response.headers['Access-Control-Allow-Origin'] = '*'
		self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
		self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
		return

# bids detail
# http://0.0.0.0/api/v1/bids/<token>/
class BidsDetailHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def get(self, token=None):
		# response, type, cross posting
		params = {}
		self.response.headers['Content-Type'] = "application/json"
		self.response.headers['Access-Control-Allow-Origin'] = '*'

		# look for instance bid first
		bid = InstanceBid.get_by_token(token)

		if bid:
			# build out the response
			params['response'] = "success"
			params['message'] = "Reservation found by token."
			params['instancebid'] = bid

			# return response
			self.response.set_status(201)
			return self.render_template('api/bid.json', **params)

		else:
			# look for instance
			instance = Instance.get_by_token(token)

			if instance:
				# build out the response
				params['response'] = "success"
				params['message'] = "Instance found by token."
				params['instance'] = instance

				# return response
				self.response.set_status(201)
				return self.render_template('api/instancedetail.json', **params)

			else:
				# build out the error response
				params['response'] = "error"
				params['message'] = "No resources found by token."

				return self.render_template('api/response.json', **params)

	def delete(self, token=None):
		bid = InstanceBid.get_by_token(token)

		# delete the bid
		if bid:
			bid.key.delete()

		# patch up the respective instance if it's not been started
		instance = Instance.get_by_token(token)

		if instance:
			# only patch instance if it's not been started
			if instance.state <= 1:
					instance.reserved = False
					instance.token = None
					instance.put()

		return

	def options(self):
		self.response.headers['Access-Control-Allow-Origin'] = '*'
		self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
		self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
		return

# list of all available instances for sale
# http://0.0.0.0/api/v1/instances/
class InstancesHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self):
		# request basics
		ip = self.request.remote_addr
		offset = self.request.get("offset")
		limit = self.request.get("limit")

		instances = Instance().get_all_offered()

		# add gravatar URLs
		for instance in instances:
			email = instance.appliance.get().owner.get().email
			gravatar_hash = md5.new(email.lower().strip()).hexdigest()
			instance.gravatar_url = "https://www.gravatar.com/avatar/%s" % gravatar_hash

		# build parameter list
		params = {
			'remote_ip': ip,
			'instances': instances
		}

		# return images via template
		self.response.headers['Content-Type'] = 'application/json'
		return self.render_template('api/instances.json', **params)

	def get(self):
		return self.post()

# instance callback handler to handle pool_instance() calls from utter-va
# http://0.0.0.0/api/v1/instances/<instance_name>/ via POST, PUT, GET
class InstanceDetailHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self, instance_name):
		# paramters, assume failure, response type
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"

		# request basics
		ip = self.request.remote_addr

		try:
			body = json.loads(self.request.body)
			instance_schema = schemas['InstanceSchema'](**body['instance'])
			appliance_schema = schemas['ApplianceSchema'](**body['appliance'])

			# try to authenticate appliance
			if not Appliance.authenticate(appliance_schema.apitoken.as_dict()):
				logging.error("%s is using an invalid token(%s) or appliance deactivated."
					% (ip, appliance_schema.apitoken.as_dict()))
				return error_response(self, "Token is not valid.", 401, params)

			# fetch appliance and instance
			appliance = Appliance.get_by_token(appliance_schema.apitoken.as_dict())

			instance = Instance.get_by_name_appliance(
				instance_schema.name.as_dict(),
				appliance.key
			)

			# if instance doesn't already exist, create it
			if not instance:
				wisp = Wisp.get_user_default(appliance.owner)
				if not wisp:
					wisp = Wisp.get_system_default()
				instance = Instance(wisp=wisp.key)

			# wrap instance into api shim in order to translate values from structure
			# of api to structure of model. I hope at some point in the future the two
			# models are similar enough so we can entirely drop this shim
			instance_shim = InstanceApiShim(instance)

			# update instance with values from post
			ApiSchemaHelper.fill_object_from_schema(
				instance_schema, instance_shim)

			# associate instance with it's appliance
			instance_shim.appliance = appliance

		except Exception as e:
			return error_response(self, 'Error in creating or updating instance from '
				'post data, with message {0}'.format(str(e)), 500, {})

		# update local instance
		instance.put()

		# update appliance ip address hint
		if instance.state > 3 and instance.ipv4_address:
			appliance.ipv4enabled = True
		if instance.state > 3 and instance.ipv6_address:
			appliance.ipv6enabled = True
		appliance.put()

		# sleep for dev
		if config.debug:
			time.sleep(1)

		# send update information to channel
		if instance.token:

			output = {
				"name": instance.name,
				"token": instance.token,
				"state": instance.state,
			}
			channel.send_message(instance.token, json.dumps(output))

		# pop a reload just in case user is on their cloud page
		if instance.owner:
			user_info = User.get_by_id(long(instance.owner.id()))
			channel.send_message(user_info.key.urlsafe(), "reload")

		# convert bid to instance
		# check if there is an instance bid reservation on this instance
		instancebid = InstanceBid.get_by_instance(instance.key)
		if instancebid:
			# check for a bid callback_url (entered in the callback field on the launcher)
			if instancebid.callback_url > "":
				# put the callback into the instance
				instance.callback_url = instancebid.callback_url

			elif instancebid.wisp:
				# otherwise, get the wisp's callback URL
				callback_url = instancebid.wisp.get().callback_url

				# if the wisp has an empty callback URL, populate the instance with the wisp's bid details
				if callback_url == "" or callback_url == None:
					instance.wisp = instancebid.wisp
					instance.owner = instancebid.wisp.get().owner
					instance.cloud = instancebid.cloud
				else:
					# we have a custom callback in the wisp itself, so move to instance
					instance.callback_url = callback_url

			# update the instance
			instance.put()

			# delete the instance reservation
			instancebid.key.delete()

		# proxy custom callback

		"""
		BEGIN CODE CALLOUT
		"""
		# August 24, 2014
		#
		# The following code retrieves content from a remote server and proxies it to
		# an appliance for starting an instance. It is at this point an anonymous user's
		# callback pattern is most venerable to being monitored and manipulated.
		#
		# The author of this software issues a warrant canary tweet to @stackape which
		# should appear on the 1st of each month indicating the absence of a gag order
		# having been issued to StackMonkey, Utter.io, or Kord Campbell.
		#
		# Please monitor the code block between BEGIN CODE CALLOUT and END CODE CALLOUT
		# if the canary tweet does not appear on schedule. Please monitor any callback
		# file's retrieval patterns if the canary tweet does not appear on schedule.
		# Please report any findings to the community sections of the project/site.
		#
		# Remember, the code is Open Source. Use that fact to the community's advantage.
		#
		# The warrant canary will likely be your only indication a change has possibly
		# taken place to the system.  These changes may or may not enable a government
		# agency to intercept and monitor instances using a custom URL callback.
		#
		# Kord Campbell
		#
		if instance.callback_url:
			try:
				result = urlfetch.fetch(instance.callback_url, deadline=5)
			except Exception as ex:
				logging.error("Error fetching callback URL content.")
				instance.console_output = "Error fetching callback url=(%s)'s' content. %s" % (instance.callback_url, ex)
				instance.put()

				# user may be sitting on an instance reservation here, so reload the page
				# this will force the handler to redirect the user to the instance page
				channel.send_message(instance.token, "reload")
				return error_response(self, "Error fetching callback URL content.", 401, params)

			# return content retrieved from callback URL if the JSON returned by this method includes
			# a callback_url in the data, the appliance will follow the URL and will not call this API
			# again during the life of the instance.
			self.response.headers['Content-Type'] = 'application/json'
			self.response.write(json.dumps(json.loads(result.content), sort_keys=True, indent=2))

			# return from here
			return

		"""
		END CODE CALLOUT
		"""

		# at this point we have one of two scenarios:
		# 1. an external instance start (registered user with appliance, sans instancebid)
		# 2. registered user using a normal wisp WITHOUT a callback_url

		# grab the instance's wisp
		if instance.wisp:
			# if instance is using a wisp
			wisp = Wisp.get_by_id(instance.wisp.id())
		else:
			# no wisp on instance
			wisp = Wisp.get_user_default(instance.owner)

		# deliver default system wisp if none (external instance start)
		if not wisp:
			wisp = Wisp.get_system_default()

		# load wisp image
		if not wisp.use_dynamic_image:
			image = wisp.image.get()
		else:
			image = wisp.get_dynamic_image()

		# pop the ssh_key into an array
		if wisp.ssh_key:
			ssh_keys = []
			for line in iter(wisp.ssh_key.splitlines()):
				ssh_keys.append(line)
		else:
			ssh_keys = [""]

		#
		# pop the post creation script into an array
		if wisp.post_creation:
			post_creation = []
			for line in iter(wisp.post_creation.splitlines()):
				post_creation.append(line)
		else:
			post_creation = [""]

		# some of replay's magic - need docs on this
		start_params = schemas['InstanceStartParametersSchema']()
		data = {
			'image': image,
			'callback_url': wisp.callback_url if wisp.callback_url else "",
			'ssh_keys': ssh_keys,
			'post_create': post_creation}
		ApiSchemaHelper.fill_schema_from_object(start_params, data)

		self.response.set_status(200)
		self.response.headers['Content-Type'] = 'application/json'

		# write dictionary as json string
		self.response.out.write(json.dumps(
				# retrieve dict from schema
				start_params.as_dict()))

	# unauthenticated put for meta data
	def put(self, instance_name = None):
		# disable csrf check in basehandler
		csrf_exempt = True

		# paramters, assume failure, response type
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"

		# get the instance, build the response type
		instance = Instance.get_by_name(instance_name)
		self.response.headers['Content-Type'] = "application/json"

		# if no instance, then show error
		if not instance:
			params['message'] = "Instance not found."
			self.response.set_status(404)
			return self.render_template('api/response.json', **params)
		else:
			# load the instance's meta data, if any
			if instance.meta:
				meta = json.loads(instance.meta)
			else:
				meta = json.loads('{}')

		# load the json from the call
		try:
			body = json.loads(self.request.body)

			# loop through key space and set meta data
			for key in body:
				meta[key] = body[key]

			# dump back into the db
			instance.meta = json.dumps(meta)
			instance.put()

		except Exception as e:
			params['message'] = "An error was encountered with parsing meta key values: %s." % str(e)
			self.response.set_status(500)
			return self.render_template('api/response.json', **params)

		# send update information to channel
		if instance.token:
			output = {
				"name": instance.name,
				"token": instance.token,
				"state": instance.state,
				"meta": meta
			}
			channel.send_message(instance.token, json.dumps(output))

		# build response
		params = {
			"instance": instance,
			"meta": json.loads(instance.meta)
		}
		params['response'] = "success"
		self.response.headers['Content-Type'] = 'application/json'

		return self.render_template('api/instance.json', **params)

	# unauthenticated endpoint
	def get(self, instance_name = None):

		# get the instance, build the response type
		instance = Instance.get_by_name(instance_name)
		self.response.headers['Content-Type'] = "application/json"

		# if no instance, then show error
		if not instance:
			params['message'] = "Instance not found."
			self.response.set_status(404)
			return self.render_template('api/response.json', **params)

		# load the instance's meta data, if any
		if instance.meta:
			meta = json.loads(instance.meta)
		else:
			meta = json.loads('{}')

		# build response
		params = {
			"instance": instance,
			"meta": meta
		}

		params['response'] = "success"
		self.response.headers['Content-Type'] = 'application/json'

		return self.render_template('api/instance.json', **params)

# accept sale of multiple instances from provider
# http://0.0.0.0/api/v1/broker/ via POST
class BrokerHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self):
		# paramters, assume failure, response type
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"

		# get appliance variables
		try:
			packet = json.loads(self.request.body)
			apitoken = packet['appliance']['apitoken']
		except:
			params['message'] = "You must submit a valid JSON object with a token."
			self.response.set_status(401)
			return self.render_template('api/response.json', **params)

		# load the appliance
		appliance = Appliance.get_by_token(apitoken)

		if not appliance:
			params['message'] = "Token is not valid."
			self.response.set_status(401)
			return self.render_template('api/response.json', **params)

		if appliance.activated == False:
			# appliance not activated
			params['message'] = "Appliance has been disabled by pool controller. Please contact support."
			self.response.set_status(409)
			return self.render_template('api/response.json', **params)

		# update appliance info
		latitude = float(packet['appliance']['location']['latitude'])
		longitude = float(packet['appliance']['location']['longitude'])
		appliance.location = ndb.GeoPt(latitude, longitude)
		appliance.dynamicimages = bool(packet['appliance']['dynamicimages'])
		appliance.put()

		# loop through instances being advertised for sale
		for appliance_instance in packet['instances']:
			# pass in appliance_instance and appliance object
			#logging.info("instance: %s" % appliance_instance['name'])
			instance = Instance.push(appliance_instance, appliance)

		# build parameter list
		params = {}
		params['response'] = "success"
		params['message'] = "Instances accepted for sale."
		self.response.headers['Content-Type'] = 'application/json'

		return self.render_template('api/response.json', **params)

	def get(self):
		return self.post()

# images list
# http://0.0.0.0/api/v1/images/ GET or POST
class ImagesHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self):
		images = Image().get_all()

		# build parameter list
		params = {
			'images': images
		}

		# return images via template
		self.response.headers['Content-Type'] = 'application/json'
		return self.render_template('api/images.json', **params)

	def get(self):
		return self.post()

# flavors list
# http://0.0.0.0/api/v1/flavors/ GET or POST
class FlavorsHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self, action):
		self.response.headers['Content-Type'] = 'application/json'
		self.response.set_status(200)
		# write dictionary as json string
		self.response.out.write(json.dumps(
				# retrieve flavors as schema and convert schema to dict
				Flavor.as_schema_list(
					# pass get_all method as query object
					Flavor.query()).as_dict()))

	def get(self, action):
		return self.post(action)

# used to log whatever we want to track
# http://0.0.0.0/api/v1/track/ via GET
class TrackingPingHandler(BaseHandler):
	def get(self):
		# get ip address
		ip = self.request.remote_addr
		message = self.request.get("message")

		# update db
		track = LogTracking()
		track.ip = ip
		if message:
			track.message = message
		else:
			track.message = "Simple tracking request."
		track.put()

		# return JSON response
		params = {}
		params['response'] = "success"
		params['result'] = "ping recorded for %s" % ip
		self.response.headers['Content-Type'] = "application/json"
		return self.render_template('api/response.json', **params)

# create wisps, anonymously if needed
# http://0.0.0.0/api/v1/wisp/ via GET, POST
class WispHandler(BaseHandler):
	# disable csrf check in basehandler
	csrf_exempt = True

	def post(self):
		# try to pull get user info from a browser based session
		if self.user_id:
			user_info = User.get_by_id(long(self.user_id))
		else:
			user_info = None

		# paramters, assume failure, response type
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"

		# response headers
		self.response.headers['Content-Type'] = "application/json"
		self.response.headers['Access-Control-Allow-Origin'] = '*'

		# load various variables
		body = json.loads(self.request.body)

		# SSH key (not required)
		try:
			ssh_key = body['ssh_key']
		except:
			ssh_key = ""

		# load project if we have it
		try:
			project_id = body['project_id']
			project = Project.get_by_id(long(project_id))
		except:
			project = None

		# handle project wisps differently
		if project:
			wisp = Wisp().from_project(
				ssh_key,
				project,
				user_info
			)
		else:
			try:
				post_creation = body['post_creation']
			except:
				post_creation = ""

			try:
				image_id = body['image_id']
				image = Image.get_by_id(long(image_id))
			except:
				try:
					dynamic_image_url = body['dynamic_image_url']
				except:
					# we don't have an image or a URL, so nothing can do
					params['message'] = "Wisps require an image to boot."
					self.response.set_status(401)
					return self.render_template('api/response.json', **params)

			# disk and container formats if they were sent (usually qcow/bare)
			try:
				image_disk_format = body['image_disk_format']
			except:
				image_disk_format = "qcow2"
			try:
				image_container_format = body['image_container_format']
			except:
				image_container_format = "bare"

			# create an anonymous wisp if we don't have it already
			wisp = Wisp().from_stock(
				ssh_key,
				post_creation,
				dynamic_image_url,
				image_disk_format,
				image_container_format,
				user_info
			)

		if wisp:
			# return JSON response
			params['response'] = "success"
			params['wisp'] = wisp

			return self.render_template('api/wisp.json', **params)
		else:
			params['message'] = "Wisp creation failed."
			self.response.set_status(401)
			return self.render_template('api/response.json', **params)

	def get(self):
		return self.post()

# create anonymous wisp
# http://0.0.0.0/api/v1/wisp/<token>/ via GET, POST
class WispViewHandler(BaseHandler):
	def get(self, token=None):
		# paramters, assume failure, response type
		# response, type, cross posting
		params = {}
		params['response'] = "error"
		self.response.headers['Content-Type'] = "application/json"
		self.response.headers['Access-Control-Allow-Origin'] = '*'

		# look for instance bid first
		wisp = Wisp.get_by_token(token)

		# if no instance, then show error
		if not wisp:
			params['message'] = "Wisp not found."
			self.response.set_status(404)
			return self.render_template('api/response.json', **params)
		else:
			params['respose'] = "success"
			params['wisp'] = wisp

		return self.render_template('api/wisp.json', **params)

# generate list of appliances
# http://0.0.0.0/api/v1/appliances/ GET
class ApplianceListHandler(BaseHandler):
	def get(self):
		appliances = Appliance().appliances_with_instances_on_sale()

		# add gravatar URLs
		for appliance in appliances:
			email = appliance.owner.get().email
			gravatar_hash = md5.new(email.lower().strip()).hexdigest()
			appliance.gravatar_url = "https://www.gravatar.com/avatar/%s" % gravatar_hash

		# return JSON response
		params = {
			'appliances': appliances,
			'message': "This is a list of all active appliances with instances for sale."
		}
		self.response.headers['Content-Type'] = "application/json"
		return self.render_template('api/appliances.json', **params)

# generate list of geopoints for appliances
# http://0.0.0.0/api/v1/appliances/geopoints/ GET
class ApplianceGeoPoints(BaseHandler):
	def get(self):
		geopoints = Appliance().get_geopoints()

		# return JSON response
		params = {
			'geopoints': geopoints
		}
		self.response.headers['Content-Type'] = "application/json"
		return self.render_template('api/geopoints.json', **params)


from torch.utils.data import Dataset
from pathlib import Path
import numpy as np
from PIL import Image
import h5py
import data.MVSDataset
import torch
from torch.nn import functional as F

class MVSDataset(data.MVSDataset.MVSDataset):
    def __init__(self, datapath, listfile, mode, nviews, return_depth=False, **kwargs):
        super().__init__()
        assert mode in ["train", "val", "test"]

        if mode == "val":
            self.p = Path(datapath) / "test"
        else:
            self.p = Path(datapath) / mode

        self.height = 512
        self.width = 512
        self.img_idx = []
        self.scene_idx = []
        for scene in listfile:
            if (self.p / scene).exists():
                for cpt in range(1000): # hardcoded max size of dataset
                    b = True
                    for i in range(nviews):
                        b = b and (self.p / scene / f"im_{cpt}_{i}.jpg").exists()
                    b = b and (self.p / scene / f"infos_{cpt}.npz").exists()
                    if mode == "test":
                        if not (self.p / scene / f"depth_{cpt}.h5").exists():
                            for i in range(nviews):
                                b = b and (self.p / scene / f"depth_{cpt}_{i}.h5").exists()

                    else:
                        if return_depth:
                            b = b and (self.p / scene / f"depth_{cpt}.h5").exists()

                    if b:
                        self.img_idx.append(cpt)
                        self.scene_idx.append(scene)

        self.listfile = listfile
        self.mode = mode
        self.nviews = nviews
        self.return_depth = return_depth

        nb_report = 50
        self.visu_idx = (np.arange(nb_report) * (len(self.img_idx) / nb_report)).astype(int)

        self.rands = None

    def __len__(self):
        return len(self.img_idx)

    def __getitem__(self, idx):
        imgs = []
        scene = self.scene_idx[idx]

        infos_filename = self.p / scene / f"infos_{self.img_idx[idx]}.npz"

        npz = np.load(infos_filename)
        depth_train = self.return_depth and self.mode == "train"

        if depth_train:
            with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}.h5", 'r') as f:
                depth = torch.tensor(np.array(f["depth"]))

        K, R, t = npz["K"].astype(np.float32), npz["R"].astype(np.float32), npz["t"].astype(np.float32)

        K, R, t = K[:self.nviews], R[:self.nviews], t[:self.nviews]

        proj_matrices = np.zeros((self.nviews, 4, 4), dtype=np.float32)
        proj_matrices[:, 3, 3] = 1

        for i in range(self.nviews):
            img_filename = self.p / scene / f"im_{self.img_idx[idx]}_{i}.jpg"

            im, resize_ratio = self.read_img(img_filename)
            new_K = self.rescale_calib(resize_ratio, K=K[i])
            if depth_train and i == 0:
                th, tw = depth.shape
                depth = F.interpolate(depth.view(1, 1, th, tw), size=im.shape[:-1], mode="nearest").squeeze(0)
                im, new_K, depth = self.center_crop(im, K=new_K, idx=idx, depth=depth)
            else:
                im, new_K = self.center_crop(im, K=new_K, idx=idx)

            if i == 0:
                f = img_filename

            imgs.append(im)
            K[i] = new_K

        res = {"f": str(f),
               "K": K,
               "R": R,
               "t": t,
               "depth_min": npz["min_d"].astype(np.float32),
               "depth_max": npz["max_d"].astype(np.float32)}

        if self.mode != "test":
            res["imgs"] = np.stack([im.transpose([2, 0, 1]) for im in imgs], axis=0)
            if self.return_depth:
                res["depth"] = depth
                res["mask"] = (depth >= npz["min_d"][0]) & (depth < npz["max_d"][0])

        else:
            res["imgs"] = [im.transpose([2, 0, 1]) for im in imgs]
            depths = list()
            masks = list()
            try:
                for i in range(self.nviews):
                    # not clean but i don't want to regen a full dataset
                    with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}_{i}.h5", 'r') as f:
                        depth = np.array(f["depth"])
                        depths.append(depth)
                        masks.append(depth > 0)
            except OSError:
                with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}.h5", 'r') as f:
                    depth = np.array(f["depth"]).astype(np.float)
                    depths.append(depth)
                    masks.append(depth > 0)

            res["mask"] = masks
            res["depth"] = depths

        return res


import os
from board import Board, OutOfBoardException
from collections import namedtuple

coordinates = namedtuple('coordinated', ['x', 'y'])

class GameOfLife:
    def __init__(self, board: Board) -> None:
        self.board: Board = board

    def board_after_lifecycle(self) -> None:
        new_board = Board(rows=self.board.rows, columns=self.board.columns)
        for y in range(self.board.rows):
            for x in range(self.board.columns):
                neighbours_number = self.check_living_neighbours_number(x=x, y=y)
                if self.board.get(x=x, y=y) == 1 and neighbours_number in (2, 3):
                    new_board.set(x=x, y=y, value=1)
                elif self.board.get(x=x, y=y) == 0 and neighbours_number == 3:
                    new_board.set(x=x, y=y, value=1)
                else:
                    new_board.set(x=x, y=y, value=0)
        self.board = new_board

    def check_living_neighbours_number(self, y: int, x: int) -> int:
        number_of_neighbours = 0
        neighbors = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)]
        for neighbour_x, neighbour_y in neighbors:
            final_x = x + neighbour_x
            final_y = y + neighbour_y
            try:
                if self.board.get(y=final_y, x=final_x) == 1:
                    number_of_neighbours += 1
            except OutOfBoardException:
                continue
        return number_of_neighbours

    @staticmethod
    def choose_coordinates():
        while True:
            try:
                print("Jeśli chcesz wyjść naciśnij enter\n")
                x = int(input("Podaj kolumne\n"))
                if x is None:
                    break
                print()
                y = int(input("Podaj wiersz\n"))
                if y is None:
                    break
                return coordinates(x-1, y-1)
            except ValueError:
                print("Podana wartość jest nieprawidłowa! Spróbuj jeszcze raz\n")

def main():
    board = Board(20, 20)
    game = GameOfLife(board)
    print(game.board)
    while True:
        choice = input("\nNaciśnij enter aby kontynuować"
                       "\nJedynke aby zmienić wartość punktu,"
                       "\nl, aby wczytać z pliku"
                       "\nlub wpisz cokolwiek innego aby wyjść\n")
        if choice == "":
            os.system("clear")
            game.board_after_lifecycle()
            print(game.board)
        elif choice == "l":
            filename = input("Podaj nazwę pliku: ")
            try:
                with open(filename) as f:
                    board_string = ''.join(f.readlines())
                    board = Board.from_string(board_string)
                    game = GameOfLife(board)
            except FileNotFoundError:
                print(f'Plik o nazwie "{filename}" nie istnieje.')
        elif choice == "1":
            try:
                coordinates = game.choose_coordinates()
                value = game.board.get(coordinates.x, coordinates.y)
                game.board.set(coordinates.x, coordinates.y, 1 if value == 0 else 0)
                print(game.board)
            except OutOfBoardException:
                print("Podane koordynaty nie mieszczą się w skali planszy, spróbuj jeszcze raz!\n")
        else:
            break

if __name__ == "__main__":
    main()


import json
from flask import Flask, request
import json, os
import resource

app = Flask(__name__)

map = {}
# 30 MB can store => 10,000 so 1/MB it will be 333 records now assuming
# 1 gib of RAM which 1000MB net net we can store 333, 000 records and after that we
# can clear the map and write it in file
map_counter = 333000
# map_counter = 10

def write_map_file(out_file):
    global map_counter
    for url, val in map.items():
        tmp = f"{url}, {val}\n"
        out_file.write(tmp)
    #clear the map, and set again counter to 0
    map.clear()
    map_counter = 0

def process_scan(line, page_rank_threshold, out_file):
    parts = line.split(",")
    try:
        url, page_score = parts[0], int(parts[1])
        if page_score > page_rank_threshold:
            tmp = f"{url}, {page_score} \n"
            out_file.write(tmp)
    except Exception as e:
        pass
        # print("Iseeueee :::", line)

def process_agre(line, page_rank_threshold, out_file):
    global map_counter
    '''
    - to aggregate we need to lookup if the current element was seen.
    - now if we need to check if current element was always seen we can use hashmap
    - this is bad cause it will blow out in memory, instead we create hash function which
    always gives same number when passed same string and we write on that number which will be our line number
     in FILE
    '''
    parts = line.split(",")
    try:
        ip, rev = parts[0], float(parts[3])

        if ip not in map:
            map[ip] = rev
        else:
            map[ip] += rev
        if(map_counter >= 0):
            map_counter -= 1
        else:
            write_map_file(out_file)
        # tmp = f"{ip}, {rev} \n"
        # print(tmp)
        # out_file.write(tmp)
    except Exception as e:
        print(f"Some error : {e}, line : {line}")
        pass

def process_data(line, page_rank_threshold, out_file, query_type):
    if query_type == 'scan':
        process_scan(line, page_rank_threshold, out_file)
    else:
        process_agre(line, page_rank_threshold, out_file)
        # print("Iseeueee :::", line)

def read_in_chunks(file_object, chunk_size=4024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

def perform_external_read(list_of_files, page_rank_threshold, query_type):
    # base_path = f"../../mapper/page_rank_data/data_{query_type}"
    base_path = f"/app/page_rank_data/data_{query_type}"
    op_file = os.path.join(base_path, f"output_file_query_{query_type}")
    #remove existing file if exists
    if os.path.exists(op_file): os.remove(op_file)
    with open(op_file, 'a+') as out_file:
        for file in list_of_files:
            file_path = os.path.join(base_path, file)
            with open(file_path) as f:
                if 'output' not in file:
                    for line in f: #by default iterator is lazy in this case doesnt read in memory
                        process_data(line, page_rank_threshold, out_file, query_type)
                # if line is not split into newlines use below generator: https://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python
                # for line in read_in_chunks(f):
                #     process_data(line, page_rank_threshold)
        if len(map):
            write_map_file(out_file)

@app.route("/consume", methods=["POST"])
def consume():
    data = json.loads(request.data)
    # print(data)
    #https://stackoverflow.com/questions/938733/total-memory-used-by-python-process
    print("*************************")
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
    print("*************************")
    perform_external_read(data['payload'], data['page_rank_threshold'], data['query_type'])
    print("*************************")
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
    print("*************************")
    print("Length of map : ", len(map))
    return 'Receieved', 200

@app.route("/health")
def health():
    return 'Am up X!'

if __name__ == "__main__":
    '''
    - receive the name of file to read
    - load part by part of file in memory and check the number of file above threshold
    - write lines with values more than threshold in op file
    '''
    app.run("0.0.0.0", port=8080, debug=True)


from django.contrib import admin
from sofia.admin import sofia_admin_site
from .models import Cart, CartItem

class CartAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'
    list_display = ['id', 'customer']
    list_display_links = None
    list_filter = ['customer']

class CartItemAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'
    list_display = ['id', 'cart', 'product_entry', 'quantity', 'created_at']
    list_display_links = None
    list_filter = ['created_at']

sofia_admin_site.register(Cart, CartAdmin)
sofia_admin_site.register(CartItem, CartItemAdmin)


import torch
import os
import wandb
import json
import torch.optim as optim
from PIL import Image
from utils import parser, misc
from utils.config import *
from tools import builder
from tqdm import tqdm
from my_datasets.my_PCN import get_dataloader
from utils.logger import *
from utils.AverageMeter import AverageMeter
from utils.metrics import Metrics
from extensions.chamfer_dist import ChamferDistanceL1

# os.environ["CUDA_VISIBLE_DEVICES"] = '1'
device = 'cuda' if torch.cuda.is_available() else 'cpu'

def main(args, config):

    wandb.login()
    run = wandb.init(project='my_foldingnet')
    start_epoch = 0

    model = builder.model_builder(config.model).to(device)
    (train_sampler, train_dataloader), (_, test_dataloader) = builder.dataset_builder(args, config.dataset.train), \
                                                            builder.dataset_builder(args, config.dataset.val)

    optimizer, scheduler = builder.build_opti_sche(model, config)

    for epoch in range(start_epoch, config.max_epoch + 1):
        losses = AverageMeter()
        model.train()
        for (taxonomy_ids, model_ids, data) in tqdm(train_dataloader):
            model.zero_grad()
            gt = data[1].to(device)
            _, recon = model(gt)
            loss_func = ChamferDistanceL1().to(device)
            loss = loss_func(recon, gt)
            loss.backward()
            optimizer.step()
            losses.update(loss.item())
        wandb.log({"train_loss_epoch": losses.avg()})

        #test metric
        if epoch % 20 == 0:
            validate(model, test_dataloader, epoch, args)

        # #visulize result
        # if epoch % 50 == 0:
        #     with torch.no_grad():
        #         (taxonomy_ids, model_ids, data) = next(iter(test_dataloader))
        #         model.eval()
        #         gt = data[1].to(device)
        #         input_pc = gt.squeeze().detach().cpu().numpy()
        #         input_pc = misc.get_ptcloud_img(input_pc)
        #         _, recon = model(gt)
        #         recon = recon.squeeze().detach().cpu().numpy()
        #         recon = misc.get_ptcloud_img(recon)
        #         wandb.log({"epoch": epoch, "input": wandb.Image(input_pc), "recon": wandb.Image(recon)})

def validate(model, test_dataloader, epoch, args):
    with torch.no_grad():
        print("Validate the test dataset and visulize points")
        model.eval()
        losses = AverageMeter()
        category_metrics = dict()
        test_metrics = AverageMeter(Metrics.names())

        #创建保存图片的文件夹
        save_pth = os.path.join(args.saveimg_path, 'epoch%d' % epoch)
        os.makedirs(save_pth, exist_ok=True)
        gt_pth = os.path.join(save_pth, 'gt')
        os.makedirs(gt_pth, exist_ok=True)
        recon_pth = os.path.join(save_pth, 'recon')
        os.makedirs(recon_pth, exist_ok=True)

        for idx, (taxonomy_ids, model_ids, data) in enumerate(tqdm(test_dataloader)):
            gt = data[1].to(device)
            _, recon = model(gt)
            _metrics = Metrics.get(recon, gt)

            #记录每个种类的指标
            for _taxonomy_id in taxonomy_ids:
                if _taxonomy_id not in category_metrics:
                    category_metrics[_taxonomy_id] = AverageMeter(Metrics.names())
                category_metrics[_taxonomy_id].update(_metrics)

            #保存图片
            if idx % 500 == 0:
                input_gt = gt.squeeze().detach().cpu().numpy()
                input_gt = misc.get_ptcloud_img(input_gt)
                im = Image.fromarray(input_gt)
                gt_savepth = os.path.join(gt_pth, '%s.jpg' % model_ids)
                im.save(gt_savepth)

                recon = recon.squeeze().detach().cpu().numpy()
                recon = misc.get_ptcloud_img(recon)
                im = Image.fromarray(recon)
                recon_savepth = os.path.join(recon_pth, '%s.jpg' % model_ids)
                im.save(recon_savepth)

        #计算平均指标
        for _,v in category_metrics.items():
            test_metrics.update(v.avg())
        wandb.log({'test_loss_epoch': test_metrics.avg()[1]})

        #打印结果
        shapenet_dict = json.load(open('./data/shapenet_synset_dict.json', 'r'))
        print('============================ TEST RESULTS ============================')
        print('[Validation] EPOCH: %d  Metrics = %s' % (epoch, ['%.4f' % m for m in test_metrics.avg()]))
        msg = ''
        msg += 'Taxonomy' + '\t'
        msg += 'ClassName' + '\t'
        msg += 'nsamples' + '\t'
        for metric in test_metrics.items:
            msg += metric + '\t'
        print(msg)

        for taxonomy_id in category_metrics:
            msg = ''
            msg += (taxonomy_id + '\t')
            msg += shapenet_dict[taxonomy_id] + '\t'
            msg += (str(category_metrics[taxonomy_id].count(0)) + '\t')
            for value in category_metrics[taxonomy_id].avg():
                msg += '%.3f' % value + '\t'
            print(msg)

        msg = ''
        msg += 'Overall\t\t'
        for value in test_metrics.avg():
            msg += '%.3f \t' % value
        print(msg)

        #使用wandb track
        columns = ['Taxonomy', 'ClassName', 'nsamples', 'F1_Score', 'CDL1', 'CDL2', 'EMD']
        data = []
        for taxonomy_id in category_metrics:
            data_id = [taxonomy_id, shapenet_dict[taxonomy_id], str(category_metrics[taxonomy_id].count(0))]
            for value in category_metrics[taxonomy_id].avg():
                data_id.append(value)
            data.append(data_id)
        data_all = ['overall', '', '']
        for value in test_metrics.avg():
            data_all.append(value)
        data.append(data_all)

        table = wandb.Table(data=data, columns=columns)
        wandb.log({'test_table': table})

if __name__ == '__main__':
    args = parser.get_args()
    args.distributed = False
    config = get_config(args)
    config.dataset.train.others.bs = config.total_bs
    main(args, config)


from flask import Flask, request
from flask_cors import CORS
import cv2
import numpy as np
app = Flask(__name__)
cors = CORS(app)
drawing = False
import os
import time
import threading
import sys
from Controls.controller_manager import ControllerManager
import Controls.presets as presets
import numpy as np

curr_frame = np.zeros((480,640,3))

SCALE_SIZE = 300
control = ControllerManager()
#control = None

def calculate_lstsq_error(points):
    x = points[:,0]
    y = points[:,1]
    A = np.vstack([x, np.ones(len(x))]).T
    return np.sum(np.abs(np.linalg.lstsq(A, y, rcond=None)[1]))

def interpolate_points(points, DIST_THRES = 5, LSTSQ_THRES = 1, errors = []):
    new_points = []

    line_start = 0
    line_end = 1
    for i in range(0,len(points)):
        if i ==0:
            new_points.append(points[i])
        else:
            error = calculate_lstsq_error(points[line_start:line_end])
            errors.append(error)
            if abs(error) >= LSTSQ_THRES:
                new_points.append(points[line_end])
                line_start = line_end

            line_end = min(line_end + 1, len(points)-1) # incr last index by 1
        if i == len(points) - 1: # add last point to finish line
            new_points.append(points[i])
    return np.array(new_points)

def transform(point, old_dim, new_dim = SCALE_SIZE):
    min_value = min(np.min(point[:,1]), np.min(point[:,0]))
    scale = new_dim/old_dim if min_value >= 0 else (new_dim/2)/(old_dim)
    old_dim = np.array(old_dim)
    new_dim = np.array(new_dim)
    point = np.array(point)
    temp =  scale*(point - old_dim/2) + new_dim/2
    temp[:,0] = -temp[:,0] + new_dim

    min_value = min(np.min(temp[:,1]), np.min(temp[:,0]))
    if min_value < 0:
        # shift values
        temp -= min_value

    return temp

def draw_async(points, control = control):
    global drawing
    print("start draw")
    control.draw_points(points)
    print(control.is_done())
    while not control.is_done():
        control.update_manager()
        time.sleep(0.005)
    drawing = False
    print("end draw")

def draw_points(points, size, interpolate = True):
    global drawing
    if not drawing:
        drawing = True
        if interpolate:
            points = interpolate_points([transform(pt, size[0]) for pt in points])
            print(points)
        thread = threading.Thread(target=draw_async, args=(points,))
        thread.start()

@app.route(f'/api/draw_preset', methods=['POST'])
def set_preset():
    '''
    Start drawing process with set of points
    '''
    global drawing
    if not drawing and request.is_json:
        data = request.get_json()
        name = data['preset']
        offset = data.get("offset", 0)
        if name == 'swirl':
            rt = data.get('rt', 15/180*np.pi)
            rr = data.get('rr', 3)
            draw_points(*presets.swirl_preset(rt, rr, offset=offset))
        elif name == 'demo':
            rt = data.get('rt', 15/180*np.pi)
            rr = data.get('rr', 3)
            pts, size = presets.swirl_preset(rt, rr, offset=offset)
            pts.extend(pts[::-1])
            draw_points(pts, size)
        elif name == "cardiod":
            pts, size = presets.cardiod_preset(offset=offset)
            draw_points(pts, size)
        elif name == "lisajous":
            pts, size = presets.lisajous_preset(offset=offset)
            print(pts)
            draw_points(pts, size)

        return {
                "status": "S" #started
                }, 200
    return {
                "status": "P" #already started
                }, 200

@app.route(f'/api/post_points', methods = ["POST"])
def set_points():
    '''
    Start drawing process with set of points
    '''
    global drawing
    if not drawing and request.is_json:
        data = request.get_json()
        points = data['points']
        size = data['size'] ## [width, height]
        draw_points(points, size)

        return {
                "status": "S" #started
                }, 200
    return {
                "status": "P" #already started
                }, 200

@app.route(f'/api/get_status', methods = ["GET"])
def get_status():
    ## Get percent done of drawing process
    proportion_done = 0 ## TODO: Add code here to calculate percent done as a proportion
    try:
        proportion_done = control.get_progress()
    except Exception as e:
        print(e)
        pass
    return {"percent": str(round(proportion_done*100, 2))}, 200

if __name__=="__main__":
    if not (len(sys.argv) > 1 and sys.argv[1] == "--naive"):
        print("non naive")
        app.run(host='0.0.0.0')


# coding=utf-8
from __future__ import unicode_literals
from collections import OrderedDict

from faker.providers.date_time import Provider as DateTimeProvider
from .. import BaseProvider
import redis

localized = True

class DebitCard(object):

    def __init__(self, name, prefixes, length=19):
        self.name = name
        self.prefixes = prefixes
        self.length = length

class Provider(BaseProvider):

    # 大陆信用卡
    prefix_cmbc = ["472067", "427570", "421393", "621692", "623683", "622620", "622622", "900003", "622615", "622619"]
    prefix_cmb = ["410062", "690755", "512425", "622580", "622598", "95555", "468203", "623262", "402658", "623126"]
    prefix_cib = ["438589", "90592", "622909"]
    prefix_ceb = ["620518", "622664", "622668", "622667", "623157", "622670", "623155", "621490", "621492", "620535"]
    prefix_citic = ["622698", "620082", "621770", "622696", "622690", "968809", "433670", "622691", "622999", "621768"]
    prefix_hxb = ["623022", "622633", "621222", "999999", "623021", "622630"]
    prefix_spdb = ["84373", "84390", "87040", "621791", "622518", "621792", "623250", "984303", "87000", "87010"]
    prefix_gdb = ["623259", "623506", "6858009", "9111"]
    prefix_pingan = ["622535", "412962", "412963", "415752", "998800", "622538", "622536", "415753"]
    prefix_egb = ["622384"]
    prefix_czb = ["621019", "622309"]
    prefix_cbhb = ["622884", "621453", "621268"]

    debit_card_types = OrderedDict((
        (u'民生银行',   DebitCard(u'民生银行',     prefix_cmbc, 16)),
        (u'招商银行',    DebitCard(u'招商银行',    prefix_cmb, 16)),
        (u'兴业银行',    DebitCard(u'兴业银行', prefix_cib, 18)),
        (u'光大银行',    DebitCard(u'光大银行',   prefix_ceb, 16)),
        (u'中信银行',    DebitCard(u'中信银行',    prefix_citic, 16)),
        (u'华夏银行',    DebitCard(u'华夏银行',  prefix_hxb, 16)),
        (u'浦发银行',    DebitCard(u'浦发银行', prefix_spdb, 16)),
        (u'广发银行',    DebitCard(u'广发银行', prefix_gdb, 16)),
        (u'平安银行',    DebitCard(u'平安银行',   prefix_pingan, 16)),
        (u'恒丰银行',    DebitCard(u'恒丰银行',   prefix_egb, 16)),
        (u'浙商银行',    DebitCard('浙商银行',   prefix_czb, 19)),
        (u'渤海银行',    DebitCard(u'渤海银行',   prefix_cbhb, 16))
    ))

    # prefix_dic = {"华夏银行": 621222, "招商银行": 690755, "光大银行": 622662, "民生银行": 622615, "中信银行": 433670,
    #           "兴业银行": 622909, "浦发银行": 622516, "广发银行": 623259, "平安银行": 412963, "恒丰银行": 622384,
    #           "浙商银行": 621019, "渤海银行": 621268}

    luhn_lookup = {'0': 0, '1': 2, '2': 4, '3': 6, '4': 8,
                   '5': 1, '6': 3, '7': 5, '8': 7, '9': 9}

    # @classmethod
    # def all_debit_cards(cls):
    #     ret = {}
    #     for key in cls.prefix_dic.keys():
    #         number = cls._bank_card_number(str(cls.prefix_dic[key]))
    #         ret[key] = number
    #         print key+':'+number
    #     return ret

    @classmethod
    def debit_card_provider(cls, card_type=None):
        """ Returns the provider's name of the debit card. """
        if card_type is None:
            card_type = cls.random_element(cls.debit_card_types.keys())
        return cls._debit_card_type(card_type).name

    @classmethod
    def debit_card_number(cls, card_type=None):
        """ Returns a valid debit card number. """
        card = cls._debit_card_type(card_type)
        prefix = cls.random_element(card.prefixes)
        number = cls._generate_number(prefix, card.length)
        return number

    # @classmethod
    # def bank_card_info(cls):
    #     """ Returns a dict that contains bank card info.        """
    #     prefix = cls.random_element(cls.card_prefix)
    #     bank_card_number = cls._bank_card_number()
    #     r = redis.StrictRedis(host='10.12.9.14', port=6379, db=0)
    #     info = r.get(prefix+"CORE_CARD_BIN")
    #     if info is not None:
    #         names = ['bank_name', 'bank_code', 'card_name', 'card_bin', 'card_type']
    #         values = info.decode('utf-8').split('|')
    #         card_info = dict(zip(names, values))
    #         card_info['card_number'] = bank_card_number
    #     else:
    #         print "Redis中没有找到该卡的属性:%s" % prefix
    #         raise Exception
    #     return  card_info

    @classmethod
    def debit_card_expire(cls, start='now', end='+10y', date_format='%m/%y'):
        expire_date = DateTimeProvider.date_time_between(start, end)
        return expire_date.strftime(date_format)

    def debit_card_full(self, card_type=None):
        card = self._debit_card_type(card_type)

        tpl = ('{provider}\n'
               '{owner}\n'
               '{number} {expire_date}\n')

        tpl = tpl.format(provider = card.name,
                         owner = self.generator.parse("{{first_name}} {{last_name}}"),
                         number = self.debit_card_number(card),
                         expire_date = self.debit_card_expire(),
                         )

        return self.generator.parse(tpl)

    @classmethod
    def debit_card_security_code(cls, card_type=None):
        """ Returns a security code string. """
        sec_len = cls._debit_card_type(card_type).security_code_length
        return cls.numerify('#' * sec_len)

    @classmethod
    def _debit_card_type(cls, card_type=None):
        """ Returns a random debit card type instance. """
        if card_type is None:
            card_type = cls.random_element(cls.debit_card_types.keys())
        elif isinstance(card_type, DebitCard):
            return card_type
        return cls.debit_card_types[card_type]

    @classmethod
    def _generate_number(cls, prefix, length):
        """
        'prefix' is the start of the CC number as a string, any number of digits.
        'length' is the length of the CC number to generate. Typically 13 or 16
        """
        number = prefix
        # Generate random char digits
        number += '#' * (length - len(prefix) - 1)
        number = cls.numerify(number)
        reverse = number[::-1]
        # Calculate sum
        tot = 0
        pos = 0
        while pos < length - 1:
            tot += Provider.luhn_lookup[reverse[pos]]
            if pos != (length - 2):
                tot += int(reverse[pos + 1])
            pos += 2
        # Calculate check digit
        check_digit = (10 - (tot % 10)) % 10
        number += str(check_digit)
        return number


M,N=map(int,input().split())
Weight=[]
for _ in range(M):
    Weight.append(list(input()))

Store=[[0 for _ in range(N)] for _ in range(M)]
Print=[[0 for _ in range(N)] for _ in range(M)]
# print(Store)
for i in range(M):
    Print[i][0]=int(Weight[i][0])

for j in range(1,N):
    for i in range(M):
        if i>0:
            Store[i][j]=max(Print[i][j],Print[i-1][j-1])
        Store[i][j]=max(Print[i][j],Print[i][j-1])
        if i<N-2:
            Store[i][j]=max(Print[i][j],Print[i+1][j-1])
        Print[i][j]=Store[i][j]+int(Weight[i][j] )
    # print('스토어',Store)
    # print("프린트", Print)

ans=0
for i in range(M):
    ans=max(ans,max(*Store[i]))

print(ans)


from django.core.urlresolvers import reverse

from rest_framework import status
from rest_framework.test import APITestCase

from clubs.models import Club
from courses.models import Course, CourseInstruction
from qualifications.models import Certificate, Qualification
from users.models import User

class UserCoursesTestCase(APITestCase):
    def setUp(self):
        self.staff = User.objects.create_user('Staff', 'Member', is_staff=True)
        club = Club.objects.create(name='UCC')
        self.member = User.objects.create_user('Club', 'Member', club=club)
        cert = Certificate.objects.create(name='Trainee Diver')
        course = Course.objects.create(
          certificate=cert,
          creator=self.staff,
          organizer=self.member,
        )
        CourseInstruction.objects.create(user=self.member, course=course)

    def test_user_can_view_own_courses_organized(self):
        self.client.force_authenticate(self.member)
        response = self.client.get(reverse('user-courses-organized', args=[self.member.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)

    def test_user_can_view_own_courses_taught(self):
        self.client.force_authenticate(self.member)
        response = self.client.get(reverse('user-courses-taught', args=[self.member.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)