import cv2
import os
import glob
import numpy
import tensorflow

IMAGES_TO_EXAMINE_FOLDER_PATH = r'images-to-examine/'
MARKED_IMAGES_FOLDER_PATH = r'marked-images/'
CLASSIFIER_PATH = r'classifier-simplified.h5'
IMAGE_SIZE = (24, 22)
DETECTOR_SCALE_FACTOR = 1.2
DETECTOR_MIN_NEIGHBORS = 5

# test function used to calibrate classifier
def show_image_with_indications():
	image = cv2.imread(MARKED_IMAGES_FOLDER_PATH + 'test1.jpg')
	classifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

	boxes = classifier.detectMultiScale(image, DETECTOR_SCALE_FACTOR, DETECTOR_MIN_NEIGHBORS)
	for box in boxes:
		x, y, width, height = box
		x2, y2 = x + width, y + height
		cv2.rectangle(image, (x, y), (x2, y2), (0,0,255), 1)

	cv2.imshow('TEST', image)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

def clear_marked_images_folder():
	files = glob.glob(MARKED_IMAGES_FOLDER_PATH + '*.jpg')
	files.append
	for f in files:
         os.remove(f)

def resize_image(image: any, x: int, x2: int, y: int, y2: int):
	spread = 0
	cropped_image = image[y - spread : y2 + spread, x - spread : x2 + spread]

	return cv2.resize(cropped_image, IMAGE_SIZE, interpolation = cv2.INTER_AREA).reshape(1, 24, 22, 3)

def examine_image(image_name: str, image_path: str, model):
	image = cv2.imread(image_path)

	cascade_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

	# get boxes containing faces
	boxes = cascade_classifier.detectMultiScale(image, DETECTOR_SCALE_FACTOR, DETECTOR_MIN_NEIGHBORS)

	for box in boxes:
		x, y, width, height = box
		x2, y2 = x + width, y + height

		# get image fragment containing face in appropriate shape
		face_fragment = resize_image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), x, x2, y, y2)

		# 0 - with, 1 - without
		pred = model.predict(face_fragment, verbose=0)

		color = (0,255,0)
		if numpy.argmax(pred, axis=1)[0] == 1:
			color = (0,0,255)

		cv2.rectangle(image, (x, y), (x2, y2), color, 5)

	# copy image to marked-images folde
	os.chdir(MARKED_IMAGES_FOLDER_PATH)
	cv2.imwrite('marked-' + image_name, image)
	os.chdir('..')

def main():
	clear_marked_images_folder()

	# get images to examine
	images_names = list(filter(lambda k: 'jpg' in k, os.listdir(IMAGES_TO_EXAMINE_FOLDER_PATH)))
	images_paths = [IMAGES_TO_EXAMINE_FOLDER_PATH + path for path in images_names]

	# load classifier
	model = tensorflow.keras.models.load_model(CLASSIFIER_PATH)

	for name, path in zip(images_names, images_paths):
		examine_image(name, path, model)

# ==========================================================================================================

main()


import copy
import os, sys
import json
import numpy as np
import torch.utils.data as data
import cv2
import scipy.misc
sys.path.append("..")
from utils import (bbox_clip_xyxy, bbox_xywh_to_xyxy, draw_origin_joints,
                cam2pixel, draw_origin_joints_index)

from transform import SimpleTransform3D

class MirrorDataset(data.Dataset):
    #               [0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17]
    HUMAN36_INDEX = [8,  9, 10, 11, 12, 13, 14,  0,  0,  0,  0,  5,  6,  7,  2,  3,  4,  1]
    VIS_MASK      = [1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1]
    bbox_3d_shape = (2000, 2000, 2000)
    joints_name = ('Pelvis',  # 0
                   'R_Hip', 'R_Knee', 'R_Ankle',  # 3
                   'L_Hip', 'L_Knee', 'L_Ankle',  # 6
                   'Torso', 'Neck',  # 8
                   'Nose', 'Head',  # 10
                   'L_Shoulder', 'L_Elbow', 'L_Wrist',  # 13
                   'R_Shoulder', 'R_Elbow', 'R_Wrist',  # 16
                   'Thorax')  # 17
    skeleton = ((1, 0), (2, 1), (3, 2),  # 2
                (4, 0), (5, 4), (6, 5),  # 5
                (7, 0), (8, 7),  # 7
                (9, 8), (10, 9),  # 9
                (11, 7), (12, 11), (13, 12),  # 12
                (14, 7), (15, 14), (16, 15),  # 15
                (17, 7))  # 16
    def __init__(self,
                root,
                cfg,
                train=True,
                skip_empty=True,
                dpg=False,
                **kwargs):
        self._root = root
        self._preset_cfg = cfg.DATA_PRESET
        self.protocol = self._preset_cfg.PROTOCOL
        self._train = train
        self._dpg = False
        self._loss_type = self._preset_cfg.HEATMAP2COORD

        self._ann_file_dir = os.path.join(self._root, "annots")
        self._img_file_dir = os.path.join(self._root, "images")
        self._k3d_file_dir = os.path.join(self._root, "keypoints3d")
        self._smpl_file_dir = os.path.join(self._root, "smpl")

        self._scale_factor = self._preset_cfg.SCALE_FACTOR
        self._color_factor = self._preset_cfg.COLOR_FACTOR
        self._rot = self._preset_cfg.ROT_FACTOR
        self._input_size = self._preset_cfg.IMAGE_SIZE
        self._output_size = self._preset_cfg.HEATMAP_SIZE
        self._occlusion = self._preset_cfg.OCCLUSION
        self._sigma = self._preset_cfg.SIGMA
        self._check_centers = False
        self.num_joints = self._preset_cfg.NUM_JOINTS

        self.num_joints_half_body = self._preset_cfg.NUM_JOINTS_HALF_BODY
        self.prob_half_body = self._preset_cfg.PROB_HALF_BODY

        self._loss_type = self._preset_cfg.HEATMAP2COORD

        self.upper_body_ids = (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)
        self.lower_body_ids = (0, 1, 2, 3, 4, 5, 6)

        self.root_idx = self.joints_name.index('Pelvis')
        self.lshoulder_idx = self.joints_name.index('L_Shoulder')
        self.rshoulder_idx = self.joints_name.index('R_Shoulder')

        self._items = self._load_jsons()

        if self._preset_cfg.TYPE == 'simple_3d':
            self.transformation = SimpleTransform3D(
                self, scale_factor=self._scale_factor,
                color_factor=self._color_factor,
                occlusion=self._occlusion,
                input_size=self._input_size,
                output_size=self._output_size,
                bbox_3d_shape=self.bbox_3d_shape,
                rot=self._rot, sigma=self._sigma,
                train=self._train, add_dpg=self._dpg,
                loss_type=self._loss_type, scale_mult=1)

        pass

    def _load_jsons(self):
        items = []

        img_dirs = os.listdir(self._img_file_dir)
        print(len(img_dirs))

        count = 0
        for _dir in img_dirs:
            img_dir = os.path.join(self._img_file_dir, _dir)
            ann_dir = os.path.join(self._ann_file_dir, _dir)
            k3d_dir = os.path.join(self._k3d_file_dir, _dir)
            smpl_dir = os.path.join(self._smpl_file_dir, _dir)

            img_list = os.listdir(img_dir)

            for _img_file in img_list:
                _id = _img_file.split('.')[0]
                _json = _id + '.json'
                _img_path = os.path.join(img_dir, _img_file)
                _ann_path = os.path.join(ann_dir, _json)
                _k3d_path = os.path.join(k3d_dir, _json)
                _smpl_path = os.path.join(smpl_dir, _json)

                with open(_ann_path, 'r') as f:
                    _ann_data = json.load(f)

                with open(_k3d_path, 'r') as f:
                    _k3d_data = json.load(f)

                with open(_smpl_path, 'r') as f:
                    _smpl_data = json.load(f)

                for i in range(len(_ann_data['annots'])):
                    #print(_img_path)

                    #keypoints2d = np.array(_ann_data['annots'][i]['keypoints'])
                    keypoints3d = np.array(_k3d_data[i]['keypoints3d'])
                    cameraK = np.array(_ann_data['K'])
                    f = [cameraK[0,0],cameraK[1,1]]
                    c = [cameraK[0,2],cameraK[1,2]]
                    joint_cam = keypoints3d[self.HUMAN36_INDEX]
                    joint_img = cam2pixel(joint_cam, f, c)
                    joint_img[:, 2] = joint_img[:, 2] - joint_cam[self.root_idx, 2]
                    joint_vis = np.ones((self.num_joints, 3))  #(18,3)
                    for j in range(joint_vis.shape[0]):
                        if self.VIS_MASK[j] == 0:
                            joint_vis[j, :] = 0

                    width = _ann_data['width']
                    height = _ann_data['height']

                    item = {
                        "img_id": count,
                        "img_path": _img_path,
                        "width": width,
                        "height": height,
                        "bbox": _ann_data['annots'][i]['bbox'][:4],
                        "joint_img": joint_img,
                        "joint_vis": joint_vis,
                        "joint_cam": joint_cam,
                        #"keypoints2d": np.array(_ann_data['annots'][i]['keypoints']),
                        #"keypoints3d": np.array(_k3d_data[i]['keypoints3d']),
                        "smpl": _smpl_data[i],
                        "cameraK": cameraK,
                        #"vanish_line": _ann_data['vanish_line'],
                        #"vanish_point": _ann_data['vanish_point']
                    }

                    count += 1

                    items.append(item)
        print(len(items))
        return items

    def __getitem__(self, idx):
        # get image id
        item = copy.deepcopy(self._items[idx])
        img_path = item["img_path"]
        img_id = item["img_id"]

        img = scipy.misc.imread(img_path, mode='RGB')
        # img = load_image(img_path)
        # img = cv2.imread(img_path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)

        # transform ground truth into training label and apply data augmentation
        target = self.transformation(img, item)
        img = target.pop('image')
        bbox = target.pop('bbox')
        return img, target, img_id, bbox

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

    @property
    def joint_pairs(self):
        """Joint pairs which defines the pairs of joint to be swapped
        when the image is flipped horizontally."""
        return ((1, 4), (2, 5), (3, 6), (14, 11), (15, 12), (16, 13))

    @property
    def bone_pairs(self):
        """Bone pairs which defines the pairs of bone to be swapped
        when the image is flipped horizontally."""
        return ((0, 3), (1, 4), (2, 5), (10, 13), (11, 14), (12, 15))

if __name__ == '__main__':
    dataset = MirrorDataset("/home/xyh/dataset/mirrored-human-base")
    #dataset._load_jsons()
    item = dataset._items[501]
    print(item["joint_vis"])
    img_path = item['img_path']
    print(img_path)
    img = scipy.misc.imread(img_path, mode='RGB')
    #keypoints2d = item['keypoints2d']
    keypoints3d = item['joint_cam']
    K = item['cameraK']
    f = [K[0,0],K[1,1]]
    c = [K[0,2],K[1,2]]

    coord = cam2pixel(keypoints3d, f, c)

    #print(coord)

    #draw_origin_joints(img, keypoints2d, output="keypoint2d.png")
    #draw_origin_joints(img, coord, output="cam2pixel.png")

    print(coord.shape)

    for i in range(coord.shape[0]):
        save_img = "k3d_%d.png" % i
        draw_origin_joints_index(img, coord, index=i, output=save_img)


import keras
import math
import numpy as np

from typing import List, Callable, Dict, Tuple, Optional, Collection

