#! /usr/bin/env python3

"""
jxl-strip

Strips the container off of a jxl file, reducing the size and removing any
potentially sensitive metadata. The original file is overwritten, so make sure
to have a copy if you are experimenting.

Currently it is possible for this program to produce invalid JXL files, if the
the image is a level 10 image, in which case the container is required. This
should be uncommon however, and really only effects CMYK, or gigapixel images.
"""

from pathlib import Path
import argparse
import sys

def has_container(bitstream: bytes) -> bool:
    """
    Determines the image type by sniffing the first few bytes.
    """
    # Test for raw JXL codestream.
    if bitstream[:2] == bytes.fromhex("FF0A"):
        return False
    # Test for JXL box structure. http://www-internal/2022/18181-2#box-types
    if bitstream[:12] == bytes.fromhex("0000 000C 4A58 4C20 0D0A 870A"):
        return True
    raise ValueError("Not a JPEG XL file.")

def decode_container(bitstream: bytes) -> bytes:
    """
    Parses the ISOBMFF container, extracts the codestream, and decodes it.
    JXL container specification: http://www-internal/2022/18181-2
    """

    def parse_box(bitstream: bytes, box_start: int) -> dict:
        LBox = int.from_bytes(bitstream[box_start : box_start + 4])
        XLBox = None
        if 1 < LBox <= 8:
            raise ValueError(f"Invalid LBox at byte {box_start}.")
        if LBox == 1:
            XLBox = int.from_bytes(bitstream[box_start + 8 : box_start + 16])
            if XLBox <= 16:
                raise ValueError(f"Invalid XLBox at byte {box_start}.")
        if XLBox:
            header_length = 16
            box_length = XLBox
        else:
            header_length = 8
            if LBox == 0:
                box_length = len(bitstream) - box_start
            else:
                box_length = LBox
        return {
            "length": box_length,
            "type": bitstream[box_start + 4 : box_start + 8],
            "data": bitstream[box_start + header_length : box_start + box_length],
        }

    # Reject files missing required boxes. These two boxes are required to be at
    # the start and contain no values, so we can manually check there presence.
    # Signature box. (Redundant as has already been checked.)
    if bitstream[:12] != bytes.fromhex("0000000C 4A584C20 0D0A870A"):
        raise ValueError("Invalid signature box.")
    # File Type box.
    if bitstream[12:32] != bytes.fromhex(
        "00000014 66747970 6A786C20 00000000 6A786C20"
    ):
        raise ValueError("Invalid file type box.")

    partial_codestream = []
    container_pointer = 32
    while container_pointer < len(bitstream):
        box = parse_box(bitstream, container_pointer)
        container_pointer += box["length"]
        if box["type"] == b"jxll":
            level = int.from_bytes(box["data"])
            if level != 5 or level != 10:
                raise ValueError("Unknown level")
        elif box["type"] == b"jxlc":
            codestream = box["data"]
        elif box["type"] == b"jxlp":
            index = int.from_bytes(box["data"][:4])
            partial_codestream.append([index, box["data"][4:]])

    if partial_codestream:
        partial_codestream.sort(key=lambda i: i[0])
        codestream = b"".join([i[1] for i in partial_codestream])

    return codestream

def main() -> int:
    """Read file from the command line, and strip its box."""

    parser = argparse.ArgumentParser(
        prog="jxl-strip",
        description="Strips the container from a JPEG XL image",
        epilog="jxl-strip will strip the container from any jxl images, reducing their size\nand removing any privacy compromising metadata.",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="explain what is happening.",
    )
    parser.add_argument(
        "file", help="JXL file to strip, will be overwritten", type=Path
    )
    args = parser.parse_args()

    # Main program logic start.
    try:
        with open(args.file, "rb") as fp:
            # has_container will raise a ValueError if not a jxl file, and only
            # reading the first 12 bytes makes this check fast. If it is a jxl
            # file, reads the rest of it.
            bitstream = fp.read(12)
            container = has_container(bitstream)
            bitstream = bitstream + fp.read()
        if container:
            # There is technically a race condition here as we are reopening the
            # file, but doing it otherwise is annoying, and it is unlikely that
            # another tool is manipulating the files at the same time.
            if args.verbose:
                print(f"Striping {args.file}", file=sys.stderr)
            with open(args.file, "wb") as fp:
                fp.write(decode_container(bitstream))
        else:
            if args.verbose:
                print(
                    f"Skipping {args.file} as it is already stripped", file=sys.stderr
                )
    except FileNotFoundError:
        print(f"{args.file} not found", sys.stderr)
        return 1
    except ValueError:
        print(f"{args.file} is not a valid JXL file", sys.stderr)
        return 1

    return 0

if __name__ == "__main__":
    sys.exit(main())


import requests
import nlptest
import testing
from anytree import Node, RenderTree
from bs4 import BeautifulSoup

subdomain_limit = 3

def find_subdomains(url):
    source = requests.get(url).text
    soup = BeautifulSoup(source, 'lxml')

    texts = []

    for tag in soup.find_all('a'):
        link = tag.get('href',None)
        if link is not None and link.startswith('http') and not link.lower().endswith(('.pdf', '.gif')) and link not in texts:
            texts.append(link)
            if len(texts) == subdomain_limit:
                break
    return texts

def print_nodes(url):
    result = ""

    array = find_subdomains(url)
    root = Node(url)

    for i in range(len(array)):
        first_depth = Node(array[i], parent=root)
        array2 = find_subdomains(array[i])
        for j in range(len(array2)):
            second_depth = Node(array2[j], parent=first_depth)

    for pre, fill, node in RenderTree(root):
        result += pre + "" + node.name + "\n"

    return result

def find_all_keywords(url):

    result_dict = {}
    result_text = ""

    dict1 = nlptest.find_keywords_for_subdomains(result_dict, url)
    result_text += "#" + url + ":\n" + testing.format_text(dict1, 25) + "\n\n"

    urls = find_subdomains(url)

    for i in range(len(urls)):
        dict2 = nlptest.find_keywords_for_subdomains(result_dict, urls[i])
        result_text += "##" + urls[i] + ":\n" + testing.format_text(dict2, 25) + "\n\n"
        urls2 = find_subdomains(urls[i])
        for j in range(len(urls2)):
            dict3 = nlptest.find_keywords_for_subdomains(result_dict, urls2[j])
            result_text += "###" + urls2[j] + ":\n" + testing.format_text(dict3, 25) + "\n\n"

    return result_dict, result_text


from flask import Flask, request, jsonify, Markup
from pyslinger import pyslinger
import simplejson as json
from markdown import markdown

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def load_item():
    if request.method == 'GET':
        # show usage docs
        return Markup(markdown(open('README.md').read()))
    if request.method == 'POST' and 'payload' in request.files:

        # Update any pyslinger constants passed
        # cq_server, username, password, static_root
        for field in request.form:
            setattr(pyslinger, field.upper(), request.form[field])

        payload = json.load(request.files['payload'])
        result = pyslinger.load_item(payload)
        return jsonify(result)

if __name__ == "__main__":
    app.run()


import argparse
import json
import re

from app_config import config
from qcs import qcsapi

parser = argparse.ArgumentParser(description="Braspag qualys integration to evaluate images in CI pipeline")
parser.add_argument("--imageid", nargs="+", help="image Id to be evaluated")
parser.add_argument("--config", nargs=1, help="JSON file to be processed", type=argparse.FileType("r"))
arguments = parser.parse_args()

# Loading arguments
image_id = arguments.imageid[0]
config_arg = json.load(arguments.config[0])
qid_list = config_arg["qid"]
severity_toblock = config_arg["severity"]
vulncount = config_arg["vulncount"]

# Check Image Pattern
imagepattern = re.compile(r"([0-9a-z]{12})")
if imagepattern.match(image_id):
    pass
else:
    raise Exception("Provide a valid Image ID")

# check CVE Pattern
cve_list = []
cvepattern = re.compile(r"CVE-\d{4}-\d{4,7}")
for each in config_arg["cves"]:
    if cvepattern.match(each):
        cve_list.append(each)
    else:
        raise Exception("Invalid cve pattern")

# Creds for Api Access
creds = config.get_config()

# get url to build
url_builder = qcsapi.UrlBuilder()

# Api Call
con = qcsapi.QualysImages(creds, url_builder)
resp = con.GetByImageId(image_id)

# Valuation by severity
valuation = qcsapi.PolicyValuation.ValuationBySeverity(resp)

# Remove Sensor
# sensor_con = qcsapi.QualysSensor(creds, url_builder)
# Remove Sensor with Type CI/CD
# sensor_resp = sensor_con.RemoveSensorByType()

# sensor_uuid = ["fc9ff560-b3af-4f9d-8206-7cb5a6398a39"]
# sensor_resp = sensor_con.RemoveBySensoruuId(sensor_uuid)


import sys
from enum import Enum
from heapq import *
from math import cos, sin, pi, sqrt, tan, nan
import random

import pygame
import copy

from client.game.src.core.bot.a_star import A_Star
from client.game.src.core.bot.maze import Maze, path_from
from client.game.src.core.stat_bar.stat_bar import StatBar
from client.game.src.utils.config import Config

class Drive(Enum):
    FORWARD = 0
    BACKWARD = 1

class Rotate(Enum):
    LEFT = 0
    RIGHT = 1

class ExpectRotate(float, Enum):
    UP = 270
    DOWN = 90
    LEFT = 180
    RIGHT = 0

class DirectionAngle(float, Enum):
    UP = 90
    DOWN = 270
    LEFT = 180
    RIGHT = 0

