from OpenGL import GL
import warnings

from .GPUProgram import GPUProgram, LinkError, LinkWarning
from .Shaders import ComputeShader
from .GLConfig import GLConfig
from .GlassConfig import GlassConfig

class ComputeProgram(GPUProgram):

	def __init__(self)->None:
		GPUProgram.__init__(self)
		self.compute_shader = ComputeShader()
		self._work_group_size:tuple = None
		self._should_join:bool = False

	@staticmethod
	def _check_work_group_size(work_group_size:tuple)->None:
		max_work_group_size = GLConfig.max_compute_work_group_size
		if work_group_size[0] > max_work_group_size[0]:
			raise ValueError("x-dimension work group size should not be greater than " + str(max_work_group_size[0]) + ", " + str(work_group_size[0]) + " were given")
		if work_group_size[1] > max_work_group_size[1]:
			raise ValueError("y-dimension work group size should not be greater than " + str(max_work_group_size[1]) + ", " + str(work_group_size[1]) + " were given")
		if work_group_size[2] > max_work_group_size[2]:
			raise ValueError("z-dimension work group size should not be greater than " + str(max_work_group_size[2]) + ", " + str(work_group_size[2]) + " were given")

		max_work_group_invocations = GLConfig.max_compute_work_group_invocations
		work_group_invocations = work_group_size[0] * work_group_size[1] * work_group_size[2]
		if work_group_invocations > max_work_group_invocations:
			raise ValueError("work group invocation should not be greater than " + str(max_work_group_invocations) + ", " + str(work_group_invocations) + " were given")

	@staticmethod
	def _check_work_group_count(work_group_count:tuple)->None:
		max_work_group_count = GLConfig.max_compute_work_group_count
		if work_group_count[0] > max_work_group_count[0]:
			raise ValueError("x-dimension work group size should not be greater than " + str(max_work_group_count[0]) + ", " + str(work_group_count[0]) + " were given")
		if work_group_count[1] > max_work_group_count[1]:
			raise ValueError("y-dimension work group size should not be greater than " + str(max_work_group_count[1]) + ", " + str(work_group_count[1]) + " were given")
		if work_group_count[2] > max_work_group_count[2]:
			raise ValueError("z-dimension work group size should not be greater than " + str(max_work_group_count[2]) + ", " + str(work_group_count[2]) + " were given")

	def compile(self, file_name:str)->None:
		self.compute_shader = ComputeShader.load(file_name)

		self._work_group_size = self.compute_shader.work_group_side
		self._uniforms_info = self.compute_shader.uniforms_info
		self._uniform_blocks_info = self.compute_shader.uniform_blocks_info
		self._shader_storage_blocks_info = self.compute_shader._shader_storage_blocks_info
		self._structs_info = self.compute_shader._structs_info

		ComputeProgram._check_work_group_size(self._work_group_size)

		self._is_linked = False

	def _apply(self)->None:
		if not self._linked_but_not_applied:
			return

		if self._id == 0:
			self._id = GL.glCreateProgram()
			if self._id == 0:
				raise MemoryError("failed to create ComputeProgram")

		GL.glAttachShader(self._id, self.compute_shader._id)
		GL.glLinkProgram(self._id)

		if GlassConfig.debug:
			message_bytes = GL.glGetProgramInfoLog(self._id)
			message = message_bytes
			if isinstance(message_bytes, bytes):
				message = str(message_bytes, encoding="utf-8")

			error_messages, warning_messages = self._format_error_warning(message)
			if warning_messages and GlassConfig.warning:
				warnings.warn("\n" + "\n".join(warning_messages), category=LinkWarning)

			if error_messages:
				self._is_linked = False
				raise LinkError("\n" + "\n".join(error_messages))

		self._apply_uniform_blocks()
		self._apply_shader_storage_blocks()

		self._linked_but_not_applied = True

	def _link(self)->None:
		if self._is_linked:
			return

		if not self.compute_shader.is_compiled:
			raise RuntimeError("should compile compute shader before link")

		self._resolve_uniforms()
		self._resolve_uniform_blocks()
		self._resolve_shader_storage_blocks()

		self._is_linked = True
		self._linked_but_not_applied = True
		if GL.glCreateProgram:
			self._apply()

	def start_computing(self, x_work_group_count:int, y_work_group_count:int=1, z_work_group_count:int=1)->None:
		ComputeProgram._check_work_group_count((x_work_group_count, y_work_group_count, z_work_group_count))
		self.use()
		GL.glDispatchCompute(x_work_group_count, y_work_group_count, z_work_group_count)
		self._should_join = True

	def join(self, barrier_type=GL.GL_ALL_BARRIER_BITS)->None:
		if self._should_join:
			GL.glMemoryBarrier(barrier_type)
			self._should_join = False

	def compute(self, x_work_group_count:int, y_work_group_count:int=1, z_work_group_count:int=1, barrier=GL.GL_ALL_BARRIER_BITS)->None:
		self.start_computing(x_work_group_count, y_work_group_count, z_work_group_count)
		self.join(barrier)

	@property
	def work_group_size(self)->tuple:
		return self._work_group_size

	@property
	def related_files(self)->list:
		return [self.compute_shader._file_name]


# returns floor(sqrt(n))
def sqroot_approx(n):
    res, i  = 0, 0
    while res <= n:
        i += 1
        res += 2*i-1

    return i-1

if __name__ == "__main__":

    s = 50
    n = 100
    for i in range(s, n+1):
        print(f'floor(sqrt({i})) = {sqroot_approx(i)}  sqrt({i}) ≈ {i**0.5}')


# server.py
from flask import Flask, render_template
import os

app = Flask(__name__, static_url_path = "/home/tatsuyasuzuki/sal_server/static", static_folder = "static")
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = os.path.join("/home/tatsuyasuzuki/sal_server/static")
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.jinja_env.auto_reload = True
print(__name__)

@app.route('/', methods=['POST', 'GET', 'PUT'])
def index():
    path2img = os.path.join(app.config['UPLOAD_FOLDER'], "output.png")
    print(path2img)
    return render_template('index.html', sal_img=path2img)

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    if 'Cache-Control' not in response.headers:
        response.headers['Cache-Control'] = 'no-store'
    return response

if __name__ == '__main__':
    app.debug = True
    app.run(host='192.168.11.61', port=10030, debug=True)


from typing import List, Dict, Tuple, Union, Optional, Type
import logging
from collections import OrderedDict
from enums.query.props.prop_enum import PropEnum
from enums.query.sort_order import SortOrder
from custom_types.openstack_query.aliases import (
    OpenstackResourceObj,
    PropValue,
    GroupMappings,
    GroupRanges,
)
from exceptions.parse_query_error import ParseQueryError

logger = logging.getLogger(__name__)

class QueryParser:
    """
    Helper class for taking query output and parsing it into a format which can then be outputted.
    Performs any sorting / grouping the user has specified
    """

    def __init__(self, prop_enum_cls: Type[PropEnum]):
        self._prop_enum_cls = prop_enum_cls
        self._sort_by = {}
        self._group_by = None
        self._group_mappings = {}

    @property
    def group_by(self):
        """
        a getter method to return group_by prop enum
        """
        return self._group_by

    @group_by.setter
    def group_by(self, prop: PropEnum):
        """
        a setter method to set group_by prop enum
        :param prop: prop enum to group by
        """
        self._group_by = prop

    @property
    def sort_by(self):
        """
        a getter method to return sort_by options
        """
        return self._sort_by

    @sort_by.setter
    def sort_by(self, sort_by: Dict[PropEnum, bool]):
        """
        a setter method to set sort_by options
        :param sort_by: a dictionary of prop enum to sort by mapped to order
        (True for Descending, False of Ascending)
        """
        self._sort_by = sort_by

    @property
    def group_mappings(self):
        """
        a getter method to set group_mappings options
        """
        return self._group_mappings

    @group_mappings.setter
    def group_mappings(self, group_mappings: GroupMappings):
        """
        a setter method to set group_mapping options
        :param group_mappings: a dictionary of group name to a list of
        property values that belong to that group
        """
        self._group_mappings = group_mappings

    def parse_sort_by(self, *sort_by: Tuple[PropEnum, SortOrder]) -> None:
        """
        Public method used to configure sorting results
        :param sort_by: one or more tuples of property name to sort by and order enum
        """
        sort_by_dict = {}
        for user_selected_prop, _ in sort_by:
            if user_selected_prop not in self._prop_enum_cls:
                raise ParseQueryError(
                    f"Error: Given property to sort by: {user_selected_prop.name} is not supported by query"
                )

        for prop, order in sort_by:
            order_log_str = "DESC" if order.value else "ASC"
            logging.debug(
                "adding sorting params: %s, order: %s", prop.name, order_log_str
            )
            sort_by_dict.update({prop: order.value})

        self.sort_by = sort_by_dict

        logging.debug(
            "sort params: %s",
            "\n\t".join(
                f"{prop}, order: {'DESC' if order else 'ASC'}"
                for prop, order in self.sort_by.items()
            ),
        )

    def parse_group_by(
        self,
        group_by: PropEnum,
        group_ranges: Optional[GroupRanges] = None,
        include_missing: Optional[bool] = False,
    ) -> None:
        """
        Public method used to configure grouping results.
        :param group_by: name of the property to group by
        :param group_ranges: a dictionary containing names of the group and list of prop values
        to select for that group
        :param include_missing: a flag which if set includes an extra grouping for values
        that don't fall into any group specified in group_ranges
        """

        if group_by not in self._prop_enum_cls:
            raise ParseQueryError(
                f"Error: Given property to group by: {group_by.name} is not supported by query"
            )

        self.group_by = group_by
        self.group_mappings = {}
        if group_ranges:
            self._parse_group_ranges(group_ranges)

        if include_missing:
            self._add_include_missing_group(group_ranges)

    def _parse_group_ranges(self, group_ranges: Optional[Dict[str, List[PropValue]]]):
        """
        helper method for parsing group ranges
        :param group_ranges: a dictionary containing names of the group and list of prop values
        to select for that group
        """
        logger.debug("creating filter functions for specified group ranges")
        prop_func = self._prop_enum_cls.get_prop_mapping(self.group_by)
        for name, prop_list in group_ranges.items():
            group_vals = tuple(prop_list)
            self.group_mappings[name] = (
                lambda obj, lst=group_vals: prop_func(obj) in lst
            )

    def _add_include_missing_group(self, group_ranges: GroupRanges):
        """
        Helper method used to add an extra group for group_by which includes
        all resource values not already included in any defined mappings
        :param group_ranges: A set of predefined group ranges to check against
        """
        # if ungrouped group wanted - filter for all not in any range specified
        all_prop_list = set()
        for _, prop_list in group_ranges.items():
            all_prop_list.update(set(prop_list))

        prop_func = self._prop_enum_cls.get_prop_mapping(self.group_by)
        logger.debug("creating filter function for ungrouped group")
        self.group_mappings["ungrouped results"] = (
            lambda obj: prop_func(obj) not in all_prop_list
        )

    def run_parser(
        self, obj_list: List[OpenstackResourceObj]
    ) -> Union[List[OpenstackResourceObj], Dict[str, List[OpenstackResourceObj]]]:
        """
        Public method used to parse query runner output - performs specified sorting and grouping
        :param obj_list: a list of openstack resource objects to parse
        """
        if not obj_list:
            return obj_list

        # we sort first - assuming sorting is commutative to grouping
        if self.sort_by:
            obj_list = self._run_sort(obj_list)

        if self.group_by:
            obj_list = self._run_group_by(obj_list)
        return obj_list

    def _run_sort(
        self,
        obj_list: List[OpenstackResourceObj],
    ) -> List[OpenstackResourceObj]:
        """
        method which sorts a list of openstack objects based on a dictionary of sort_by specs
        :param obj_list: A list of openstack objects to sort
            - descending - True, ascending - False
        """

        logger.debug("running multi-sort")
        sort_num = len(self.sort_by)
        for i, (sort_key, reverse) in enumerate(
            reversed(tuple(self.sort_by.items())), 1
        ):
            logger.debug("running sort %s / %s", i, sort_num)
            logger.debug("sorting by: %s, reverse=%s", sort_key, reverse)
            prop_func = self._prop_enum_cls.get_prop_mapping(sort_key)
            obj_list.sort(key=prop_func, reverse=reverse)
        return obj_list

    def _build_unique_val_groups(
        self,
        obj_list: List[OpenstackResourceObj],
    ) -> GroupMappings:
        """
        helper method to find all unique values for a given property in query results, and then,
        for each unique value, create a group mapping
        :param obj_list: A list of openstack objects to group
        """
        prop_func = self._prop_enum_cls.get_prop_mapping(self.group_by)
        # ordered dict to mimic ordered set
        # this is to preserve order we see unique values in - in case a sort has been done already
        unique_vals = OrderedDict({prop_func(obj): None for obj in obj_list})
        logger.debug(
            "unique values found %s - each will become a group",
            ",".join(f"{val}" for val in unique_vals),
        )

        group_mappings = {}

        # build groups
        for val in unique_vals.keys():
            group_key = val
            group_mappings[group_key] = (
                lambda obj, test_val=val: prop_func(obj) == test_val
            )

        return group_mappings

    def _run_group_by(
        self,
        obj_list: List[OpenstackResourceObj],
    ) -> Dict[str, List[OpenstackResourceObj]]:
        """
        helper method apply a set of group mappings onto a list of openstack objects. Returns a dictionary of grouped
        values where the key is the group name and value is a list of openstack objects that belong to that group
        :param obj_list: list of openstack objects to group
        """

        # if group mappings not specified - make a group for each unique value found for prop
        if not self.group_mappings:
            logger.info(
                "no group ranges specified - grouping by unique values of %s property",
                self.group_by.name,
            )
            self.group_mappings = self._build_unique_val_groups(obj_list)

        return {
            name: [item for item in obj_list if map_func(item)]
            for name, map_func in self.group_mappings.items()
        }