class DataSequence(keras.utils.Sequence):
    x: List
    batch_size: int
    length: int
    shuffle: bool
    keep_remainder: bool
    map_fn: Callable
    batches: List[Tuple[int, int]]
    indices: np.ndarray

    def __init__(self,
                 x: Collection,
                 batch_size: int = 32,
                 shuffle: bool = True,
                 map_fn: Optional[Callable] = None,
                 keep_remainder: bool = True) -> None:
        assert isinstance(batch_size, int) and batch_size > 0
        self.batch_size = batch_size
        self.shuffle = bool(shuffle)
        self.keep_remainder = bool(keep_remainder)
        data_length = len(x)  # Implicitly check that x has length
        self.x = list(x)
        # self.map_fn = (lambda inputs, labels: (inputs, labels)) if map_fn is None else map_fn
        self.map_fn = map_fn
        assert callable(self.map_fn)
        if self.keep_remainder:
            self.length = math.ceil(data_length / batch_size)
        else:
            self.length = math.floor(data_length / batch_size)
        assert self.length > 0  # There are some batches to iterate through

        self.batches = [(i * batch_size, min(data_length, (i + 1) * batch_size)) for i in range(self.length)]
        self.indices = np.arange(data_length)
        if self.shuffle:
            np.random.shuffle(self.indices)

    def __getitem__(self, index: int):
        batch_start, batch_end = self.batches[index]
        batch_indices = self.indices[batch_start:batch_end]
        return self.map_fn([self.x[i] for i in batch_indices])

    def __len__(self):
        return self.length

    def on_epoch_end(self):
        if self.shuffle:
            np.random.shuffle(self.indices)


#! /usr/bin/env python3

import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "BrownBat",
    version = "0.0b2",
    author = "Douglas RAILLARD",
    author_email = "public.douglas.raillard@gmail.com",
    description = "A lazy source code generation library",
    long_description=read('README.rst'),
    license = "GNU Lesser General Public License v3 or later (LGPLv3+)",
    keywords = "source generation lazy code meta",
    url = "https://github.com/DouglasRaillard/BrownBat",
    packages = ['brownbat'],
    classifiers=[
        "Operating System :: OS Independent",
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
        "Programming Language :: Python :: 3 :: Only",
        "Topic :: Software Development :: Code Generators",
    ],
)


#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib.request, json, pickle, urllib, os, re

# Open the pickle, and load it into the dict
with open('ponyFMdb.pickle', 'rb') as handle:
	dict = pickle.load(handle)

currentFile = ""
currentNum = 1

try:
	# For each item in the pickle...
	for key, value in dict.items():
		streams = value['streams']
		dlLink = streams['mp3']
		track  = str(value['id'])

		# Check if file exists (already downloaded)
		currentFile = "dl/" + track + ".mp3"
		if not os.path.isfile(currentFile):
			# OK then, actually download the song now!
			try:
				testfile = urllib.request.URLopener()
				urllib.request.urlretrieve(dlLink, currentFile )
				print (track + " done! (" + str(currentNum) + " of " + str(len(dict)) + ")")
			except Exception:
				try:
					# Not sure why, but there's actually a lot of corrupt songs.
					# I contacted the site owner, but they didn't seem to care?
					print (track + " failed: " + value['title'])
				except Exception:
					print ("Printing the name of the file that failed has failed.")
		currentNum += 1
# If you ctrl-C it, remove the partially-downloaded file.
except KeyboardInterrupt:
	os.remove(currentFile)


"""Contains functions which provide corresponding name and remedy of ICP numbers."""
from collections import namedtuple
from importlib.resources import files
from pathlib import PurePath
from functools import lru_cache
import csv
from edcon.utils.logging import Logging

@lru_cache
def read_icp_map_file(icp_map_file: str = None):
    """Creates a dict based on a provided ICP name map file

    Parameters:
        icp_map_file (str): Optional file to use for mapping.
                                 If nothing provided try to load mapping shipped with package.
    Returns:
        dict: With the first column values as keys and namedtuple values
    """
    if not icp_map_file:
        icp_map_file = PurePath(files('edcon') / 'edrive' / 'data' / 'icp_map.csv')

    with open(icp_map_file, encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile, delimiter=';')
        # Define a namedtuple where the header row determines the field names
        icp_item = namedtuple('icp_item', next(reader, None))
        # Create a dict where the first column determines the key
        icp_name_dict = {int(row[0]): icp_item(*row) for row in reader}
    return icp_name_dict

def diagnosis_name(icp_number: int, icp_map_file: str = None) -> str:
    """Determines the corresponding name to a provided icp_number, can be
       determined either via a provided icp_map_file or
       by the icp_map_file shipped with the package.

    Parameters:
        icp_number (int): ICP number whose name should be determined.
        icp_map_file (str): Optional file name for icp_map.
                                 By default installed icp_map file is used.
    Returns:
        value: Name of corresponding ICP
    """
    icp_map = read_icp_map_file(icp_map_file)
    if not icp_number in icp_map.keys():
        Logging.logger.error(f'No entry for ICP {icp_number}')
    return icp_map[icp_number].name

def diagnosis_remedy(icp_number: int, icp_map_file: str = None) -> list:
    """Determines the corresponding remedies to a provided icp_number, can be
       determined either via a provided icp_map_file or
       by the icp_map_file shipped with the package.

    Parameters:
        icp_number (int): ICP number whose remedy should be determined.
        icp_map_file (str): Optional file name for icp_map.
                                 By default installed icp_map file is used.
    Returns:
        value: List of str containing potential remedies for the corresponding ICP
    """
    icp_map = read_icp_map_file(icp_map_file)
    if not icp_number in icp_map.keys():
        Logging.logger.error(f'No entry for ICP {icp_number}')
    remedy_list = [x.strip('-')
                   for x in icp_map[icp_number].remedy.split('\n')]
    return remedy_list


from django.conf.urls import url,include
from django.urls import path
import django.contrib.auth.views
from . import views
from .models import CS096
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'product', views.ProductViewSet)

urlpatterns = [

        path('', views.CS096ListView.as_view(), name='entry_list'),
        path('add/', views.CS096CreateView.as_view(), name='entry_add'),
        path('user/<int:pk>/', views.AddUserView.as_view(), name='user_add'),
        path('details/<int:pk>/',views.CS096UpdateView.as_view(), name='entry_update'),
        path('ajax/load-protocols/', views.load_protocols, name='ajax_load_protocols'),
        path('delete/<int:pk>/',views.CS096DeleteView.as_view(), name='entry_delete'),
        url(r'^', include(router.urls)),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
        path('user_details/<int:pk>/', views.CS096UpdateUserView.as_view(), name='user_update'),
        path('user_delete/<int:pk>/', views.CS096DeleteUserView.as_view(), name='user_delete'),

]


import sys

sys.setrecursionlimit(10 ** 5)
arr = [1, 2, 3]

def ott_sum(k, cnt):
    result = 0
    if k == 0:
        return 1
    else:
        for j in arr:
            if j <= k:
                result += ott_sum(k - j, cnt + 1)

    return result

n = int(input())
for i in range(n):
    num = int(input())
    print(ott_sum(num, 0))


import unittest
import numpy as np
import src.feature_extraction as fe
import src.signal_process_tools as spt
import pandas as pd

class TestFeatureExtraction(unittest.TestCase):
    def setUp(self):
        self.data = np.array(np.loadtxt('../dataFeb/AmplitudeNov19_2stand.out', dtype=float, delimiter=','))

    def test_extract_features(self):
        feature_funcs = {
            'velocity': fe.extract_velocity_features,
            'acceleration': fe.extract_acceleration_features,
            'amplitude': fe.extract_amplitude_features,
            'frequency': fe.extract_frequency_features
        }
        feature_extractor = fe.FeatureExtractor(
            feature_functions=feature_funcs
        )
        print(feature_extractor.generate([1,2,3]))

    def test_learning_pd(self):
        mock_dic = {'1':[],'2':[],'3':[]}
        dt = pd.DataFrame(columns=mock_dic.keys())
        dt.to_csv('test')

if __name__ == '__main__':
    unittest.main()


from openpyxl import load_workbook
import os.path
from openpyxl.styles import NamedStyle, Font, colors
from ProjVar.var import *
from Util.fromattime import *

class Excel:
    def __init__(self, excel_file_path):
        self.sheet = None
        self.column_num = None
        self.row_num = None
        if os.path.exists(excel_file_path):
            self.excel_file_path = excel_file_path
            self.wb = load_workbook(self.excel_file_path)
        else:
            print("%s e文件的路劲不存在，请重新设定！" % excel_file_path)

    # 通过sheet名字来获取操作的sheet
    def set_sheet_by_name(self, sheet_name):
        if sheet_name in self.wb.sheetnames:
            self.sheet = self.wb[sheet_name]
        else:
            print("%s sheet不存在，请重新指定！" % sheet_name)

    # 通过序号来获取操作的sheet
    def set_sheet_by_index(self, index):
        if isinstance(index, int) and 1 <= index <= len(self.get_all_sheet_names()):
            sheet_name = self.get_all_sheet_names()[index - 1]
            self.sheet = self.wb[sheet_name]
        else:
            print("%s sheet 序号不存在，请重新设定" % index)

    # 获取当前sheet和title的名称
    def get_current_sheet_name(self):
        return self.sheet.title

    # 获取所有sheet的名称
    def get_all_sheet_names(self):
        return self.wb.sheetnames

    # 获取sheet的总行数，从0开始，返回list
    def get_rows_object(self):
        return list(self.sheet.rows)

    # 获取sheet的总列数，从0开始，返回list
    def get_cols_object(self):
        return list(self.sheet.columns)

    # 获取某行的对象，第一行从0开始
    def get_row(self, row_no):
        return self.get_rows_object()[row_no]

    def get_excel_value_list(self, row_no):
        row = self.get_row(row_no)
        row_value_dic = {}
        if self.column_num:
            for i in range(self.column_num):
                row_value_dic[row[i].value]=i
        return row_value_dic

    # 获取某一列对象，第一列从0开始
    def get_col(self, col_no):
        return self.get_cols_object()[col_no]

    # 获取某个单元格对象
    def get_cell_value(self, row_no, col_no):
        if isinstance(row_no, int) and isinstance(col_no, int) and \
                1 <= row_no <= len(self.get_rows_object()) and \
                1 <= row_no <= len(self.get_cols_object()):
            return self.sheet.cell(row=row_no, column=col_no).value
        else:
            print("%s,%s 行号或者列号不存在，请重新设定行号或者列表读取！" % (row_no, col_no))

    # 给某一个单元格写入指定内容，行号、列号从1开始
    # 调用此方法时，excel不要处于打开状态
    def write_cell_value(self, row_no, col_no, value, color=None):
        if isinstance(row_no, int) and isinstance(col_no, int):
            if color is None:
                font = Font(bold=False, size=10, color=colors.BLACK)
                self.sheet.cell(row=row_no, column=col_no).font = font
                self.sheet.cell(row=row_no, column=col_no).value = value
            elif color == "green":
                font = Font(bold=True, size=13, color=colors.GREEN)
                self.sheet.cell(row=row_no, column=col_no).font = font
                self.sheet.cell(row=row_no, column=col_no).value = value
            elif color == "red":
                font = Font(bold=True, size=13, color=colors.RED)
                self.sheet.cell(row=row_no, column=col_no).font = font
                self.sheet.cell(row=row_no, column=col_no).value = value
            self.wb.save(self.excel_file_path)
        else:
            print("%s,%s 行号或者列号不是数字，请重新设定行号或者列表读取！" % (row_no, col_no))

    def write_current_time(self, row_no, col_no):
        if isinstance(row_no, int) and isinstance(col_no, int):
            self.sheet.cell(row=row_no, column=col_no).value = get_current_date_and_time()
            self.wb.save(self.excel_file_path)

if __name__ == "__main__":
    pass


from tkinter import *