class BotController:
    SHOT_DISTANCE = 30
    ANGLE_OFFSET = 10
    POS_OFFSET = 20
    COLISION_OFFSET = 10
    DETECTION_OFFSET = 30
    FLEE_ANGLE = 70
    DISTANCE_OFFSET = 15
    ANGLE_SENSITIVITY = 30

    def __init__(self, screen, game, player, id):
        self.id = id
        self.screen = screen
        self.game = game
        self.player = player
        self.map = self.read_map(game.map.data)
        self.node = None
        self.x = 0
        self.y = 0
        self.glitch_time = 0
        self.flee_timer = 0
        self.flee_dir = 0
        self.last_bullet_angle = 0
        self.enemy = None

    def distance(self, player):
        return abs(self.player.position[0] - player.position[0]) + abs(self.player.position[1] - player.position[1])

    def set_enemy(self):
        self.enemy = self.find_closest_player()

    def find_closest_player(self):
        minDistance = sys.maxsize
        minPlayer = None

        for player in self.game.players:
            if player != self.player:
                if minDistance > self.distance(player):
                    minDistance = self.distance(player)
                    minPlayer = player
        return minPlayer

    def read_map(self, map):
        # for i in range(len(map)):
        #     print(map[i])
        for i in range(len(map)):
            map[i] = list(map[i])
            for j in range(len(map[i])):
                if map[i][j] == 'S':
                    map[i][j] = '.'

        return map

    def astar(self, maze):
        start_node = maze.find_node('S')
        self.node = (start_node.x, start_node.y)
        start_node.visited = True
        end_node = maze.find_node('E')
        start_node.cost = abs(end_node.x - start_node.x) + abs(end_node.y - start_node.y)
        q = []
        id = 0
        heappush(q, (start_node.cost, id, start_node))
        while q:
            node = heappop(q)[2]  # LIFO
            node.visited = True
            if node.type == 'E':
                return path_from(node)

            children = maze.get_possible_movements(node)
            for child in children:
                if not child.visited:
                    child.parent = node
                    child.moves_cost = node.moves_cost + maze.move_cost(child)
                    child.cost = abs(end_node.x - child.x) + abs(end_node.y - child.y) + child.moves_cost
                    id += 1
                    heappush(q, (child.cost, id, child))

        return None

    def find_path(self):
        # player = self.find_closest_player()  # gdyby bylo wiecej graczy trzeba uzywac tej metody
        player = self.enemy
        new_map = copy.deepcopy(self.map)
        width = self.game.assets.width
        height = self.game.assets.height

        self.x = int(self.player.position[0] / width)
        self.y = int(self.player.position[1] / height)

        new_map[self.y][self.x] = 'S'
        x2 = int(player.position[0] / width)
        y2 = int(player.position[1] / height)
        new_map[y2][x2] = 'E'

        if (self.x, self.y) == (x2, y2):
            return None, None, 0
        maze = Maze(new_map)
        maze.path = self.astar(maze)
        # maze.draw()

        act = maze.path[len(maze.path) - 1]
        new = maze.path[len(maze.path) - 2]
        return (act.x, act.y), (new.x, new.y), len(maze.path)

    def move(self):
        if self.enemy.is_alive():
            actual_point, new_point, length = self.find_path()
            if actual_point:
                if actual_point[1] < new_point[1]:
                    return length, ExpectRotate.UP
                if actual_point[1] > new_point[1]:
                    return length, ExpectRotate.DOWN
                if actual_point[0] < new_point[0]:
                    return length, ExpectRotate.RIGHT
                if actual_point[0] > new_point[0]:
                    return length, ExpectRotate.LEFT
        return 0, self.player.angle  # stay

    def diagonal_distance(self):
        """
        :return: diagonal distance between bot and an enemy.
        :rtype: float
        """
        e_x, e_y = self.enemy.position
        b_x, b_y = self.player.position
        return sqrt(pow(b_x - e_x, 2) + pow(b_y - e_y, 2))

    def checkMove(self, directory, pos):
        # for i in range(len(self.map)):
        #   print(self.map[i])

        if directory == DirectionAngle.DOWN and self.map[pos[1] + 1][pos[0]] != "#":
            return True
        elif directory == DirectionAngle.UP and self.map[pos[1] - 1][pos[0]] != "#":
            return True
        elif directory == DirectionAngle.RIGHT and self.map[pos[1]][pos[0] + 1] != "#":
            return True
        elif directory == DirectionAngle.LEFT and self.map[pos[1]][pos[0] - 1] != "#":
            return True

        return False

    @property
    def move2(self):
        moves = []
        self.actual_pos = ""
        if self.enemy.is_alive():
            self.actual_pos, new_point, length = self.find_path()
            if self.actual_pos:
                moves = [DirectionAngle.DOWN, DirectionAngle.UP, DirectionAngle.RIGHT, DirectionAngle.LEFT]
                opponent_possition = None
                if (self.actual_pos[1] < new_point[1]):
                    opponent_possition = DirectionAngle.DOWN
                elif (self.actual_pos[1] > new_point[1]):
                    opponent_possition = DirectionAngle.UP
                elif (self.actual_pos[0] < new_point[0]):
                    opponent_possition = DirectionAngle.RIGHT
                elif (self.actual_pos[0] > new_point[0]):
                    opponent_possition = DirectionAngle.LEFT

                # print("oppo:", opponent_possition)
                moves.remove(opponent_possition)
                for move in moves:
                    if not self.checkMove(move, self.actual_pos):
                        moves.remove(move)

                if len(moves) == 0 and self.checkMove(opponent_possition, self.actual_pos):
                    moves.append(opponent_possition)

        if len(moves):
            # print(self.actual_pos, new_point, moves, self.player.angle, self.player.lastMove)
            for angle in moves:
                # if self.lastMove and ((angle - 1 < self.lastMove < angle + 1) or (angle == DirectionAngle.RIGHT and 359 < self.lastMove < 361)):  # stay
                if self.player.lastMove != None and angle == self.player.lastMove and self.checkMove(self.player.lastMove, self.actual_pos):
                    return length, self.player.lastMove

            r = random.randrange(0, len(moves), 1)
            self.player.lastMove = moves[r]
            # print("a? ", moves[r])
            return length, moves[r]
        # print("C")
        self.player.lastMove = self.player.angle
        return 0, self.player.angle  # stay

    def shot_condition(self, length):
        """
        Checks if enemy is in a straight line with a bot and if bot faces the enemy.
        :param int length: Length of a shortest path between bot and an enemy in a number of tiles.
        :return: If bot is supposed to shot.
        :rtype: bool
        """
        if self.enemy.is_alive():
            e_x, e_y = self.enemy.position
            b_x, b_y = self.player.position
            b_angle = self.player.angle
            width = self.game.assets.width
            height = self.game.assets.height
            tile_size = (width + height) / 2
            if length - 1 <= self.diagonal_distance() / tile_size:
                if b_x - self.POS_OFFSET <= e_x <= b_x + self.POS_OFFSET:
                    # enemy above
                    if b_y > e_y:
                        if DirectionAngle.UP - self.ANGLE_OFFSET <= b_angle <= DirectionAngle.UP + self.ANGLE_OFFSET:
                            return True
                    # enemy below
                    if b_y < e_y:
                        if DirectionAngle.DOWN - self.ANGLE_OFFSET <= b_angle <= DirectionAngle.DOWN + self.ANGLE_OFFSET:
                            return True
                elif b_y - self.POS_OFFSET <= e_y <= b_y + self.POS_OFFSET:
                    # enemy on a left
                    if b_x > e_x:
                        if DirectionAngle.LEFT - self.ANGLE_OFFSET <= b_angle <= DirectionAngle.LEFT + self.ANGLE_OFFSET:
                            return True
                    # enemy on a right
                    if b_x < e_x:
                        if DirectionAngle.RIGHT - self.ANGLE_OFFSET <= b_angle <= DirectionAngle.RIGHT + self.ANGLE_OFFSET:
                            return True
        return False

    @staticmethod
    def whole_angle(angle):
        """
        Check which angle from {0, 90, 180, 270} is closest to the given one.
        :param float angle:
        :return: angle from a range of {0, 90, 180, 270}.
        :rtype: float
        """
        if 45 < angle <= 135:
            return 90
        elif 135 < angle <= 225:
            return 180
        elif 225 < angle <= 315:
            return 270
        else:
            return 0

    def on_trajectory(self, bullet):
        """
        Checks if bot is on the bullet whole trajectory, including the one behind it.
        :param bullet: Bullet Object
        :return: If bot is on the bullet trajectory. If yes also bullet angle.
        :rtype: bool, float
        """
        bullet_x, bullet_y = bullet.position
        bot_x, bot_y = self.player.position
        offset = 2
        if 90 - offset <= bullet.angle <= 90 + offset:
            hit_x = bullet_x
            hit_y = bot_y
        elif 0 <= bullet.angle <= offset or 360 - offset <= bullet.angle <= 360:
            hit_x = bot_x
            hit_y = bullet_y
        elif 270 - offset <= bullet.angle <= 270 + offset:
            hit_x = bullet_x
            hit_y = bot_y
        elif 180 - offset <= bullet.angle <= 180 + offset:
            hit_x = bot_x
            hit_y = bullet_y
        else:
            bullet_a = tan(-bullet.angle * pi / 180)
            bullet_b = bullet_y - (bullet_a * bullet_x)

            bot_a = - 1 / bullet_a if bullet_a else - 1 / pow(10, -20)
            bot_b = bot_y - (bot_a * bot_x)

            hit_x = (bot_b - bullet_b) / (bullet_a - bot_a) if bullet_a - bot_a else (bot_b - bullet_b) / pow(10, -20)
            hit_y = (bullet_a * hit_x) + bullet_b

        dist = sqrt(pow(bot_x - hit_x, 2) + pow(bot_y - hit_y, 2))

        if dist < self.DETECTION_OFFSET:
            return True, bullet.angle
        return False, None
        # return True, object.angle

    def at_gunpoint(self):
        """
        Check if bot might get hit by any bullet on a map except his.
        :return: If bot might get hit if not moved. If yes also bullet angle.
        :rtype: bool, float
        """
        for bullet in self.game.bullet_controller.bullets:
            if bullet.player.id != self.player.id:

                bullet_x, bullet_y = bullet.position
                bot_x, bot_y = self.player.position
                if bullet_x < bot_x - self.DETECTION_OFFSET and 90 <= bullet.angle <= 270:
                    # print("x< ", self.id)
                    continue
                elif bullet_x > bot_x + self.DETECTION_OFFSET and (
                        0 <= bullet.angle <= 90 and 270 <= bullet.angle <= 360):
                    # print("x> ", self.id)
                    continue
                elif bullet_y < bot_y - self.DETECTION_OFFSET and 0 <= bullet.angle <= 180:
                    # print("y< ", self.id)
                    continue
                elif bullet_y > bot_y + self.DETECTION_OFFSET and 180 <= bullet.angle <= 360:
                    # print("y> ", self.id)
                    continue
                else:
                    # print("check")
                    endangered, angle = self.on_trajectory(bullet)
                    if endangered:
                        return endangered, angle
        return False, None

    def paul(self, time):
        if self.player.is_alive():
            flee, bullet_angle = self.at_gunpoint()
            if self.flee_timer <= 0 or flee:
                self._reload(time)
                length, rotate = self.move()
                shot = self.shot_condition(length)
                angle = self.player.angle - rotate
                width = self.game.assets.width
                height = self.game.assets.height

                if self.player.angle > 180 and rotate == DirectionAngle.RIGHT:
                    angle = angle - 360
                elif self.player.angle <= 0 and rotate == DirectionAngle.DOWN:
                    angle = (360 + angle)

                if angle != 0 and (-1 < self.player.angle < 1 and self.x * width > self.player.position[0] - width / 2
                                   or 179 < self.player.angle < 181 and self.player.position[0] > (
                                           self.x + 1) * width - width / 2
                                   or 269 < self.player.angle < 271 and self.y * height >= self.player.position[
                                       1] - height / 2
                                   or 89 < self.player.angle < 91 and self.player.position[1] > (
                                           self.y + 1) * height - height / 2)\
                                   or 359 < self.player.angle < 361 and self.player.position[0] > (
                                           self.x + 1) * width - width / 2:
                    angle = 0

                if shot:
                    self.shot()

                move_value = 0
                if flee:
                    self.last_bullet_angle = bullet_angle
                    self.flee_timer = 20
                    rev_b_angle = (bullet_angle + 180) % 360
                    if rev_b_angle - self.FLEE_ANGLE <= self.player.angle <= rev_b_angle + self.FLEE_ANGLE:
                        if self.flee_dir:
                            self.rotate(Rotate.LEFT, 3 * time)
                        else:
                            self.rotate(Rotate.RIGHT, 3 * time)
                        self.drive(Drive.BACKWARD, time)
                    else:
                        self.drive(Drive.BACKWARD, time)
                elif self.glitch_time < 0:
                    self.drive(Drive.BACKWARD, time)
                    if self.flee_dir:
                        self.rotate(Rotate.LEFT, time / 2)
                    else:
                        self.rotate(Rotate.LEFT, time / 2)
                    move_value = 1
                elif angle > 1:
                    self.rotate(Rotate.RIGHT, time)
                elif angle < -1:
                    self.rotate(Rotate.LEFT, time)
                else:
                    self.flee_dir = 0 if self.flee_dir else 1
                    self.player.rotate(self.whole_angle(self.player.angle) - self.player.angle, time)
                    b_x, b_y = self.player.position
                    e_x, e_y = self.enemy.position
                    re_angle = (self.enemy.angle + 180) % 360
                    dist_offset = self.DISTANCE_OFFSET
                    ang_offset = self.ANGLE_SENSITIVITY
                    # bot and enemy facing each other and on the +/- same x position
                    if re_angle - ang_offset <= self.player.angle <= re_angle + ang_offset and \
                            e_x - dist_offset <= b_x <= e_x + dist_offset and \
                            e_y - self.COLISION_OFFSET <= b_y <= e_y + self.COLISION_OFFSET:
                        if length <= 3 and \
                                (90 - ang_offset <= re_angle <= 90 + ang_offset or \
                                270 - ang_offset <= re_angle <= 270 + ang_offset):
                            move_value = -10
                        else:
                            move_value = self.drive(Drive.FORWARD, time)
                    # bot and enemy facing each other and on the +/- same y position
                    elif re_angle - ang_offset <= self.player.angle <= re_angle + ang_offset and \
                            e_y - dist_offset <= b_y <= e_y + dist_offset and \
                            e_x - self.COLISION_OFFSET <= b_x <= e_x + self.COLISION_OFFSET:
                        if length <= 3 and \
                                (0 <= re_angle <= ang_offset or 360 - ang_offset <= re_angle <= 360 or \
                                180 - ang_offset <= re_angle <= 180 + ang_offset):
                            move_value = -10
                        else:
                            move_value = self.drive(Drive.FORWARD, time)
                    # bot or enemy is turned to the other one in a 90 degree angle
                    elif re_angle + 90 - ang_offset <= self.player.angle <= re_angle + 90 + ang_offset or \
                          re_angle - 90 - ang_offset <= self.player.angle <= re_angle - 90 + ang_offset: \
                        move_value = self.drive(Drive.FORWARD, time)
                    elif length > 2:
                        move_value = self.drive(Drive.FORWARD, time)
                    else:
                        move_value = -10 - random.randrange(10)
                self.glitch_time += move_value
                if self.glitch_time >= 100:
                    self.glitch_time = -40 + random.randrange(10)
                elif move_value == 0:
                    self.glitch_time = 0
            else:
                shot = self.shot_condition(1)
                self.flee_timer -= 1

    def piotrek(self, time):
        if self.player.is_alive():
            self._reload(time)
            length, rotate = self.move()
            shot = self.shot_condition(length)
            angle = self.player.angle - rotate
            width = self.game.assets.width
            height = self.game.assets.height

            if self.player.angle > 180 and rotate == DirectionAngle.RIGHT:
                angle = angle - 360
            elif self.player.angle <= 0 and rotate == DirectionAngle.DOWN:
                angle = (360 + angle)

            if angle != 0 and (-1 < self.player.angle < 1 and self.x * width > self.player.position[0] - width / 2
                               or 179 < self.player.angle < 181 and self.player.position[0] > (
                                       self.x + 1) * width - width / 2
                               or 269 < self.player.angle < 271 and self.y * height >= self.player.position[
                                   1] - height / 2
                               or 89 < self.player.angle < 91 and self.player.position[1] > (
                                       self.y + 1) * height - height / 2)\
                               or 359 < self.player.angle < 361 and self.player.position[0] > (
                                       self.x + 1) * width - width / 2:
                angle = 0

            if shot:
                self.shot()

            move_value = 0
            if self.glitch_time < 0:
                self.drive(Drive.BACKWARD, time)
                if self.flee_dir:
                    self.rotate(Rotate.LEFT, time / 2)
                else:
                    self.rotate(Rotate.LEFT, time / 2)
                move_value = 1
            elif angle > 1:
                self.rotate(Rotate.RIGHT, time)
            elif angle < -1:
                self.rotate(Rotate.LEFT, time)
            else:
                self.flee_dir = 0 if self.flee_dir else 1
                self.player.rotate(self.whole_angle(self.player.angle) - self.player.angle, time)
                b_x, b_y = self.player.position
                e_x, e_y = self.enemy.position
                re_angle = (self.enemy.angle + 180) % 360
                dist_offset = self.DISTANCE_OFFSET
                ang_offset = self.ANGLE_SENSITIVITY
                # bot and enemy facing each other and on the +/- same x position
                if re_angle - ang_offset <= self.player.angle <= re_angle + ang_offset and \
                        e_x - dist_offset <= b_x <= e_x + dist_offset and \
                        e_y - self.COLISION_OFFSET <= b_y <= e_y + self.COLISION_OFFSET:
                    if length <= 3 and \
                            (90 - ang_offset <= re_angle <= 90 + ang_offset or \
                            270 - ang_offset <= re_angle <= 270 + ang_offset):
                        move_value = -10
                    else:
                        move_value = self.drive(Drive.FORWARD, time)
                # bot and enemy facing each other and on the +/- same y position
                elif re_angle - ang_offset <= self.player.angle <= re_angle + ang_offset and \
                        e_y - dist_offset <= b_y <= e_y + dist_offset and \
                        e_x - self.COLISION_OFFSET <= b_x <= e_x + self.COLISION_OFFSET:
                    if length <= 3 and \
                            (0 <= re_angle <= ang_offset or 360 - ang_offset <= re_angle <= 360 or \
                            180 - ang_offset <= re_angle <= 180 + ang_offset):
                        move_value = -10
                    else:
                        move_value = self.drive(Drive.FORWARD, time)
                # bot or enemy is turned to the other one in a 90 degree angle
                elif re_angle + 90 - ang_offset <= self.player.angle <= re_angle + 90 + ang_offset or \
                      re_angle - 90 - ang_offset <= self.player.angle <= re_angle - 90 + ang_offset: \
                    move_value = self.drive(Drive.FORWARD, time)
                elif length > 2:
                    move_value = self.drive(Drive.FORWARD, time)
                else:
                    move_value = -10 - random.randrange(10)
            self.glitch_time += move_value
            if self.glitch_time >= 100:
                self.glitch_time = -40 + random.randrange(10)
            elif move_value == 0:
                self.glitch_time = 0

    def john(self, time):
        if self.player.is_alive():
            self._reload(time)
            length, rotate = self.move2
            shot = self.shot_condition(length)
            angle = self.player.angle - rotate
            width = self.game.assets.width
            height = self.game.assets.height

            if self.player.angle > 180 and rotate == DirectionAngle.RIGHT:
                angle = angle - 360
            elif self.player.angle <= 0 and rotate == DirectionAngle.DOWN:
                angle = (360 + angle)

            if angle != 0 and (-1 < self.player.angle < 1 and self.x * width > self.player.position[0] - width / 2
                               or 179 < self.player.angle < 181 and self.player.position[0] > (
                                       self.x + 1) * width - width / 2 + 6
                               or 269 < self.player.angle < 271 and self.y * height >= self.player.position[
                                   1] - height / 2 + 7
                               or 89 < self.player.angle < 91 and self.player.position[1] > (
                                       self.y + 1) * height - height / 2
                    or 359 < self.player.angle < 361 and self.player.position[0] > (
                    self.x + 1) * width - width / 2 + 6):

                # print("b")
                angle = 0

            if shot:
                self.shot()
            if angle > 1:
                self.rotate(Rotate.RIGHT, 2*time)
            elif angle < -1:
                self.rotate(Rotate.LEFT, 2*time)
            else:
                if angle > 0.05:
                    self.rotate(Rotate.RIGHT, time/5)
                elif angle < -0.05:
                    self.rotate(Rotate.LEFT, time/5)

                if self.glitch_time < 0:
                    self.drive(Drive.BACKWARD, time)
                    move_value = 1
                    self.player.lastMove = None
                else:
                    move_value = self.drive(Drive.FORWARD, time)

                self.glitch_time += move_value
                if self.glitch_time == 100:
                    self.glitch_time = -50
                elif move_value == 0:
                    self.glitch_time = 0

    def _reload(self, time):
        self.player.reload_time -= time
        StatBar.show_reload(self.screen, self.player)
        if self.player.reload_time <= 0:
            if self.player.is_current:
                StatBar.show_magazine(self.screen, self.player)

    def _reload_magazine(self):
        if self.player.bullets != Config.player['tank']['magazine']:
            self.player.reload_magazine()
            self.player.reload_time = Config.player['tank']['reload_magazine']

    def drive(self, drive: Drive, time):
        x, y = self.player.position
        radians = -self.player.angle * pi / 180
        if drive == Drive.FORWARD:
            speed = Config.player['speed']['drive']['forward'] * time
            new_x = x + (speed * cos(radians))
            new_y = y + (speed * sin(radians))
        else:
            speed = Config.player['speed']['drive']['backward'] * time
            new_x = x - (speed * cos(radians))
            new_y = y - (speed * sin(radians))

        new_position = (new_x, new_y)

        self.player.move(new_position)
        if (x, y) == self.player.position:
            return 1
        else:
            return 0
        # TODO: Send new position to the server

    def rotate(self, angle: Rotate, time):
        rotate_speed = Config.player['speed']['rotate'] * time
        if angle == Rotate.LEFT:
            new_angle = rotate_speed
        else:
            new_angle = -rotate_speed

        if new_angle > 360:
            new_angle -= 360
        elif new_angle < -360:
            new_angle += 360

        self.player.rotate(new_angle, 1)
        # TODO: Send new angle to the server

    def shot(self):
        if self.player.reload_time <= 0:
            self.player.reload_time = Config.player['tank']['reload_bullet']
            self.player.shot()
            if self.player.is_current:
                StatBar.show_magazine(self.screen, self.player)
            if self.player.bullets == 0:
                self._reload_magazine()
            # TODO: Send bullet position to the server