import itertools
import math
n = int(input())
pattern = list(itertools.permutations(range(n)))
xy = [list(map(int,input().split())) for _ in range(n)]
n2 = 1

for i in range(1,n+1):
    n2 *=i
ans = 0
for j in pattern:
    for k in range(n-1):
        ans += ((xy[j[k+1]][0] - xy[j[k]][0])**2 + (xy[j[k+1]][1] - xy[j[k]][1])**2)**0.5

print(ans/n2)


import cv2
import numpy as np
import sys
from collections import OrderedDict
import matplotlib.pyplot as plt

def lk_flow(img1,img2, k): #Windows size - k

    #Initializing gradient matrices for 3 dimensions
    gx = np.zeros(img1.shape, dtype=np.float32)
    gy = np.zeros(img1.shape, dtype=np.float32)
    gt = np.zeros(img1.shape, dtype=np.float32)

    #Calculating gradients
    gx[1:-1, 1:-1] = cv2.subtract(img1[1:-1, 2:], img1[1:-1, :-2]) / 2
    gy[1:-1, 1:-1] = cv2.subtract(img1[2:, 1:-1], img1[:-2, 1:-1]) / 2
    gt[1:-1, 1:-1] = cv2.subtract(img1[1:-1, 1:-1], img2[1:-1, 1:-1])

    specs = np.zeros(img1.shape + (5,))
    specs[..., 0] = gx ** 2
    specs[..., 1] = gy ** 2
    specs[..., 2] = gx * gy
    specs[..., 3] = gx * gt
    specs[..., 4] = gy * gt

    specs = np.zeros(img1.shape + (5,))
    specs[..., 0] = gx ** 2
    specs[..., 1] = gy ** 2
    specs[..., 2] = gx * gy
    specs[..., 3] = gx * gt
    specs[..., 4] = gy * gt
    del gt, gx, gy
    cum_specs = np.cumsum(np.cumsum(specs, axis=0), axis=1)
    del specs
    k_specs = (cum_specs[2 * k + 1:, 2 * k + 1:] -
                  cum_specs[2 * k + 1:, :-1 - 2 * k] -
                  cum_specs[:-1 - 2 * k, 2 * k + 1:] +
                  cum_specs[:-1 - 2 * k, :-1 - 2 * k])
    del cum_specs

    flow = np.zeros(img1.shape + (2,))
    det = k_specs[...,0] * k_specs[..., 1] - k_specs[..., 2] **2

    flow_x = np.where(det != 0,
                     (k_specs[..., 1] * k_specs[..., 3] -
                      k_specs[..., 2] * k_specs[..., 4]) / det,
                      0)
    flow_y = np.where(det != 0,
                     (k_specs[..., 0] * k_specs[..., 4] -
                      k_specs[..., 2] * k_specs[..., 3]) / det,
                      0)
    flow[k + 1: -1 - k, k + 1: -1 - k, 0] = flow_x[:-1, :-1]
    flow[k + 1: -1 - k, k + 1: -1 - k, 1] = flow_y[:-1, :-1]
    flow = flow.astype(np.float32)
    return flow

#Simple implementation but not so good at performance
def lk_flow_alternate(frame1, frame2, filter_size=5):
    gt = cv2.subtract(frame1, frame2).astype(np.float32)
    gx, gy = np.gradient(frame1)
    gx = gx.astype(np.float32)
    gx = gx.astype(np.float32)

    #Calculating the Gradient Product accumulations for each pixel
    gxx = cv2.boxFilter(gx**2, -1, ksize=(filter_size,)*2, normalize=True)
    gxy = cv2.boxFilter(gx*gy, -1, ksize=(filter_size,)*2, normalize=True)
    gyy = cv2.boxFilter(gy**2, -1, ksize=(filter_size,)*2, normalize=True)
    gxt = cv2.boxFilter(gx*gt, -1, ksize=(filter_size,)*2, normalize=True)
    gyt = cv2.boxFilter(gy*gt, -1, ksize=(filter_size,)*2, normalize=True)
    del gt, gx, gy

    #Calculating the Displacement Matrices U, V
    rows, cols = frame1.shape
    flow = np.zeros((rows, cols, 2), dtype=np.float32)
    A = np.dstack((gxx, gxy, gxy, gyy))
    b = np.dstack((-gxt, -gyt))
    for r in range(rows):
        for c in range(cols):
            flow[r,c,:] = np.linalg.lstsq(A[r,c].reshape((2,2)), b[r,c])[0]

    return -flow

def draw_flow_on_original(img, flow, filename):
    x = np.arange(0, img.shape[1], 1)
    y = np.arange(0, img.shape[0], 1)

    #Creating a grid
    x, y = np.meshgrid(x, y)
    plt.figure()
    fig = plt.imshow(img, cmap='gray', interpolation='bicubic')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    step = int(img.shape[0] / 50)
    plt.quiver(x[::step, ::step], y[::step, ::step], flow[::step, ::step, 0], flow[::step, ::step, 1], color='r', pivot='middle', headwidth=2, headlength=3)
    plt.savefig(filename, bbox_inches='tight', pad_inches=0)