class MyApp:

    def __init__(self):
        self.window = Tk()
        self.window.title("MAGESTI")
        self.screen_x = self.window.winfo_screenwidth()
        self.screen_y = self.window.winfo_screenheight()
        self.window_x = 700
        self.window_y = 300
        self.pos_x = (self.screen_x//2)-(self.window_x//2)
        self.pos_y = (self.screen_y//2)-(self.window_y//2)
        geo=f"{self.window_x}x{self.window_y}+{self.pos_x//2}+{self.pos_y//2}"
        self.window.geometry(geo)
        self.window.resizable(width='False', height='False')
        self.window.iconbitmap("")
        self.window.config(background='#7a1f5c')

        # initialization des composants
        self.frame = Frame(self.window, bg='#7a1f5c')

        # creation des composants
        self.create_widgets()

        # empaquetage
        self.frame.pack(expand=YES)

    def create_widgets(self):
        self.create_title()
        self.create_subtitle()
        self.create_button()

    def create_title(self):
        label_title = Label(self.frame, text="Bienvenue sur l'application MAGESTI", font=("Courrier", 30), bg='#7a1f5c',
                            fg='white')
        label_title.pack()

    def create_subtitle(self):
        label_subtitle = Label(self.frame, text="c'est une application pour gérer les dossiers des patientes;dévélopper par RAKOTONDRANIVO R Flavien", font=("Courrier", 10), bg='#7a1f5c',
                               fg='white')
        label_subtitle.pack()

    def create_button(self):
        start_button = Button(self.frame, text="Demarrer", font=("Courrier", 20), bg='white', fg='#7a1f5c',
                           command=self.page_login)
        start_button.pack(pady=25, fill=X)

    def page_login(self):
        self.window.destroy()
        import registre_login

# afficher
app = MyApp()
app.window.mainloop()


import pyautogui,cv2,numpy as np,time,tkinter
from tkinter import simpledialog
def ask_for_field_status():
    return "sow"
    root=tkinter.Tk()
    root.withdraw()
    return simpledialog.askstring("Input","If fields are already sown enter: sow\nelse enter: harvest")

def check_ad(last_time):
    if last_time==0:
        return time.time(),1
    else:
        if time.time()-last_time>=300:
            return time.time(),1
        else:
            return 0,0

def ask_for_wheat_count():
    return 500
    root=tkinter.Tk()
    root.withdraw()

    top_level = tkinter.Toplevel(root)
    top_level.title("Input")
    # top_level.attributes("-topmost", True)
    top_level.grab_set()
    top_level.focus_force()

    return simpledialog.askinteger("Input","How much wheat you have")

def find_image(image_path):
    template = cv2.imread(image_path)
    # template = cv2.cvtColor(template, cv2.COLOR_RGB2BGR)
    template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
    screenshot = pyautogui.screenshot()
    # screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_BGR2GRAY)
    result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    if(max_val<0.7):
        return None
    else:
        top_left = max_loc
        bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
        center_x = (top_left[0] + bottom_right[0]) // 2
        center_y = (top_left[1] + bottom_right[1]) // 2

        return (center_x,center_y)

def find_image_lp(image_path):
    template = cv2.imread(image_path)

    screenshot = pyautogui.screenshot()
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

    result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    top_left = max_loc
    bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
    center_x = (top_left[0] + bottom_right[0]) // 2
    center_y = (top_left[1] + bottom_right[1]) // 2
    return (center_x,center_y)

def find_shop():
    shop=None
    while shop is None:
        shop=find_image_lp("shop_unsold.png")
        if shop is None:
            shop=find_image_lp("shop_sold.png")
    return shop

def calibrate_field(cur_op,start):
    field_location=None
    if cur_op=="sow":
        # print("c")
        field_location=find_image("full_fields.png")
    else:
        field_location=find_image("empty_fields.png")
    # print("d")
    pyautogui.moveTo(field_location,duration=2)
    pyautogui.mouseDown(button='left')
    # time.sleep(0.001)
    pyautogui.moveTo(start,duration=4)
    # time.sleep(0.5)
    pyautogui.mouseUp(button='left')
    pyautogui.moveTo(start[0],start[1]+50,duration=1)
    pyautogui.click(pyautogui.position())
    pyautogui.moveTo(start,duration=1)

# from pynput.keyboard import Listener as keyboardlistener,Key
# from pynput.mouse import Listener as mouselistener

# start_implementation=""

# def on_press(key):
#     global start_implementation
#     if key==Key.space:
#         start_implementation=" "
#         keyboardlistener.stop()

# def on_click(x,y,button,pressed):
#     global start
#     if pressed:
#         if start is None:
#             start=(x,y)
#             mouselistener.stop()

# with keyboardlistener(on_press=on_press) as keyboardlistener:
#     keyboardlistener.join()

# if start_implementation==" ":
#     with mouselistener(on_click=on_click) as mouselistener:
#         mouselistener.join()
#     time.sleep(3)
#     calibrate_field("sow")


#
#
#

from __future__ import absolute_import, division, print_function, \
    unicode_literals

from six import text_type

from ..source.base import BaseSource
from ..zone import Zone
from .plan import Plan

class BaseProvider(BaseSource):

    def __init__(self, id, apply_disabled=False,
                 manage_root_ns=False,
                 update_pcent_threshold=Plan.MAX_SAFE_UPDATE_PCENT,
                 delete_pcent_threshold=Plan.MAX_SAFE_DELETE_PCENT):
        super(BaseProvider, self).__init__(id)
        self.log.debug('__init__: id=%s, apply_disabled=%s, '
                       'update_pcent_threshold=%.2f, '
                       'delete_pcent_threshold=%.2f',
                       id,
                       apply_disabled,
                       update_pcent_threshold,
                       delete_pcent_threshold)
        self.apply_disabled = apply_disabled
        self.manage_root_ns = manage_root_ns
        self.update_pcent_threshold = update_pcent_threshold
        self.delete_pcent_threshold = delete_pcent_threshold

    def _check_root_ns(self, change):
        '''
        Checks ability for provider root NS support.
        '''

        return not (change.record._type == 'NS' and
                    change.record.name == '' and
                    not (self.SUPPORTS_ROOT_NS and
                         self.manage_root_ns))

    def _include_change(self, change):
        '''
        An opportunity for providers to filter out false positives due to
        peculiarities in their implementation. E.g. minimum TTLs.
        '''
        return True

    def _extra_changes(self, existing, desired, changes):
        '''
        An opportunity for providers to add extra changes to the plan that are
        necessary to update ancillary record data or configure the zone. E.g.
        base NS records.
        '''
        return []

    def plan(self, desired):
        self.log.info('plan: desired=%s', desired.name)

        existing = Zone(desired.name, desired.sub_zones)
        exists = self.populate(existing, target=True, lenient=True)
        if exists is None:
            # If your code gets this warning see Source.populate for more
            # information
            self.log.warn('Provider %s used in target mode did not return '
                          'exists', self.id)

        # compute the changes at the zone/record level
        changes = existing.changes(desired, self)

        # allow the provider to filter out false positives
        before = len(changes)
        changes = [c for c in changes if self._include_change(c) and
                   self._check_root_ns(c)]
        after = len(changes)
        if before != after:
            self.log.info('plan:   filtered out %s changes', before - after)

        # allow the provider to add extra changes it needs
        extra = self._extra_changes(existing=existing, desired=desired,
                                    changes=changes)
        if extra:
            self.log.info('plan:   extra changes\n  %s', '\n  '
                          .join([text_type(c) for c in extra]))
            changes += extra

        if changes:
            plan = Plan(existing, desired, changes, exists,
                        self.update_pcent_threshold,
                        self.delete_pcent_threshold)
            self.log.info('plan:   %s', plan)
            return plan
        self.log.info('plan:   No changes')
        return None

    def apply(self, plan):
        '''
        Submits actual planned changes to the provider. Returns the number of
        changes made
        '''
        if self.apply_disabled:
            self.log.info('apply: disabled')
            return 0

        self.log.info('apply: making changes')
        self._apply(plan)
        return len(plan.changes)

    def _apply(self, plan):
        raise NotImplementedError('Abstract base class, _apply method '
                                  'missing')


#!/usr/bin/python
#-*- coding: utf8 -*-
#报数改进版
#from leetcode-StefanPochmann
import re
class Solution:
    def countAndSay(self, n):
        s = '1'
        for _ in range(n - 1):
            s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s)
        return s
solution=Solution()
output=solution.countAndSay(5)
print(output)


from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import re
import sys

imgw=0
imgh=0
scalex=0
scaley=0
#img = Image.new("RGB",(300,300),"red")
#img.save("./test.jpg")

def getScale(width, height, lines):
    wordnum=0
    for line in lines:
        words = re.split(":", line)
        if (len(words) != 2) :
            print("Error : The format is not correct")
            exit()
        words[1]=line
        if (wordnum <= len(words[1])):
            wordnum = len(words[1])
    scale_x = width / (wordnum+1)
    scale_y = height / len(lines)
    return int(scale_x), int(scale_y)

def drawText(img,basex,basey,word):
    do = ImageDraw.Draw(img)
    fontsize=int(scalex*2)
    font = ImageFont.truetype("mplus-1p-regular.ttf", fontsize)
    do.text((basex,basey),word,fill="black",font=font)

def drawChart(img,basex,basey,line):
    do = ImageDraw.Draw(img)
    scaley2 = scaley * 7 / 10
    wid=int(scaley/20)
    fontsize=int(scalex*2)
    font = ImageFont.truetype("mplus-1p-regular.ttf", fontsize)
    preword=""
    textbuf=""
    textanc=basex+(scalex/2)
    for i in range(len(line)):
        word=line[i]
        if (word == "_"):
            if (preword == "~"):
                do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            elif (preword == "-"):
                do.line([(basex+scalex*i,basey), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey+(scaley2/2)), (basex+scalex*(i+1),basey+(scaley2/2))], fill="black", width=wid)
        elif (word == "~"):
            if (preword == "_"):
                do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            elif (preword == "-"):
                do.line([(basex+scalex*i,basey), (basex+scalex*i,basey-(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*(i+1),basey-(scaley2/2))], fill="black", width=wid)
        elif (word == "-"):
            if (preword == "_"):
                do.line([(basex+scalex*i,basey), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            elif (preword == "~"):
                do.line([(basex+scalex*i,basey), (basex+scalex*i,basey-(scaley2/2))], fill="black", width=wid)
            elif (preword == "="):
                do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey), (basex+scalex*(i+1),basey)], fill="black", width=wid)
        elif (word == "="):
            if (textbuf != ""):
                do.text((textanc,basey-scaley2/2),textbuf,fill="black",font=font)
                textbuf=""
            do.line([(basex+scalex*i,basey+(scaley2/2)), (basex+scalex*(i+1),basey+(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*(i+1),basey-(scaley2/2))], fill="black", width=wid)
        else:
            if ((preword == "=") or (preword == "-")):
                textanc=(basex+scalex*i+scalex/2)
                do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*i,basey+(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey+(scaley2/2)), (basex+scalex*(i+1),basey+(scaley2/2))], fill="black", width=wid)
            do.line([(basex+scalex*i,basey-(scaley2/2)), (basex+scalex*(i+1),basey-(scaley2/2))], fill="black", width=wid)
            textbuf=textbuf+word
        preword=word

if __name__ == '__main__':
    if (len(sys.argv) != 2) :
        print("Error : Argument is not correct.")
        exit()
    srcpath = sys.argv[1]
    srcfp = open(srcpath)
    lines = srcfp.readlines()
    srcfp.close()

    for i in range(len(lines)):
        lines[i] = lines[i].replace('\r', '')
        lines[i] = lines[i].replace('\n', '')
        #line = line.rstrip('\n')

    ## Info Check
    line = lines.pop(0)
    words = re.split(",", line)
    imgw = int(words[0])
    imgh = int(words[1])
    img = Image.new("RGB",(imgw,imgh),"white")
    scalex, scaley = getScale(imgw,imgh,lines)
    print("----------------")
    print("sizeX :"+str(imgw)+" sizeY :"+str(imgh))
    print("scaleX:"+str(scalex)+" scaleY:"+str(scaley))
    print("----------------")

    ##
    for i in range(len(lines)):
        line = lines[i]
        words = re.split(":", line)
        if (len(words) != 2) :
            print("Error : The format is not correct")
            exit()
        print(words[1])
        drawText(img,scalex/2,(scaley*i)+(scaley/8),words[0])
        drawChart(img,scalex*(len(words[0])+1),(scaley*i)+(scaley/2),words[1])
    img.save("./chart.jpg")