"""
Run theano functions in parallel on multiple GPUs (data parallelism).

This file has everything unique to the workers.
"""

import os
import pickle
from threading import BrokenBarrierError

from .variables import Inputs, Shareds, SynkFunction
from .common import use_gpu
from .common import (PKL_FILE, FUNCTION, GPU_COMM, BROADCAST, REDUCE, ALL_REDUCE,
                  ALL_GATHER, GATHER, WORKER_OPS, AVG_ALIASES, CPU_COMM, SCATTER)

class Function(SynkFunction):

    rank = None
    master_rank = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._build_output_subset_shmem(False)

    def __call__(self, sync, g_inputs, gpu_comm):
        """
        1. Gather the right inputs from mp shared values.
        2. Execute local theano function on those inputs.
        3. Send results back to master.
        """
        my_inputs = self.receive_inputs(g_inputs)
        output_subset, output_set = self._receive_output_subset()
        my_results = self._call_theano_function(my_inputs, output_subset)  # (always returns a tuple)
        self._collect_results(my_results, gpu_comm, output_set)

    def receive_inputs(self, g_inputs):
        assign_idx = g_inputs.sync.assign_idx[self._ID]
        my_idx = (assign_idx[self.rank], assign_idx[self.rank + 1])
        my_inputs = list()
        for input_ID, scatter in zip(self._input_IDs, self._inputs_scatter):
            if g_inputs.sync.tags[input_ID] != g_inputs.tags[input_ID]:
                # then a new shmem has been allocated, need to get it.
                shape = g_inputs.sync.shapes[input_ID][:]
                tag_ID = g_inputs.sync.tags[input_ID]
                g_inputs.alloc_shmem(input_ID, shape, tag_ID, False)
            shmem = g_inputs.shmems[input_ID]
            if scatter:
                my_inputs.append(shmem[my_idx[0]:my_idx[1]])
            else:
                my_inputs.append(shmem[:g_inputs.sync.max_idx[input_ID]])
        return tuple(my_inputs)

    def _receive_output_subset(self):
        output_set = [i for i, x in enumerate(self._output_subset_shmem) if x]
        output_subset = None if all(output_set) else output_set
        return output_subset, output_set

    def _collect_results(self, my_results, gpu_comm, output_set):
        for idx, r in zip(output_set, my_results):
            mode = self._collect_modes[idx]
            op = self._reduce_ops[idx]
            if mode == "reduce":
                gpu_comm.reduce(r, op=op, root=self.master_rank)
            elif mode == "gather":
                gpu_comm.all_gather(r)
            elif mode is not None:
                raise RuntimeError("Unrecognized collect mode in worker function.")