def draw_flow(flow):
    mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
    hsv = np.zeros(flow.shape[:2]+(3,), dtype=np.uint8)
    hsv[...,0] = ang*180/np.pi/2
    hsv[...,1] = 255
    hsv[...,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
    flow_vis = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    return flow_vis

def lk():
    print('Testing on easy images - 2-5 pixel shift')
    img1 = cv2.imread('resources/TestSeq/Shift0.png', cv2.IMREAD_GRAYSCALE)
    img2 = cv2.imread('resources/TestSeq/ShiftR2.png', cv2.IMREAD_GRAYSCALE)
    img3 = cv2.imread('resources/TestSeq/ShiftR5U5.png', cv2.IMREAD_GRAYSCALE)

    flow12 = lk_flow(img1, img2, 15)
    flow13 = lk_flow(img1, img3, 15)
    print('Flow Calculation Complete')
    #flow12 = cv2.calcOpticalFlowFarneback(img1, img2, None, 0.5, 3, 15, 3, 5, 1.2, 0)
    #flow13 = cv2.calcOpticalFlowFarneback(img1, img2, None, 0.5, 3, 15, 3, 5, 1.2, 0)

    draw_flow_on_original(img1, flow12, 'results/flowdir1-2.png')
    draw_flow_on_original(img1, flow13, 'results/flowdir1-3.png')
    print('Flow direction images saved successfully')

    cv2.imwrite('results/flow1-2.jpg', draw_flow(flow12))
    cv2.imwrite('results/flow1-3.jpg', draw_flow(flow13))
    print('Raw Flow images saved successfully\n')

    print('Testing on hard images - 10-40 pixel shift')
    img4 = cv2.imread('resources/TestSeq/ShiftR10.png', cv2.IMREAD_GRAYSCALE)
    img5 = cv2.imread('resources/TestSeq/ShiftR20.png', cv2.IMREAD_GRAYSCALE)
    img6 = cv2.imread('resources/TestSeq/ShiftR40.png', cv2.IMREAD_GRAYSCALE)

    flow14 = lk_flow(img1, img4, 15)
    flow15 = lk_flow(img1, img5, 15)
    flow16 = lk_flow(img1, img6, 15)
    print('Flow Calculation Complete')

    draw_flow_on_original(img1, flow14, 'results/flowdir1-4.png')
    draw_flow_on_original(img1, flow15, 'results/flowdir1-5.png')
    draw_flow_on_original(img1, flow16, 'results/flowdir1-6.png')
    print('Flow direction images saved successfully')

    cv2.imwrite('results/flow1-4.jpg', draw_flow(flow14))
    cv2.imwrite('results/flow1-5.jpg', draw_flow(flow15))
    cv2.imwrite('results/flow1-6.jpg', draw_flow(flow16))
    print('Raw Flow images saved successfully\n')

if __name__ == '__main__':
    print('Executing Lucas Kanade optic flow\n')
    lk()


from flask import Flask, Response
from flask import request
from revChatGPT.ChatGPT import Chatbot
import os
import json
app = Flask(__name__)

class MockChatBot:
    def ask(self, message, conversation_id=None, parent_id=None):
        return {'message': f'わかりません。すみません。\n\n{message}' }

def create_chatbot():
    chatbot = Chatbot({
        "session_token": os.environ['CHATGPT_TOKEN']
    }, conversation_id=None, parent_id=None)
    return chatbot

chatbot = MockChatBot()
# chatbot = create_chatbot()

requests = []
responses = []
current_module = None

context = {}

@app.route("/messages", methods=['GET'])
def messages():
    print(request.args)
    if request.args.get('idx'):
        idx = int(request.args.get('idx'))
        print(f'Input[{idx}]:\n')
        print(requests[idx])
        print(f'Output[{idx}]:\n')
        print(responses[idx])
        data = {'input':requests[idx], 'output': responses[idx]}
        data = json.dumps(data, ensure_ascii=False)
        return Response(data, content_type="application/json; charset=utf-8")
    else:
        return '404'

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.args:
        module = open(request.args['filename']).read()
        for k, v in request.args.items():
            context[k] = v
        print(f'Query[{len(responses)}] :>', context)

        print('\nCall Module:')
        print('-' * 30)
        print(module)

        exec(module)

        print(f'Input[{len(responses)-1}]:\n')
        print('-' * 30)
        print(requests[-1])

        print(f'Output[{len(responses)-1}]:\n')
        print('-' * 30)
        print(responses[-1])
        return '200'
    else:
        return '404'

if __name__ == "__main__":
    app.run(host='localhost', port='43560')


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

import logging
from engine.base import BaseBot
from engine.game_types import CraftItem

logger = logging.getLogger(__name__)

class LocalBrainBot(BaseBot):

    def perform_action(self):

        if not self.get_params().switch_local_brain_bot:
            return

        # Чистим закончившиеся платные мозги
        for buyed_brain in self.get_game_state().get_state().buyedBrains:
            if self.get_timer().has_elapsed(buyed_brain.endTime):
                self.get_game_state().get_state().buyedBrains.remove(buyed_brain)

        # Если нужно поддерживать мозги
        if self.get_params().buyed_brains_count:

            buyed_brains_count = self.get_params().buyed_brains_count
            activated_brains = 0

            for buyed_brain in self.get_game_state().get_state().buyedBrains:
                if not self.get_timer().has_elapsed(buyed_brain.endTime, -10):
                    activated_brains += buyed_brain.count

            delta_brains = buyed_brains_count - activated_brains
            if delta_brains:
                # список что мы будем крафтить вообще
                will_crafts = self.get_params().crafts
                found = False
                signal = u'brains',

                # Ищем нужную запись для крафтинга
                for will_craft in will_crafts:
                    if will_craft.signal == signal:
                        # Ставим нужное количество для крафтинга
                        will_craft.count = delta_brains

                        # отмечаем что нашли такую позицию
                        found = True

                        # активируем сигнал для крафта
                        self.get_game_state().set_signal(signal, True)
                        break

                # Если не нашли
                if not found:
                    # создаем сигнал для активации
                    self.get_game_state().set_signal(signal, True)

                    # создаем новый параметр для крафтинга с нужным нам значением
                    will_crafts.append(CraftItem(building=u'@B_OSTANKINO', craft_id=0, count=delta_brains,
                                                 signal=signal))


import math

# Converts a a base 10 number to a base 2(binary) number.
def converter(temp):
    number = int(temp[2])
    value = ''
    while number > 0:
        value += f"{number % 2}"
        number = math.floor(number / 2)
    return value

def main():
    with open('input.txt', 'r') as raw:
        current_mask = None
        mem = {}
        for line in raw:
            temp = line.strip().split()
            if temp[0] == 'mask':
                current_mask = temp[2]
            elif 'mem' in temp[0]:
                value = converter(temp)
                value = value[::-1].zfill(36)[::-1]
                result = ""
                for index, bi in enumerate(current_mask[::-1]):
                    if bi == 'X':
                        result += value[index]
                    elif bi == '1':
                        result += '1'
                    else:
                        result += '0'
                result_ = [2 ** i for i in range(len(result)) if result[i] == '1']
                mem[int("".join(i for i in temp[0] if i.isdigit()))] = sum(result_)

        memory_sum = 0
        for val in mem.values():
            memory_sum += val
        print(f"The sum of all values left in memory is: {memory_sum}.")

if __name__ == "__main__":
    main()


from mitreattack.stix20 import MitreAttackData

def main():
    mitre_attack_data = MitreAttackData("enterprise-attack.json")

    # get subtechniques of techniques
    subtechniques = mitre_attack_data.get_all_subtechniques_of_all_techniques()

    print(f"Sub-techniques of techniques ({len(subtechniques.keys())} parent techniques):")
    for id, subs in subtechniques.items():
        print(f"* {id} has {len(subs)} {'sub-technique' if len(subs) == 1 else 'sub-techniques'}")

if __name__ == "__main__":
    main()


# fmt: off
import logging
from pathlib import Path

from farm.data_handler.data_silo import DataSilo
from farm.data_handler.processor import TextPairClassificationProcessor
from farm.experiment import initialize_optimizer
from farm.infer import Inferencer
from farm.modeling.adaptive_model import AdaptiveModel
from farm.modeling.language_model import LanguageModel
from farm.modeling.prediction_head import TextClassificationHead
from farm.modeling.tokenization import Tokenizer
from farm.train import Trainer
from farm.utils import set_all_seeds, MLFlowLogger, initialize_device_settings

def text_pair_classification():
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s -   %(message)s",
        datefmt="%m/%d/%Y %H:%M:%S",
        level=logging.INFO)

    ml_logger = MLFlowLogger(tracking_uri="https://public-mlflow.deepset.ai/")
    ml_logger.init_experiment(experiment_name="Public_FARM", run_name="Run_text_pair_classification")

    ##########################
    ########## Settings ######
    ##########################
    set_all_seeds(seed=42)
    device, n_gpu = initialize_device_settings(use_cuda=True)
    n_epochs = 2
    batch_size = 64
    evaluate_every = 500
    lang_model = "bert-base-cased"
    label_list = ["0", "1"]

    # 1.Create a tokenizer
    tokenizer = Tokenizer.load(
        pretrained_model_name_or_path=lang_model,
        do_lower_case=False)

    # 2. Create a DataProcessor that handles all the conversion from raw text into a pytorch Dataset.
    # The TextPairClassificationProcessor expects a csv with columns called "text', "text_b" and "label"
    processor = TextPairClassificationProcessor(tokenizer=tokenizer,
                                                label_list=label_list,
                                                metric="f1_macro",
                                                max_seq_len=128,
                                                train_filename="train.tsv",
                                                dev_filename="dev.tsv",
                                                test_filename=None,
                                                data_dir=Path("../data/asnq_binary"),
                                                delimiter="\t")

    # 3. Create a DataSilo that loads several datasets (train/dev/test), provides DataLoaders for them and calculates a few descriptive statistics of our datasets
    data_silo = DataSilo(
        processor=processor,
        batch_size=batch_size)

    # 4. Create an AdaptiveModel
    # a) which consists of a pretrained language model as a basis
    language_model = LanguageModel.load(lang_model)
    # b) and a prediction head on top that is suited for our task
    prediction_head = TextClassificationHead(num_labels=len(label_list))

    model = AdaptiveModel(
        language_model=language_model,
        prediction_heads=[prediction_head],
        embeds_dropout_prob=0.1,
        lm_output_types=["per_sequence_continuous"],
        device=device)

    # 5. Create an optimizer
    model, optimizer, lr_schedule = initialize_optimizer(
        model=model,
        learning_rate=2e-5,
        device=device,
        n_batches=len(data_silo.loaders["train"]),
        n_epochs=n_epochs)

    # 6. Feed everything to the Trainer, which keeps care of growing our model into powerful plant and evaluates it from time to time
    trainer = Trainer(
        model=model,
        optimizer=optimizer,
        data_silo=data_silo,
        epochs=n_epochs,
        n_gpu=n_gpu,
        lr_schedule=lr_schedule,
        evaluate_every=evaluate_every,
        device=device)

    # 7. Let it grow
    trainer.train()

    # 8. Hooray! You have a model. Store it:
    save_dir = Path("saved_models/text_pair_classification_model")
    model.save(save_dir)
    processor.save(save_dir)

    # 9. Load it & harvest your fruits (Inference)
    #    Add your own text adapted to the dataset you provide
    # For correct Text Pair Classification on raw dictionaries (inference mode), we need to put both
    # texts (text, text_b) into a tuple.
    # See corresponding conversion in the file_to_dicts() method of TextPairClassificationProcessor: https://github.com/deepset-ai/FARM/blob/5ab5b1620cb51ceb874d4b30c887e377ad1a6e9a/farm/data_handler/processor.py#L744
    basic_texts = [
        {"text": ("how many times have real madrid won the champions league in a row",
                  "They have also won the competition the most times in a row, winning it five times from 1956 to 1960")},
        {"text": ("how many seasons of the blacklist are there on netflix", "Retrieved March 27 , 2018 .")},
    ]

    model = Inferencer.load(save_dir)
    result = model.inference_from_dicts(dicts=basic_texts)

    print(result)
    model.close_multiprocessing_pool()

if __name__ == "__main__":
    text_pair_classification()

# fmt: on


"""
機能
・分析補助モジュール記述
・プロパティを持つinput
"""

import numpy as np
import sys

class CommonMainModule:
    def __init__(self, MyAnalysisID):
        self.MyAnalysis = MyAnalysisID
        self.exceptRoopList = ["end"]

    def ChangeMenu(self, keyString):
        "mainとmenuの変更"
        self.MyAnalysis.main = self.MyAnalysis.mainMenu[keyString]
        if(keyString != "end"):
            self.MyAnalysis.mainMenu = self.MyAnalysis.menuList[keyString]
            self.ShowMenu()

    def InputChangeMenu(self, questionString = "メニュー選択 : "):

        option = input(questionString + self.MyAnalysis.fileClass.QuestionString())

        if option in self.MyAnalysis.mainMenu["main"].keys():
           self.MyAnalysis.main = self.MyAnalysis.mainMenu["main"][option]
           self.MyAnalysis.mainMenu = self.MyAnalysis.menuList[option]
           self.ShowMenu()

        elif option in self.MyAnalysis.mainMenu["sub"].keys():
             self.MyAnalysis.mainMenu["sub"][option]()
             if option != "end":
                 self.InputChangeMenu(questionString)
        else:
             self.InputChangeMenu(questionString)

    def ShowMenu(self):
        print(self.MyAnalysis.mainMenu["main"].keys())
        print(self.MyAnalysis.mainMenu["sub"].keys())

class CommonModule:
    def __init__(self):
        self.NGList = np.array([]) #fileNameListを追加する

    def PrintLog(self, log):
        print(" - " + str(log))

    def IsFloat(self, str):
        result = None

        try:
            resultVariable = float(str)
            result = True
        except ValueError:
            result = False

        return result

    def inputInOption(self, str, option):
        result = input(str)
        if result not in option:
            print("入力ミスです。")
            result = self.inputInOption(str, option)

        return result

    def printList(self, targetlist):
        print(targetlist) #後で実装

    def printWithNumber(self, ndarray):
        noline = ndarray.shape[0]
        for i in range(noline):
            print(str(i) + ". " + str(ndarray[i]))

    #ver3
    def UpdateWithoutOverride(originaldic, adddic):
        CommonModule.CheckKeyDuplication(originaldic, adddic, qstr="存在しているキーが含まれています。")
        originaldic.update(adddic) #dicは参照型

    def CheckKeyDuplication(dic1, dic2, qstr="キーが重複しています。"):
        for key in [*dic1]:
            if key in [*dic2]:
                raise KeyError(qstr)