import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = '20'

# helper functions
def getXY(matrix, type):
    try:
        x_data = []
        y_data = []

        if type == 1:
            for val in matrix:
                x_data.append(val[0])
                y_data.append(val[1])
        elif type == 2:
            for val in matrix:
                x_data.append(val[2])
                y_data.append(val[3]/val[2])

        return [x_data, y_data]
    except:
        print("Failed to get X and Y coordinates. Check dimensions of matrix passed, it must be of Nx2 size.")
        exit()

def getNormalFuncFirstOrder(data, partnum):
    [x, y] = getXY(data, 1)

    # make A and B matrices
    mat_a = np.empty((0, 2), dtype=float)
    for i in range(len(x)):
        mat_a = np.append(mat_a, np.array([[x[i], 1]]), axis=0)

    mat_a = np.matrix(mat_a)
    mat_b = np.matrix(y, dtype=float).getT()

    # show data as it appears
    plt.scatter(x, y, marker='o')

    plt.xlabel('x-axis', fontsize=30)
    plt.ylabel('y-axis', fontsize=30)
    plt.title('Part ' + str(partnum), fontsize=32)
    # plt.show()

    mat_x = (mat_a.getT() * mat_a)
    mat_x = np.linalg.inv(mat_x)
    mat_x = mat_x * mat_a.getT() * mat_b

    print('Solution to normal equation in part ' + str(partnum) + ':')
    print(mat_x)
    print()

    # get form of y = m*x + b
    m = float(mat_x[0])
    b = float(mat_x[1])

    x2 = np.linspace(min(x), max(x), 100)
    y2 = m * x2 + b

    plt.plot(x2, y2, 'r')
    plt.ylim([0, 15])

    plt.xlim([4, 10])
    plt.show()
    plt.close()

def getNormalFuncInvX(data, partnum):
    [x, y] = getXY(data3, 2)

    # make A and B matrices
    mat_a = np.empty((0, 2), dtype=float)
    for i in range(len(x)):
        mat_a = np.append(mat_a, np.array([[1 / x[i], 1]]), axis=0)

    mat_a = np.matrix(mat_a)
    mat_b = np.matrix(y, dtype=float).getT()

    # show data as it appears
    plt.scatter(x, y, marker='.')
    #plt.grid()

    plt.xlabel('# of Bites', fontsize=30)
    plt.ylabel('Kcals/bite', fontsize=30)
    plt.title('Part ' + str(partnum), fontsize=32)

    mat_x = (mat_a.getT() * mat_a)
    mat_x = np.linalg.inv(mat_x)
    mat_x = mat_x * mat_a.getT() * mat_b

    print('Solution to normal equation in part ' + str(partnum) + ':')
    print(mat_x)
    print()

    # get form of y = m*(1/x) + b
    m = float(mat_x[0])
    b = float(mat_x[1])

    x2 = np.linspace(0.5, max(x), 10000)
    y2 = m * (1 / x2) + b

    plt.xlim([-10, 200])
    plt.ylim([-10, 150])
    # plt.yscale("log")
    # plt.xscale("log")
    plt.plot(x2, y2, 'r')

    plt.show()
    plt.close()

def readData(file_in):

    fpt = ''  # fixes error in IDE of fpt not existing in scope (try/except will never allow for it to not be in scope)
    try:
        fpt = open(file_in)
    except:
        print(file_in + ' could not be opened. Check the filename and try again.')
        exit()
    try:
        file_array = []

        for line in fpt.readlines():
            temp_array = line.replace('\n', '').split(' ')
            for i in range(len(temp_array)):
                temp_array[i] = float(temp_array[i])
            if temp_array:  # use implicit boolean property of list
                file_array.append(temp_array)

        fpt.close()

        return file_array
    except:
        print('Something went wrong in parsing the data from ' + file_in)

# ====================================================== PART 1 ====================================================== #
data1 = [[5, 1],
         [6, 1],
         [7, 2],
         [8, 3],
         [9, 5]]

getNormalFuncFirstOrder(data1, 1)  # get normal function of data based on a first order linear regression

# ====================================================== PART 2 ====================================================== #
data2 = [[5, 1],
         [6, 1],
         [7, 2],
         [8, 3],
         [8, 14],  # added point to reduce model accuracy
         [9, 5]]

getNormalFuncFirstOrder(data2, 2)  # get normal function of data based on a first order linear regression

# ====================================================== PART 3 ====================================================== #

data3 = readData('data.txt')

getNormalFuncInvX(data3, 3)


class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:

        # This range type problem can be solved using prefix sum. We help in make it linear, First we create an array with word being vowels eligible by boolean value.

        prefix_sum = [0] # We add 0 intially in prefix_sum array because it shows what is sum till this index.

        sum = 0
        for word in words:
            if word[0] in "aeiou" and word[-1] in "aeiou":
                sum += 1
            prefix_sum.append(sum)
        res = []

        for l,r in queries:
            res.append(prefix_sum[r+1]-prefix_sum[l])
        return res

class Solution:

    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:

        # we can do this same problem with accumulate function to create prefix sum

                                                                # Example:
                                                                #    words = ['aba','bcb','ece','aa','e']
                                                                #  queries = [[0,2], [1,4], [1,1]]

        vowels = lambda w: w[0] in 'aeiou' and w[-1] in 'aeiou' #  <-- boolean function

        words = map(vowels, words)                              #    words = [True, False, True, True, True]

        pref = list(accumulate(words, initial = 0))             #     pref = [0, 1, 1, 2, 3, 4]

        return [pref[r+1] - pref[l] for l,r in queries]         #   return [2-0, 4-1, 1-1] = [2,3,0]

#         # This solution will not work because of quadratic time complexity.
#         # map for vowels
#         map = {"a","e","i","o","u"}

#         def isvowel(w): # A function to tell if a word is vowel
#             if w[0] in map and w[-1] in map:
#                 return True
#             else:
#                 return False

#         res = []  # result

#         for q in queries:

#             sum = 0 # initialising sum

#             for j in range(q[0],q[1]+1):

#                 if isvowel(words[j]):
#                     sum += 1

#             res.append(sum)

#         return res


from functools import *

lst = list(range(0,10))

even = list(filter(lambda a : a%2 == 0, lst))
print(even)

double = list(map(lambda a: a*2, even))
print(double)

add = reduce(lambda a,b : a+b, double)
print(add)


import json
import sys, re, copy
from numerics import *
import config
from operator import *
from sym import SYM
import math

def misc1(fun, iterable):
    """
    Maps the function over the iterable
    fun : Function that must be applied on each element of iterable
    iterable : iterable over which function must be mapped onto
    """
    u = []
    if iterable is None:
        return None
    elif fun is None:
        return u
    else:
        return [fun(i) for i in iterable]

def eg(key, str, fun):
    """
    Function for running the example test cases in test files and main.py
    """
    config.egs[key] = fun
    global help
    help = help + '  -g ' + key + '\t' + str + '\n'

def keys(t: dict):
    """
    Returns the sorted list of dictionary keys
    t : dictionary
    """
    return sorted(t)

def fmt(*strings):
    """
    Emulating Print function
    """
    for string in strings:
        string = str(string)
        for s in string:
            sys.stdout.write(s)

def oo(t):
    """
    Emulating Print function and returning sorted value
    """
    print(t)
    if not isinstance(t, dict):
        return t
    else:
        return dict(sorted(t.items(), key=itemgetter(1)))

def settings(s):
    """
    Using REGEX to read the settings
    """
    return dict(re.findall("\n[\s]+[-][\S]+[\s]+[-][-]([\S]+)[^\n]+= ([\S]+)", s))

def dofile(sFile):
    file = open(sFile, 'r', encoding='utf-8')
    text  = re.findall(r'(?<=return )[^.]*', file.read())[0].replace('{', '[').replace('}',']').replace('=',':').replace('[\n','{\n' ).replace(' ]',' }' ).replace('\'', '"').replace('_', '"_"')
    file.close()
    return json.loads(re.sub("(\w+):", r'"\1":', text))

def coerce(s):
    """
    Reading the values in s and reformatting it for test use
    """

    def fun(s1):
        if s1 == "true" or s1 == "True":
            return True
        elif s1 == "false" or s1 == "False":
            return False
        return s1

    if s.isdigit():
        return int(s)
    elif "." in s and s.replace(".", "").isdigit():
        return float(s)
    else:
        print('llllllllllllllllllll',fun(s.strip()))
        return fun(s.strip())

def cli(options):
    """
    Function for displaying and for printing the command line interface options.
    """
    arg = sys.argv[1:]
    for k, v in options.items():
        v = str(v)
        for n, x in enumerate(arg):
            if x == "-" + k[0] or x == "--" + k:
                if v == "false":
                    v = "true"
                elif v == "true":
                    v = "false"
                else:
                    v = arg[n + 1]
            options[k] = coerce(v)

        return options

def kap(iterable, fun):
    """
    Applies a function over a iterable and returns the result as key value pair with key as index
    and value as result of the function
    """
    result = {}
    for i in iterable:
        s1 = iterable.index(i)
        i, s1 = fun(s1,i)
        result[s1 or len(result)] = i
    return result

def dkap(t, fun):
    u = {}
    for k,v in t.items():
        v, k = fun(k,v)
        u[k or len(u)] = v
    return u

def push(t, x):
    t.append(x)
    return x

def any(iterable):
    """
    Returns random item from an iterable
    """
    return iterable[rint(0, len(iterable) - 1)]

def many(iterable, n):
    """
    Returns a few items from an iterable
    """
    u = []
    for _ in range(1, n + 1):
        u.append(any(iterable))
    return u

def show(node, what, cols, n_places, lvl=0):
    """
    Prints the tree
    """
    if node:
        print('| ' * lvl + str(len(node['data'].rows)) + '  ', end='')
        if not node.get('left') or lvl == 0:
            print(node['data'].stats(node['data'].cols.y, n_places, "mid"))
        else:
            print('')
        show(node.get('left'), what, cols, n_places, lvl + 1)
        show(node.get('right'), what, cols, n_places, lvl + 1)

def deepcopy(t):
    return copy.deepcopy(t)

def get_mean(data_obj_list):
    mean = {}
    n_iter = len(data_obj_list)

    # For each data_obj, get sum of mid/mode
    for data_obj in data_obj_list:
        for k, v in data_obj.stats().items():
            mean[k] = mean.get(k, 0) + v

    # Convert sums to averages
    for k in mean:
        mean[k] = round(mean[k] / n_iter, 2)

    return mean
def repPlace(data):
    n,g = 20,{}
    for i in range(1, n+1):
        g[i]={}
        for j in range(1, n+1):
            g[i][j]=' '
    maxy = 0
    print('')
    for r,row in enumerate(data.rows):
        c = chr(97+r).upper()
        print(c, row.cells[-1])
        x,y= row.x*n//1, row.y*n//1
        maxy = int(max(maxy,y+1))
        g[y+1][x+1] = c
    print('')
    for y in range(1,maxy+1):
        print(' '.join(g[y].values()))

def showTree(node, what, cols, nPlaces, lvl = 0):
  if node:
    print('|.. ' * lvl + '[' + str(len(node['data'].rows)) + ']' + '  ', end = '')
    if not node.get('left') or lvl==0:
        print(node['data'].stats("mid",node['data'].cols.y,nPlaces))
    else:
        print('')
    showTree(node.get('left'), what,cols, nPlaces, lvl+1)
    showTree(node.get('right'), what,cols,nPlaces, lvl+1)