def unpack_functions(theano_functions, sync_dict, n_fcn):
    """
    Worker will recover variables in the same order as the master committed
    them, so they will have the same ID (index).
    """
    collect_modes_all = sync_dict["collect_modes"]
    reduce_ops_all = sync_dict["reduce_ops"]
    inputs_scatter_all = sync_dict["inputs_scatter"]
    synk_functions = list()
    g_inputs = Inputs()
    g_shareds = Shareds()
    for idx, fcn in enumerate(theano_functions[:n_fcn]):
        input_IDs = g_inputs.register_func(fcn)
        g_shareds.register_func(fcn, build_avg_func=False)
        synk_functions.append(Function(ID=idx,
                                       theano_function=fcn,
                                       input_IDs=input_IDs,
                                       inputs_scatter=inputs_scatter_all[idx],
                                       collect_modes=collect_modes_all[idx],
                                       reduce_ops=reduce_ops_all[idx],
                                       )
                              )
    g_shareds.avg_functions = theano_functions[n_fcn:]
    # g_shareds.unpack_avg_facs()  # (only needed for changing avg_fac later)
    return synk_functions, g_inputs, g_shareds

def receive_distribution(rank, n_gpu, sync):
    sync.barriers.distribute.wait()
    if not sync.distributed.value:
        return False
    sync_dict = sync.dict.copy()  # (retrieve it as a normal dict)
    with open(PKL_FILE, "rb") as f:
        theano_functions = pickle.load(f)  # should be all in one list
    if sync.barriers.delete_pkl.wait() == 0:
        os.remove(PKL_FILE)  # leave no trace
    synk_functions, g_inputs, g_shareds = \
        unpack_functions(theano_functions, sync_dict, sync.n_user_fcns.value)
    g_inputs.build_sync(len(synk_functions), n_gpu, False)
    g_shareds.build_sync(False)
    return synk_functions, g_inputs, g_shareds

def do_gpu_comms(sync, g_shareds, gpu_comm, master_rank):
    shared_IDs = g_shareds.sync.shared_IDs[:sync.n_shared.value]
    comm_ID = sync.comm_ID.value
    if comm_ID in [REDUCE, ALL_REDUCE]:
        op = WORKER_OPS.get(sync.comm_op.value, None)
        assert op is not None
        avg = op in AVG_ALIASES
        op = "sum" if avg else op
    if comm_ID == ALL_GATHER:
        src = g_shareds.gpuarrays[shared_IDs[0]]
        dest = g_shareds.gpuarrays[shared_IDs[1]]
        gpu_comm.all_gather(src, dest)
    else:
        for shared_ID in shared_IDs:
            src = g_shareds.gpuarrays[shared_ID]
            if comm_ID == BROADCAST:
                gpu_comm.broadcast(src, root=master_rank)
            elif comm_ID == REDUCE:
                gpu_comm.reduce(src, op=op, root=master_rank)
            elif comm_ID == ALL_REDUCE:
                gpu_comm.all_reduce(src, op=op, dest=src)
            elif comm_ID == GATHER:
                gpu_comm.all_gather(src)
            else:
                raise RuntimeError("Unrecognized GPU communication \
                    type in worker.")
        if comm_ID == ALL_REDUCE and avg:
            for shared_ID in shared_IDs:
                g_shareds.avg_functions[shared_ID]()

def do_cpu_comms(sync, g_shareds, rank):
    shared_ID = sync.shared_IDs[0]
    comm_ID = sync.comm_ID.value
    if comm_ID == SCATTER:
        if g_shareds.shmems[shared_ID] is None:
            g_shareds.alloc_shmem(shared_ID, rank, False)
        g_shareds.vars[shared_ID].set_value(g_shareds.shmems[shared_ID])
    else:
        raise RuntimeError("Unrecognized CPU comm type in worker.")

def error_close(sync):
    sync.workers_OK.value = False
    try:
        sync.barriers.exec_out.wait(1)
    except BrokenBarrierError:
        pass

def worker_exec(rank, n_gpu, master_rank, sync):
    gpu_comm = use_gpu(rank, n_gpu, sync, False)
    if not gpu_comm:
        return  # (exit quietly)

    distribution = receive_distribution(rank, n_gpu, sync)
    if not distribution:
        return  # (exit quietly)
    else:
        synk_functions, g_inputs, g_shareds = distribution

    Function.rank = rank  # endow all functions
    Function.master_rank = master_rank

    import atexit
    atexit.register(error_close, sync)

    while True:
        sync.barriers.exec_in.wait()
        if sync.quit.value:
            atexit.unregister(error_close)
            return  # (exit successfully)
        if sync.exec_type.value == FUNCTION:
            synk_functions[sync.func_ID.value](sync, g_inputs, gpu_comm)
        elif sync.exec_type.value == GPU_COMM:
            do_gpu_comms(sync, g_shareds, gpu_comm, master_rank)
        elif sync.exec_type.value == CPU_COMM:
            do_cpu_comms(sync, g_shareds, rank)
        else:
            raise RuntimeError("Unrecognized execution type in worker.")
        sync.barriers.exec_out.wait()  # Prevent premature shmem overwriting.


import dpath
max = 100000
disk = 70000000
needed = 30000000

with open('./input', 'r') as f:
    lines = [line[:-1] for line in f]

sizes = {}
counted = []
wd = ''
fs = {'root': {'_size': 0}}

def get(p):
    return dpath.get(fs, p)

def sets(p, v):
    dpath.new(fs, p, v)

def cd(p):
    global wd
    if p == '..':
        wd = '/'.join(wd.split('/')[:-1])
    elif p == '/':
        wd = 'root'
    else:
        wd = wd + '/' + p

def cont(p):
    a, b = p.split(' ')
    if a == 'dir':
        try:
            dpath.get(wd + '/' + b)
        except:
            sets(wd + '/' + b, {'_size': 0})
    else:
        if wd + '/' + b in counted:
            return
        counted.append(wd + '/' + b)
        recursiz(wd + '/' + p, int(a))

def recursiz(p, n):
    pth = 'root'
    for chnk in p.split('/')[1:]:
        sz = get(pth + '/_size') + n
        sets(pth + '/_size', sz)
        sizes[pth] = sz
        pth += '/' + chnk

for line in lines:
    if line == 'ls':
        continue
    if line.startswith('$ cd'):
        cd(line.split(' ')[2])
    elif line[0] == '$':
        continue
    else:
        cont(line)

total = 0
for k, v in sizes.items():
    if v <= max:
        total += v
print('part 1:', total)

for sois in sorted(sizes.values()):
    if sois >= needed - (disk - get('root/_size')):
        print('part 2:', sois)
        break


# %%
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import os
import numpy as np
from PIL import Image
import torchvision.utils
import matplotlib.pyplot as plt

# This is for the progress bar.
from tqdm.auto import tqdm

# %%
# parameters
batch_size = 4
n_epochs = 10
patience = 5  # If no improvement in 'patience' epochs, early stop

## blur
### b15
# train_set_dir = "blur/15/train"
# test_set_dir = "blur/15/test"
# model_path = "./model_b15.ckpt"

### b45
# train_set_dir = "blur/45/train/"
# test_set_dir = "blur/45/test/"
# model_path = "./model_b45.ckpt"

### b99
# train_set_dir = "blur/99/train/"
# test_set_dir = "blur/99/test/"
# model_path = "./model_b99.ckpt"

## pixel
### p4
# train_set_dir = "pixel/4/train/"
# test_set_dir = "pixel/4/test/"
# model_path = "./model_p4.ckpt"

### p8
# train_set_dir = "pixel/8/train/"
# test_set_dir = "pixel/8/test/"
# model_path = "./model_p8.ckpt"

### p16
# train_set_dir = "pixel/16/train/"
# test_set_dir = "pixel/16/test/"
# model_path = "./model_p16.ckpt"

### ori
train_set_dir = "att_img_flat/train/"
test_set_dir = "att_img_flat/test/"
model_path = "./model_ori.ckpt"

# %%
transform = transforms.Compose(
    [
        transforms.ToTensor(),
        transforms.Resize((128, 128), antialias=True),
        transforms.Normalize((0.5), (0.5)),
    ]
)

# %%
class mydataset(Dataset):
    def __init__(self, path, tfm=transform, files=None):
        super(mydataset).__init__()
        self.path = path
        self.files = sorted(
            [os.path.join(path, x) for x in os.listdir(path) if x.endswith(".png")]
        )
        if files:
            self.files = files
        print(f"One {path} sample", self.files[0])
        self.transform = tfm

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

    def __getitem__(self, idx):
        fname = self.files[idx]
        im = Image.open(fname)
        im = self.transform(im)
        try:
            label = int(fname.split("s")[-1].split("_")[0])
        except:
            label = -1  # test has no label
        return im, label

# %%
train_set = mydataset(train_set_dir, tfm=transform)
test_set = mydataset(test_set_dir, tfm=transform)

train_loader = DataLoader(
    train_set, batch_size=batch_size, shuffle=True, num_workers=0, pin_memory=True
)
test_loader = DataLoader(
    test_set, batch_size=batch_size, shuffle=True, num_workers=0, pin_memory=True
)

# %%
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.cnn = nn.Sequential(
            nn.Conv2d(1, 64, 1, 1, 1),  # [64, 128, 128]
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2, 2, 0),  # [64, 64, 64]
            nn.Conv2d(64, 128, 3, 1, 1),  # [128, 64, 64]
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.MaxPool2d(2, 2, 0),  # [128, 32, 32]
            nn.Conv2d(128, 256, 3, 1, 1),  # [256, 32, 32]
            nn.BatchNorm2d(256),
            nn.ReLU(),
            nn.MaxPool2d(2, 2, 0),  # [256, 16, 16]
            nn.Conv2d(256, 512, 3, 1, 1),  # [512, 16, 16]
            nn.BatchNorm2d(512),
            nn.ReLU(),
            nn.MaxPool2d(2, 2, 0),  # [512, 8, 8]
            nn.Conv2d(512, 512, 3, 1, 1),  # [512, 8, 8]
            nn.BatchNorm2d(512),
            nn.ReLU(),
            nn.MaxPool2d(2, 2, 0),  # [512, 4, 4]
        )
        self.fc = nn.Sequential(
            nn.Linear(512 * 4 * 4, 1024),
            nn.ReLU(),
            nn.Linear(1024, 512),
            nn.ReLU(),
            nn.Linear(512, 41),
        )

    def forward(self, x):
        out = self.cnn(x)
        out = out.view(out.size()[0], -1)
        return self.fc(out)