class CommandModule:
    def __init__(self, **kwargs):

        self.option = {"commandquestion" : "command : ",
                       "cancelstr" : "キャンセルされました。",
                       "cancelcommand" : "cancel",
                       "cancelfunc" : self.Cancel,
                       "subcommand" : {},
                       "transcommand" : {}}
        self.option.update(kwargs)

        self.CM = CommonModule()

        self.__isPlay = True
        self.__subcommand = {"showcommand" : self.ShowCommand}
        self.__transcommand = {self.option["cancelcommand"] : self.option["cancelcommand"]}
        self.commandquestion = self.option["commandquestion"]
        self.cancelstr = self.option["cancelstr"]
        self.subcommand = self.option["subcommand"]
        self.transcommand = self.option["transcommand"]

        self.UpdateWithoutOverride(self.__subcommand, self.subcommand)
        self.UpdateWithoutOverride(self.__transcommand, self.transcommand)
        self.CheckKeyDuplication(self.__subcommand, self.__transcommand)

    def UpdateWithoutOverride(self, originaldic, adddic):
        self.CheckKeyDuplication(originaldic, adddic, qstr="存在しているキーが含まれています。")
        originaldic.update(adddic) #dicは参照型

    def CheckKeyDuplication(self, dic1, dic2, qstr="キーが重複しています。"):
        for key in [*dic1]:
            if key in [*dic2]:
                raise KeyError(qstr)

    def Cancel(self):
        print(self.cancelstr)

    def ShowCommand(self):
        self.CM.printList([*self.__subcommand])
        self.CM.printList([*self.__transcommand])

    def Main(self):
        self.__isPlay = True
        self.command = None

        while self.__isPlay:
            self.command = input(self.commandquestion)

            if self.command in [*self.__transcommand]:
                self.__transcommand[self.command]()
                self.__isPlay = False
            elif self.command in [*self.__subcommand]:
                self.__subcommand[self.command]()

#ver3
class OriginalClass:
    def __init__(self, MyAnalysis, **kwargs):
        self.CM = CommonModule()
        self.MyAnalysis = MyAnalysis
        self.option = {"question" : "command : ",
                       "funclist" : {},
                       "phaselist" : []}
        self.option.update(kwargs)

        self.funclist = {"showcommand" : self.ShowCommand,
                         "end" : self.EndProgram}
        self.phaselist = self.option["phaselist"]

        CommonModule.UpdateWithoutOverride(self.funclist, self.option["funclist"])
        self.question = self.option["question"]

    def Main(self):
        command = input(self.question)
        if command in [*self.funclist]:
            self.funclist[command]()
        elif command in self.phaselist:
            self.ChangePhase(command)

    def ShowCommand(self):
        print(self.phaselist)
        print([*self.funclist])

    def EndProgram(self):
        self.MyAnalysis.isPlay = False
        print("プログラムを終了します。。。")

    def ChangePhase(self, nextphase):
        self.MyAnalysis.MainClass = self.MyAnalysis.AllMode[nextphase]
        self.MyAnalysis.MainClass.ShowCommand()


"""Module responsible for handling all Function Content parsing in Lexer"""
from typing import TYPE_CHECKING
from json import dumps

from .vanilla_command import COMMANDS as VANILLA_COMMANDS
from .tokenizer import Tokenizer, Token, TokenType
from .exception import EXCEPTIONS, JMCSyntaxException, MinecraftSyntaxWarning
from .log import Logger
from .utils import convention_jmc_to_mc, is_decorator, is_number, is_connected, search_to_string
from .datapack import DataPack
from .command.condition import BOOL_FUNCTIONS
from .header import Header
from .command import (FLOW_CONTROL_COMMANDS,
                      variable_operation,
                      JMCFunction,
                      FuncType,
                      )

if TYPE_CHECKING:
    from .lexer import Lexer

logger = Logger(__name__)

EXECUTE_EXCLUDED_COMMANDS = JMCFunction.get_subclasses(
    FuncType.EXECUTE_EXCLUDED)
"""Dictionary of command's name and a class of JMCFunction type for custom jmc command that can't be used with `/execute`"""
LOAD_ONCE_COMMANDS = JMCFunction.get_subclasses(FuncType.LOAD_ONCE)
"""Dictionary of command's name and a class of JMCFunction type for custom jmc command that can be only used *once* in load"""
JMC_COMMANDS = JMCFunction.get_subclasses(FuncType.JMC_COMMAND)
"""Dictionary of command's name and a class of JMCFunction type for custom jmc command"""
LOAD_ONLY_COMMANDS = JMCFunction.get_subclasses(FuncType.LOAD_ONLY)
"""Dictionary of command's name and a class of JMCFunction type for custom jmc command that can only be used in load"""

FIRST_ARGUMENTS = {
    *FLOW_CONTROL_COMMANDS,
    *LOAD_ONCE_COMMANDS,
    *LOAD_ONLY_COMMANDS,
    *JMC_COMMANDS,
    *FLOW_CONTROL_COMMANDS,
    *EXECUTE_EXCLUDED_COMMANDS,
    *VANILLA_COMMANDS,
    "class",
    "import",
    "new"
}
"""Set of all vanilla commands and JMC custom syntax"""

FIRST_ARGUMENTS_EXCEPTION = {
    "give": {"effect", "recipe", "give"},
    "clear": {"effect", "schedule"},
    "if": {"execute"},
    "summon": {"execute"},
    "function": {"schedule"},
    "trigger": {"scoreboard"},
    "bossbar": {"execute"},
    "title": {"title"},
    "item": {"summon"},
    "loot": {"loot", "give"},
    "data": {"execute"},
    "playsound": {"weather"},
    "particle": {"item"}
}
"""Dictionary of (FIRST_ARGUMENTS that can also be used as normal argument in a command) and (those commands)

Example: `/effect clear` -> `"clear": {"effect"}`"""

# ALLOW_KEYWORD_AFTER_CURLY_PAREN = {
#     "give",
#     "clear",
#     "setblock"
# }
# """Set of vanilla command to stop JMC from terminating line from curly bracket (Allow number after curly bracket)"""

def append_commands(commands: list[str], string: str) -> None:
    """
    Append a new argument to a comand(list of minecraft arguments)

    :param commands: Entire command(list of minecraft arguments) to add to
    :param string: A new argument to add
    """
    if commands and commands[-1] == "run" and string.startswith("execute "):
        commands[-1] = string[8:]  # len('execute ') = 8
    else:
        commands.append(string)