def cliffsDelta(ns1,ns2):
    if len(ns1) > 256:
        ns1 = many(ns1,256)
    if len(ns2) > 256:
        ns2 = many(ns2,256)
    if len(ns1) > 10*len(ns2):
        ns1 = many(ns1,10*len(ns2))
    if len(ns2) > 10*len(ns1):
        ns2 = many(ns2,10*len(ns1))
    n,gt,lt = 0,0,0
    for x in ns1:
        for y in ns2:
            n = n + 1
            if x > y:
                gt = gt + 1
            if x < y:
                lt = lt + 1
    return abs(lt - gt)/n > config.the['cliffs']

def RANGE_1(at,txt,lo,hi=None):
    return {'at':at,'txt':txt,'lo':lo,'hi':lo or hi or lo,'y':SYM()}

def itself(x):
    return x


from django.conf.urls import patterns, include, url
from DAS_core.views import *
from django.contrib import admin
from django.views.generic import TemplateView

admin.autodiscover()

urlpatterns = patterns('',
    url('^', include('django.contrib.auth.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^home/$', Home.as_view(), name='home'),
    url(r'^home-prof/$', home_prof, name='home-prof'),
    url(r'^home-aluno/$', home_aluno, name='home-aluno'),
    url(r'^home-prof/disc-inserir-freq/(?P<pk>\d+)/$', FreqForm.as_view(), name='inserir-freq-disc'),
    url(r'^home-prof/disc-inserir-nota/(?P<pk>\d+)/$', NotaForm.as_view(), name='inserir-nota-disc'),
    url(r'^home-prof/disc-inserir-noticia/(?P<pk>\d+)/$', NoticiaForm.as_view(), name='inserir-noticia-disc'),
    url(r'^disc-inserir-arquivo/(?P<pk>\d+)/$', ArquivoForm.as_view(), name='inserir-arquivo-disc'),
    url(r'^disc-detail-freq/(?P<pk>\d+)/$', disc_detail, name='detalhe-freq-disc'),
    #url(r'^disc-inserir-nota/$', inserir_nota, name='inserir-nota-disc'),
)


import random as rd
import csv
import argparse

rd.seed(2020)

def read_txt(filename):
    dataset = []
    with open(filename, 'r', encoding="utf-8", newline='') as f:
        for line in f.readlines():
            label = line[0]
            doc = line[1:].strip()

            dataset.append((label, doc))

        print("Number of data in {} : {} ".format(filename, len(dataset)))
    return dataset

def save_csv(filename, dataset):
    with open(filename, 'w', encoding="utf-8", newline='') as f:
        wr = csv.writer(f)
        for data in dataset:
            wr.writerow(data)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--task', default='sst2', help='sst2 or sst5')
    args = parser.parse_args()

    if args.task.lower() == 'sst2':
        TRAIN_PATH = "data_in/sst2/stsa_binary_train.txt"
        DEV_PATH = "data_in/sst2/stsa_binary_dev.txt"
        TEST_PATH = "data_in/sst2/stsa_binary_test.txt"

    elif args.task.lower() == 'sst5':
        TRAIN_PATH = "data_in/sst5/stsa_fine_train.txt"
        DEV_PATH = "data_in/sst5/stsa_fine_dev.txt"
        TEST_PATH = "data_in/sst5/stsa_fine_test.txt"

    else:
        raise Exception("task : sst2 or sst5")

    TRAIN_SAVE_PATH = "data_in/train.csv"
    DEV_SAVE_PATH = "data_in/dev.csv"
    TEST_SAVE_PATH = "data_in/test.csv"

    train = read_txt(TRAIN_PATH)
    dev = read_txt(DEV_PATH)
    test = read_txt(TEST_PATH)

    save_csv(TRAIN_SAVE_PATH, train)
    save_csv(DEV_SAVE_PATH, dev)
    save_csv(TEST_SAVE_PATH, test)

if __name__ == "__main__":
    main()


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

__all__ = ["html_start", "html_end", "html_h1", "html_h2"]

def html_start(title: str, author: str = None, description: str = None, additional_style: str = "") -> str:
    html_code = "<!DOCTYPE html>\n"
    html_code += "\n"
    html_code += html_head(title, author, description, additional_style)
    html_code += "\n\n"
    return html_code

def html_end() -> str:
    html_code = "\n\n"
    html_code += "\n"
    return html_code

def html_h1(header: str) -> str:
    return f"
{header}
\n"

def html_h2(sub_header: str) -> str:
    return f"
{sub_header}
\n"

def html_head(title: str, author: str, description: str, additional_style: str) -> str:
    html_text = f"\n\n"
    html_text += f"\t<meta charset=\"UTF-8\">\n"
    html_text += f"\t<title>{title}</title>\n"
    if description is not None:
        html_text += f"\t<meta name=\"description\" content=\"{description}\"\n>"
    if author is not None:
        html_text += f"<\tmeta name=\"description\" content=\"{author}\"\n>"
    html_text += html_style(additional_style)
    html_text += "\n\n\n"
    return html_text

def html_style(additional_style: str) -> str:
    html_code = "\t\n"
    return html_code


from DPLL import main_SAT, main_graph, parse_sat, parse_graph
from drawgraph import drawGraph
import os
from os.path import isfile, join

instance = ""

dir_path = os.path.dirname(os.path.realpath(__file__))
dir_GRAPH = os.path.join(dir_path, "GRAPH")
dir_GRAPH_SOLVED = os.path.join(dir_path, "GRAPH_SOLVED")
dir_SAT = os.path.join(dir_path, "SAT")

files_GRAPH = [" ".join((f, "(" + str(i + 1) + ")"))
               for i, f in enumerate(os.listdir(dir_GRAPH)) if isfile(join(dir_GRAPH, f))]
files_SAT = [" ".join((f, "(" + str(i + 1) + ")"))
             for i, f in enumerate(os.listdir(dir_SAT)) if isfile(join(dir_SAT, f))]

while True:
    sat_or_graph = input(
        "Test de DPLL avec une instance de SAT (S) ou graphe (G) ? \n S/G ? ")
    if sat_or_graph == "S":
        instance = sat_or_graph
        print("instance de SAT")
        break
    elif sat_or_graph == "G":
        instance = sat_or_graph
        print("instance de Graphe")
        break
    else:
        print("ERREUR, choisir entre 'S' ou 'G'")
        continue
['./SAT/aim-50-1_6-no-1.cnf (1)', './SAT/jnh1.cnf (2)', './SAT/logistics.a.cnf (3)', './SAT/uf20-01.cnf (4)', './SAT/uf50-01.cnf (5)', './SAT/uuf125-01.cnf (6)', './SAT/uuf50-05.cnf (7)']
{1: './SAT/aim-50-1_6-no-1.cnf', 2: './SAT/jnh1.cnf', 3: './SAT/logistics.a.cnf', 4: './SAT/uf20-01.cnf', 5: './SAT/uf50-01.cnf', 6: './SAT/uuf125-01.cnf', 7: './SAT/uuf50-05.cnf'}

if instance == "S":
    filesSAT = files_SAT
    dictSAT = {(i + 1): f for i, f in enumerate(filesSAT)}
    print("HEEEEEEEEEEEEEEEERE", filesSAT)
    # print(dictSAT)
    max_idx = str(len(filesSAT))
    str_to_display = "\n".join(filesSAT)
    while True:
        filechoosen = input(
            f"Choisissez l'instance de SAT à résoudre : \n{str_to_display}\nDonnez le numéro du fichier à résoudre [1 à {max_idx}]: ")
        try:
            file_to_solve = os.path.join("SAT", (dictSAT[int(filechoosen)]))
            # file_to_solve = "SAT/" + (dictSAT[int(filechoosen)])
            break
        except KeyError:
            print("Numéro de fichier invalide")
            continue

    print("----"*25)
    print(f"DEBUT DE LA RESOLUTION DE {file_to_solve.split()[0]}")
    p, C = parse_sat(file_to_solve.split()[0])
    print("... résolution en cours ...")
    main_SAT(p, C)

if instance == "G":
    filesGRAPH = files_GRAPH
    dictGRAPH = {(i + 1): f.split()[0] for i, f in enumerate(filesGRAPH)}
    max_idx = str(len(filesGRAPH))
    str_to_display = "\n".join(filesGRAPH)
    while True:
        filechoosen = input(
            f"Choisissez l'instance de SAT à résoudre : \n{str_to_display}\nDonnez le numéro du fichier à résoudre [1 à {max_idx}]: ")
        try:
            file_to_solve = os.path.join(
                "GRAPH", (dictGRAPH[int(filechoosen)]))
            # file_to_solve = "GRAPH/" + (dictGRAPH[int(filechoosen)])
            break
        except:
            print("Numéro de fichier invalide")
            continue

    while True:
        k_choosenstr = input(f"Choisissez le nombre de couleurs K (K >= 1) : ")
        try:
            K = int(k_choosenstr)
            break
        except:
            continue

    print("----"*25)
    print(f"DEBUT DE LA RESOLUTION DE {file_to_solve}")
    print("... résolution en cours ...")
    R = main_graph(file_to_solve, K)
    if R:
        print("Vous pouvez voir la couleur assigné à chaque sommet dans",
              "SOLVED/" + file_to_solve.split("/")[-1])
        if K <= 12:
            rep = input(
                "Voulez vous afficher une représentation du graphe colorié ? (Y/N)")
            if rep == "Y":
                drawGraph(file_to_solve, os.path.join("GRAPH_SOLVED", file_to_solve.split(os.sep)[-1]))
    else:
        print(
            f"On ne peut pas colorier {file_to_solve.split('/')[-1]} avec K = {K}")


import pandas
from numpy import corrcoef
from scipy.sparse import hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import PCA
import sys

from sklearn.linear_model import Ridge

sys.path.append("..")
from util import print_answer
from sklearn.feature_extraction import DictVectorizer

data = pandas.read_csv('close_prices.csv')
x = data.loc[:, 'AXP':]
pca = PCA(n_components=10)
pca.fit(x.values)

variance = 0
i = 0
for v in pca.explained_variance_ratio_:
    i += 1
    variance += v
    if variance >= 0.9:
        break

print_answer(1, i)

df_comp = pandas.DataFrame(pca.transform(x))
comp0 = df_comp[0]

df2 = pandas.read_csv('djia_index.csv')
dji = df2['^DJI']
corr = corrcoef(comp0, dji)
print_answer(2, corr[1, 0])

comp0_w = pandas.Series(pca.components_[0])
comp0_w_top = comp0_w.sort_values(ascending=False).head(1).index[0]
company = x.columns[comp0_w_top]
print_answer(3, company)


class Solution:
    """
    https://leetcode.com/problems/binary-watch/
    401. Binary Watch
    Easy
    """

    def readBinaryWatch(self, num):
        return self.readBinaryWatch_5(num)

    def readBinaryWatch_1(self, num):
        """
        本题虽然是easy难度,但是如果思路不对是很难做出来的.
        穷举法是最简单的方法之一.参考思路如下:
        https://leetcode.com/problems/binary-watch/discuss/88458/Simple-Python%2BJava
        :param num:
        :return:
        """
        if 0 > num >= 10:
            return []
        ret = []
        for h in range(12):
            for m in range(60):
                if self.getBinaryOneCount(h) + self.getBinaryOneCount(m) == num:
                    ret.append("%d:%02d" % (h, m))

        return ret

    def getBinaryOneCount(self, num):
        """
        获取num中二进制各位=1的数量
        :param num:
        :return:
        """
        tmp = num
        count = 0
        while tmp > 0:
            count += tmp & 1
            tmp >>= 1
        return count

    def readBinaryWatch_2(self, num):
        """
        方法readBinaryWatch_1的简化版,
        :param num:
        :return:
        """
        if 0 > num >= 10:
            return []
        ret = []
        for h in range(12):
            for m in range(60):
                if (bin(h) + bin(m)).count('1') == num:
                    ret.append("%d:%02d" % (h, m))

        return ret

    def readBinaryWatch_3(self, num):
        """
        方法readBinaryWatch_1的最简版
        参考如下:
        https://leetcode.com/problems/binary-watch/discuss/88458/Simple-Python%2BJava
        :param num:
        :return:
        """
        return ['%d:%02d' % (h, m)
                for h in range(12) for m in range(60)
                if (bin(h) + bin(m)).count('1') == num]

    def readBinaryWatch_4(self, num):
        """
        与前面的方面思路完全不同,不是采用穷举法,而是采用类似推导/演绎的方法.
        为了避免多重嵌套循环,采用了递归(栈)进行遍历计算.
        采用permutation and combination的思路.
        参考文档:
        https://leetcode.com/problems/binary-watch/discuss/88456/3ms-Java-Solution-Using-Backtracking-and-Idea-of-%22Permutation-and-Combination%22
        :param num:
        :return:
        """
        ret = []
        hours = [8, 4, 2, 1]
        minutes = [32, 16, 8, 4, 2, 1]
        for i in range(num + 1):
            # 分治法
            h_combination = self.generateTime(hours, i)
            m_combination = self.generateTime(minutes, num - i)

            for h in h_combination:
                for m in m_combination:
                    if sum(h) < 12 and sum(m) < 60:
                        ret.append("%d:%02d" % (sum(h), sum(m)))

        return ret

    def generateTime(self, nums, count):
        """
        采用Combination思路
        :param nums:
        :param count:
        :return:
        """
        ret = []
        self.generateTimeCombination(nums, count, 0, [], ret)
        return ret

    def generateTimeCombination(self, nums, count, beg, present, ret):
        if count == 0:
            ret.append(present.copy())
            return
        for i in range(beg, len(nums)):
            present.append(nums[i])
            self.generateTimeCombination(nums, count - 1, i + 1, present, ret)
            present.remove(nums[i])

    def readBinaryWatch_5(self, num):
        """
        readBinaryWatch_4的代码简化版本.
        主要是优化sum(h) < 12 ,sum(m), present三个部分
        参考文档:
        https://leetcode.com/problems/binary-watch/discuss/88456/3ms-Java-Solution-Using-Backtracking-and-Idea-of-%22Permutation-and-Combination%22
        :param num:
        :return:
        """
        ret = []
        hours = [8, 4, 2, 1]
        minutes = [32, 16, 8, 4, 2, 1]
        for i in range(num + 1):
            # 分治法
            h_combination = self.generateTime_5(hours, i)
            m_combination = self.generateTime_5(minutes, num - i)

            for h in h_combination:
                for m in m_combination:
                    if h < 12 and m < 60:
                        ret.append("%d:%02d" % (h, m))

        return ret

    def generateTime_5(self, nums, count):
        """
        采用Combination思路
        :param nums:
        :param count:
        :return:
        """
        ret = []
        self.generateTimeCombination_5(nums, count, 0, 0, ret)
        return ret

    def generateTimeCombination_5(self, nums, count, beg, present, ret):
        if count == 0:
            ret.append(present)
            return
        for i in range(beg, len(nums)):
            self.generateTimeCombination_5(nums, count - 1, i + 1, present + nums[i], ret)

def main():
    a = 1
    ret = Solution().readBinaryWatch(a)
    print(ret)
    print("------------")

    a = 2
    ret = Solution().readBinaryWatch(a)
    print(ret)
    print("------------")

    # nums = [1, 2, 4, 8]
    # ret = []
    # Solution().permutation_combination(nums, 3, 0, ret)
    # print(ret)

if __name__ == "__main__":
    main()


######################################
# Creator: Alfio Raymond
# Date: 7 Feb 2023
#
# Exercise 3 in Chapter 6
# Encapsulate this code in a function named count, and generalize
# it so that it accepts the string and the letter as arguments.
#
# N/A
######################################

def count(strInput, letterInput):
    word = strInput
    count = 0
    for letter in word:
        if letter == letterInput:
            count = count + 1
    print(letterInput.capitalize() + "'s:",count)

def main():

    while True:
        strInput = input("Enter a string (Type 'done' to exit): ")

        if strInput == 'done':
            break
        elif strInput == '':
            continue
        else:
            letterInput = input("What letter should be found: ")
            count(strInput, letterInput)

main()


from constraint import *
import numpy as np

class ConstraintBuilder:
    def __init__(self, hp_sequence, hcore, lattice):
        self._hcore_nodes = hcore.vertices  # .astype(int)
        # self._hcore_nodes -= self._hcore_nodes.min(axis=0)
        self._hcore_node_depths = hcore.compute_buriedness()
        self._hp_sequence = hp_sequence
        self._basis = lattice.vectors

    def check_feasibility(self, verbose=False):
        # TODO: distance to prev also!
        hp_dists = {"H-P": [],
                    "P-H": []}
        for i in range(len(self._hp_sequence)):
            if self._hp_sequence[i] == "P":
                tgt_monomer = "H"
                key = "P-H"
            else:
                tgt_monomer = "P"
                key = "H-P"

            d_to_prev = self._hp_sequence[:i + 1][::-1].find(tgt_monomer)
            d_to_next = self._hp_sequence[i:].find(tgt_monomer)
            d_to_prev = d_to_prev if d_to_prev > 0 else len(self._hp_sequence)
            d_to_next = d_to_next if d_to_next > 0 else len(self._hp_sequence)
            d_to_nearest = min(d_to_next,
                               d_to_prev)
            hp_dists[key] = hp_dists[key] + [d_to_nearest]

        if max(self._hcore_node_depths) > max(hp_dists["H-P"]):
            if verbose:
                return {"verdict": False,
                        "max_core_depth": max(self._hcore_node_depths),
                        "max_H-P_dist": max(hp_dists["H-P"]),
                        "max_P-H_dist": max(hp_dists["P-H"])}
            return False

        # TODO: other filtration criteria?

        if verbose:
            return {"verdict": True,
                    "max_core_depth": max(self._hcore_node_depths),
                    "max_H-P_dist": max(hp_dists["H-P"]),
                    "max_P-H_dist": max(hp_dists["P-H"])}
        return True

    def get_constraints(self):
        seq_analysis = self.check_feasibility(verbose=True)
        if not seq_analysis["verdict"]:
            # return None
            raise Exception("H-Core and HP-sequence do not fit!")

        def __constraint_no_overlay(p, q):
            return p != q

        constraints = []
        var_ranges = {}

        h_nodes = {d: [] for d in np.unique(self._hcore_node_depths)}
        for i in range(len(self._hcore_nodes)):
            h_nodes[self._hcore_node_depths[i]] = h_nodes[self._hcore_node_depths[i]] + [self._hcore_nodes[i].tolist()]
        p_nodes = {d: [] for d in np.unique(self._hcore_node_depths)}
        for offset in range(1, seq_analysis["max_P-H_dist"] + 1):
            off_nodes = [(node + offset * np.array(v)).astype(int).tolist() for node in self._hcore_nodes for v in self._basis]
            off_nodes = [node for node in off_nodes if node not in (self._hcore_nodes.tolist() if offset == 1 else p_nodes[offset - 1])]
            off_nodes = [list(node) for node in list(set([tuple(node) for node in off_nodes]))]
            p_nodes[offset] = off_nodes

        for i in range(len(self._hp_sequence)):
            var_name = f"L_{i}"

            if i > 0:
                constraints += [(lambda p, q: [np.round(p[l] - q[l]) for l in range(len(p))] in self._basis,
                                 (f"L_{i}", f"L_{i - 1}"))]

            for j in range(0, i - 1):
                constraints += [(__constraint_no_overlay,  # lambda x_i, y_i, x_j, y_j: (x_i != x_j) and (y_i != y_j),
                                (f"L_{i}", f"L_{j}"))]

            if self._hp_sequence[i] == "H":
                d_to_prev_p = self._hp_sequence[:i + 1][::-1].find("P")
                d_to_next_p = self._hp_sequence[i:].find("P")
                d_to_prev_p = d_to_prev_p if d_to_prev_p > 0 else len(self._hp_sequence)
                d_to_next_p = d_to_next_p if d_to_next_p > 0 else len(self._hp_sequence)
                d_to_nearest_p = min(d_to_next_p,
                                     d_to_prev_p)
                var_range = []
                for k in range(1, d_to_nearest_p + 1):
                    if k not in h_nodes.keys():
                        break
                    var_range += h_nodes[k]
                var_ranges[var_name] = var_range

            else:
                d_to_prev_h = self._hp_sequence[:i + 1][::-1].find("H")
                d_to_next_h = self._hp_sequence[i:].find("H")
                d_to_prev_h = d_to_prev_h if d_to_prev_h > 0 else len(self._hp_sequence)
                d_to_next_h = d_to_next_h if d_to_next_h > 0 else len(self._hp_sequence)
                d_to_nearest_h = min(d_to_next_h, d_to_prev_h)
                var_range = []
                for k in range(1, d_to_nearest_h + 1):
                    var_range += p_nodes[k]
                var_ranges[var_name] = var_range

        return {"ranges": var_ranges,
                "constraints": constraints}

class HCoreCSP:
    def __init__(self, sequence, hcore, lattice):
        self._sequence = sequence
        self._core_nodes = hcore.vertices.tolist()
        self._core_node_depths = hcore.compute_buriedness()
        self._core_nodes_str_set = set([f"{node[0]}_{node[1]}" for node in self._core_nodes])

        if len(self._core_nodes) != len([m for m in self._sequence if m == "H"]):
            raise ValueError("H-Core Power and H number in sequence do not match!")
        self._lat_basis = lattice.vectors # .tolist()
        # self._init_configuration()

        self._problem = Problem()
        config = ConstraintBuilder(sequence, hcore, lattice).get_constraints()
        for k,v in config["ranges"].items():
            self._problem.addVariable(k, v)
        for constr in config["constraints"]:
            self._problem.addConstraint(constr[0],
                                        constr[1])

    def solve(self, ax=None, return_all=False):
        # print(f"entered solve. problem = {self._problem}")
        if return_all:
            return self._problem.getSolutions()

        solution = self._problem.getSolution()
        if solution is None:
            return {}
        if ax is not None:
            points = np.array([solution[f"L_{i}"] for i in range(len(self._sequence))])
            ax.scatter(*points[np.array(list(self._sequence)) != "H"].T,
                       # c=["red" if self._sequence[i] == "H" else "green" for i in range(len(self._sequence))],
                       facecolors="white", edgecolors="black",
                       s=100,
                       zorder=1)
            ax.scatter(*points[np.array(list(self._sequence)) == "H"].T,
                       c="black", # ["red" if self._sequence[i] == "H" else "green" for i in range(len(self._sequence))],
                       # facecolors="none", edgecolors="black",
                       s=100,
                       zorder=1)
            ax.plot(*points.T, c="black", linewidth=1, zorder=0)

        return solution

    def generate_H_constraints(self):
        node_groups_by_depth = {}
        for i in range(len(self._core_node_depths)):
            if self._core_node_depths[i] not in node_groups_by_depth:
                node_groups_by_depth[self._core_node_depths[i]] = []
            node_groups_by_depth[self._core_node_depths[i]] = node_groups_by_depth[self._core_node_depths[i]] + [self._core_nodes[i]]


import numpy as np, time

def snap(fpga, snap_id, bytes=4096, fmt='uint32'):
    """Retrieve & unpack data from a snap block"""

    fpga.write_int(snap_id+'_ctrl', 0, blindwrite=True)
    fpga.write_int(snap_id+'_ctrl', 1, blindwrite=True)
    packed = fpga.read(snap_id+'_bram', bytes)

    data = np.fromstring(packed, dtype=fmt).byteswap()

    return data

def multisnap(fpga, snaplist, bytes, fmt='uint32'):
    """ Snaps a list of different registers """

    dataDict = {}

    for snapblock in snaplist:
        dataDict[snapblock] = snap(fpga, snapblock, bytes, fmt)

    return dataDict

def stitch(array1,array2):
    """ Stitch together even and odd values.
    Example
    -------
    a1=[0 2 4], a2 =[1 3 5]
    stitch(a1,a2) = [0 1 2 3 4 5]
    """
    # Create a 2xN numpy array, transpose then ravel into 1D
    data = np.array([array1,array2])

    return np.array(data.transpose().ravel())


from datetime import datetime, timedelta
from pytz import timezone, utc

from odoo import api, fields, models, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.addons.resource.models.utils import float_to_time
from odoo.tools import is_html_empty
from odoo.tools.translate import html_translate

class Sponsor(models.Model):
    _name = "event.sponsor"
    _description = 'Event Sponsor'
    _order = "sequence, sponsor_type_id"
    # _order = 'sponsor_type_id, sequence' TDE FIXME
    _rec_name = 'name'
    _inherit = [
        'mail.thread',
        'mail.activity.mixin',
        'website.published.mixin',
        'chat.room.mixin'
    ]

    def _default_sponsor_type_id(self):
        return self.env['event.sponsor.type'].search([], order="sequence desc", limit=1).id

    event_id = fields.Many2one('event.event', 'Event', required=True)
    sponsor_type_id = fields.Many2one(
        'event.sponsor.type', 'Sponsorship Level',
        default=lambda self: self._default_sponsor_type_id(), required=True, auto_join=True)
    url = fields.Char('Sponsor Website', compute='_compute_url', readonly=False, store=True)
    sequence = fields.Integer('Sequence')
    active = fields.Boolean(default=True)
    # description
    subtitle = fields.Char('Slogan')
    exhibitor_type = fields.Selection(
        [('sponsor', 'Footer Logo Only'), ('exhibitor', 'Exhibitor'), ('online', 'Online Exhibitor')],
        string="Sponsor Type", default="sponsor")
    website_description = fields.Html(
        'Description', compute='_compute_website_description',
        sanitize_overridable=True,
        sanitize_attributes=False, sanitize_form=True, translate=html_translate,
        readonly=False, store=True)
    # contact information
    partner_id = fields.Many2one('res.partner', 'Partner', required=True, auto_join=True)
    partner_name = fields.Char('Name', related='partner_id.name')
    partner_email = fields.Char('Email', related='partner_id.email')
    partner_phone = fields.Char('Phone', related='partner_id.phone')
    partner_mobile = fields.Char('Mobile', related='partner_id.mobile')
    name = fields.Char('Sponsor Name', compute='_compute_name', readonly=False, store=True)
    email = fields.Char('Sponsor Email', compute='_compute_email', readonly=False, store=True)
    phone = fields.Char('Sponsor Phone', compute='_compute_phone', readonly=False, store=True)
    mobile = fields.Char('Sponsor Mobile', compute='_compute_mobile', readonly=False, store=True)
    # image
    image_512 = fields.Image(
        string="Logo", max_width=512, max_height=512,
        compute='_compute_image_512', readonly=False, store=True)
    image_256 = fields.Image("Image 256", related="image_512", max_width=256, max_height=256, store=False)
    image_128 = fields.Image("Image 128", related="image_512", max_width=128, max_height=128, store=False)
    website_image_url = fields.Char(
        string='Image URL',
        compute='_compute_website_image_url', compute_sudo=True, store=False)
    # live mode
    hour_from = fields.Float('Opening hour', default=8.0)
    hour_to = fields.Float('End hour', default=18.0)
    event_date_tz = fields.Selection(string='Timezone', related='event_id.date_tz', readonly=True)
    is_in_opening_hours = fields.Boolean(
        'Within opening hours', compute='_compute_is_in_opening_hours')
    # chat room
    chat_room_id = fields.Many2one(readonly=False)
    room_name = fields.Char(readonly=False)
    # country information (related to ease frontend templates)
    country_id = fields.Many2one(
        'res.country', string='Country',
        related='partner_id.country_id', readonly=True)
    country_flag_url = fields.Char(
        string='Country Flag',
        compute='_compute_country_flag_url', compute_sudo=True)

    @api.depends('partner_id')
    def _compute_url(self):
        for sponsor in self:
            if sponsor.partner_id.website or not sponsor.url:
                sponsor.url = sponsor.partner_id.website

    @api.depends('partner_id')
    def _compute_name(self):
        self._synchronize_with_partner('name')

    @api.depends('partner_id')
    def _compute_email(self):
        self._synchronize_with_partner('email')

    @api.depends('partner_id')
    def _compute_phone(self):
        self._synchronize_with_partner('phone')

    @api.depends('partner_id')
    def _compute_mobile(self):
        self._synchronize_with_partner('mobile')

    @api.depends('partner_id')
    def _compute_image_512(self):
        self._synchronize_with_partner('image_512')

    @api.depends('image_512', 'partner_id.image_256')
    def _compute_website_image_url(self):
        for sponsor in self:
            if sponsor.image_512:
                # image_512 is stored, image_256 is derived from it dynamically
                sponsor.website_image_url = self.env['website'].image_url(sponsor, 'image_256', size=256)
            elif sponsor.partner_id.image_256:
                sponsor.website_image_url = self.env['website'].image_url(sponsor.partner_id, 'image_256', size=256)
            else:
                sponsor.website_image_url = 'website_event_exhibitor/static/src/img/event_sponsor_default_0.jpeg'

    def _synchronize_with_partner(self, fname):
        """ Synchronize with partner if not set. Setting a value does not write
        on partner as this may be event-specific information. """
        for sponsor in self:
            if not sponsor[fname]:
                sponsor[fname] = sponsor.partner_id[fname]

    @api.onchange('exhibitor_type')
    def _onchange_exhibitor_type(self):
        """ Keep an explicit onchange to allow configuration of room names, even
        if this field is normally a related on chat_room_id.name. It is not a real
        computed field, an onchange used in form view is sufficient. """
        for sponsor in self:
            if sponsor.exhibitor_type == 'online' and not sponsor.room_name:
                if sponsor.name:
                    room_name = "odoo-exhibitor-%s" % sponsor.name
                else:
                    room_name = self.env['chat.room']._default_name(objname='exhibitor')
                sponsor.room_name = self._jitsi_sanitize_name(room_name)
            if sponsor.exhibitor_type == 'online' and not sponsor.room_max_capacity:
                sponsor.room_max_capacity = '8'

    @api.depends('partner_id')
    def _compute_website_description(self):
        for sponsor in self:
            if is_html_empty(sponsor.website_description):
                sponsor.website_description = sponsor.partner_id.website_description

    @api.depends('event_id.is_ongoing', 'hour_from', 'hour_to', 'event_id.date_begin', 'event_id.date_end')
    def _compute_is_in_opening_hours(self):
        """ Opening hours: hour_from and hour_to are given within event TZ or UTC.
        Now() must therefore be computed based on that TZ. """
        for sponsor in self:
            if not sponsor.event_id.is_ongoing:
                sponsor.is_in_opening_hours = False
            elif sponsor.hour_from is False or sponsor.hour_to is False:
                sponsor.is_in_opening_hours = True
            else:
                event_tz = timezone(sponsor.event_id.date_tz)
                # localize now, begin and end datetimes in event tz
                dt_begin = sponsor.event_id.date_begin.astimezone(event_tz)
                dt_end = sponsor.event_id.date_end.astimezone(event_tz)
                now_utc = utc.localize(fields.Datetime.now().replace(microsecond=0))
                now_tz = now_utc.astimezone(event_tz)

                # compute opening hours
                opening_from_tz = event_tz.localize(datetime.combine(now_tz.date(), float_to_time(sponsor.hour_from)))
                opening_to_tz = event_tz.localize(datetime.combine(now_tz.date(), float_to_time(sponsor.hour_to)))
                if sponsor.hour_to == 0:
                    # when closing 'at midnight', we consider it's at midnight the next day
                    opening_to_tz = opening_to_tz + timedelta(days=1)

                opening_from = max([dt_begin, opening_from_tz])
                opening_to = min([dt_end, opening_to_tz])

                sponsor.is_in_opening_hours = opening_from <= now_tz < opening_to

    @api.depends('partner_id.country_id.image_url')
    def _compute_country_flag_url(self):
        for sponsor in self:
            if sponsor.partner_id.country_id:
                sponsor.country_flag_url = sponsor.partner_id.country_id.image_url
            else:
                sponsor.country_flag_url = False

    # ------------------------------------------------------------
    # MIXINS
    # ---------------------------------------------------------

    @api.depends('name', 'event_id.name')
    def _compute_website_url(self):
        super(Sponsor, self)._compute_website_url()
        for sponsor in self:
            if sponsor.id:  # avoid to perform a slug on a not yet saved record in case of an onchange.
                base_url = sponsor.event_id.get_base_url()
                sponsor.website_url = '%s/event/%s/exhibitor/%s' % (base_url, slug(sponsor.event_id), slug(sponsor))

    # ------------------------------------------------------------
    # CRUD
    # ------------------------------------------------------------

    @api.model_create_multi
    def create(self, values_list):
        for values in values_list:
            if values.get('is_exhibitor') and not values.get('room_name'):
                exhibitor_name = values['name'] if values.get('name') else self.env['res.partner'].browse(values['partner_id']).name
                name = 'odoo-exhibitor-%s' % exhibitor_name or 'sponsor'
                values['room_name'] = name
        return super(Sponsor, self).create(values_list)

    def write(self, values):
        toupdate = self.env['event.sponsor']
        if values.get('is_exhibitor') and not values.get('chat_room_id') and not values.get('room_name'):
            toupdate = self.filtered(lambda exhibitor: not exhibitor.chat_room_id)
            # go into sequential update in order to create a custom room name for each sponsor
            for exhibitor in toupdate:
                values['room_name'] = 'odoo-exhibitor-%s' % exhibitor.name
                super(Sponsor, exhibitor).write(values)
        return super(Sponsor, self - toupdate).write(values)

    # ------------------------------------------------------------
    # ACTIONS
    # ---------------------------------------------------------

    def get_backend_menu_id(self):
        return self.env.ref('event.event_main_menu').id

    # ------------------------------------------------------------
    # MESSAGING
    # ------------------------------------------------------------

    def _message_get_suggested_recipients(self):
        recipients = super(Sponsor, self)._message_get_suggested_recipients()
        for sponsor in self:
            if sponsor.partner_id:
                sponsor._message_add_suggested_recipient(
                    recipients,
                    partner=sponsor.partner_id,
                    reason=_('Sponsor')
                )
        return recipients


from __future__ import annotations

import dataclasses
import typing

from retro_data_structures.formats.mlvl import Mlvl
from retro_data_structures.formats.script_object import InstanceId
from retro_data_structures.properties import field_reflection
from retro_data_structures.properties.base_property import BaseObjectType, BaseProperty
from retro_data_structures.properties.echoes import objects

from pwime.operations.base import Operation

if typing.TYPE_CHECKING:
    from retro_data_structures.formats.script_object import ScriptInstance

    from pwime.asset_manager import OurAssetManager
    from pwime.project import Project
    from pwime.util.json_lib import JsonObject

@dataclasses.dataclass(frozen=True)
class InstanceReference:
    mlvl: int
    mrea: int
    instance_id: InstanceId

    def to_json(self) -> JsonObject:
        return {
            "mlvl": self.mlvl,
            "mrea": self.mrea,
            "instance_id": self.instance_id,
        }

    @classmethod
    def from_json(cls, data: JsonObject) -> typing.Self:
        data_json = typing.cast(dict[str, int], data)
        return cls(data_json["mlvl"], data_json["mrea"], InstanceId(data["instance_id"]))

@dataclasses.dataclass(frozen=True)
class PropReference:
    instance: InstanceReference
    path: tuple[str, ...]

    def append(self, field: str) -> PropReference:
        return PropReference(self.instance, self.path + (field,))

def get_instance(manager: OurAssetManager, reference: InstanceReference) -> ScriptInstance:
    """Gets a ScriptInstance from a InstanceReference"""
    mlvl = manager.get_file(reference.mlvl, Mlvl)
    area = mlvl.get_area(reference.mrea)
    return area.get_instance(reference.instance_id)

PropType = typing.TypeVar("PropType", bound=BaseObjectType)

def _modified_fields(prop: type[BaseProperty], delta: JsonObject, parent: str = "") -> list[str]:
    result = []

    for name, reflection in field_reflection.get_reflection(prop).items():
        key = f"0x{reflection.id:08X}"
        if key not in delta:
            continue

        if issubclass(reflection.type, BaseProperty) and field_reflection.get_reflection(reflection.type):
            result.extend(_modified_fields(reflection.type, delta[key], f"{parent}{name}."))
        else:
            result.append(f"{parent}{name}")

    return result

def create_patch_for(instance: ScriptInstance, value_path: tuple[str, ...], new_value: typing.Any) -> JsonObject:
    delta = {}
    current_type = instance.type
    current_value = delta

    for i, name in enumerate(value_path):
        reflection = field_reflection.get_reflection(current_type)[name]
        current_type = reflection.type
        key = f"0x{reflection.id:08X}"
        if i == len(value_path) - 1:
            current_value[key] = reflection.to_json(new_value)
        else:
            current_value[key] = {}
            current_value = current_value[key]

    return delta

def patch_property(prop: PropType, delta: JsonObject) -> None:
    for name, reflection in field_reflection.get_reflection(type(prop)).items():
        key = f"0x{reflection.id:08X}"
        if key not in delta:
            continue

        if issubclass(reflection.type, BaseProperty) and field_reflection.get_reflection(reflection.type):
            patch_property(getattr(prop, name), delta[key])
        else:
            setattr(prop, name, reflection.from_json(delta[key]))

class ScriptInstancePropertyEdit(Operation, typing.Generic[PropType]):
    """Represents changing a property of an existing script object."""

    reference: InstanceReference
    prop_type: type[PropType]
    delta: JsonObject
    old_value: PropType | None = None

    def __init__(self, reference: InstanceReference, prop_type: type[PropType], delta: JsonObject):
        self.reference = reference
        self.prop_type = prop_type
        self.delta = delta

    def perform(self, project: Project) -> None:
        """Performs the change."""
        instance = get_instance(project.asset_manager, self.reference)
        self.old_value = instance.get_properties()

        with instance.edit_properties(self.prop_type) as prop:
            patch_property(prop, self.delta)

    def undo(self, project: Project) -> None:
        """Reverts the change."""
        assert self.old_value is not None
        instance = get_instance(project.asset_manager, self.reference)
        instance.set_properties(self.old_value)

    def _modified_fields(self) -> list[str]:
        return _modified_fields(self.prop_type, self.delta)

    def overwrites_operation(self, operation: Operation) -> bool:
        """Yes if changing the same field of the same object."""
        if isinstance(operation, ScriptInstancePropertyEdit):
            if self.reference != operation.reference:
                return False
            return self._modified_fields() == operation._modified_fields()
        return False

    def describe(self) -> str:
        return (
            f"Edited fields {', '.join(self._modified_fields())} of `{self.reference.instance_id}`,"
            f" a {self.prop_type.__name__}"
        )

    def to_json(self) -> JsonObject:
        return {
            "kind": "script_instance_property_edit",
            "reference": self.reference.to_json(),
            "prop_type": self.prop_type.object_type(),
            "delta": self.delta,
        }

    @classmethod
    def from_json(cls, data: JsonObject) -> typing.Self:
        return cls(
            reference=InstanceReference.from_json(data["reference"]),
            prop_type=objects.get_object(data["prop_type"]),
            delta=data["delta"],
        )


from .forms import UserRegistrationForm
from django.shortcuts import render, redirect

def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            print("Form is valid")
            form.save()
            return redirect('login')
        else:
            print("form has errors")

    else:
        form = UserRegistrationForm()
    return render(request, 'users/register.html', {'form': form})


from __future__ import division
import torch
import torch.nn as nn
import torch.autograd as autograd

class Jacobian(nn.Module):
    '''
    Loss criterion that computes the trace of the square of the Jacobian.
    Arguments:
        n (int, optional): determines the number of random projections.
            If n=-1, then it is set to the dimension of the output
            space and projection is non-random and orthonormal, yielding
            the exact result.  For any reasonable batch size, the default
            (n=1) should be sufficient.
    '''

    def __init__(self, n=-1):
        assert n == -1 or n > 0
        self.n = n
        super(Jacobian, self).__init__()

    def forward(self, x, y):
        '''
        computes (1/2) tr |dy/dx|^2
        '''
        B, C = y.shape #32 10
        if self.n == -1:
            num_proj = C
        else:
            num_proj = self.n
        J2 = 0
        for ii in range(num_proj):
            if self.n == -1:
                # orthonormal vector, sequentially spanned
                v = torch.zeros(B, C)
                v[:, ii] = 1
            else:
                # random properly-normalized vector for each sample
                v = self._random_vector(C=C, B=B)
            if x.is_cuda:
                v = v.cuda()
            print("v:", v)
            Jv = self._jacobian_vector_product(y, x, v, create_graph=True)
            print("Jv:", Jv.shape)
            J2 += C * torch.norm(Jv) ** 2 / (num_proj * B)
        R = (1 / 2) * J2
        return R

    def _random_vector(self, C, B):
        '''
        creates a random vector of dimension C with a norm of C^(1/2)
        (as needed for the projection formula to work)
        '''
        if C == 1:
            return torch.ones(B)
        v = torch.randn(B, C)
        arxilirary_zero = torch.zeros(B, C)
        vnorm = torch.norm(v, 2, 1, True)
        v = torch.addcdiv(arxilirary_zero, 1.0, v, vnorm)
        return v

    def _jacobian_vector_product(self, y, x, v, create_graph=False):
        '''
        Produce jacobian-vector product dy/dx dot v.
        Note that if you want to differentiate it,
        you need to make create_graph=True
        '''
        flat_y = y.reshape(-1)
        flat_v = v.reshape(-1)
        grad_x, = torch.autograd.grad(flat_y, x, flat_v,
                                      retain_graph=True,
                                      create_graph=create_graph)
        return grad_x

class JacobianAugmentation(object):
    def __init__(self, copy_model):
        self.lammda=0.1
        self.copy_model=copy_model
        # self.queried_y=queried_y #should be torch

    def get_synthesizing_set(self, inputs, targets):
        #let input_shape a list
        # extended for Jacobian calculation

        # Jacobian computed by the improved method
        # On Colab CPU 0.16s, K80 GPU 0.14s
        # with JacobianMode(self.copy_model):
        #     out = self.copy_model(inputs).cpu()
        #     out.sum().backward()
        #     jac = self.copy_model.jacobian()
        inputs = inputs.cuda()
        targets = targets.cuda()
        inputs.requires_grad_()
        targets.requires_grad_()

        inputs.requires_grad = True
        outputs = self.copy_model(inputs)
        # pred = jacobian(targets, inputs, outputs, create_graph=True)#targets
        # jacobian=Jacobian()
        # jac_on_copy=jacobian(inputs, outputs)
        # print("jac_on_copy", jac_on_copy)
        grad_x, = torch.autograd.grad(outputs, inputs, targets, allow_unused=True)#retain_graph=True,
                                       #create_graph=True
        #outputs: _TensorOrTensors,
        #inputs: _TensorOrTensors,
        #grad_outputs
        #jacobian is calculated on the copy model/substitute model
        # print("grad_x", grad_x[0])
        # print('x', inputs[0])
        #calculate new set
        synthesizing_set = inputs + self.lammda * torch.sign(grad_x) #if all these two is torch
        # synthesizing_set=[]
        return synthesizing_set


# Counting Sundays
# Problem 19
# You are given the following information, but you may prefer to do some research for yourself.
#
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years, twenty-nine.
# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

from itertools import takewhile

def next_day(date=(0, 'Monday', 0, 1900)):
    day_strings = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
    next_day_string = {day_strings[d % 7]: day_strings[(d + 1) % 7] for d in range(0, 7)}
    days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

    while True:  # no tail recursion in python :(
        day, day_string, month, year = date
        offset = 1 if month == 1 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 0
        month_boundary = days_in_month[month] + offset
        new_day = (day + 1) % month_boundary
        new_month = (month + 1) % 12 if new_day == 0 else month
        new_year = year + 1 if new_day == 0 and new_month == 0 else year

        new_date = (new_day, next_day_string[day_string], new_month, new_year)
        yield new_date
        date = new_date

sundays_on_first = filter(lambda day: day[0] == 0 and day[1] == 'Sunday', next_day())
from_1901 = filter(lambda day: day[3] > 1900, sundays_on_first)
until_2001 = takewhile(lambda day: day[3] < 2001, from_1901)
print(len(list(until_2001)))


__all__ = ['test']

# Don't look below, you will not understand this Python code :) I don't.

from js2py.pyjs import *
# setting scope
var = Scope( JS_BUILTINS )
set_global_object(var)

# Code follows:
var.registers(['display'])
@Js
def PyJsHoisted_display_(e, this, arguments, var=var):
    var = Scope({'e':e, 'this':this, 'arguments':arguments}, var)
    var.registers(['e', 'PORT', 'i', 'net', 'http', 'HOST', 'ser', 'n', 'je'])
    var.get('console').callprop('log', Js(''))
    var.get('console').callprop('log', Js('HASH VALES'))
    var.put('n', var.get('e').get('length'))
    #for JS loop
    var.put('i', Js(0.0))
    while (var.get('i')<var.get('n')):
        try:
            var.get('console').callprop('log', var.get('e').get(var.get('i')))
        finally:
                (var.put('i',Js(var.get('i').to_number())+Js(1))-Js(1))
    var.get('console').callprop('log', Js(''))
    var.get('console').callprop('log', var.get('e'))
    var.put('je', var.get('JSON').callprop('stringify', var.get('e')))
    var.get('console').callprop('log', var.get('je'))
    var.put('http', var.get('require')(Js('http')))
    var.put('net', var.get('require')(Js('net')))
    var.put('HOST', Js('localhost'))
    var.put('PORT', Js(65432.0))
    @Js
    def PyJs_anonymous_0_(req, res, this, arguments, var=var):
        var = Scope({'req':req, 'res':res, 'this':this, 'arguments':arguments}, var)
        var.registers(['res', 'req'])
        var.get('console').callprop('log', Js('sending data'))
        var.get('res').callprop('setHeader', Js('Content-Type'), Js('application/json'))
        var.get('res').callprop('writeHead', Js(200.0), Js({'Content-Type':Js('text/plain'),'Access-Control-Allow-Origin':Js('*'),'Access-Control-Allow-Methods':Js('GET,PUT,POST,DELETE')}))
        var.get('res').callprop('end', var.get('JSON').callprop('stringify', var.get('e')))
    PyJs_anonymous_0_._set_name('anonymous')
    var.put('ser', var.get('http').callprop('createServer', PyJs_anonymous_0_))
    var.get('ser').callprop('listen', var.get('PORT'), var.get('HOST'))
PyJsHoisted_display_.func_name = 'display'
var.put('display', PyJsHoisted_display_)
pass
pass

# Add lib to the module scope
test = var.to_python()


from . import views
from django.urls import path

app_name = 'release'

urlpatterns = [
    path('addAlbumRelease', views.AlbumView.as_view(), name='addNewAlbumRelease'),
    path('addSinglesRelease', views.SinglesView.as_view(), name='addNewSinglesRelease'),
    path('displayAlbum', views.DisplayAlbumView.as_view(), name='displayAlbum'),
    path('displaySingle', views.DisplaySingleView.as_view(), name='displaySingle'),
]