net = Net()

# %%
def fgsm_attack(model, loss, images, labels, eps) :
# adversarial attack

    images = images.to(device)
    labels = labels.to(device)
    images.requires_grad = True

    outputs = model(images)

    cost = loss(outputs, labels).to(device)
    model.zero_grad()
    cost.backward()

    attack_images = images + eps*images.grad.sign()
    attack_images = torch.clamp(attack_images, -1, 1)

    return attack_images

#%%
def imshow(img):
    npimg = img.numpy()
    fig = plt.figure(figsize = (5, 15))
    plt.imshow(np.transpose(npimg,(1,2,0)))
    plt.show()

# %%
torch.cuda.is_available = lambda: False
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Initialize a model, and put it on the device specified.
model = Net().to(device)
model.load_state_dict(torch.load(model_path))

# For the classification task, we use cross-entropy as the measurement of performance.
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.0003, weight_decay=1e-5)

# Initialize trackers, these are not parameters and should not be changed
stale = 0
best_acc = 0

for epoch in range(n_epochs):

    # ---------- Testing ----------
    # Make sure the model is in eval mode so that some modules like dropout are disabled and work normally.
    model.eval()

    # These are used to record information in testing.
    test_loss = []
    test_accs = []

    # Iterate the testing set by batches.
    for batch in tqdm(test_loader):

        images, labels = batch
        #imshow(torchvision.utils.make_grid(images, normalize=True))

        images = fgsm_attack(model, criterion, images, labels, 0).to(device)
        #imshow(torchvision.utils.make_grid(images, normalize=True))

        with torch.no_grad():
            logits = model(images.to(device))

        # We can still compute the loss (but not the gradient).
        loss = criterion(logits, labels.to(device))

        # Compute the accuracy for current batch.
        acc = (logits.argmax(dim=-1) == labels.to(device)).float().mean()

        # Record the loss and accuracy.
        test_loss.append(loss.item())
        test_accs.append(acc)
        # break

    # The average loss and accuracy for entire testing set is the average of the recorded values.
    test_loss = sum(test_loss) / len(test_loss)
    test_acc = sum(test_accs) / len(test_accs)

    # Print the information.
    print(
        f"[ Test | {epoch + 1:03d}/{n_epochs:03d} ] loss = {test_loss:.5f}, acc = {test_acc:.5f}"
    )

    # if not testing, save the last epoch
    if len(test_loader) == 0:
        torch.save(model.state_dict(), model_path)
        print("saving model at last epoch")

# %%
# get reports
from sklearn.metrics import classification_report, accuracy_score, hamming_loss

model_best = Net().to(device)
model_best.load_state_dict(torch.load(model_path))
model_best.eval()

label_pred = []
label_true = []

with torch.no_grad():
    for data, labels in tqdm(test_loader):
        test_pred = model_best(data.to(device))
        test_label = np.argmax(test_pred.cpu().data.numpy(), axis=1)
        if len(test_label) > 1 and len(labels) > 1:
            label_pred += test_label.squeeze().tolist()
            label_true += labels.squeeze().tolist()
        else:
            label_pred += test_label.tolist()
            label_true += labels.tolist()

    report = classification_report(
        label_true, label_pred, labels=[i for i in range(1, 41)], zero_division=0
    )
    print(report)

    test_acc = accuracy_score(label_true, label_pred)
    test_loss = hamming_loss(label_true, label_pred)

    # Print the information.
    print(f"loss = {test_loss:.5f}, acc = {test_acc:.5f}")

    with open("".join(model_path[2:].split(".")[:-1]) + "_report.txt", "w") as f:
        f.write(report)
        f.write(f"\nacc: {test_acc}\nloss: {test_loss}\n")


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression
from sklearn import datasets
diabetes=datasets.load_diabetes()
#print (diabetes.data.shape)
#print (diabetes.target.shape)
#print (diabetes.feature_names)
feature_cols=diabetes.feature_names
#diabetes=pd.DataFrame(diabetes)
#print (diabetes.iloc[0:100,:])
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(diabetes.data,diabetes.target,test_size=0.2,random_state=0)
#print(X_train)
model=LinearRegression()
model.fit(X_train,y_train)
print ("Model_Score or R-Squared",model.score(X_test,y_test))
print ("Model_Quotients",model.coef_)
print ("Model Intercept",model.intercept_)
#To View featurewise model co-efficients
A=list(zip(feature_cols,model.coef_))
print("Feature wise co-efficients",A)
#print(model.predict(X_test))
y_pred=model.predict(X_test)
plt.plot(y_test,y_pred,".")
x = np.linspace(0, 330, 100)
y = x
plt.plot(x, y)
#plt.show()
from sklearn import metrics
#Absolute Mean Squared Error
print("Absolute_Mean_Squared_Error",metrics.mean_absolute_error(y_test,y_pred))
#Mean Squared Error
print("Mean_Squared_Error",metrics.mean_squared_error(y_test,y_pred))
#Root Mean squared error
print("RMSE",np.sqrt(metrics.mean_squared_error(y_test,y_pred)))

#To get r_squared and adjusted_r_squared
SS_Residual = sum((y_test-y_pred)**2)
SS_Total = sum((y_test-np.mean(y_test))**2)
r_squared = 1 - (float(SS_Residual))/SS_Total
print (r_squared,"r_squared")
adjusted_r_squared = 1 - (1-r_squared)*(len(y_test)-1)/(len(y_test)-X_train.shape[1]-1)
print(adjusted_r_squared,"adjusted_r_squared")

#shapes
print(X_train.shape[0])#rows
print(X_train.shape[1])#columns

#To check the significant variables
X2 = sm.add_constant(X_train)
est = sm.OLS(y_train, X2)
est2 = est.fit()
print(est2.summary())

#Calculate ViF
from statsmodels.stats.outliers_influence import variance_inflation_factor
X_train=pd.DataFrame(X_train)
vif=pd.DataFrame()
vif["Vif Factor"] = [variance_inflation_factor(X_train.values, i) for i in range(X_train.shape[1])]
vif["Features"]=X_train.columns
print (vif.round(1))


from flask import Flask, redirect, render_template, request, session, url_for
import os

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/result", methods=["POST"])
def result():
    # Imports the Google Cloud client library
    from google.cloud import language
    import numpy, re

    # Instantiates a client
    language_client = language.Client()

    # The text to analyze
    para = request.form["text"]
    thresholdFactor = int(request.form["thresholdFactor"])
    text = re.split(r'[.!?]+', para)

    pair_message = []

    for data in text:
        data = data.strip()
        document = language_client.document_from_text(data)
        # Detects the sentiment of the text
        sentiment = document.analyze_sentiment().sentiment
        pair_message.append([data, sentiment.magnitude])

    mean_mag = numpy.mean([x[1] for x in pair_message])
    median_mag = numpy.median([x[1] for x in pair_message])

    print
    processed_text = ""
    count = 0
    threshold = min(mean_mag, median_mag)
    for sentence in pair_message:
        if sentence[1] >= threshold * ((thresholdFactor - 0.5)/ 2):
            count += 1
            location = para.index(sentence[0])
            processed_text += para[location:location + len(sentence[0]) + 1] + " "
    return render_template("success.html", display = processed_text)

if __name__ == '__main__':
     app.debug = True
     port = int(os.environ.get("PORT", 5000))
     app.run(host='0.0.0.0', port=port)


import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
from PIL import Image,ImageOps
import numpy as np

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, [None, 784])

def define_variable(shape,name):
    return tf.Variable(tf.truncated_normal(shape,stddev=0.1),name)

input_image = tf.reshape(x, [-1, 28, 28, 1])
W_conv1 = define_variable([5, 5, 1, 6], "W_conv1")
b_conv1 = define_variable([6], "b_conv1")

conv1 = tf.nn.conv2d(input_image, W_conv1, strides=[1, 1, 1, 1],padding='SAME')
relu1 = tf.nn.relu(conv1 + b_conv1)
pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

W_conv2 = define_variable([5, 5, 6, 16], "W_conv2")
b_conv2 = define_variable([16], "b_conv2")

conv2 = tf.nn.conv2d(pool1, W_conv2, strides=[1, 1, 1, 1],padding='VALID')
relu2 = tf.nn.relu(conv2 + b_conv2)
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

W_conv3 = define_variable([5, 5, 16, 120], "W_conv3")
b_conv3 = define_variable([120], "b_conv3")

conv3 = tf.nn.conv2d(pool2, W_conv3, strides=[1, 1, 1, 1],padding='VALID')
relu3 = tf.nn.relu(conv3 + b_conv3)

flat = tf.reshape(relu3,[-1,120])

W_fc1 = define_variable([120,84], "W_fc1")
b_fc1 = define_variable([84], "b_fc1")

fc1 = tf.nn.relu(tf.matmul(flat, W_fc1) + b_fc1)

dropout1 = tf.placeholder("float")
fc1_dropout = tf.nn.dropout(fc1, dropout1)

W_fc2 = define_variable([84, 10], "W_fc2")
b_fc2 = define_variable([10], "b_fc2")

y_output = tf.nn.softmax(tf.nn.relu(tf.matmul(fc1_dropout, W_fc2) + b_fc2))

model_path="checkpoint/variable"
saver = tf.train.Saver()

load_path = saver.restore(sess, model_path)

def inference(image):
    img = image.convert('L')
    img = img.resize([28,28],Image.ANTIALIAS)
    x_input = np.array(img,dtype="float32")/255
    x_input = np.reshape(x_input,[-1,784])
    output = y_output.eval(feed_dict={x:x_input,dropout1 : 1.0})
    return tf.argmax(output,1).eval()

#output = y_output.eval(feed_dict={x:img,dropout1 : 1.0})
#a =  tf.argmax(output,1)
#print a.eval()
"""
for i in range(10000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x:batch[0], y: batch[1], dropout1: 1.0})
        print "step %d, training accuracy %g"%(i, train_accuracy)
    train_step.run(feed_dict={x: batch[0], y: batch[1], dropout1: 0.5})
print "test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y: mnist.test.labels, dropout1: 1.0})
"""


from random import randrange, sample
from converter import *
from functools import reduce

def calculate_B(k, ID, n, e, inv, size = 2**20):
    B, quadruples = [[0 for i in range(2*k)] for i in range(2)]
    f_x_y = []
    for i in range(2 * k):
        a_i, c_i, d_i, r_i = [randrange(1, size) for x in range(4)]
        B[i] = calculate_B_i(a_i, c_i, d_i, r_i, ID, e, n, f_x_y)
        quadruples[i] = a_i, c_i, d_i, r_i
    return B, quadruples, f_x_y

def calculate_B_i(a, c, d, r, ID, e, n, f = None):
    x_i = sha1_hash(a + c)
    y_i = sha1_hash(a ^ ID + d)
    f_x_y = bytes_to_int(x_i) * bytes_to_int(y_i)

    if f is not None:
        f.append(f_x_y)
    B_i = r**e * f_x_y % n
    return B_i