class FuncContent:
    """
    A class representation of a raw function for parsing content inside the function

    :param tokenizer: Tokenizer
    :param programs: List of commands(List of arguments(Token))
    :param is_load: Whether the function is a load function
    """
    __slots__ = "tokenizer", "programs", "is_load", "command_strings", "__commands", "command", "is_expect_command", "is_execute", "lexer", "expanded_commands"

    command: list[Token]
    is_expect_command: bool
    expanded_commands: list[str] | None
    is_execute: bool

    def __init__(self, tokenizer: Tokenizer,
                 programs: list[list[Token]], is_load: bool, lexer: "Lexer") -> None:

        self.tokenizer = tokenizer
        self.programs = programs
        self.is_load = is_load
        self.command_strings: list[str] = []
        self.__commands: list[str] = []
        self.lexer = lexer
        self.expanded_commands = None

    def parse_self_command(self):
        """
        Parse self.command
        """
        if self.command[0].token_type != TokenType.KEYWORD:
            raise JMCSyntaxException(
                f"Expected keyword (got {self.command[0].token_type.value})", self.command[0], self.tokenizer)
        if self.command[0].string == "new":
            raise JMCSyntaxException(
                "'new' keyword found in function", self.command[0], self.tokenizer)
        if self.command[0].string == "class":
            raise JMCSyntaxException(
                "'class' keyword found in function", self.command[0], self.tokenizer)
        if self.command[0].string == "function" and len(self.command) == 4:
            raise JMCSyntaxException(
                "Function declaration found in function", self.command[0], self.tokenizer)
        if is_decorator(self.command[0].string):
            raise JMCSyntaxException(
                "Decorated function declaration found in function", self.command[0], self.tokenizer)
        if self.command[0].string == "import":
            raise JMCSyntaxException(
                "Importing found in function", self.command[0], self.tokenizer)

        # Boxes check
        if self.lexer.do_while_box is not None:
            if self.command[0].string != "while":
                raise JMCSyntaxException(
                    "Expected 'while'", self.command[0], self.tokenizer)
        if self.lexer.if_else_box:
            if self.command[0].string != "else":
                append_commands(
                    self.__commands, self.lexer.parse_if_else(
                        self.tokenizer))

        if self.__commands:
            if self.expanded_commands is not None:
                for expanded_command in self.expanded_commands:
                    self.command_strings.append(
                        " ".join(self.__commands) + " " + (expanded_command if "\n" not in expanded_command else self.lexer.datapack.add_private_function('expand', expanded_command)))
            else:
                self.command_strings.append(" ".join(self.__commands))
            self.__commands = []
            self.expanded_commands = None

        self.__parse_commands()

    def parse(self) -> list[str]:
        """
        Parse the content
        :return: List of commands(String)
        """
        for command in self.programs:
            self.command = command
            self.parse_self_command()

        # Boxes check
        if self.lexer.do_while_box is not None:
            raise JMCSyntaxException(
                "Expected 'while'", self.programs[-1][-1], self.tokenizer)
        if self.lexer.if_else_box:
            append_commands(
                self.__commands,
                self.lexer.parse_if_else(
                    self.tokenizer))

        if self.__commands:
            if self.expanded_commands is not None:
                for expanded_command in self.expanded_commands:
                    self.command_strings.append(
                        " ".join(self.__commands) + " " + (expanded_command if "\n" not in expanded_command else self.lexer.datapack.add_private_function('expand', expanded_command)))
            else:
                self.command_strings.append(" ".join(self.__commands))
            self.__commands = []
            self.expanded_commands = None
        return self.command_strings

    def __parse_commands(self) -> None:
        """Parse command in self.commands"""
        self.is_expect_command = True
        self.is_execute = (self.command[0].string == "execute")
        command_pos = None

        for key_pos, token in enumerate(self.command):
            if not self.is_expect_command:
                if command_pos is None:
                    raise ValueError("Unknown command_pos")
                self.__not_expect_command(key_pos, token, command_pos)
                continue
            command_pos = key_pos
            if self.__expect_command(key_pos, token):
                break

    def __optimize(self, token: Token) -> bool:
        """
        Optimize minecraft command by removing redundancy
        :param token: Current token
        :return: Whether to cancel appending this token
        """
        if token.token_type != TokenType.KEYWORD:
            return False
        if not self.__commands:
            return False

        # `execute as @s`
        if (
            token.string == "@s" and
            self.__commands[-1] == "as" and
            self.__commands[-2] not in {"rotated", "positioned"}
        ):

            self.__commands[-1] = "if entity"
            return False

        # `execute run`
        if (
            token.string == "run"
            and self.__commands[-1] == "execute"
        ):
            del self.__commands[-1]
            return True

        # `run execute`
        if (
            token.string == "execute"
            and self.__commands[-1] == "run"
            and self.__commands[0] == "execute"
        ):
            del self.__commands[-1]
            return True

        return False

    def __not_expect_command(
            self, key_pos: int, token: Token, command_pos: int) -> None:
        """
        Called when expecting an argument of command

        :param key_pos: Current index in self.command
        :param token: token
        :param key_pos: Index of latest command in self.command
        :return: Whether to break out of the loop
        """
        if token.string == "run" and token.token_type == TokenType.KEYWORD:
            if not self.is_execute:
                raise MinecraftSyntaxWarning(
                    "'run' keyword found outside 'execute' command", token, self.tokenizer)
            self.is_expect_command = True

        if token.string == "expand" and token.token_type == TokenType.KEYWORD:
            if self.is_execute:
                self.is_expect_command = True
                self.expanded_commands = []

        __is_first_arg = (
            token.string in FIRST_ARGUMENTS
            or
            token.string in Header().commands
            or is_decorator(token.string)
        )
        __is_not_exception = (
            len(self.__commands) > command_pos and
            not (
                token.string in FIRST_ARGUMENTS_EXCEPTION
                and
                self.__commands[command_pos] in FIRST_ARGUMENTS_EXCEPTION[token.string]
            )
        )
        __is_not_connected = not is_connected(token, self.command[key_pos - 1])
        __is_not_deleted = token.string not in Header().dels

        if (
            token.token_type == TokenType.KEYWORD and
            __is_first_arg and
            __is_not_exception and
            __is_not_connected and
            __is_not_deleted
        ):
            raise JMCSyntaxException(
                f"Keyword({token.string}) at line {token.line} col {token.col} is recognized as a command.\nExpected semicolon(;)", self.command[key_pos - 1], self.tokenizer, col_length=True)

        if self.__optimize(token):
            return

        if token.token_type == TokenType.PAREN_ROUND:
            self.__commands[-1], success = search_to_string(
                self.__commands[-1], token, DataPack.var_name, self.tokenizer)
            if not success:
                if is_connected(token, self.command[key_pos - 1]):
                    self.__commands[-1] += self.lexer.clean_up_paren_token(
                        token, self.tokenizer)
                else:
                    append_commands(
                        self.__commands, self.lexer.clean_up_paren_token(token, self.tokenizer))
        elif token.token_type in {TokenType.PAREN_CURLY, TokenType.PAREN_SQUARE}:
            if is_connected(token, self.command[key_pos - 1]):
                self.__commands[-1] += self.lexer.clean_up_paren_token(
                    token, self.tokenizer)
            else:
                append_commands(
                    self.__commands, self.lexer.clean_up_paren_token(token, self.tokenizer))
        elif token.token_type == TokenType.STRING:
            if is_connected(
                    token, self.command[key_pos - 1]) and self.command[key_pos - 1].token_type == TokenType.KEYWORD:
                raise JMCSyntaxException(
                    "Expected whitespace between string and a keyword", self.command[key_pos - 1], self.tokenizer, col_length=True)
            append_commands(self.__commands, dumps(token.string))
        elif (
            token.token_type == TokenType.KEYWORD
            and
            is_connected(token, self.command[key_pos - 1])
            and
            self.command[key_pos - 1].token_type == TokenType.STRING
        ):
            raise JMCSyntaxException(
                "Expected whitespace between string and a keyword", self.command[key_pos - 1], self.tokenizer, col_length=True)
        elif (
            token.token_type in {TokenType.OPERATOR, TokenType.KEYWORD}
            and
            is_connected(token, self.command[key_pos - 1])
        ):
            self.__commands[-1] += token.string
        else:
            append_commands(self.__commands, token.string)

    def __expect_command(self, key_pos: int, token: Token) -> bool:
        """
        Called when expecting a command

        :param key_pos: Current index in self.command
        :param token: token
        :return: Whether to break out of the loop
        """
        self.is_expect_command = False

        # Handle Errors
        if token.token_type != TokenType.KEYWORD:
            if token.token_type == TokenType.PAREN_CURLY and self.is_execute:
                if self.expanded_commands is not None:
                    self.expanded_commands = self.lexer.datapack.parse_function_token(
                        token, self.tokenizer)
                    self.__commands[-1] = "run"
                else:
                    append_commands(self.__commands, self.lexer.datapack.add_arrow_function(
                        "anonymous", token, self.tokenizer))
                return True
            raise JMCSyntaxException(
                "Expected keyword", token, self.tokenizer)

        # End Handle Errors

        if is_number(token.string) and key_pos == 0:
            self.__is_number(key_pos, token)
            return True

        if token.string == "say":
            self.__is_say(key_pos, token)
            return True

        if token.string == "schedule":
            if self.__is_schedule(key_pos):
                return True

        if token.string.startswith(DataPack.VARIABLE_SIGN):
            if self.__is_startswith_var(key_pos):
                return True

        if len(self.command[key_pos:]
               ) > 2 and self.command[key_pos + 1].string == ":":
            if self.__is_startswith_var(key_pos):
                return True

        if self.__is_jmc_function(key_pos, token):
            if len(self.command[key_pos:]) > 2:
                raise JMCSyntaxException(
                    f"Unexpected token({self.command[key_pos+2].string}) after function call. Expected semicolon(;)", self.command[key_pos + 1], self.tokenizer, col_length=True)
            return True

        if self.__is_flow_control_command(key_pos, token):
            return True

        if token.string in {"new", "class", "import"} or (
            token.string == "function"
            and
            len(self.command) == key_pos + 4
            and self.command[key_pos + 2].token_type == TokenType.PAREN_ROUND
            and self.command[key_pos + 3].token_type == TokenType.PAREN_CURLY
        ) or is_decorator(token.string):
            if self.is_execute:
                raise JMCSyntaxException(
                    f"This feature({token.string}) can only be used in load function", token, self.tokenizer)
        if len(self.command[key_pos:]) >= 2 and self.command[key_pos +
                                                             1].token_type == TokenType.PAREN_ROUND:
            if len(self.command[key_pos:]) > 2:
                if token.string == "unless":
                    raise JMCSyntaxException(
                        f"Unexpected token({self.command[key_pos+2].string}) after function call. Expected semicolon(;)", self.command[key_pos + 1], self.tokenizer, col_length=True, suggestion="Did you mean `if (!...`? ('unless' is not a keyword)")
                raise JMCSyntaxException(
                    f"Unexpected token({self.command[key_pos+2].string}) after function call. Expected semicolon(;)", self.command[key_pos + 1], self.tokenizer, col_length=True)

            if self.command[key_pos + 1].string != "()":
                raise JMCSyntaxException(
                    f"Argument is not supported in custom function({token.string}).\nExpected 0 argument, `()`", self.command[key_pos], self.tokenizer, suggestion="You might have misspelled the built-in function name. (It is case-sensitive.)")
            func = convention_jmc_to_mc(token, self.tokenizer)
            self.lexer.datapack.functions_called[func] = token, self.tokenizer
            append_commands(self.__commands,
                            f"function {self.lexer.datapack.namespace}:{func}")
            return True

        if token.string not in VANILLA_COMMANDS and token.string not in Header().commands:
            if not self.command_strings:
                raise JMCSyntaxException(
                    f"Unrecognized command ({token.string})", token, self.tokenizer)

            # if not self.command_strings[-1].startswith("execute"):
            #     # for _cmd in ALLOW_KEYWORD_AFTER_CURLY_PAREN:
            #     #     if self.command_strings[-1].startswith(_cmd):
            #     #         self.command_strings[-1] += " " + token.string
            #     #         return True
            #     raise JMCSyntaxException(
            # f"Unrecognized command ({token.string})", token, self.tokenizer)

            # for _cmd in ALLOW_KEYWORD_AFTER_CURLY_PAREN:
            #     if _cmd in self.command_strings[-1]:
            #         self.command_strings[-1] += " " + token.string
            #         return True

            raise JMCSyntaxException(
                f"Unrecognized command ({token.string})", token, self.tokenizer)

        if self.__optimize(token):
            return False
        append_commands(self.__commands, token.string)
        return False

    def __is_number(self, key_pos: int, token: Token) -> None:
        if len(self.command[key_pos:]) > 1:
            raise JMCSyntaxException(
                "Unexpected token", self.command[key_pos + 1], self.tokenizer, display_col_length=False)

        if not self.command_strings:
            raise JMCSyntaxException(
                "Expected command, got number", token, self.tokenizer, display_col_length=False)

        # if not self.command_strings[-1].startswith("execute"):
        #     for _cmd in ALLOW_KEYWORD_AFTER_CURLY_PAREN:
        #         if self.command_strings[-1].startswith(_cmd):
        #             self.command_strings[-1] += " " + token.string
        #             return
        #     raise JMCSyntaxException(
        #         "Unexpected number", token, self.tokenizer, display_col_length=False)

        # for _cmd in ALLOW_KEYWORD_AFTER_CURLY_PAREN:
        #     if _cmd in self.command_strings[-1]:
        #         self.command_strings[-1] += " " + token.string
        #         return

        raise JMCSyntaxException(
            "Unexpected number", token, self.tokenizer, display_col_length=False)

    def __is_say(self, key_pos: int, token: Token) -> None:
        if len(self.command[key_pos:]) == 1:
            raise JMCSyntaxException(
                "Expected string after 'say' command", token, self.tokenizer)

        if self.command[key_pos + 1].token_type != TokenType.STRING:
            raise JMCSyntaxException(
                "Expected string after 'say' command", self.command[key_pos + 1], self.tokenizer, suggestion="(In JMC, you are required to wrapped say command's argument in quote.)")

        if len(self.command[key_pos:]) > 2:
            raise JMCSyntaxException(
                "Unexpected token", self.command[key_pos + 2], self.tokenizer, display_col_length=False)

        if "\n" in self.command[key_pos + 1].string:
            raise JMCSyntaxException(
                "Unexpected newline in say command", self.command[key_pos + 1], self.tokenizer, suggestion=r"Use '\\n' instead of '\n'")
        append_commands(
            self.__commands, f"say {self.command[key_pos+1].string}")

    def __is_schedule(self, key_pos: int) -> bool:
        if len(self.command) < key_pos + 3:
            return False
        if (
            self.command[key_pos + 2].token_type == TokenType.PAREN_CURLY
        ):
            # `schedule 1t {say "command";}`
            append_commands(self.__commands, "schedule")
            append_commands(self.__commands, self.lexer.datapack.add_arrow_function(
                "anonymous", self.command[key_pos + 2], self.tokenizer, force_create_func=True))
            append_commands(self.__commands, self.command[key_pos + 1].string)
            return True
        if len(self.command) < key_pos + 4:
            return False
        if (
            self.command[key_pos + 2].token_type == TokenType.KEYWORD
            and
            self.command[key_pos + 3].token_type == TokenType.PAREN_ROUND
        ):
            # `schedule function myFunc() 1t append;`
            if self.command[key_pos + 1].string not in {"function", "clear"}:
                raise JMCSyntaxException(
                    "Expected 'function' or 'clear' after 'schedule'", self.command[key_pos + 1], self.tokenizer)
            if self.command[key_pos + 3].string != "()":
                raise JMCSyntaxException(
                    "'schedule' does not support argument is not supported.\nExpected empty bracket", self.command[key_pos + 3], self.tokenizer)
            append_commands(self.__commands, "schedule")
            append_commands(self.__commands, self.command[key_pos + 1].string)
            append_commands(
                self.__commands,
                f"{self.lexer.datapack.namespace}:{convention_jmc_to_mc(self.command[key_pos + 2], self.tokenizer)}")
            if self.command[key_pos + 1].string == "clear":
                if len(self.command) > key_pos + 4:
                    raise JMCSyntaxException(
                        "Unexpected token in schedule clear", self.command[key_pos + 3], self.tokenizer)
                return True
            if len(self.command) < key_pos + 5:
                raise JMCSyntaxException(
                    "Expected time in schedule call", self.command[key_pos + 3], self.tokenizer)
            append_commands(self.__commands, self.command[key_pos + 4].string)
            if len(self.command) == key_pos + 6:
                if self.command[key_pos +
                                5].string not in {"append", "replace"}:
                    raise JMCSyntaxException(
                        f"Expected 'append' or 'replace' (got {self.command[key_pos + 5]}", self.command[key_pos + 5], self.tokenizer)
                append_commands(self.__commands,
                                self.command[key_pos + 5].string)
            if len(self.command) > key_pos + 6:
                raise JMCSyntaxException(
                    "Unexpected token in schedule", self.command[key_pos + 5], self.tokenizer)
            return True
        if (
            self.command[key_pos + 3].token_type == TokenType.PAREN_CURLY
        ):
            # `schedule 1t append {say "command";}`
            if self.command[key_pos +
                            2].string not in {"append", "replace"}:
                raise JMCSyntaxException(
                    f"Expected 'append' or 'replace' (got {self.command[key_pos + 2]}", self.command[key_pos + 2], self.tokenizer)
            append_commands(self.__commands, "schedule")
            append_commands(self.__commands, self.lexer.datapack.add_arrow_function(
                "anonymous", self.command[key_pos + 3], self.tokenizer, force_create_func=True))
            append_commands(self.__commands, self.command[key_pos + 1].string)
            append_commands(self.__commands, self.command[key_pos + 2].string)
            return True
        return False

    def __is_startswith_var(self, key_pos: int) -> bool:
        try:
            append_commands(self.__commands, variable_operation(
                self.command[key_pos:], self.tokenizer, self.lexer.datapack, self.is_execute, type(self), FIRST_ARGUMENTS))
        except EXCEPTIONS as var_error:
            if key_pos != 0:
                raise var_error
            first_token = self.command[0]
            self.command[0] = Token(first_token.token_type,
                                    first_token.line,
                                    first_token.col + 1,
                                    first_token.string[1:],
                                    first_token._macro_length)
            try:
                self.parse_self_command()
            except EXCEPTIONS as normal_error:
                token = self.command[0]
                if token.string not in VANILLA_COMMANDS and token.string not in Header(
                ).commands and token.string != "":
                    raise var_error
                raise normal_error
            self.__commands[0] = "$" + self.__commands[0]
        return True

    def __is_jmc_function(self, key_pos: int, token: Token) -> bool:
        load_once_command = self.get_function(token, LOAD_ONCE_COMMANDS)
        if load_once_command is not None:
            if self.is_execute:
                raise JMCSyntaxException(
                    f"This feature({token.string}) cannot be used with 'execute'", token, self.tokenizer)
            if token.string in self.lexer.datapack.used_command:
                raise JMCSyntaxException(
                    f"This feature({token.string}) can only be used once per datapack", token, self.tokenizer)
            if not self.is_load:
                raise JMCSyntaxException(
                    f"This feature({token.string}) can only be used in load function", token, self.tokenizer)

            self.lexer.datapack.used_command.add(token.string)
            append_commands(self.__commands, load_once_command(
                self.command[key_pos + 1], self.lexer.datapack, self.tokenizer).call())
            return True

        execute_excluded_command = self.get_function(
            token, EXECUTE_EXCLUDED_COMMANDS)
        if execute_excluded_command is not None:
            if self.is_execute:
                append_commands(self.__commands, self.lexer.datapack.add_raw_private_function("anonymous", [execute_excluded_command(
                    self.command[key_pos + 1], self.lexer.datapack, self.tokenizer).call()]))
            else:
                append_commands(self.__commands, execute_excluded_command(
                    self.command[key_pos + 1], self.lexer.datapack, self.tokenizer).call())
            return True

        load_only_command = self.get_function(token, LOAD_ONLY_COMMANDS)
        if load_only_command is not None:
            if self.is_execute:
                raise JMCSyntaxException(
                    f"This feature({token.string}) cannot be used with 'execute'", token, self.tokenizer)
            if not self.is_load:
                raise JMCSyntaxException(
                    f"This feature({token.string}) can only be used in load function", token, self.tokenizer)
            append_commands(self.__commands, load_only_command(
                self.command[key_pos + 1], self.lexer.datapack, self.tokenizer).call())
            return True

        jmc_command = self.get_function(token, JMC_COMMANDS)
        if jmc_command is not None:
            if len(self.command) > key_pos + 2:
                raise JMCSyntaxException(
                    "Unexpected token", self.command[key_pos + 2], self.tokenizer, display_col_length=False, suggestion="Expected semicolon")
            append_commands(self.__commands, jmc_command(
                self.command[key_pos + 1], self.lexer.datapack, self.tokenizer, is_execute=self.is_execute).call())
            return True

        if token.string in BOOL_FUNCTIONS:
            raise JMCSyntaxException(
                f"This feature({token.string}) only works in JMC's custom condition", token, self.tokenizer)

        return False

    def __is_flow_control_command(self, key_pos: int, token: Token) -> bool:
        flow_control_command = FLOW_CONTROL_COMMANDS.get(
            token.string, None)
        if flow_control_command is not None:
            if self.is_execute:
                raise JMCSyntaxException(
                    f"This feature({token.string}) cannot be used with 'execute'", token, self.tokenizer)
            return_value = flow_control_command(
                self.command[key_pos:], self.lexer.datapack, self.tokenizer)
            if return_value is not None:
                append_commands(self.__commands, return_value)
            return True
        return False

    def get_function(self, token: Token,
                     command_functions: dict[str, type["JMCFunction"]]) -> type["JMCFunction"] | None:
        """
        Get jmc function (class)

        :return: The JMCFunction's subclass
        """
        return command_functions.get(token.string, None)


import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import googleapiclient.discovery
import os

np.random.seed(42)

from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string2'

from flask_bootstrap import Bootstrap
Bootstrap(app)

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer

class LabForm(FlaskForm):
    latitude = StringField('latitude', validators=[DataRequired()])
    longitude = StringField('longitude', validators=[DataRequired()])
    month = StringField('month', validators=[DataRequired()])
    day = StringField('day', validators=[DataRequired()])
    avg_temp = StringField('avg_temp', validators=[DataRequired()])
    max_temp = StringField('max_temp', validators=[DataRequired()])
    max_wind_speed = StringField('max_wind_speed', validators=[DataRequired()])
    avg_wind = StringField('avg_wind', validators=[DataRequired()])
    submit = SubmitField('Submit')

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

@app.route('/prediction', methods=['GET', 'POST'])
def lab():
    form = LabForm()
    if form.validate_on_submit():
        X_test = np.array([[float(form.latitude.data),
                            float(form.longitude.data),
                            str(form.month.data),
                            str(form.day.data),
                            float(form.avg_temp.data),
                            float(form.max_temp.data),
                            float(form.max_wind_speed.data),
                            float(form.avg_wind.data)]])
        print(X_test.shape)
        print(X_test)
        fires = pd.read_csv('./sanbul-5.csv', sep=',')
        fires_num = fires.drop(["burned_area"], axis=1)
        num = fires_num.drop(['month', 'day'], axis=1)

        #DataFrame으로 컬럼을 추가해주고
        df = pd.DataFrame(X_test, columns=["latitude", "longitude", "month", "day", "avg_temp", "max_temp", "max_wind_speed", "avg_wind"])
        #df_num = df.drop(["month", "day"], axis=1)
        print(df)

        # pipeline
        num_pipeline = Pipeline([('std_scaler', StandardScaler()), ])

        #df_num_tr = num_pipeline.fit(df_num)
        #print(df_num_tr)

#        fires_num_tr = num_pipeline.fit(fires_num)  # 문제시 여기 수정해보자.
        #print(fires_num_tr)

        num_attribs = list(num)
        cat_attribs = ["month", "day"]

        full_pipeline = ColumnTransformer([("num", num_pipeline, num_attribs), ("cat", OneHotEncoder(), cat_attribs), ])

        fires_prepared = full_pipeline.fit_transform(fires)
        X_test = full_pipeline.fit_transform(df)

#################
        # X = fires.values[:, 0:8]
        # y = fires.values[:, 8]
        #
        # scaler = MinMaxScaler()
        # scaler.fit(X)

        MODEL_NAME = "my_pima_model"
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:\\Users\\Taeho\\Desktop\\대학교 자료\\20년 4학년 1학기\\인공지능\\Term_Project\\소스코드\\my-first-project-279810-aca50529313d.json"
        project_id = "my-first-project-279810"
        model_id = MODEL_NAME
        model_path = "projects/{}/models/{}".format(project_id, model_id)
        model_path += "/versions/v0001/"
        ml_resource = googleapiclient.discovery.build("ml", "v1").projects()

        input_data_json = {"signature_name": "serving_default", "instances": X_test.tolist()}

        request = ml_resource.predict(name=model_path, body=input_data_json)
        response = request.execute()
        if "error" in response:
            raise RuntimeError(response["error"])

        predD = np.array([pred['dense_2'] for pred in response["predictions"]])
        print(predD[0][0])
        res = predD[0][0]

        return render_template('result.html', res=res)

    return render_template('prediction.html', form=form)

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


import torch
from torch.utils.data import TensorDataset, DataLoader
from torch.optim import Adam
import numpy as np
import logictensornetworks as ltn
import argparse

def parse_args():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--csv-path',type=str,default=None)
    parser.add_argument('--epochs',type=int,default=1000)
    parser.add_argument('--batch-size',type=int,default=64)
    args = parser.parse_args()
    dict_args = vars(args)
    return dict_args

args = parse_args()
batch_size = args['batch_size']
EPOCHS = args['epochs']
csv_path = args['csv_path']

# # Data
# Sample data from [0,1]^2.
# The groundtruth positive is data close to the center (.5,.5) (given a threshold)
# All the other data is considered as negative examples
nr_samples = 100
data = np.random.uniform([0,0],[1,1],(nr_samples,2))
t_data = torch.tensor(data)
labels = np.sum(np.square(data-[.5,.5]),axis=1)<.09
t_labels = torch.tensor(labels)
# 50 examples for training; 50 examples for testing
ds_train = TensorDataset(t_data[:50],t_labels[:50])
dl_train = DataLoader(ds_train, batch_size=batch_size)
ds_test = TensorDataset(t_data[50:],t_labels[50:])
dl_test = DataLoader(ds_test, batch_size=batch_size)

# # LTN

A = ltn.Predicate.MLP([2],hidden_layer_sizes=(16,16))
print('-----\n',A,'\n------')

# # Axioms
#
# ```
# forall x_A: A(x_A)
# forall x_not_A: ~A(x_not_A)
# ```