def receive_signature(B, ID, priv_key, e, n, R, quadruples):
    for i in R:
        a, c, d, r = quadruples[i]
        B_i = calculate_B_i(a, c, d, r, ID, e, n)
        if(B_i != B[i]):
            raise Exception("Values are not equal")
    R_sign = [i for i in range(len(B)) if i not in R]
    B_to_sign = [B[i] for i in R_sign]
    signed_B = pow(reduce(lambda x, y : x * y %n, B_to_sign), priv_key, n)
    return signed_B, R_sign

def calc_S(signed_B, quadruples, n, R_sign):
    r = [quadruples[i][3] for i in R_sign]
    S = signed_B * mulinv(reduce(lambda x, y : x * y , r), n) % n
    return S

# Taken from
#https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def extendex_euc_alg(x, n):
    x0, x1, y0, y1 = 1, 0, 0, 1
    while n != 0:
        q, x, n = x // n, n, x % n
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    return  x, x0, y0

# x = mulinv(b) mod n, (x * b) % n == 1
def mulinv(b, n):
    g, x, _ = extendex_euc_alg(b, n)
    if g == 1:
        return x % n

def totient(p, q):
    return (p - 1) * (q - 1)

p, q, e = 1300097, 1299721, 17
n = p * q # 127*89= 11303
totient_n = totient(p, q)
ID =  1251261711
k = 100
priv_key  = mulinv(e, totient_n)
# print("INV", priv_key)
for i in range(1000):
    B, quadruples, f_x_y = calculate_B(k, ID, n, e, priv_key) # STEP 1
    R = sample(range(len(B)), len(B) // 2) # STEP 2
    quadruples_R = {i: quadruples[i] for i in R}
    signed_B, R_sign = receive_signature(B, ID, priv_key, e, n, R, quadruples_R) #STEP 3.2

    f_sign = [f_x_y[i] for i in R_sign]
    prod_sum_f = reduce(lambda x, y: x * y, f_sign)
    x = pow(prod_sum_f, priv_key, n)

    S = calc_S(signed_B, quadruples, n, R_sign)
    print("SIGNED VALUE OK", S == x)
    print("SIGNATURE OK", prod_sum_f % n == pow(S, e, n))
    # print(S)


"""
Create Models which will be mapped to tables in our database migrations.

Models include:
    Rooms: Has a title and description, can have attachments to other rooms and contain players
    Players: Has a corresponding user, a current room.

"""

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
import uuid

class Room(models.Model):
    """Creates room model (table in database)
    Has a title, description, and n_to, s_to, e_to and w_to, which represent
    connections to other rooms.
    """
    title = models.CharField(max_length=50, default="DEFAULT TITLE")
    description = models.CharField(max_length=500, default="DEFAULT DESCRIPTION")
    n_to = models.IntegerField(default=0)
    s_to = models.IntegerField(default=0)
    e_to = models.IntegerField(default=0)
    w_to = models.IntegerField(default=0)
    def connectRooms(self, destinationRoom, direction):
        '''Connects rooms together, checking to see if input direction and destination room are valid'''
        destinationRoomID = destinationRoom.id
        try:
            destinationRoom = Room.objects.get(id=destinationRoomID)
        except Room.DoesNotExist:
            print("That room does not exist")
        else:
            if direction == "n":
                self.n_to = destinationRoomID
            elif direction == "s":
                self.s_to = destinationRoomID
            elif direction == "e":
                self.e_to = destinationRoomID
            elif direction == "w":
                self.w_to = destinationRoomID
            else:
                print("Invalid direction")
                return
            self.save()
    def playerNames(self, currentPlayerID):
        '''Returns all players in a given room'''
        return [p.user.username for p in Player.objects.filter(currentRoom=self.id) if p.id != int(currentPlayerID)]
    def playerUUIDs(self, currentPlayerID):
        '''Returns all player UUIDs in a given room'''
        return [p.uuid for p in Player.objects.filter(currentRoom=self.id) if p.id != int(currentPlayerID)]

class Player(models.Model):
    '''Creates a Player model (table in database) takes in a User, the current room, and a uuid'''
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    currentRoom = models.IntegerField(default=0)
    uuid = models.UUIDField(default=uuid.uuid4, unique=True)
    def initialize(self):
        '''Check to see if initial room is not yet set, and if so, sets it to the first room in the Room table (model)'''
        if self.currentRoom == 0:
            self.currentRoom = Room.objects.first().id
            self.save()
    def room(self):
        '''Returns the id of the current room the player is in. If invalid room id, calls initialize'''
        try:
            return Room.objects.get(id=self.currentRoom)
        except Room.DoesNotExist:
            self.initialize()
            return self.room()

@receiver(post_save, sender=User)
def create_user_player(sender, instance, created, **kwargs):
    '''Creates a user player'''
    if created:
        Player.objects.create(user=instance)
        Token.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_player(sender, instance, **kwargs):
    '''Saves a player to the database'''
    instance.player.save()


from contextlib import contextmanager as _contextmanager

from fabric.api import env, cd, run, prefix
from fabric.context_managers import settings
from fabric.operations import sudo

env.hosts = ['reddyprasad.me']

django_collectstatic_prompt = 'Type \'yes\' to continue, or \'no\' to cancel: '

@_contextmanager
def virtualenv():
    with prefix('source ~/.envs/blog/bin/activate'):
        yield

def bootstrap():
    env.user = 'ubuntu'

    sudo('apt update && apt upgrade')
    sudo('apt install python-virtualenv python-pip nginx')
    sudo('pip install --upgrade pip')
    run('mkdir -p apps')
    run('mkdir -p .envs')
    with cd('.envs'):
        run('virtualenv blog')
    with cd('apps'):
        run('git clone https://github.com/dev-drprasad/my_blog.git')

def pull():
    env.user = 'ubuntu'
    with cd('apps'):
        with cd('my_blog'):
            run('git pull')

            with virtualenv():
                run('pip install --upgrade pip')
                run('pip install -r requirements.txt')
                with cd('src'):
                    run('python manage.py migrate')
                    with settings(prompts={django_collectstatic_prompt: 'yes'}):
                        run('python manage.py collectstatic --settings=project.settings.production')


from __future__ import unicode_literals
__author__ = 'lexxodus'

from app import db
from app.api import api
from app.models import LevelSkill as LevelSkillModel
from datetime import datetime, timedelta
from dateutil import parser
from flask import abort, request
from flask.ext.restful import Resource

def get_level_skill_json(level_skill, public=False):
    data = {}
    data["id"] = level_skill.id
    data["pid"] = level_skill.pid
    data["lid"] = level_skill.lid
    data["calculated_on"] = level_skill.calculated_on.isoformat()
    data["considered_rows"] = level_skill.considered_rows
    data["skill_points"] = level_skill.skill_points
    data["high_score"] = level_skill.high_score
    data["attempt"] = level_skill.attempt
    if public:
        data['api_url'] = "%s%s" % (api.url_for(LevelSkill), level_skill.id)
    return data

class LevelSkill(Resource):

    def post(self):
        required_values = ["pid", "lid"]
        data = request.get_json()
        if not all(v in data for v in required_values):
            abort(404)
        pid = data["pid"]
        lid = data["lid"]
        until = data.get("until", None)
        if until:
            until = parser.parse(until)
        level_skill = LevelSkillModel(pid, lid, until)
        db.session.add(level_skill)
        db.session.commit()
        return get_level_skill_json(level_skill), 201

    def get(self, id=None):
        if id:
            level_skill = LevelSkillModel.query.get(id)
            if not level_skill:
                abort(404)
            return get_level_skill_json(level_skill)
        else:
            return self.get_all()

    def get_all(self):
        args = request.args
        level_skills = LevelSkillModel.query
        pids = args.getlist("pid")
        lids = args.getlist("lid")
        interval = args.get("interval", None)
        last = args.get("last", None)
        if pids:
            level_skills = level_skills.filter(LevelSkillModel.pid.in_(pids))
        if lids:
            level_skills = level_skills.filter(LevelSkillModel.lid.in_(lids))
        if interval:
            level_skills = level_skills.filter(LevelSkillModel.calculated_on >= datetime.now() - timedelta(seconds=interval))
        if last:
            level_skills = level_skills.order_by(LevelSkillModel.calculated_on.desc()).limit(last)
        else:
            level_skills = level_skills.order_by(LevelSkillModel.calculated_on).all()
        data = []
        for l in level_skills:
            data.append(get_level_skill_json(l))
        return data

    def delete(self, id):
        level_skill = LevelSkillModel.query.get(id)
        if not level_skill:
            abort(404)
        db.session.delete(level_skill)
        db.session.commit()
        return "", 204


import subprocess, sys

def pipInstall(package):
	subprocess.call([sys.executable, "-m", "pip", "install", package])

try:
	from freetype import *
except ImportError:
	pipInstall("freetype-py")
finally:
	from freetype import *

try:
	import numpy as np
except ImportError:
	pipInstall("numpy")
finally:
	import numpy as np

try:
	import OpenGL.GL as gl
	import OpenGL.GLU as glu
	import OpenGL.GLUT as glut
except ImportError:
	# pip by default fucks this up and installs 32 bit version.
	# However I have 64 bit python installed on my machine.
	# That is why we use pre-downloaded whl.
	# Make sure that the whl matches your python version.
	# For 32 bit python use 32 bit whl.
	pipInstall("PyOpenGL-3.1.6-cp39-cp39-win_amd64.whl")
	pipInstall("PyOpenGL_accelerate-3.1.6-cp39-cp39-win_amd64.whl")
finally:
	import OpenGL.GL as gl
	import OpenGL.GLU as glu
	import OpenGL.GLUT as glut

from serial_reader_thread import SerialReaderThread, Quat

import math

vertices= (
	(1, -1, -1),
	(1, 1, -1),
	(-1, 1, -1),
	(-1, -1, -1),
	(1, -1, 1),
	(1, 1, 1),
	(-1, -1, 1),
	(-1, 1, 1)
)

edges = (
	(0,1),
	(0,3),
	(0,4),
	(2,1),
	(2,3),
	(2,7),
	(6,3),
	(6,4),
	(6,7),
	(5,1),
	(5,4),
	(5,7)
)

surfaces = (
	(0,1,2,3),
	(3,2,7,6),
	(6,7,5,4),
	(4,5,1,0),
	(1,5,7,2),
	(4,0,3,6)
)

colors = (
	(255/255,0/255 ,0/255),  # red
	(255/255,99/255,71/255), # tomato
	(178/255,34/255,34/255), # firebrick
	(220/255,20/255,60/255), # crimson

	(0/255  ,128/255,0/255), # green
	(50/255 ,205/255,50/255), # lime green
	(0/255  ,255/255,127/255), # spring green
	(124/255,252/255,0/255), # lawn green

	(0/255  , 0/255 ,255/255), # blue
	(30/255 ,144/255,255/255), # dodger blue
	(100/255,149/255,237/255), # corn flower blue
	(65/255 ,105/255,225/255), # royal blue

	(255/255,165/255,0/255), # orange
	(255/255,215/255,0/255), # gold
	(240/255,230/255,140/255), # khaki
	(255/255,140/255,0/255), # dark orange

	(139/255,0/255,139/255), # magenta
	(128/255,0/255,128/255), # purple
	(148/255,0/255,211/255), # dark violet
	(255/255,20/255,147/255), # deep pink

	(0/255  ,255/255,255/255), # aqua
	(64/255 ,224/255,208/255), # turquoise
	(127/255,255/255,212/255), # aqua marine
	(0/255  ,206/255,209/255), # dark turquoise
)

class Window():
	def __init__(self, width, height, title):
		self.window = None
		self.base = 0
		self.texid = 0

		glut.glutInit(sys.argv)
		glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
		self.window = glut.glutCreateWindow(title)
		glut.glutReshapeWindow(width, height)
		glut.glutDisplayFunc(self.on_display)
		glut.glutReshapeFunc(self.on_reshape)
		glut.glutKeyboardFunc(self.on_keyboard)

		gl.glTexEnvf(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)
		# gl.glEnable(gl.GL_DEPTH_TEST)
		# gl.glEnable(gl.GL_BLEND)
		gl.glEnable(gl.GL_COLOR_MATERIAL)
		gl.glColorMaterial(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT_AND_DIFFUSE)
		gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
		gl.glEnable(gl.GL_TEXTURE_2D)

		gl.glShadeModel(gl.GL_SMOOTH)
		gl.glClearColor(0, 0, 0, 0)
		gl.glClearDepth(1)
		gl.glEnable(gl.GL_DEPTH_TEST)
		gl.glDepthFunc(gl.GL_LEQUAL)
		gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST)

		self.make_font("JetBrainsMono-Medium.ttf", 64)

		self.serial = SerialReaderThread()
		self.serial.start()

		glut.glutTimerFunc(25, self.timer_event, 1)

		glut.glutMainLoop()

	def __del__(self):
		if self.window is not None:
			glut.glutDestroyWindow(self.window)
			self.window = None
		self.serial.stopped = True
		self.serial.join()

	def timer_event(self, value):
		glut.glutPostRedisplay()
		glut.glutTimerFunc(25, self.timer_event, 1)

	def make_font(self, filename, size):
		# Load font  and check it is monotype
		face = Face(filename)
		face.set_char_size( size*64 )
		if not face.is_fixed_width:
			raise 'Font is not monotype'

		# Determine largest glyph size
		width, height, ascender, descender = 0, 0, 0, 0
		for c in range(32,128):
			face.load_char(chr(c), FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT)
			bitmap	= face.glyph.bitmap
			width	 = max( width, bitmap.width )
			ascender  = max( ascender, face.glyph.bitmap_top )
			descender = max( descender, bitmap.rows-face.glyph.bitmap_top )
		height = ascender+descender

		# Generate texture data
		Z = np.zeros((height*6, width*16), dtype=np.ubyte)
		for j in range(6):
			for i in range(16):
				face.load_char(chr(32+j*16+i), FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT)
				bitmap = face.glyph.bitmap
				x = i*width  + face.glyph.bitmap_left
				y = j*height + ascender - face.glyph.bitmap_top
				Z[y:y+bitmap.rows,x:x+bitmap.width].flat = bitmap.buffer

		# Bound texture
		self.texid = gl.glGenTextures(1)
		gl.glBindTexture(gl.GL_TEXTURE_2D, self.texid)
		gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
		gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
		gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, Z.shape[1], Z.shape[0], 0,
						gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, Z)

		# Generate display lists
		dx, dy = width/float(Z.shape[1]), height/float(Z.shape[0])
		self.base = gl.glGenLists(8*16)
		for i in range(8*16):
			c = chr(i)
			x = i%16
			y = i//16-2
			gl.glNewList(self.base+i, gl.GL_COMPILE)
			if (c == '\n'):
				gl.glPopMatrix()
				gl.glTranslatef( 0, -height, 0)
				gl.glPushMatrix()
			elif (c == '\t'):
				gl.glTranslatef(4*width, 0, 0)
			elif (i >= 32):
				gl.glBegin(gl.GL_QUADS)
				gl.glTexCoord2f((x  )*dx, (y+1)*dy), gl.glVertex(0,	 -height)
				gl.glTexCoord2f((x  )*dx, (y  )*dy), gl.glVertex(0,	 0 )
				gl.glTexCoord2f((x+1)*dx, (y  )*dy), gl.glVertex(width, 0 )
				gl.glTexCoord2f((x+1)*dx, (y+1)*dy), gl.glVertex(width, -height)
				gl.glEnd()
				gl.glTranslatef(width, 0, 0)
			gl.glEndList()

	def draw_text(self, text, x, y):
		gl.glEnable(gl.GL_BLEND)
		gl.glBindTexture(gl.GL_TEXTURE_2D, self.texid)
		gl.glColor(1,1,1,1) # white
		gl.glPushMatrix()
		gl.glTranslate(x, y, -5)
		gl.glPushMatrix()
		gl.glScalef(0.003, 0.003, 0.003)
		gl.glListBase(self.base)
		gl.glCallLists([ord(c) for c in text])
		gl.glPopMatrix()
		gl.glPopMatrix()
		gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
		gl.glDisable(gl.GL_BLEND)

	def draw_cube_lines(self):
		gl.glBegin(gl.GL_LINES)
		gl.glColor3fv((0.1,0.1,0.1))
		for edge in edges:
			for vertex in edge:
				gl.glVertex3iv(vertices[vertex])
		gl.glEnd()

	def draw_cube_surfaces(self):
		gl.glBegin(gl.GL_QUADS)
		x = 0
		for surface in surfaces:
			for vertex in surface:
				gl.glColor3fv(colors[x])
				x+=1
				gl.glVertex3fv(vertices[vertex])
		gl.glEnd()

	def on_display(self):
		gl.glClearColor(0,0,0,0)
		gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

		gl.glLoadIdentity()
		gl.glTranslatef(0, 0, -7.0) # zoom out
		q = self.serial.quat
		degrees = 2 * math.acos(q.w) * 180.00/math.pi
		gl.glRotatef(degrees, -1 * q.nx, q.nz, q.ny)
		self.draw_cube_lines()
		self.draw_cube_surfaces()

		gl.glLoadIdentity()
		self.draw_text(f"Quat: {q.w:.3f}, {q.nx:.3f}, {q.ny:.3f}, {q.nz:.3f}", -2, -1.4)
		euler = self.serial.euler
		self.draw_text(f"Roll: {euler.roll:.1f}, Pitch: {euler.pitch:.1f}, Yaw: {euler.yaw:.1f}", -2, -1.65)

		glut.glutSwapBuffers()

	def on_reshape(self, width, height):
		if height == 0:
			height = 1

		aspect_ratio = width/height
		field_of_view = 45
		zNear = 0.1 #closer clipping plane
		zFar = 100.0 # further clipping plane

		gl.glViewport(0, 0, width, height)
		gl.glMatrixMode(gl.GL_PROJECTION)
		gl.glLoadIdentity()
		glu.gluPerspective(field_of_view, 1.0*aspect_ratio, zNear, zFar)
		gl.glMatrixMode(gl.GL_MODELVIEW)
		gl.glLoadIdentity()

	def on_keyboard(self, key, x, y):
		int_key = int.from_bytes(key, "little")
		if int_key == 27: # ESC key
			glut.glutDestroyWindow(self.window)
			self.window = None