Not = ltn.Wrapper_Connective(ltn.fuzzy_ops.Not_Std())
And = ltn.Wrapper_Connective(ltn.fuzzy_ops.And_Prod())
Or = ltn.Wrapper_Connective(ltn.fuzzy_ops.Or_ProbSum())
Implies = ltn.Wrapper_Connective(ltn.fuzzy_ops.Implies_Reichenbach())
Forall = ltn.Wrapper_Quantifier(ltn.fuzzy_ops.Aggreg_pMeanError(p=2),semantics="forall")
Exists = ltn.Wrapper_Quantifier(ltn.fuzzy_ops.Aggreg_pMean(p=2),semantics="exists")

formula_aggregator = ltn.fuzzy_ops.Aggreg_pMeanError(p=2)

def axioms(data, labels):
    x_A = ltn.variable("x_A",data[labels])
    x_not_A = ltn.variable("x_not_A",data[torch.logical_not(labels)])
    axioms = [
        Forall(x_A, A(x_A)),
        Forall(x_not_A, Not(A(x_not_A)))
    ]
    axioms = torch.stack(axioms)
    sat_level = formula_aggregator(axioms)
    return sat_level, axioms

# Initialize all layers and the static graph.

for data, labels in dl_test:
    print("Initial sat level %.5f"%axioms(data, labels)[0])
    break

# # Training
#
# Define the metrics

# TODO: create metrics with Pytorch
# metrics_dict = {
#     'train_sat': tf.keras.metrics.Mean(name='train_sat'),
#     'test_sat': tf.keras.metrics.Mean(name='test_sat'),
#     'train_accuracy': tf.keras.metrics.BinaryAccuracy(name="train_accuracy",threshold=0.5),
#     'test_accuracy': tf.keras.metrics.BinaryAccuracy(name="test_accuracy",threshold=0.5)
# }
metrics_dict = {}

optimizer = Adam(params=A.parameters() ,lr=0.001)

def train_step(data, labels):
    # sat and update
    optimizer.zero_grad()
    sat = axioms(data,labels)[0]
    loss = 1.-sat
    loss.backward()
    optimizer.step()
    # TODO: collect metrics
    # metrics_dict['train_sat'](sat)
    # # accuracy
    # predictions = A.model(data)
    # metrics_dict['train_accuracy'](labels,predictions)
    return sat

def test_step(data, labels):
    # sat and update
    sat = axioms(data, labels)[0]
    # TODO: collect metrics
    # metrics_dict['test_sat'](sat)
    # # accuracy
    # predictions = A.model(data)
    # metrics_dict['test_accuracy'](labels,predictions)
    return sat

import commons_pytorch

commons_pytorch.train(
    EPOCHS,
    metrics_dict,
    dl_train,
    dl_test,
    train_step,
    test_step,
    csv_path=csv_path,
    track_metrics=20
)

x = ltn.variable("x",data[:50])
result=A(x)
print(result)


from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter
from django.urls import path, include
from .views import (
    AnalysisViewSet,
    AnalysisResultCreateListView,
    AnalysisResultDestoryView,
    AuthRetrieveAnalysisResultsImageView,
    AuthRetrieveAnalysisResultsFileView,
    AnalysisResultImageDeleteView,
    AnalysisResultFileDeleteView,
)

if settings.DEBUG:
    router = DefaultRouter()
else:
    router = SimpleRouter()

router.register("analisys", AnalysisViewSet, basename="analisys")
# router.register('independent-researchs',
#                IndependentResearchViewSet,
#                basename='independent-researchs')
# router.register('independent-research-results',
#                ResultIndependentResearchViewSet,
#                basename='independent-research-results')
# app_name = "analisys"

urlpatterns = [
    path(
        "analysis-results-images/<int:pk>/",
        AnalysisResultImageDeleteView.as_view(),
        name="analysis-results-images-delete",
    ),
    path(
        "analysis-results-files/<int:pk>/",
        AnalysisResultFileDeleteView.as_view(),
        name="analysis-results-files-delete",
    ),
    path(
        "analysis-results/<int:pacient_id>/<int:analysis_id>/",
        AnalysisResultCreateListView.as_view(),
    ),
    path(
        "analysis-results-delete/<int:pacient_id>/<int:analysis_result_id>/",
        AnalysisResultDestoryView.as_view(),
    ),
    path(
        "auth-request-analisis_results-files/",
        AuthRetrieveAnalysisResultsFileView.as_view(),
    ),
    path(
        "auth-request-analisis_results-images/",
        AuthRetrieveAnalysisResultsImageView.as_view(),
    ),
    path("", include(router.urls)),
]


from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from app import models
import json

@login_required(login_url="/login/")
def quiz_exercises(request):
    quiz_exercises = models.QuizExercise.objects.all()
    specific_topic = None

    # Creating breadcrumbs
    breadcrumbs = [
        { "text": "Home", "link": "/" },
        { "text": "Exercises", "link": "/exercises/" },
        { "text": "Quiz Exercises", "link": "/exercises/quiz-exercises/" }
    ]

    return render(request, "app/exercises/quiz-exercises/quiz-exercises.html", context={
        "exercises": quiz_exercises,
        "topic": specific_topic,
        "breadcrumbs": breadcrumbs
    })

@login_required(login_url="/login/")
def quiz_exercise(request):
    quiz_id = request.GET.get("id")
    if quiz_id:
        if models.QuizExercise.objects.filter(id=quiz_id).exists():
            quiz_exercise = models.QuizExercise.objects.get(id=quiz_id)
        else:
            return render(request, "errors/exercise-does-not-exist.html")
    else:
        return render(request, "errors/exercise-does-not-exist.html")

    # Creating breadcrumbs
    breadcrumbs = [
        { "text": "Home", "link": "/" },
        { "text": "Exercises", "link": "/exercises/" },
        { "text": "Quiz Exercises", "link": "/exercises/quiz-exercises/" },
        { "text": quiz_exercise.name, "link": None }
    ]

    # Checking to see if user already took this quiz
    user_already_taken_quiz = False
    for completed_quiz_exercise in list(request.user.profile.completed_quiz_exercises.all()):
        if completed_quiz_exercise.quiz_exercise == quiz_exercise:
            user_already_taken_quiz = True

    return render(request, "app/exercises/quiz-exercises/quiz-exercise.html", context={
        "exercise": quiz_exercise,
        "resources": list(quiz_exercise.resources.all()),
        "breadcrumbs": breadcrumbs,
        "user_already_taken_quiz": user_already_taken_quiz
    })

@login_required(login_url="/login/")
def take_quiz(request):
    quiz_id = request.GET.get("id")
    if quiz_id:
        if models.QuizExercise.objects.filter(id=quiz_id).exists():
            quiz_exercise = models.QuizExercise.objects.get(id=quiz_id)
        else:
            return render(request, "errors/exercise-does-not-exist.html")
    else:
        return render(request, "errors/exercise-does-not-exist.html")

    # Creating breadcrumbs
    breadcrumbs = [
        { "text": "Home", "link": "/" },
        { "text": "Exercises", "link": "/exercises/" },
        { "text": "Quiz Exercises", "link": "/exercises/quiz-exercises/" },
        { "text": quiz_exercise.name, "link": "/exercises/quiz-exercises/exercise/?id=" + quiz_exercise.id },
        { "text": "Take Quiz", "link": None }
    ]

    # Formatting questions with question and answers
    questions = []
    for question in list(quiz_exercise.questions.all()):
        questions.append({
            "question": question.question,
            "answers": question.answers
        })

    questions = json.dumps(questions)

    # Checking to see if user already took this quiz
    user_already_taken_quiz = False
    for completed_quiz_exercise in list(request.user.profile.completed_quiz_exercises.all()):
        if completed_quiz_exercise.quiz_exercise == quiz_exercise:
            user_already_taken_quiz = True

    return render(request, "app/exercises/quiz-exercises/take-quiz.html", context={
        "quiz": quiz_exercise,
        "breadcrumbs": breadcrumbs,
        "questions": questions,
        "user_already_taken_quiz": user_already_taken_quiz
    })

@login_required(login_url="/login/")
def quiz_results(request):
    # Grabbing quiz from query parameters
    quiz_id = request.GET.get("id")
    if quiz_id:
        if models.QuizExercise.objects.filter(id=quiz_id).exists():
            quiz_exercise = models.QuizExercise.objects.get(id=quiz_id)
        else:
            return render(request, "errors/exercise-does-not-exist.html")
    else:
        return render(request, "errors/exercise-does-not-exist.html")

    # Creating breadcrumbs
    breadcrumbs = [
        { "text": "Home", "link": "/" },
        { "text": "Exercises", "link": "/exercises/" },
        { "text": "Quiz Exercises", "link": "/exercises/quiz-exercises/" },
        { "text": quiz_exercise.name, "link": "/exercises/quiz-exercises/exercise/?id=" + quiz_exercise.id },
        { "text": "Quiz Results", "link": None }
    ]

    # Grabbing completed quiz exercise
    if models.CompletedQuizExercise.objects.filter(quiz_exercise=quiz_exercise).exists():
        for completed_exercise in models.CompletedQuizExercise.objects.filter(quiz_exercise=quiz_exercise):
            if completed_exercise in list(request.user.profile.completed_quiz_exercises.all()):
                completed_quiz_exercise = completed_exercise
    else:
        return HttpResponse("You haven't completed this quiz yet.")

    # Organizing questions and answers for easy access
    quiz_questions = list(quiz_exercise.questions.all())
    user_answers = completed_quiz_exercise.answers
    results = []
    for i in range(len(quiz_questions)):
        result = {}
        current_question = quiz_questions[i]

        result["got_this_correct"] = (current_question.answers[current_question.correct_answer_index] == user_answers[i])
        result["question"] = current_question.question
        result["answers"] = current_question.answers
        result["correct_answer"] = current_question.answers[current_question.correct_answer_index]
        result["user_answer"] = user_answers[i]

        results.append(result)

    # results = json.dumps(results)

    return render(request, "app/exercises/quiz-exercises/quiz-results.html", context={
        "quiz_exercise": quiz_exercise,
        "completed_quiz_exercise": completed_quiz_exercise,
        "breadcrumbs": breadcrumbs,
        "results": results
    })


import pickle
import os
import numpy as np
from random import randint
import random
input_path ='/home/prithvi/Downloads/extract/extras/all_dcs_lemmas_matrix.p'
input_load = pickle.load(open(input_path, "rb"))

class beamsearch:
    def __init__(self,k,levels,max_conflicting_nodes):
        self.k=k    #beam search width
        self.levels = levels   # number of levels
        self.max_conflicting_nodes = max_conflicting_nodes  #number of maximum conflictiong nodes in a level
        #generating a list of number of confliction nodes at each level
        self.cn_at_each_level=self.g(levels,max_conflicting_nodes)
        #generating the nodes ie. the node indexes which are conflicting at each level.This is a list of lists
        self.nodes_list=self.generate_nodes(self.cn_at_each_level)
        print("List of node indexes at each level")
        print(self.nodes_list)
        print("Top k  paths greedy")
        self.k_paths_greedy=self.top_k_paths_greedy(self.nodes_list,k)
        print(self.k_paths_greedy)
        print("Top k  paths optimal")
        self.k_paths_optimal,self.p_values=self.top_k_paths_optimal(self.nodes_list,k)
        print(self.k_paths_optimal)
        print(self.p_values)
    def g(self,levels,m):
        return [randint(1,m) for x in range(0,levels)]
    def generate_nodes(self,c):
        return [random.sample(range(0, 66914), i) for i in c]
    def top_k_paths_greedy(self,l,k):
        s = [[] for _ in range(k)]
        for i in range(0,len(l)):
            if i==0:
                temp = []