if __name__ == '__main__':
	window = Window(800, 600, "Quat visualization")


# -*- coding: utf-8 -*-
# -*- by:sboxm-*-
# 设置部分
from tkinter import Label, Button, Tk, StringVar, OptionMenu
from json import load

class GUI:
    # 渲染主窗体
    def __init__(self, configs):
        # 配置读取部分
        self.hitokoto_cfg = configs['hitokoto']
        self.biying_cfg = configs['biying']
        self.category_cfg = configs['category']
        self.mode_cfg = configs['mode']
        self.onchange_cfg = configs['onchange']
        # 窗体部分
        self.window = Tk()
        self.window.title("设置")
        self.window.geometry("190x230")
        self.window.attributes("-toolwindow", True)
        self.window.minsize(190, 250)
        self.window.maxsize(190, 250)
        self.title = Label(self.window, text="壁纸鸭设置\n——————————————", anchor='center')
        self.title.grid(row=0, column=0, columnspan=4)
        # 一言
        self.hitokoto_text = Label(self.window, text='一言')
        self.hitokoto_button = Button(self.window, text='开' if self.hitokoto_cfg else '关',
                                      command=self.toggle_hitokoto)
        self.hitokoto_text.grid(row=1, column=0)
        self.hitokoto_button.grid(row=1, column=1)
        # 必应
        self.biying_text = Label(self.window, text='必应')
        self.biying_button = Button(self.window, text='开' if self.biying_cfg else '关',
                                    command=self.toggle_biying)
        self.biying_text.grid(row=2, column=0)
        self.biying_button.grid(row=2, column=1)
        # 类型
        self.category_text = Label(self.window, text='类型')
        self.options = ['随机', '4K', '美女', '美图', '风景', '小清新', '动漫卡通', '明星', '动物', '游戏']
        self.selected = StringVar(value=self.options[self.category_cfg])
        self.selection = OptionMenu(self.window, self.selected, *self.options, command=self.toggle_category)
        self.category_text.grid(row=3, column=0)
        self.selection.grid(row=3, column=1, columnspan=3)
        # 模式
        self.mode_text = Label(self.window, text='模式')
        self.mode_button = Button(self.window, text='临时' if self.mode_cfg == 0 else '永久',
                                  command=self.toggle_mode)
        self.mode_text.grid(row=4, column=0)
        self.mode_button.grid(row=4, column=1)
        # 保存按钮
        self.save_button = Button(self.window, text='保存并应用', command=self.save_settings)
        self.save_button.grid(row=5, column=0, columnspan=4)
        # 底部信息
        self.title = Label(self.window, text="——————————————\n版本 V1.0.0  主打就是一个简陋", anchor='center')
        self.title.grid(row=6, column=0, columnspan=4)
        self.window.mainloop()

    # 保存设置
    def save_settings(self):
        with open('config.json', 'w') as fp:
            hitokoto = 'true' if self.hitokoto_cfg else 'false'
            biying = 'true' if self.biying_cfg else 'false'
            update_config = '{\n"hitokoto":' + hitokoto + ',\n"biying":' + biying + ',\n"category":' + str(
                self.category_cfg) + ',\n"mode":' + str(self.mode_cfg) + ',\n"updatecycle":10,\n"onchange":true\n}'
            fp.write(update_config)

    def toggle_mode(self):
        if self.mode_button["text"] == "临时":
            self.mode_cfg = 1
            self.mode_button["text"] = "永久"
        else:
            self.mode_cfg = 0
            self.mode_button["text"] = "临时"

    def toggle_category(self, event=None):
        option_dict = {'随机': 0, '4K': 1, '美女': 2, '美图': 3, '风景': 4, '小清新': 5, '动漫卡通': 6, '明星': 7,
                       '动物': 8, '游戏': 9}
        self.category_cfg = option_dict[self.selected.get()]

    def toggle_biying(self):
        if self.biying_button["text"] == "开":
            self.biying_cfg = False
            self.biying_button["text"] = "关"
        else:
            self.biying_cfg = True
            self.biying_button["text"] = "开"

    def toggle_hitokoto(self):
        if self.hitokoto_button["text"] == "开":
            self.hitokoto_cfg = False
            self.hitokoto_button["text"] = "关"
        else:
            self.hitokoto_cfg = True
            self.hitokoto_button["text"] = "开"

if __name__ == '__main__':
    # 读取config配置
    try:
        config = open('config.json', 'r')
        config_dit = load(config)
        window1 = GUI(config_dit)
    except FileNotFoundError:
        pass


import re
import math
import operator
from collections import defaultdict, deque
from pathlib import Path

def gen_recipe(lines):
    ingredient_regex = re.compile(r"(\d+ [A-Z]+),?\s*(.*)")
    result_regex = re.compile(r"=> (\d+ [A-Z]+)")

    for line in lines:
        ingredients = []
        while True:
            m = ingredient_regex.match(line)
            if m:
                ing, line = m.groups()
                quant, name = ing.split()
                ingredients.append((int(quant), name))
                continue
            m = result_regex.match(line)
            if m:
                (res,) = m.groups()
                quant, name = res.split()
                result = (int(quant), name)
                break
            raise RuntimeError(line)
        yield ingredients, result

def calculate_top_order(ratios, name):
    if name == "ORE":
        return 0
    return sum(calculate_top_order(ratios, n) for _, n in ratios[name]) + 1

def calculate_ore_for_fuel(ratios, amounts_produced, amount_fuel):
    requirements = defaultdict(int)
    requirements["FUEL"] = amount_fuel
    stockpile = defaultdict(int)

    while [x for x in requirements if x != "ORE"]:
        current_ing, _ = max(
            [(n, calculate_top_order(ratios, n)) for n in requirements],
            key=operator.itemgetter(1),
        )
        amount_required = requirements.pop(current_ing)
        amount_required -= stockpile[current_ing]
        stockpile[current_ing] = 0

        quant_multiplier = math.ceil(amount_required / amounts_produced[current_ing])
        excess = amounts_produced[current_ing] * quant_multiplier - amount_required
        stockpile[current_ing] += excess

        for quant, name in ratios[current_ing]:
            amount_ingredient_required = quant * quant_multiplier
            requirements[name] += amount_ingredient_required
    return requirements["ORE"]

def part1():
    lines = Path("input/14.txt").read_text().strip().split("\n")

    recipe = list(gen_recipe(lines))
    amounts_produced = {ing: c for _, (c, ing) in recipe}
    ratios = {ing: req for req, (_, ing) in recipe}

    required_ore = calculate_ore_for_fuel(ratios, amounts_produced, 1)
    print(required_ore)

def find_max_fuel(ratios, amounts_produced):
    total_ore = 1000000000000

    possible_fuel = 1
    prev_possible_fuel = 1
    while True:
        required_ore = calculate_ore_for_fuel(ratios, amounts_produced, possible_fuel)
        if required_ore > total_ore:
            break
        prev_possible_fuel = possible_fuel
        possible_fuel *= 2

    possible_fuels = list(range(prev_possible_fuel, possible_fuel))
    start = 0
    stop = len(possible_fuels) - 1

    while start <= stop:
        mid = start + (stop - start) // 2
        possible_fuel = possible_fuels[mid]
        required_ore = calculate_ore_for_fuel(ratios, amounts_produced, possible_fuel)

        if required_ore < total_ore:
            start = mid + 1
        elif required_ore > total_ore:
            stop = mid - 1
        else:
            break

    if required_ore > total_ore:
        possible_fuel = possible_fuels[mid - 1]
    return possible_fuel

def part2():
    lines = Path("input/14.txt").read_text().strip().split("\n")

    recipe = list(gen_recipe(lines))
    amounts_produced = {ing: c for _, (c, ing) in recipe}
    ratios = {ing: req for req, (_, ing) in recipe}
    max_fuel = find_max_fuel(ratios, amounts_produced)
    print(max_fuel)

if __name__ == "__main__":
    # part1()
    part2()


from django.urls import path
from . import views

urlpatterns = [
    path("signup/", views.UserSignup.as_view(), name="user-signup"),
    path("signin/", views.UserSignin.as_view(), name="user-signin"),
    path("profile/", views.MyProfile.as_view(), name="user-profile"),
    path("profile/<username>/", views.UserProfile.as_view(), name="user-profile"),
    path("logout/", views.UserLogout.as_view(), name="user-logout"),
    path("follow/", views.UserRelation.as_view(), name="relations"),
    path("posts/", views.Posts.as_view(), name="posts"),
    path("posts/<int:page>/<int:offset>/", views.Posts.as_view(), name="posts"),
    path("posts/<int:page>/<int:offset>/<username>/", views.Posts.as_view(), name="my-posts"),
    path("test/", views.test, name="test")
]


from django.shortcuts import render
from django.http import Http404
from django.shortcuts import get_list_or_404
from .models import Livre
from categorie.models import Categorie
import re

# Create your views here.

def listLivre(request):

    listLivre = Livre.objects.all()
    context = {
        'listLivre':listLivre ,
    }

    return render(request , 'index.html' , context)

def detLivre(request , id):

    try:
        if request.session['idcl'] != None:
            detLivre = Livre.objects.get(id=id)
            context = {
                'detLivre':detLivre ,
            }
            return render(request , 'details.html' , context)

    except KeyError:
        return render(request, 'signin.html')

def LivreCat(request , id):

    cat = Categorie.objects.get(id=id)
    listLivre = Livre.objects.filter(categorie = cat)
    #cat = Categorie.objects.get(id=idcat)
    context = {
      'listLivre':listLivre,
      'cat':cat,
    }
    return render(request, 'Categorie.html', context)

def Search(request):
    mot = request.POST.get('search')

    if mot:
        results = []
        article_list = get_list_or_404(Livre)
        for article in article_list:
            if re.findall(mot, article.titre):
                results.append(article)
        '''for article in results:
            article.body = markdown.markdown(article.body, )
        tag_list = Tag.objects.all().order_by('name')'''

        return render(request, 'search.html', {'article_list': results})
    else:
        return listLivre(request)


import pytest
from airbyte_cdk.models.airbyte_protocol import AdvancedAuth, ConnectorSpecification
from airbyte_cdk.sources.declarative.models.declarative_component_schema import AuthFlow
from airbyte_cdk.sources.declarative.spec.spec import Spec

@pytest.mark.parametrize(
    "test_name, spec, expected_connection_specification",
    [
        (
            "test_only_connection_specification",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}),
            ConnectorSpecification(connectionSpecification={"client_id": "my_client_id"}),
        ),
        (
            "test_with_doc_url",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}, documentation_url="https://airbyte.io"),
            ConnectorSpecification(connectionSpecification={"client_id": "my_client_id"}, documentationUrl="https://airbyte.io"),
        ),
        (
            "test_auth_flow",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}, advanced_auth=AuthFlow(auth_flow_type="oauth2.0")),
            ConnectorSpecification(
                connectionSpecification={"client_id": "my_client_id"}, advanced_auth=AdvancedAuth(auth_flow_type="oauth2.0")
            ),
        ),
    ],
)
def test_spec(test_name, spec, expected_connection_specification):
    assert spec.generate_spec() == expected_connection_specification


from typing import List, Any

from matplotlib.animation import FuncAnimation
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.lines import Line2D

from villageswar.main import WorldUpdater
from villageswar.util import Barrier
from villageswar.village import Village
from villageswar.world import World

def get_jobs(village): ...

class PlotAnim(object):
    ...

    def __init__(self, titles: List[str], world_updater: WorldUpdater, barrier: Barrier):
        self.xlim = None  # type: int
        self.ylim = None  # type: int
        self.curr_xlim = None  # type: int
        self.curr_ylim = None  # type: int
        self.world_obj = None  # type: World
        self.world_updater = None  # type: WorldUpdater
        self.village_obj1 = None  # type: Village
        self.village_obj2 = None  # type: Village
        self.barrier = None  # type: Barrier
        self.titles = None  # type: List[str]
        self.animation = None  # type: FuncAnimation
        self.fig = None  # type: Figure

        self.pop_ax1 = None  # type: Axes
        self.pop_ax2 = None  # type: Axes
        self.pop_line1 = None  # type: Line2D
        self.pop_line2 = None  # type: Line2D
        self.pop_data_x = None  # type: (List[int], List[int])
        self.pop_data_y = None  # type: (List[int], List[int])

        self.job_ax1 = None  # type: Axes
        self.job_ax2 = None  # type: Axes
        self.job_line1_w = None  # type: Line2D
        self.job_line1_b = None  # type: Line2D
        self.job_line1_h = None  # type: Line2D
        self.job_line2_w = None  # type: Line2D
        self.job_line2_b = None  # type: Line2D
        self.job_line2_h = None  # type: Line2D
        self.job_data_x = None  # type: (List[(int, int, int)], List[(int, int, int)])
        self.job_data_y = None  # type: (List[(int, int, int)], List[(int, int, int)])

        self.dead_ax1 = None  # type: Axes
        self.dead_ax2 = None  # type: Axes
        self.dead_line1 = None  # type: Line2D
        self.dead_line2 = None  # type: Line2D
        self.dead_data_x = None  # type: (List[int], List[int])
        self.dead_data_y = None  # type: (List[int], List[int])

        self.all_lines = None  # type: List[Line2D]
        ...

    def init(self) -> List[Line2D]: ...

    def update_data(self): ...

    def update_limits(self): ...

    def animate(self, *unused: List[Any]) -> List[Line2D]: ...

    def start_animation(self): ...

    def handle_close(self, *unused): ...


import asyncio, pprint, traceback
from components import abstracts, pluginmanager, config

defaults = {"Administration": {"Admin": ""}}
cfg = config.load("discordplm", defaults)

class Plugin(abstracts.Plugin):

    def handlers(self):
        return [abstracts.Handler('DSC:COMMAND:?PLM', self, self.command)]

    def command(self, message=None, args=None, **kw):
        bot = pluginmanager.resources["DSC"]["BOT"]
        loop = pluginmanager.resources["DSC"]["LOOP"]
        if len(args)>0:
            if str(message.author.id)==cfg["Administration"]["Admin"]:
                if args[0]=='unload' and len(args)>1:
                    try:
                        pluginmanager.unloadPlugin(args[1])
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsup:'), loop)
                    except RuntimeError:
                        pass
                    else:
                        traceback.print_exc()
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsdown:'), loop)
                elif args[0]=='reload' and len(args)>1:
                    try:
                        pluginmanager.reloadPlugin(args[1])
                        asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, ':thumbsup:'), loop)
                    except:
                        traceback.print_exc()
            else:
                asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, 'You don\'t have permission for that.'), loop)
        else:
            asyncio.run_coroutine_threadsafe(bot.send_message(message.channel, pprint.pformat(pluginmanager.plugins.keys(), indent=2, width=40)), loop)


import json

# 아래 코드 수정 금지
movie_json = open("data/movie.json", encoding="UTF8")
movie = json.load(movie_json)

genres_json = open("data/genres.json", encoding="UTF8")
genres_list = json.load(genres_json)

# 이하 문제 해결을 위한 코드 작성

# movie는 dict, genres_list는 list 유형

this_movie_ids = movie['genre_ids']
result = []

for i in genres_list:
    if this_movie_ids[1] == i['id']:
        result.append(i['name'])
    if this_movie_ids[0] == i['id']:
        result.append(i['name'])

print(result)

# genre_list = []
# for genre_id in this_movie_ids:
    # for genre_dict in genre_list:
        # if genre_id == genre_dict['id']:
            # genre_list.append(genre_dict['name'])