#                 if(len(l[i])>k):
#                     v = random.sample(range(0,len(l[i])),k)
#                     for j in v:
#                         temp.append([l[i][j]])
#                 else:
                for j in range(0,len(l[i])):
                    temp.append([l[i][j]])
                s=temp
            else:
                count = 0
                for m in s:
                    if m:
                        count+=1
                t = np.zeros(shape=(count,len(l[i])))
                for p in range(0,t.shape[0]):
                    for q in range(0,t.shape[1]):
                        t[p,q]=input_load[s[p][-1]][l[i][q]]
                t_1d = t.flatten()
                idx_1d = t_1d.argsort()[-k:][::-1]
                x_idx, y_idx = np.unravel_index(idx_1d, t.shape)
                temp = []
                for x, y, in zip(x_idx, y_idx):
                    temp.append(s[x]+[l[i][y]])
                s = temp
        return s
    def top_k_paths_optimal(self,l,k):
        s = [[] for _ in range(k)]
        p_values=[]
        for i in range(0,len(l)):
            if i==0:
                temp = []
#                 if len(l[i])>k:
#                     v = random.sample(range(0,len(l[i])),k)
#                     for j in v:
#                         temp.append([l[i][j]])
#                 else:
                for j in range(0,len(l[i])):
                    temp.append([l[i][j]])
                p_values = [0.5]*len(temp)
                s=temp
            else:
                count = 0
                for m in s:
                    if m:
                        count+=1
                t = np.zeros(shape=(count,len(l[i])))
                for p in range(0,t.shape[0]):
                    for q in range(0,t.shape[1]):
                        t[p,q]=input_load[s[p][-1]][l[i][q]]
                t = (t.T * p_values).T
                t_1d = t.flatten()
                idx_1d = t_1d.argsort()[-k:][::-1]
                x_idx, y_idx = np.unravel_index(idx_1d, t.shape)
                temp = []
                for x, y, in zip(x_idx, y_idx):
                    temp.append(s[x]+[l[i][y]])
                p_values = [t[x][y] for x, y, in zip(x_idx, y_idx)]
                s = temp
        return s,p_values
def main():
    k=2
    levels=4
    max_conflicting_nodes=3
    bs = beamsearch(k,levels,max_conflicting_nodes)
if __name__ == "__main__": main()

helpers and outdated/sequence-to-sequence/beam search/greedyoptimal_beam_Search.py


# -*- coding: utf-8 -*-
#
# Bounding Box Editor and Exporter (BBoxEE)
# Author: Julie Young
#
# --------------------------------------------------------------------------
#
# This file is part of Animal Detection Network's (Andenet)
# Bounding Box Editor and Exporter (BBoxEE)
#
# BBoxEE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BBoxEE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>.
#
# --------------------------------------------------------------------------
import os
import sys
from PyQt6 import QtCore, QtWidgets, uic

if getattr(sys, 'frozen', False):
    bundle_dir = sys._MEIPASS
else:
    bundle_dir = os.path.dirname(__file__)
DIALOG, _ = uic.loadUiType(os.path.join(bundle_dir, 'filter_dialog.ui'))

class FilterDialog(QtWidgets.QDialog, DIALOG):
    filtered_list = QtCore.pyqtSignal(list)
    BBX_file_selected = QtCore.pyqtSignal(str)

    def __init__(self, data, parent):
        QtWidgets.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle('Filter')
        self.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
        self.activateWindow()
        self.data = data
        self.parent = parent
        self.redisplay_filter_results = False

        self.pb_cancel.clicked.connect(self.close)
        self.pb_filter_confirmed.clicked.connect(self.filter_type)

        self.list_widget = QtWidgets.QListWidget()
        self.list_widget.setWindowTitle('Matching BBX Files')
        self.list_widget.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
        self.list_widget.itemDoubleClicked.connect(self.double_click)

    def double_click(self, item_clicked):
        file_selected = item_clicked.text()

        self.redisplay_filter_results = True

        self.list_widget.close()
        self.close()

        self.BBX_file_selected.emit(file_selected)

    def filter(self):
        input_label = self.input_label.text()
        temp_image_list = []

        if self.cb_flagged.isChecked():
            temp_image_list = temp_image_list + self.data['review']

        if input_label != "":
            for image in self.data['images']:
                ann = self.data['images'][image]['annotations']
                for a in ann:
                    if self.match(input_label, a['label']):
                        temp_image_list.append(image)

        if len(temp_image_list) == 0:
            message = ('No results')
            QtWidgets.QMessageBox.warning(self,
                                          'WARNING',
                                          message,
                                          QtWidgets.QMessageBox.StandardButton.Ok)
        else:
            temp_image_list.sort()
            self.filtered_list.emit(temp_image_list)
            self.close()

    def filterBBX(self):
        if self.data:
            needle = self.input_label.text()
            temp_bbx_list = []
            matches = False

            for bbx_file in self.data:
                if self.cb_flagged.isChecked() and self.data[bbx_file]['flagged_images']:
                    matches = True
                    temp_bbx_list.append(bbx_file)
                    continue
                if needle != '' and bbx_file not in temp_bbx_list:
                    for label in self.data[bbx_file]['labels']:
                        if self.match(needle, label):
                            temp_bbx_list.append(bbx_file)
                            matches = True

            if matches:
                self.list_widget.clear()

                for bbx_file in temp_bbx_list:
                    self.list_widget.addItem(bbx_file)

                # resize widget
                max_width = int(self.parent.width() * .8)
                max_height = int(self.parent.height() * .8)
                width = 300
                height = 100

                width = self.list_widget.sizeHintForColumn(0)
                if width > max_width:
                    width = max_width
                height = self.list_widget.sizeHintForRow(0) * self.list_widget.count()
                if height < 200:
                    height = 200
                elif height > max_height:
                    height = max_height
                width += 25

                # centering widget around filter dialog
                centerX = self.pos().x() + self.width() / 2
                centerY = self.pos().y() + self.height() / 2
                list_widget_posX = int(centerX - width / 2)
                list_widget_posY = int(centerY - height / 2)

                self.list_widget.resize(width, height)
                self.list_widget.move(list_widget_posX, list_widget_posY)
                self.list_widget.show()
            else:
                if self.redisplay_filter_results is False:
                    QtWidgets.QMessageBox.information(self, 'Matching BBX Files', 'No bbx files were found containing the label: {}'.format(needle))

    def filter_type(self):
        if "schema" in self.data:
            self.filter()
        else:
            self.filterBBX()

    def match(self, needle, haystack):
        if self.cb_case_sensitive.isChecked() is False:
            needle = needle.lower()
            haystack = haystack.lower()

        if self.cb_exact_match.isChecked():
            return needle == haystack
        else:
            return needle in haystack

    def redisplay(self):
        if self.redisplay_filter_results:
            # self.show()
            self.filterBBX()
            self.redisplay_filter_results = False


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('monitor', '0023_auto_20151028_1248'),
    ]

    operations = [
        migrations.AddField(
            model_name='projeto',
            name='codIBGE',
            field=models.CharField(default=b'', max_length=10, blank=True),
        ),
    ]


from django.conf.urls import patterns, include, url
from django.contrib import admin
from mysite.views import home, portofolio, project_handler, academic_career,\
    skill_chart, contact, professional_career, anything, blog_list, site_map, \
    search, about_me, add_testimonial, achievement, blog_post

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'PersonalWebsite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^/?$', home),
    url(r'^portofolio/?$', portofolio),
    url(r'^portfolio/?$', portofolio),
    url(r'^skills/?$', portofolio),
    url(r'^abilities/?$', portofolio),
    url(r'^projects/([a-zA-Z0-9_]+)/?$', project_handler),
    url(r'^project/([a-zA-Z0-9_]+)/?$', project_handler),
    url(r'^career/?$', academic_career),
    url(r'^career/academic/?$', academic_career),
    url(r'^career/professional/?$', professional_career),
    url(r'^charts/skill$', skill_chart),
    url(r'^life_of_a_debugger/?$', blog_list),
    url(r'^blog/?$', blog_list),
    url(r'^blog/([a-zA-Z0-9_]+)/?$', blog_post),
    url(r'^life_of_a_debugger/([a-zA-Z0-9_]+)/?$', blog_post),
    url(r'^addtestimonial/?$', add_testimonial),
    url(r'^add_testimonial/?$', add_testimonial),
    url(r'^testimonial_add/?$', add_testimonial),
    url(r'^contact/?$', contact),
    url(r'^aboutme/?$', about_me),
    url(r'^about_me/?$', about_me),
    url(r'^achievements/?$', achievement),
    url(r'^sitemap/?$', site_map),
    url(r'^site_map/?$', site_map),
    url(r'^sitemap.xml$', site_map),
    url(r'^search/?', search),
    url(r'^ashish1294_secret/admin/?$', include(admin.site.urls)),
    url(r'^(.*)$', anything),
)


# -*- coding: utf-8 -*-
"""
Created on Sun Jul 18 14:38:28 2021

@author: aa
"""

# rotates the problem created by mesh2d in fypymesh
import json

nnodex = 65
nnodey = 97

nelem  = (nnodex-1)*(nnodey-1) + (nnodey-1)

with open('linear.json.in','rt') as fin:
    inputfile_dict=json.load(fin)

# need to modify nelem (more traction elements in y-direction)
# gdofn (because nodes in x and y are not equal)
# ideqn,trac and conn

gdofn = 2*nnodex*nnodey - nnodey - 1

ideqn = []
# set x dofs on left edge
# first node constrained in both x and y direction
ideqnno=0
for inodex in range(nnodex):
    for inodey in range(nnodey):
        # first node
        if ((inodex==0) and (inodey==0)):
            ideqn.append([-1,-1])
        # node on the left which is not first node
        elif (inodex==0):
            ideqn.append([-1,ideqnno])
            ideqnno +=1
        else:
            ideqn.append([ideqnno,ideqnno+1])
            ideqnno +=2

# set trac
trac = [[0.0,0.0]]*(nnodex*nnodey)
for inode in range(nnodex*nnodey-nnodey+1,nnodex*nnodey+1):
    trac[inode-1] = [-0.06,0.0]

# set connectivity
conn = inputfile_dict['conn']
conn = conn[:(nnodex-1)*(nnodey-1)]

for inode in range(nnodex*nnodey-nnodey+1,nnodex*nnodey):
    conn.append([inode,inode+1,'linelastrac2d'])

inputfile_dict['nelem']=nelem
inputfile_dict['gdofn']=gdofn
inputfile_dict['ideqn']=ideqn
inputfile_dict['conn']=conn
inputfile_dict['trac']=trac

with open('linear_rotate.json.in','wt') as fout:
    json.dump(inputfile_dict,fout,indent=4)