import flet as ft
import services.personajes_service as PJ
from typing import Callable
from utils import COLOR_PALETTE

def characters_view(update_func: Callable, page : ft.Page):
    #Funcion de control de paginas
    def next_page(e):
        r.controls.clear()
        if int(txt_number.value) < int(totalPages.value) :
            txt_number.value = int(txt_number.value) +1
            cards(page.client_storage.get("objectsPage"))
        else:
            txt_number.value = 1
            cards(page.client_storage.get("objectsPage"))

    def before_page(e):
        r.controls.clear()
        if int(txt_number.value) == 1:
            txt_number.value = int(totalPages.value)
            cards(page.client_storage.get("objectsPage"))

        else:
            txt_number.value = int(txt_number.value) - 1
            cards(page.client_storage.get("objectsPage"))

    def cards(cardsPage):
        if cardsPage != []:
            if int(txt_number.value) == int(totalPages.value):
                [
                    r.controls.append(
                        ft.Card(
                            ft.Container(
                                ft.Column(
                                    [
                                        ft.Text(cardsPage[i-1]["nombre"],color = COLOR_PALETTE["On-Primary"], text_align = "center" , selectable=False , ),
                                        ft.Image(
                                            src=cardsPage[i-1]['imagen'],
                                            width=100,
                                            height=100,
                                        ),
                                        ft.Text(cardsPage[i-1]["id"],color = COLOR_PALETTE["On-Primary"],selectable=False,text_align = "center", ),
                                        ft.Text(cardsPage[i-1]["descripcion"][:23]+"...",color = "#381e72",selectable=False,text_align = "center",),
                                    ],
                                    alignment=ft.MainAxisAlignment.CENTER,
                                    horizontal_alignment = ft.CrossAxisAlignment.CENTER,
                                ),
                                bgcolor= "#cfbcff",
                                border= ft.border.all(1,  "#C4ACFF"),
                                border_radius= ft.border_radius.all(5),
                                alignment = ft.alignment.center,
                            ),
                            width=200,
                            height=200,
                        )
                    )

                    for i in range(((-9)+(int(txt_number.value)*9))+1, (len(cardsPage))+1)
                ]

            else:
                [
                    r.controls.append(
                        ft.Card(
                            ft.Container(
                                ft.Column(
                                    [
                                        ft.Text(cardsPage[i-1]["nombre"],color = COLOR_PALETTE["On-Primary"], text_align = "center" , selectable=False , ),
                                        ft.Image(
                                            src=cardsPage[i-1]['imagen'],
                                            width=100,
                                            height=100,
                                        ),
                                        ft.Text(cardsPage[i-1]["id"],color = COLOR_PALETTE["On-Primary"],selectable=False,text_align = "center" , ),
                                        ft.Text(cardsPage[i-1]["descripcion"][:23]+"...",color = COLOR_PALETTE["On-Primary"],selectable=False,text_align = "center", ),
                                    ],
                                    alignment=ft.MainAxisAlignment.CENTER,
                                    horizontal_alignment = ft.CrossAxisAlignment.CENTER,
                                ),
                                bgcolor= "#cfbcff",
                                border= ft.border.all(1, "#C4ACFF"),
                                border_radius= ft.border_radius.all(5),
                                alignment = ft.alignment.center,
                            ),
                            width=200,
                            height=200,
                        )
                    )

                    for i in range(((-9)+(int(txt_number.value)*9))+1 ,(int(txt_number.value)*9)+1)
                ]

        else:
            r.controls.append(
                ft.Card(
                    ft.Container(
                        ft.Column(
                            [
                                ft.Text("No hay personajes", text_align = "center" ,color = "#381e72", selectable=False ),
                            ],
                            alignment=ft.MainAxisAlignment.CENTER,
                            horizontal_alignment = ft.CrossAxisAlignment.CENTER,
                        ),
                        bgcolor= COLOR_PALETTE["On-Error"],
                        border= ft.border.all(1,"#FCA196"),
                        border_radius= ft.border_radius.all(5),
                        alignment = ft.alignment.center,
                    ),
                    width=200,
                    height=200,
                ),
            ),

        update_func()

    def dropdown_changed(e):
        r.controls.clear()
        txt_number.value = 1
        update_func()

        if dd.value == "ALL The Characters":
            page.client_storage.set("objectsPage", requestF.copy())
            totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9)
        elif dd.value == "Characters with comics":
            page.client_storage.set("objectsPage", [data for data in requestF if data['comics'] != []])
            if len(page.client_storage.get("objectsPage")) % 9 == 0:
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9)
            else :
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9) + 1
        elif dd.value == "The *Avengers* comics":
            unique_sweets = []
            [unique_sweets.append(sweet) for sweet in [data for data in requestF for comic in data['comics'] if 'Avengers' in comic] if sweet not in unique_sweets]
            page.client_storage.set("objectsPage",unique_sweets)
            if len(page.client_storage.get("objectsPage")) % 9 == 0:
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9)
            else :
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9) + 1
        elif dd.value == "X-MEN comics":
            unique_sweets = []
            [unique_sweets.append(sweet) for sweet in [data for data in requestF for comic in data['comics'] if 'X-MEN' in comic] if sweet not in unique_sweets]
            page.client_storage.set("objectsPage",unique_sweets)
            if len(page.client_storage.get("objectsPage")) % 9 == 0:
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9)
            else :
                totalPages.value = int(len(page.client_storage.get("objectsPage")) / 9) + 1

        cards(page.client_storage.get("objectsPage"))

    requestF = PJ.get_data("personajes")()
    page.client_storage.set("objectsPage" ,requestF.copy())
    txt_number =  ft.Text(value="1",text_align="center",width=50)
    totalPages = ft.Text(value=int(len(page.client_storage.get("objectsPage")) / 9),text_align="center",width=50)
    r =  ft.Row(wrap=True, scroll="none", expand=True,)

    dd = ft.Dropdown(
        hint_text="Choose your filter",
        text_size= 20,
        alignment=ft.alignment.bottom_center,
        on_change=dropdown_changed,
        options=[
            ft.dropdown.Option("ALL The Characters"),
            ft.dropdown.Option("Characters with comics"),
            ft.dropdown.Option("The *Avengers* comics"),
            ft.dropdown.Option("X-MEN comics"),
        ],
    )

    appbar=ft.AppBar(
            title=ft.Text("Personajes", text_align="center", size=30, color = "#ffb0c9"),
            center_title=True,
            bgcolor=ft.colors.SURFACE_VARIANT,
            actions=[
                ft.Container(
                    content = ft.Row([dd,],alignment = ft.MainAxisAlignment.END,),
                    width = 800,
                    height=300,
                    margin = ft.margin.only(left=0,top=10,right=0,bottom=5),
                    alignment= ft.alignment.bottom_center ,
                ),
            ],
    )

    body = ft.Container(
        ft.Column(
            [
                ft.Container(
                    ft.Stack(
                        #Cuadricula INFO
                        [
                            r
                        ]
                    ),
                    border_radius=8,
                    padding=5,
                    width=800,
                    height=650,
                    alignment= ft.alignment.center,
                ),
                #Fila de flechas pra siguiente pagina
                ft.Row(
                    [
                        ft.IconButton(ft.icons.NAVIGATE_BEFORE_ROUNDED,on_click=before_page),
                        txt_number,
                        ft.IconButton(ft.icons.NAVIGATE_NEXT_ROUNDED,on_click=next_page),
                    ],
                    alignment= ft.MainAxisAlignment.CENTER,
                ),
                ft.Row(
                    [
                        totalPages,
                    ],
                    alignment= ft.MainAxisAlignment.END,
                ),
            ],
            horizontal_alignment = ft.CrossAxisAlignment.CENTER,
            alignment= "center",
        ),
        alignment=ft.alignment.center
    )

    cards(page.client_storage.get("objectsPage"))

    return [appbar, body]


class Solution:
    def findTheLongestSubstring(self, s: str) -> int:
        table = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}
        state = [-1] * (2**5)
        state[0] = 0
        cur = 0
        cnt = 0
        res = 0

        for i in s:
            if i in table:
                cur ^= table[i]
            if state[cur] != -1:
                res = max(res, cnt + 1 - state[cur])
            else:
                state[cur] = cnt + 1
            cnt += 1
        return res

if __name__ == '__main__':
    s = Solution()
    print(s.findTheLongestSubstring("eleetminicoworoep"))


import rdflib
from rdflib.term import Literal
from rdflib.term import URIRef
from itertools import groupby

TYPE_PRED = URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
DOMAIN_PRED = URIRef('http://www.w3.org/2000/01/rdf-schema#domain')
RANGE_PRED = URIRef('http://www.w3.org/2000/01/rdf-schema#range')
LABEL_PRED = URIRef('http://www.w3.org/2000/01/rdf-schema#label')
COMMENT_PRRD = URIRef('http://www.w3.org/2000/01/rdf-schema#comment')
DEFINEDBY_PRED = URIRef('http://www.w3.org/2000/01/rdf-schema#isDefinedBy')

SKIPPABLE_PREDS = [DEFINEDBY_PRED]

PROP_TYPE1 = rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#Property')
PROP_TYPE2 = rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#Property')
CLASS_TYPE = rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#Class')

def get_types(g):
    """
    Find all the top-level kinds in a RDF graph.
    """
    types = set()
    for subj, pred, obj in g:
        if pred == TYPE_PRED:
            types.add(obj)
    return sorted(types)

def get_subjects_by_type(g, typeval):
    """
    Find all all subjects of type `typeval`.
    """
    return g.subjects(predicate=TYPE_PRED, object=typeval)

# all_props =
# # A class --> property mapping (all properties that have domain one of these classes)

CONCEPT_PRED = URIRef('http://www.w3.org/2004/02/skos/core#Concept')
CONCEPT_SCHEME_PRED = URIRef('http://www.w3.org/2004/02/skos/core#ConceptScheme')
W3DTF_DATATYPE = URIRef('http://purl.org/dc/terms/W3CDTF')

# TODO: handle list-like attrs
# HAS_TOP_CONCEPT_PRED = URIRef('http://www.w3.org/2004/02/skos/core#hasTopConcept')

def get_vocab_props(g):
    concept_scheme = list(get_subjects_by_type(g, CONCEPT_SCHEME_PRED))[0]
    print('found concept_scheme=', concept_scheme)
    vocab_dict = {}
    vocab_dict['uri'] = str(concept_scheme)
    for pred, obj in g.predicate_objects(subject=concept_scheme):
        short_pred = g.namespace_manager.normalizeUri(pred)
        if isinstance(obj, URIRef):
            short_obj = g.namespace_manager.normalizeUri(obj)
            vocab_dict[short_pred] = short_obj
        elif isinstance(obj, Literal):
            if obj.datatype == W3DTF_DATATYPE:
                vocab_dict[short_pred] = str(obj)
            else:
                vocab_dict[short_pred] = obj.value
        else:
            print('found unexpected obj kind', kind(obj))
    return vocab_dict

def get_terms_props(g):
    concepts_list = []
    concepts = list(get_subjects_by_type(g, CONCEPT_PRED))
    print('found', len(concepts), 'concepts')
    for concept in concepts:
        concept_dict = {}
        concept_dict['uri'] = str(concept)
        for pred, obj in g.predicate_objects(subject=concept):
            short_pred = g.namespace_manager.normalizeUri(pred)
            if isinstance(obj, URIRef):
                short_obj = g.namespace_manager.normalizeUri(obj)
                concept_dict[short_pred] = short_obj
            elif isinstance(obj, Literal):
                if obj.datatype == W3DTF_DATATYPE:
                    concept_dict[short_pred] = str(obj)
                else:
                    concept_dict[short_pred] = obj.value
            else:
                print('found unexpected obj kind', kind(obj))
        concepts_list.append(concept_dict)
    return concepts_list

VOCAB_EXTRACT_DICT = {
    'description': 'dc:description',
    'title': 'dc:title',
}

VOCAB_TERM_EXTRACT_DICT = {
    'label': 'skos:prefLabel',
    'alt_label': 'skos:altLabel',
    'definition': 'skos:definition'
}

def skos_to_terms(g):
    vocab_data = {}
    # vocab
    vocab_dict = get_vocab_props(g)
    vocab_name = guess_name_from_uri(vocab_dict['uri'])
    vocab_data['type'] = 'ControlledVocabulary'
    vocab_data['name'] = vocab_name
    vocab_data['uri'] = vocab_dict['uri']
    for keydest, keysrc in VOCAB_EXTRACT_DICT.items():
        vocab_data[keydest] = vocab_dict.get(keysrc, None)
    # terms
    vocab_data['terms'] = []
    concepts_list = get_terms_props(g)
    for concept_dict in concepts_list:
        concept_data = {}
        term = concept_dict['uri'].split(vocab_name)[1].strip('/')
        if '/' in term:
            raise NotImplementedError('FOUND NESTED TERMS --- need to update code')
        concept_data['term'] = term
        for keydest, keysrc in VOCAB_TERM_EXTRACT_DICT.items():
            concept_data[keydest] = concept_dict.get(keysrc, None)
        concept_data['source_uri'] = concept_dict['uri']
        vocab_data['terms'].append(concept_data)
    return vocab_data

def guess_name_from_uri(uri):
    """
    Given a URI like host.tld/bla/fah/jah or host.tld/bla/fah/jah/, returns jah.
    """
    split_uri = uri.split('/')
    if split_uri[-1]:
        return split_uri[-1]    # no trailing slash
    else:
        return split_uri[-2]    # has trailing slash

# OLD

def build_class_props_map(g):
    class_props_map = {}

    # build dict with classes and class attrs first...
    all_classes = get_subjects_by_type(g, CLASS_TYPE)
    for aclass in all_classes:
        class_dict = {'properties':{}}
        class_dict['uri'] = aclass
        short_aclass = g.namespace_manager.normalizeUri(aclass)
        class_props_map[short_aclass] = class_dict
        for pred, obj in g.predicate_objects(subject=aclass):
            if pred in SKIPPABLE_PREDS:
                continue
            short_pred = g.namespace_manager.normalizeUri(pred)
            if isinstance(obj, URIRef):
                short_obj = g.namespace_manager.normalizeUri(obj)
                class_dict[short_pred] = short_obj
            elif isinstance(obj, Literal):
                class_dict[short_pred] = obj.value
            else:
                print('found unexpected obj kind', kind(obj))

    # now attach all the properties
    all_props = []
    all_props.extend(g.subjects(predicate=TYPE_PRED, object=PROP_TYPE1))
    all_props.extend(g.subjects(predicate=TYPE_PRED, object=PROP_TYPE2))
    for prop in all_props:
        prop_dict = {}
        for pred, obj in g.predicate_objects(subject=prop):
            if pred in SKIPPABLE_PREDS:
                continue
            if pred == DOMAIN_PRED:
                aclass = obj
                short_aclass = g.namespace_manager.normalizeUri(aclass)
                short_prop = g.namespace_manager.normalizeUri(prop)
                class_props_map[short_aclass]['properties'][short_prop] = prop_dict
            short_pred = g.namespace_manager.normalizeUri(pred)
            if isinstance(obj, URIRef):
                short_obj = g.namespace_manager.normalizeUri(obj)
                prop_dict[short_pred] = short_obj
            elif isinstance(obj, Literal):
                prop_dict[short_pred] = obj.value
            else:
                print('found unexpected obj kind', kind(obj))

    return class_props_map

def print_class_props_map(g, class_props_map):
    for short_aclass, aclass_dict in class_props_map.items():
        print(short_aclass, 'label=', aclass_dict.get('rdfs:label'))
        for short_prop, prop_dict in aclass_dict['properties'].items():
            print(short_prop +'\t' + prop_dict.get('rdfs:range', ''))
        print()


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 11:34:14 2019

@author: tqc268
"""

import pandas as pd
import pickle
import numpy as np
# if potato has a funny name
for key, value in allresults.items():
    for kl, vl in value.items():
        if kl == 'Potato; Sava_Figaro':
            value['Potato'] = value.pop(kl)

#data = pickle.load(open("dict.pkl","rb"))

data = allresults
# Assuming some precedence of attributes for your data here!
index = ['Rotation','ManureMass', 'IsConventional', 'SoilType','Weather','InitLevel','Crop','Yield']

# Creating an empty Pandas Dataframe with the columns from above
mDf = pd.DataFrame(columns=index)
mDf.head()

# Loading your dictionary to Pandas

df = pd.DataFrame.from_dict(data)
df
# Column names will be split and entered as new entries per row
colNames = list(df.columns)

# Crops are stored as row names in pandas
crops = list(df.index)

# Lot of things are going on here!
# You can check out what's going on.
# There are two list comprehensions: Inner one makes one row entry with your file name now appended with crop name and yield
# Outer one loops through each of the 162 entries

hierEntries = [np.asarray([(colNames[i]+'_'+crops[b]+'_'+repr(df.iloc[b,i])).split('_') for b in range(len(crops))]) for i in range(len(df.columns))]

# The previous step results in a 3D array; changing it to 2d arrays
hierEntries = (np.asarray(hierEntries)).reshape(-1,len(index))

# Make a Pandas dataframe out of these entries
hierEntries = pd.DataFrame(hierEntries,columns=index)

# Load it into the empty frame we made
mDf = mDf.append(hierEntries)

# The coolest step is this one which just takes your frame from above and
# makes a hierarchical array as shown below.
# The keys to sort are all but the yield.
# This resembles the table you had printed!
hierDf = mDf.set_index(index[:-1])
dfH = hierDf.swaplevel('ManureMass', 'InitLevel')
# dfH = hierDf.reorder_levels(order =['Rotation','InitLevel', 'IsConventional', 'SoilType','Weather','ManureMass', 'Crop'] )


#
# @lc app=leetcode.cn id=6 lang=python3
#
# [6] Z 字形变换
#

# @lc code=start
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        end_str = ''
        for i in range(numRows):
            sl = len(s) / (2 * numRows - 2)
            sl = int(sl) + 1 if sl > int(sl) else int(sl)
            for j in range(sl):
                k = i + j * (2 * numRows - 2)
                if k >= len(s):
                    break
                end_str += s[k]

                if i != 0 and i != (numRows - 1):
                    k1 = (numRows - i) * 2 - 2 + k
                    if k1 >= len(s):
                        break
                    end_str += s[k1]
        return end_str
# @lc code=end


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

#########################################################################################################################
# IMPORTATION
#########################################################################################################################
import sys
import PyQt5
from PyQt5.QtWidgets import QWidget, QFrame, QApplication
from PyQt5.QtWidgets import QVBoxLayout,QHBoxLayout,QSplitter,QGridLayout
from PyQt5.QtWidgets import QLabel, QPushButton, QLineEdit, QSpinBox, QDoubleSpinBox, QSlider, QComboBox, QFileDialog
from PyQt5.QtCore    import Qt, QThread, QTimer, QObject, pyqtSignal, pyqtSlot, QRect, QLine
from PyQt5.QtGui     import QPainter

import numpy     as np
import pyqtgraph as pg
import os

from s_LogDisplay_class               import LogDisplay
from s_Workers_class                  import *
from s_ToolObjects_class              import QVLine
from s_Miscellaneous_functions        import *
from s_SimuCamera_class               import SimuCamera
from s_Camera_class                   import Camera

import time
#########################################################################################################################
# FUNCTIONS
#########################################################################################################################

class CameraDisplay(QWidget):
    frame_updated = pyqtSignal()
    # ~~~~~~~~~~~~~~~~~~~~~~~~ #
    def __init__(self, camera=None, log=None, fps=10.):
        super().__init__()
        # ---  --- #
        if log != None:
            self.log = log
        else:
            self.log = LogDisplay()
        #self.log.show()
        # --- default --- #
        self.fps       = fps
        self.normalise_hist = True
        self.cmap      = 'jet'
        # --- main attriute --- #
        self.camera    = camera
        self.contview  = ContinuousView(fps=self.fps)
        self.timer     = pg.QtCore.QTimer() #QTimer()# pg.QtCore.QTimer()
        self.qlabl_max = QLabel()
        self.isOn      = False
        self.frame     = None
        # --- color acuisition --- #
        self.initColorDic()
        # ---  --- #
        self.initUI()
        self.initCamera(camera)
        # ---  --- #
        self.camera.setExposure( self.exposure.value() )

    def initUI(self):
        # ---  --- #
        self.layout      = QVBoxLayout(self)
        self.initView()
        # --- button widget --- #
        self.button_startstop = QPushButton('Start/Stop')
        self.button_startstop.setStyleSheet("background-color: red")
        self.button_nextFrame = QPushButton('Next frame')
        # ---  --- #
        self.fps_input     = QSpinBox()
        self.fps_input.setRange(1, 48)
        self.fps_input.setValue(self.fps)
        self.exposure      = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.cam_framerate = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.pixelclock    = QDoubleSpinBox()
        self.which_camera  = QComboBox()
        self.which_camera.addItem('USB camera')
        self.which_camera.addItem('From Image Dir.')
        # --- set default --- #
        self.exposure.setRange(0.10, 99.0)
        self.exposure.setValue(12.5)
        self.cam_framerate.setRange(1.00, 15.0)
        self.cam_framerate.setValue( 10.0 )
        self.pixelclock.setRange(5, 30)
        self.pixelclock.setValue(20)
        # --- connections --- #
        self.button_startstop.clicked.connect(self.startStop_continuous_view)
        self.fps_input.valueChanged.connect(self.setFPS)
        self.button_nextFrame.clicked.connect( self.nextFrame )
        self.exposure.valueChanged.connect( self.update_exposure )
        self.cam_framerate.valueChanged.connect( self.update_camFPS )
        self.pixelclock.valueChanged.connect( self.update_pixelClock )
        self.which_camera.currentIndexChanged.connect( self.changeCameraStyle )
        # --- layout --- #
        label_1 = QLabel('fps :')
        label_1.setWordWrap(True)
        label_2 = QLabel('value max:')
        label_2.setWordWrap(True)
        label_3 = QLabel('Which camera')
        label_3.setWordWrap(True)
        label_4 = QLabel('Exposure (ms):')
        label_4.setWordWrap(True)
        label_5 = QLabel('Camera fps:')
        label_5.setWordWrap(True)
        label_6 = QLabel('Pixel clock (MHz):')
        label_6.setWordWrap(True)
        grid = QGridLayout()
        grid.addWidget( self.button_startstop, 0,0)
        grid.addWidget( self.button_nextFrame, 0,1)
        grid.addWidget( label_1              , 0,2)
        grid.addWidget( self.fps_input       , 0,3)
        grid.addWidget( label_2              , 0,4)
        grid.addWidget( self.qlabl_max       , 0,5)
        grid.addWidget(QVLine()              , 0,6 , 2,1)
        grid.addWidget(label_3               , 0,7)
        grid.addWidget( self.which_camera    , 1,7 , 2,1)
        grid.addWidget(label_4               , 1,0)
        grid.addWidget( self.exposure        , 1,1)
        grid.addWidget(label_5               , 1,2)
        grid.addWidget( self.cam_framerate   , 1,3)
        grid.addWidget(label_6               , 1,4)
        grid.addWidget( self.pixelclock      , 1,5)
        self.layout.addLayout(grid)
        self.layout.addWidget(self.image_view)
        self.setLayout(self.layout)

    def initColorDic(self):
        self.colordic = {}
        # --- jet-like cmap --- #
        alpha     = 1.0
        positions = [0.2, 0.5, 0.75, 1.0]
        colors    = [[0,0,1.,alpha],[0,1.,1.,alpha],[1.,1.,0,alpha],[170/255,0,0,alpha]] #colors    = ['#0000ff', '#00ffff', '#ffff00', '#aa0000']
        self.colordic['jet'] = pg.ColorMap(positions, colors)
        # --- jet reversed cmap --- #
        positions_r = [1-p_ for p_ in positions]
        self.colordic['jet_r'] = pg.ColorMap(positions_r, colors)
        # --- plasma cmap --- #
        self.colordic['plasma'] = generatePgColormap('plasma')

    def initView(self):
        self.image_view     = pg.ImageView()
        # ---  --- #
        self.image_view.setColorMap(self.colordic[self.cmap])
        self.image_view.setLevels(0,255)
        self.image_view.getHistogramWidget().item.setHistogramRange(0,255)
        # ---  --- #
        self.image_view.setMinimumWidth(800)
        self.image_view.setMinimumHeight(600)

    def initCamera(self, camera):
        self.default_camera = camera
        self.simu_camera    = SimuCamera(directory_path=os.getcwd(), log=self.log)
        # ---  --- #
        self.camera = self.default_camera
        if not self.camera.isCameraInit:
            self.camera.__init__()

    def hideHistogram(self):
        self.image_view.ui.histogram.hide()

    def hidePlotButtons(self):
        self.image_view.ui.roiBtn.hide()
        self.image_view.ui.menuBtn.hide()

    def setFPS(self):
        self.fps = self.fps_input.value()
        self.contview.setFPS( self.fps )
        self.timer.setInterval(1e3/self.fps)

    def update_frame(self):
        self.frame = self.camera.get_frame()
        self.qlabl_max.setText( str(np.max(self.frame)) )
        self.image_view.setImage(self.frame.T, autoHistogramRange=False, autoLevels=False)
        self.frame_updated.emit()

    def update_exposure(self):
        self.camera.setExposure( self.exposure.value() )
        self.log.addText( 'New exposure: {}ms'.format( self.camera.getExposure() ) )
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )

    def update_camFPS(self):
        newfps = self.camera.setFrameRate( self.cam_framerate.value() )
        self.log.addText('New camera fps: {:.3f}'.format( self.camera.getFrameRate() ) )
        self.cam_framerate.setValue(newfps)
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def update_pixelClock(self):
        self.camera.setPixelClock( int(self.pixelclock.value()) )
        self.log.addText( 'New pixel clock: {}Mhz'.format( self.camera.getPixelClock() ))
        # ---  --- #
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def nextFrame(self):
        wasOn = self.isOn
        if not self.isOn:
            self.camera.capture_video()
        # ---  --- #
        self.update_frame()
        # ---  --- #
        if not wasOn:
            self.camera.capture_video()

    def startStop_continuous_view(self):
        if  self.isOn:
            self.stop_continuous_view()
            self.button_startstop.setStyleSheet("background-color: red")
            self.button_nextFrame.setFlat(False)
            self.button_nextFrame.setEnabled(True)
        else:
            self.start_continuous_view()
            self.button_startstop.setStyleSheet("background-color: green")
            self.button_nextFrame.setFlat(True)
            self.button_nextFrame.setEnabled(False)

    def start_continuous_view(self):
        self.camera.capture_video()
        if   True:
            self.start_continuous_view_qtimer()
        elif False:
            self.start_continuous_view_qthread()
        # ---  --- #
        self.isOn = True

    def stop_continuous_view(self):
        self.camera.stop_video()
        if   True:
            self.stop_continuous_view_qtimer()
        elif False:
            self.stop_continuous_view_qthread()
        # ---  --- #
        self.isOn = False

    def start_continuous_view_qthread(self):
        # ---  --- #
        self.thread = QThread()
        self.thread.setTerminationEnabled(True)
        # --- connect --- #
        self.contview.moveToThread(self.thread)
        self.thread.started.connect(self.contview.startFeed)
        self.contview.newshot.connect(self.update_image)
        self.contview.finished.connect(self.thread.quit)
        # ---  --- #
        self.thread.start()

    def stop_continuous_view_qthread(self):
        self.contview.stopFeed()

    def start_continuous_view_qtimer(self):
        # ---  --- #
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1e3/self.fps) #ms

    def stop_continuous_view_qtimer(self):
        self.timer.stop()

    def changeCameraStyle(self):
        self.camera.stop_video()
        # ---  --- #
        indx = self.which_camera.currentIndex()
        if   indx == 0:
            self.camera = self.default_camera
            # ---  --- #
            self.exposure.setEnabled(True)
            self.cam_framerate.setEnabled(True)
            self.pixelclock.setEnabled(True)
        elif indx == 1:
            self.camera.stop_video()
            dir_path    = QFileDialog().getExistingDirectory()
            self.log.addText('NEW DIR PATH: {}'.format(dir_path))
            self.simu_camera.setDirectoryPath( dir_path )
            self.simu_camera.initialize()
            self.camera = self.simu_camera
            # ---  --- #
            self.exposure.setEnabled(False)
            self.cam_framerate.setEnabled(False)
            self.pixelclock.setEnabled(False)

#########################################################################################################################
# CODE
#########################################################################################################################
if __name__ == '__main__':
    print('STARTING')
    dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
    camera   = Camera(cam_id=0)
    if not camera.isCameraInit:
        camera = SimuCamera(0, directory_path=dir_path)
        camera.__info__()

    app = QApplication([])
    start_window = CameraDisplay(camera)
    start_window.show()
    app.exit(app.exec_())
    print('Close camera')
    camera.close_camera()

    print('FINISHED')


import numpy as np
import tensorflow as tf
#产生资料集
def CreateDatasets(Category,Amount,Dimension):
    #测试特征
    x_list = np.random.random((Amount, Dimension)) * Category    #建立好维度，乘上分类大小。

    #测试标签
    y_list = ((x_list[:,0]+x_list[:,1])/2).astype(int)       #将两个特征值平均后，取整数(转int取整)。

    #测试答案-向量化
    y_list2=tf.keras.utils.to_categorical(y_list, num_classes=(Category)) #记得最后一个建构子不要乱填。

    #回传
    return x_list, y_list,y_list2

#资料设定
category=4  #答案的种类数，也会决定特征的最大数值
dimension=2 #特征数

#呼叫函式
x_train,y_train,y_train2=CreateDatasets(category,2000,dimension)

#-------------------------------------------------------------------

units_Base=3
#建立模型
model=tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=10*units_Base,activation=tf.nn.relu,input_dim=dimension),
    tf.keras.layers.Dense(units=10*units_Base,activation=tf.nn.relu),
    tf.keras.layers.Dense(units=10*units_Base,activation=tf.nn.relu),
    tf.keras.layers.Dense(units=category,activation=tf.nn.relu),
])

#编译
model.compile(optimizer='adam',
              loss=tf.keras.losses.categorical_crossentropy,
              metrics=['accuracy'])

#训练
epochs_Base=10
model.fit(x_train,y_train2,epochs=10*epochs_Base,batch_size=30)

#测试
x_test,y_test,y_test2=CreateDatasets(category,10,dimension) #产生测试用资料集
score= model.evaluate(x_test,y_test2,batch_size=50)
print('权重：',score)


# -*- coding: utf-8 -*-
# To install 'inotify'
# $ pip install inotify --no-binary :all:
#
# To install 'boto3'
# $ pip install boto3
#
# To connect AWS, you should set up authentication credentials.
# note: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html
#
#
# This is Amazon S3 Examples
# > https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-examples.html

import inotify.adapters
import boto3

# Create an S3 client
s3 = boto3.client('s3')

i = inotify.adapters.Inotify()

# monitor specific folders
# 기본 dir 에 python 파일이 존재하고, jetson 에 sd card 에서 detect 한 이미지가 업로드되는 상황
watch_path = '../../media/nvidia/test_sd'
i.add_watch(watch_path)

for event in i.event_gen(yield_nones = False):
    (header, type_names, path, saved_filename) = event
    # print("PATH=[{}]\tFILENAME=[{}]\tEVENT_TYPES={}".format(path, filename, type_names))

    # 모니터 하고 있는 폴더에 파일이 생성될 때만 실행
    if type_names[0] == 'IN_CREATE':

        # type_names[0]의 type은 유니코드인데
        # s3에 올리기 위해서는 string이어야 하기 때문에 "utf-8"로 인코딩
        upload_file_name = saved_filename.encode("utf-8")

        # *S3 업로드 설정*
        # s3에 올리고자 하는 파일의 이름(폴더에 저장된 파일의 이름)
        filename = upload_file_name

        # aws s3에서 저장을 원하는 bucket 지정
        bucket_name = 'flexadstest'

        # s3에서의 objectname 설정
        objectname = filename
        # objectname = 'FlexAds_logo_init.png'

        # upload the file to AWS S3
        # 업로드 할 파일의 이름을 지정할 때, 본 파일과 같은 경로에 저장할 수도 있기 떄문에
        # 파일 이름에 경로까지 지정해주어야 업로드가 정상적으로 작동함
        s3.upload_file(watch_path + filename, bucket_name, objectname)


import cv2

# our video
video = cv2.VideoCapture('Self-Driving.mp4')

# our pre-trained car classifier
cls_file = 'car_detector.xml'

# create car classifier
car_tracker = cv2.CascadeClassifier(cls_file)

# Run forever..
while True:
    # Read the current frame from video
    (read_successful, frame) = video.read()

    # safe coding
    if read_successful:
        grayscale_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    else:
        break

    # detect car
    cars = car_tracker.detectMultiScale(grayscale_frame)

    # Draw rectangles around the cars
    for (x, y, w, h) in cars:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)

    # Display the image with the faces spotted
    cv2.imshow('Car Detector', frame)

    # Dont autoclose
    key = cv2.waitKey(1)

    if key == 81 or key == 113:
        break

# releasing all frames..
video.release()


# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>

#PUNTO 1B
from pylab import *

import csv
import matplotlib.pyplot as plt
import pandas
from pandas import *

df_bog=pandas.read_csv('Bogota.csv', sep=' ')
df_bquilla=pandas.read_csv('Barranquilla.csv', sep=' ')
df_bucara=pandas.read_csv('Bucaramanga.csv', sep=' ')
df_cali=pandas.read_csv('Cali.csv', sep=' ')
df_ipiales=pandas.read_csv('Ipiales.csv', sep=' ')

F_bog=df_bog['yr']
F_bquilla=df_bquilla['yr']
F_bucara=df_bucara['yr']
F_cali=df_cali['yr']
F_ipiales=df_ipiales['yr']

Temp_bog=df_bog['Temperatura']
Temp_bquilla=df_bquilla['Temperatura']
Temp_bucara=df_bucara['Temperatura']
Temp_cali=df_cali['Temperatura']
Temp_ipiales=df_ipiales['Temperatura']

L=range(len(Temp_bog))

#ORIGINAL
plot(F_bog,Temp_bog,label=r"$Bogota$")
plot(F_bquilla,Temp_bquilla,label=r"$Baranquilla$")
plot(F_bucara,Temp_bucara,label=r"$Bucaramanga$")
plot(F_cali,Temp_cali,label=r"$Cali$")
plot(F_ipiales,Temp_ipiales,label=r"$Ipiales$")
legend(loc=0, fontsize=7)
title("Temperatura ciudades de Colombia")
ylabel('Temperatura')
xlabel('Yr')
show()

#INTERPOLACION LINEAL
LIN_bog=Series(Temp_bog).interpolate()
LIN_bquilla=Series(Temp_bquilla).interpolate()
LIN_bucara=Series(Temp_bucara).interpolate()
LIN_cali=Series(Temp_cali).interpolate()
LIN_ipiales=Series(Temp_ipiales).interpolate()

plot(F_bog,LIN_bog,label=r"$Bogota$")
plot(F_bquilla,LIN_bquilla,label=r"$Baranquilla$")
plot(F_bucara,LIN_bucara,label=r"$Bucaramanga$")
plot(F_cali,LIN_cali,label=r"$Cali$")
plot(F_ipiales,LIN_ipiales,label=r"$Ipiales$")
legend(loc=0, fontsize=7)
title("Temperatura ciudades de Colombia - Interp. Lineal")
ylabel('Temperatura')
xlabel('Yr')
show()

#INTERPOLACION POLINOMICA (Grado 2)
POL_bog=Series.interpolate(Temp_bog,method='quadratic')
POL_bquilla=Series.interpolate(Temp_bquilla, method='quadratic')
POL_bucara=Series.interpolate(Temp_bucara,method='quadratic')
POL_ipiales=Series.interpolate(Temp_ipiales, method='quadratic')
POL_cali=Series.interpolate(Temp_cali,method='quadratic')

plot(F_bog,POL_bog,label=r"$Bogota$")
plot(F_bquilla,POL_bquilla,label=r"$Baranquilla$")
plot(F_bucara,POL_bucara,label=r"$Bucaramanga$")
plot(F_cali,POL_cali,label=r"$Cali$")
plot(F_ipiales,POL_ipiales,label=r"$Ipiales$")
legend(loc=0, fontsize=7)
title("Temperatura ciudades de Colombia - Interp. Cuadratica")
ylabel('Temperatura')
xlabel('Yr')
show()

#Interpolacion por splines
SP_bog=Temp_bog.interpolate(method='spline', order=3)
SP_bquilla=Temp_bquilla.interpolate(method='spline', order=3)
SP_bucara=Temp_bucara.interpolate(method='spline', order=3)
SP_ipiales=Temp_ipiales.interpolate(method='spline', order=3)
SP_cali=Temp_cali.interpolate(method='spline', order=3)

plot(F_bog,SP_bog,label=r"$Bogota$")
plot(F_bquilla,SP_bquilla,label=r"$Baranquilla$")
plot(F_bucara,SP_bucara,label=r"$Bucaramanga$")
plot(F_cali,SP_cali,label=r"$Cali$")
plot(F_ipiales,SP_ipiales,label=r"$Ipiales$")
legend(loc=0, fontsize=7)
title("Temperatura ciudades de Colombia - Interp. Spline")
ylabel('Temperatura')
xlabel('Yr')
show()

#Conclusion: Mejor predictor
#Aunque en realidad el primer grafico de la serie de tiempo pertenece a una distribucion discreta se genera con lineas (continua con saltos) para que sea mas simple la comparacion entre el original y la extrapolacion de datos que rellenaria la serie con datos estimados a partir de los datos originales.

#A simple vista el que mejor parece ajustarse a los datos  es el metodo de spline, seguido por el lineal y finalmente el cuadratico. Con respecto al metodo cuadratico se observa que arroja datos muy incoerentes que se salen del rango de Temperaturas normales para Colombia

plot(F_bog,LIN_bog,label=r"$Bogota_LIN$")
plot(F_bog,POL_bog,label=r"$Bogota_POL$")
plot(F_bog,SP_bog,label=r"$Bogota_SP$")

legend(loc=0, fontsize=7)
title("Temperatura ciudades de Colombia - Interp.")
ylabel('Temperatura')
xlabel('Yr')
show()

#Se observa que la interpolacion por spline y la lineal se encuentran en rangos normales y tienen una secuencia consistente entre los datos predichos y los datos dados.

#Los archivos .csv para cada una de las ciudades son generados a partir de el script .R hay que tener cuidado porque en ocasiones no se guardan en la carpeta en la cual se esta trabajando
#!("rm Bogota.csv")
#!("rm Barranquilla.csv")
#!("rm Bucaramanga.csv")
#!("rm Cali.csv")
#!("rm Ipiales.csv")


#FIO-specific functions for AEP dimms
from generic import *
import pprint
import os
import sys

#Get NUMA Node of pmem device
def getPmemNode(pmemdev):
	pmem_mdev = pmemdev.replace('/dev/', '')
	nnode = None
	try:
		with open("/sys/block/%s/device/numa_node" % pmem_mdev, 'r') as iFD:
			nnode = int(iFD.readline().strip())
	except:
		generic.wlprint("ERROR: Could not open numa_node for `%s`" % pmemdev)

	return nnode

#Execute FIO with json output; iops and throughput only.
# Latency later maybe down the road.
#
# Return a json of the output
def fioExecute(jobfile):
	pass

# Create a simple jobfile based on simple input data
def genFio(pmemdev, oFile, append=False):
	pass

#These should be untouched globals so we always know how to find them
FIORunFile="/tmp/test.fiojob"
FIOOutFile="/tmp/test.fioout"

def formulateResults(fioJsonOut):
	results = None
	try:
		with open(fioJsonOut, 'r') as iFD:
			results = json.loads(iFD.read())

	except:
		wlprint("ERROR: Could not load json file %s" % fioJsonOut)

	output = {
		'totals':{
			'read':0,
			'readio':0,
			'write':0,
			'writeio':0,
		},
		'disk':{},
	}

	for entry in results['jobs']:
		# print("Entry for formulateResults")
		# pprint.pprint(entry)
		if entry['jobname'] not in  output['disk']:
			output['disk'][entry['jobname']] = {
				'read':0,
				'readio':0,
				'write':0,
				'writeio':0,
			}

		#BW entries are in bytes; we'll keep them as-is initially.
		output['disk'][entry['jobname']]['read'] += entry['read']['bw_bytes']
		output['disk'][entry['jobname']]['write'] += entry['write']['bw_bytes']

		output['disk'][entry['jobname']]['readio'] += entry['read']['iops']
		output['disk'][entry['jobname']]['writeio'] += entry['write']['iops']

		output['totals']['read'] += entry['read']['bw_bytes']
		output['totals']['write'] += entry['write']['bw_bytes']
		output['totals']['readio'] += entry['read']['iops']
		output['totals']['writeio'] += entry['write']['iops']

	return output

#This expects results from formulateResults.
# bwInData should be a 4 value dict
def validateResults(inData, jsonIn):
	perDisk = {}

	for entry in inData:
		if inData[entry] != -1:
			perDisk[entry] = inData[entry]/len(jsonIn['disk'])

	errors = []
	warnings = []
	for entry in jsonIn['disk']:
		for value in perDisk:
			if jsonIn['disk'][entry][value] < (perDisk[value] - (perDisk[value]*0.1) ):
				errors.append("ERROR: %s is outside of perDisk value for %s (%s) with data: %s" % (entry, value, str(perDisk[value]), str(jsonIn['disk'][entry][value])))
			elif jsonIn['disk'][entry][value] > (perDisk[value] + (perDisk[value]*0.1)):
				warnings.append("WARNING: %s is outside of perDisk value for %s (%s) with data: %s" % (entry, value, str(perDisk[value]), str(jsonIn['disk'][entry][value])))

	if len(errors):
		wlprint("ERRORS Occurred during validateResults:")
		for entry in errors:
			wlprint(entry)

	for entry in warnings:
		wlprint(entry)

	return len(errors)

#Indata formatter for validateresults
def validateResultsInData(readbw=-1, readio=-1, writebw=-1, writeio=-1):
	return {
		"read":readbw,
		"write":writebw,
		"readio":readio,
		"writeio":writeio,
	}

# Create a simple jobfile based on pmem name, then execute it.
# pmemdev should be a list
# outputAppend changes the output file to be concat'd with outputAppend
def quickFio(pmemdev, rwmode="write", directory=None, single=False, outputAppend=""):
	data = [
		"[global]",
		"direct=1",
		"ioengine=libaio",
		# "runtime=180",
		"runtime=5",
		"iodepth=1",
		"bs=4M",
		"disable_lat=1",
		"disable_clat=1",
		"disable_slat=1",
		"lat_percentiles=0",
		"clat_percentiles=0",
	]

	if rwmode == "write":
		data.append("numjobs=4")
	elif rwmode == "read":
		data.append("numjobs=12")
	elif rwmode == "rw":
		data.append("numjobs=4")
	elif rwmode == "randwrite":
		data.append("numjobs=4")
	elif rwmode == "randread":
		data.append("numjobs=12")
	elif rwmode == "randrw":
		data.append("numjobs=4")
	else:
		data.append("numjobs=4")

	data.append("rw=%s" % rwmode)

	if not isinstance(pmemdev, list):
		wlprint("ERROR: quickFio() called with non-list pmemdev")
		return -1

	if directory:
		#data.append("fill_fs=1")
		data.append("size=1G")
		if not os.path.exists(directory):
			os.mkdir(directory)

		if not os.path.isdir(directory):
			wlprint("ERROR: quickFio() directory is not a directory `%s`" % directory)
			sys.exit(-1)
	else:
		data.append("fill_device=1")

	data.append(" ")

	with open(FIORunFile, "w+") as oFD:
		for line in data:
			oFD.write("%s\n" % line)

	for entry in pmemdev:
		pmemn = entry.split("/")[-1]

		numanode = getPmemNumaNode(entry)
		with open(FIORunFile, "a+") as oFD:

			oFD.write("[%s]\n" % pmemn)
			if single == True:
				oFD.write("stonewall\n")

			oFD.write("numa_cpu_nodes=%s\n" % numanode)

			if directory:
				#Purge and recreate the directory
				if os.path.exists("%s/%s" % (directory, pmemn)):
					shutil.rmtree("%s/%s" % (directory, pmemn))

				os.mkdir("%s/%s" % (directory, pmemn))

				# oFD.write("size=1G\n")
				oFD.write("directory=%s\n" % directory)
				# oFD.write("filename=%s_io\n\n" % pmemn)

			else:
				oFD.write("filename=%s\n\n" % entry)

	fioData = getProcRC(["/usr/local/bin/fio", FIORunFile, "--output-format=json", "--output=%s" % str(FIOOutFile + str(outputAppend)) ])
	if fioData:
		wlprint("ERROR: quickFio() fio got bad return code %d" % fioData)
		return 3

	return 0

#Not in use yet
# Create a detailed jobfile based on complex input data.
# All negative numbers mean the argument gets purged
def genFioD(pmemdev, oFile, bs, iodepth, ioengine, append=False):
	pass

#Not in use yet
fioCPArgs = {
	'bs':['4k','8k','64k','128k','256k','1m','2m','4m','8m'],
	'iodepth':[1,2,4,8,16,32,64,128,256,512],
	'numjobs':[1,2,4,8,16,20,24],
	'rw':['read','write','rw','randread','randwrite','randrw'],
	'rwmixread':[5,10,30,50,70,90,95],
	'ioengine':['sync','libaio'],
}

#Not in use yet
# Create cartesian product jobfile with a predetermined set of arguments
def genFioCP(pmemdev, oFile):
	pass

# Write with FIO until the disk is full
# Return fioExecute output
def writeSingleFile(disk, mountp):
	pass


# @Author: u14e
# @Time  : 2019/1/20 17:41
# @description:
import time

def count(num):
    print(f'start count {num}')
    time.sleep(1)
    print(f'end count {num}')

def main():
    for i in range(1, 4):
        count(i)

if __name__ == '__main__':
    import time
    s = time.perf_counter()

    main()

    elapsed = time.perf_counter() - s
    print(f'{__file__} executed in {elapsed:0.2f} seconds.')


list1=[]
n=int(input("Enter no of elements in list "))
print("Enter list elements ")
for i in range(n):
    list1.append(int(input()))

def Even(my_list):
    evn=[]
    for i in my_list:
        if i%2==0:
            evn.append(i)

    return evn

print("Even no list : ",Even(list1))


#! /usr/bin/env python3

import sys
from rich import print
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
import aoc_utils
import collections

day = '07'
test_assertion_a = 37
test_assertion_b = 168

def part_a(lines):
    crab_positions = sorted([int(p) for p in lines[0].split(',')])
    max_position = crab_positions[-1]
    # crabs_at_positions represents how many crabs are at each position
    crabs_at_positions = [0] * (max_position + 1)
    for crab in crab_positions:
        crabs_at_positions[crab] += 1
    # Strategy - The cost for moving all crabs to position P is the sum of
    # 1. The cost of moving all crabs to the left of P to P and
    # 2. The cost of moving all the crabs to the right of P to P
    # Working from left to right we calculate the cost of moving all the crabs to the left
    # of each position to that position (cost_left). This is O(N) time.
    # Then we do the mirror - work from right to left calculating the cost of moving all the
    # crabs to the right of each position to that position (cost_right). Also O(N) time.
    # Then at each position sum the values of cost_left and cost_right to get the total
    # cost of moving all crabs to that position.
    cost_left = [0] * (max_position + 1)
    num_crabs_left = 0
    for pos in range(len(cost_left)):
        if pos > 0:
            # Start with the cost of the previous position
            cost_left[pos] += cost_left[pos-1]
            # Add the crabs at position-1 to the total number to the left
            num_crabs_left += crabs_at_positions[pos-1]
            # Add the cost of moving all the crabs to the left one more position
            cost_left[pos] += num_crabs_left
    # Repeat as above, except from the right
    cost_right = [0] * (max_position + 1)
    num_crabs_right = 0
    for pos in range(len(cost_right) - 1, -1, -1):
        if pos < len(cost_right) - 1:
            cost_right[pos] += cost_right[pos + 1]
            num_crabs_right += crabs_at_positions[pos+1]
            cost_right[pos] += num_crabs_right
    cost = [cost_left[i] + cost_right[i] for i in range(max_position + 1)]
    return min(cost)

def part_b(lines):
    crab_positions = sorted([int(p) for p in lines[0].split(',')])
    max_position = crab_positions[-1]
    crabs_positions = collections.Counter(crab_positions)
    cost = [0] * (max_position + 1)
    # Brute force seems sloppy, but can't think of a better way at the moment.
    # This is O(NR) time where
    # - N is number of crabs
    # - R is the range of positions they occupy
    # Rather than keeping a running step_cost for each crab we could use something like
    # step_cost = (d^2 + d)/2 where d = abs(p-pos) # arithemtic progression
    # which would save a bit of space.
    for pos, count in crabs_positions.items():
        step_cost = 0
        for p in range(pos - 1, -1, -1):
            step_cost += count * abs(p - pos)
            cost[p] += step_cost
        step_cost = 0
        for p in range(pos + 1, max_position + 1):
            step_cost += count * abs(p - pos)
            cost[p] += step_cost
    return min(cost)

aoc_utils.test_and_execute(part_a, day, test_assertion_a, Path(__file__).parent)
aoc_utils.test_and_execute(part_b, day, test_assertion_b, Path(__file__).parent)


"""Create necessary functionality to setup the database."""

import os
import sys
import transaction
import datetime

from pyramid.paster import (
    get_appsettings,
    setup_logging,
)

from pyramid.scripts.common import parse_vars

from ..models.meta import Base
from ..models import (
    get_engine,
    get_session_factory,
    get_tm_session,
)
from ..models.mymodel import JournalEntry
from ..data.lj_entries import ENTRIES

def usage(argv):
    """Do some stuff that I don't understand."""
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)

def main(argv=sys.argv):
    """Set up and handle the database."""
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    settings['sqlalchemy.url'] = os.environ['DATABASE_URL']
    engine = get_engine(settings)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    session_factory = get_session_factory(engine)
    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)
        for entry in ENTRIES:
            model = JournalEntry(title=entry['title'],
                                 body=entry['body'],
                                 author=entry['author'],
                                 date=datetime.datetime.strptime(entry['date'],
                                                                 '%Y-%m-%d'))
            dbsession.add(model)


import unittest

class TreeBase:
    """
    Abstract base class
    """

    class Position:
        def element(self):
            raise NotImplementedError

        def __eq__(self, other):
            raise NotImplementedError

        def __ne__(self, other):
            return not (self == other)

    def root(self):
        raise NotImplementedError

    def is_root(self, p):
        return self.root() == p

    def parent(self, p):
        raise NotImplementedError

    def num_children(self, p):
        raise NotImplementedError

    def children(self, p):
        raise NotImplementedError

    def is_leaf(self, p):
        return self.num_children(p) == 0

    def __len__(self):
        raise NotImplementedError

    def is_empty(self):
        return len(self) == 0

class BinaryTreeBase(TreeBase):
    def __init__(self):
        super().__init__()

    def left(self, p):
        raise NotImplementedError

    def right(self, p):
        raise NotImplementedError

    def sibling(self, p):
        parent = self.parent(p)
        if parent is None:
            return None
        if self.left(parent) == p:
            return self.right(parent)
        else:
            return self.left(parent)

    def children(self, p):
        # iterator
        if self.left(p) is not None:
            yield self.left(p)
        if self.right(p) is not None:
            yield self.right(p)

class BinaryTree(BinaryTreeBase):
    def __init__(self):
        super().__init__()
        self._root = None
        self.size = 0

    class _Node:
        def __init__(self, data, left=None, right=None, parent=None):
            self.data = data
            self.left = left
            self.right = right
            self.parent = parent

    class Position:
        def __init__(self, node, container):
            self.node = node
            self.container = container

        def element(self):
            return self.node.data

        def __eq__(self, other):
            return type(other) is type(self) and self.node is other.node

        def __ne__(self, other):
            return not (self == other)

    def check_position(self, p):
        """
        Positions won't necessarily refer to this particular container so must be validated
        :return:
        """
        if p.container is not self:
            raise ValueError("Position does not belong to this tree")
        if not isinstance(p, self.Position):
            raise TypeError("Must be Position type")
        if p.node.parent is p.node:  # when a node is deleted, its child takes its place
            raise ValueError("Deleted node")
        return p.node

    def position(self, node):
        if node is None:
            return None
        return self.Position(node, self)

    def root(self):
        return self.position(self._root)

    def add_root(self, data):
        node = self._Node(data)
        self._root = node
        self.size += 1
        return self.position(node)

    def parent(self, p):
        node = self.check_position(p)
        return self.position(node.parent)

    def left(self, p):
        node = self.check_position(p)
        return self.position(node.left)

    def right(self, p):
        node = self.check_position(p)
        return self.position(node.right)

    def add_left(self, p, data):
        node = self._Node(data)
        parent = self.check_position(p)
        parent.left = node
        node.parent = parent
        self.size += 1
        return self.position(node)

    def add_right(self, p, data):
        node = self._Node(data)
        parent = self.check_position(p)
        parent.right = node
        node.parent = parent
        self.size += 1
        return self.position(node)

    def num_children(self, p):
        num = 0
        if self.right(p):
            num += 1
        if self.left(p):
            num += 1
        return num

    def delete(self, p):
        node = self.check_position(p)
        if self.num_children(p) > 1:
            raise ValueError("Position has 2 children")
        parent = node.parent
        if node.right:
            child = node.right
        else:
            child = node.left
        if child:
            child.parent = parent
        if not node.parent:  # node is root
            self._root = child
        else:
            if parent.left is node:
                parent.left = child
            else:
                parent.right = child
        node.parent = node
        self.size -= 1
        return node.data

    def attach(self, p, left_tree, right_tree):
        node = self.check_position(p)
        if not self.is_leaf(p):
            raise ValueError("Position is not leaf")
        self.size += len(left_tree) + len(right_tree)
        if type(self) is type(left_tree) is type(right_tree):
            raise TypeError("Trees are not of correct type")
        if not left_tree.is_empty():
            node.left = left_tree._root
            node.left.parent = node.left
            left_tree._root = None
            left_tree.size = None
        if not right_tree.is_empty():
            node.right = right_tree._root
            node.right.parent = node.right
            right_tree._root = None
            right_tree.size = None

    def __len__(self):
        return self.size

class BinaryTreeTest(unittest.TestCase):
    def test_init(self):
        tree = BinaryTree()
        with self.assertRaises(AttributeError):
            tree.add_left(tree.root(), "root")
        tree.add_root("root")
        root = tree.root()
        self.assertEqual(root.element(), "root")
        tree.add_left(root, "left")
        tree.add_right(root, "right")
        self.assertEqual(tree.left(root).element(), "left")
        self.assertEqual(tree.right(root).element(), "right")

    def test_size(self):
        tree = BinaryTree()
        root = tree.add_root("root")
        left = tree.add_left(root, "left")
        right = tree.add_right(root, "right")
        tree.add_left(left, "left-left")
        tree.add_right(left, "left-right")
        self.assertEqual(len(tree), 5)

    def test_children(self):
        # create a tree with a child with left and right children
        # check no. of children, if they're leaves and siblings
        tree = BinaryTree()
        root = tree.add_root("root")
        left = tree.add_left(root, "left")
        child_left = tree.add_left(left, "left-left")
        child_right = tree.add_right(left, "left-right")
        self.assertEqual(tree.num_children(left), 2)
        self.assertEqual(tree.is_leaf(left), False)
        self.assertEqual(tree.is_leaf(child_left), True)
        children = [i for i in tree.children(left)]
        self.assertEqual(children, [child_left, child_right])
        self.assertEqual(tree.sibling(child_left), child_right)

    def test_delete(self):
        tree = BinaryTree()
        root = tree.add_root("root")
        left = tree.add_left(root, "left")
        child_left = tree.add_left(left, "left-left")
        child_right = tree.add_right(left, "left-right")
        with self.assertRaises(ValueError):
            tree.delete(left)
        self.assertEqual(tree.delete(child_left), "left-left")
        self.assertEqual(len(tree), 3)
        self.assertEqual(tree.delete(left), "left")
        left = tree.left(tree.root())
        self.assertEqual(tree.delete(root), "root")
        root = tree.root()
        self.assertEqual(tree.delete(root), "left-right")

        self.assertEqual(tree.is_empty(), True)
        self.assertEqual(len(tree), 0)

    def test_attach(self):
        tree1 = BinaryTree()
        root1 = tree1.add_root("root1")
        tree1.add_left(root1, "left1")

        tree2 = BinaryTree()
        root2 = tree2.add_root("root2")
        tree2.add_left(root2, "left2")
        tree2.add_right(root2, "right2")

        tree = BinaryTree()
        root = tree.add_root("root")

        tree.attach(root, tree1, tree2)
        self.assertEqual(len(tree), 6)
        children = [i for i in tree.children(root)]
        self.assertEqual(children, [root1, root2])

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


"""Global topics on the message bus."""

AUTH = 'EO-AUTH'
CERTS = 'EO-CERTS'
DELEGATES = 'EO-DELEGATES'
KEYS = 'EO-KEYS'
MEASUREMENTS = 'EO-MEASUREMENTS'
MEASUREMENTS_COMMANDS = 'EO-MEASUREMENTS-COMMANDS'
METERINGPOINTS = 'EO-METERINGPOINTS'
METERINGPOINTS_COMMANDS = 'EO-METERINGPOINTS_COMMANDS'
TECHNOLOGIES = 'EO-TECHNOLOGIES'
USERS = 'EO-USERS'


import finder_utils

from policy_file import PolicyFile

class PolicyFinder:

    GLOB_PATTERN = 'app/policies/**/*.rb'

    def __init__(self, context):
        self.context = context
        self.root_path = context['__root_path']

    def find_files(self):
        files = finder_utils.glob_project(self.root_path, self.GLOB_PATTERN)
        return [PolicyFile(filename) for filename in files]


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

# set 和 dict 类似，也是一组key的集合，但不存储 value，由于key 不能重复，所以在set 中，没有重复的key
# set 可以看作是 无序，不重复的元素的集合

# 要创建一个 set，需要提供一个 list 作为输入集合

L = [1,2,3,4,2]
print("list L:",L)  #list L: [1, 2, 3, 4, 2]

s = set(L)
print('set s:',s)  # 去掉了重复的key set s: {1, 2, 3, 4}

#add Add an element to a set. This has no effect if the element is already present.

element = 10

s.add(element)
s.add(element)
s.add(element)

print('set s:',s) #set s: {1, 2, 3, 4, 10}

#remove Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError

s.remove(element)

print('set s:',s) #set s: {1, 2, 3, 4}

# set 可以做 交集，并集等操作

s1 = set([1,2,3])
s2 = set([2,3,4])

print(s1&s2) #{2, 3}
print(s1|s2) #{1, 2, 3, 4}


import unittest
import numpy as np
from bubble_sort import bubble_sort

class SortTestCase(unittest.TestCase):

	def test_bubble_sort(self):
		input_testing =  [0, 3, 1, 7, 5, 8, 2, 9, 6, 4]
		expected_result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
		result = bubble_sort(input_testing)
		self.assertEqual(result, expected_result)

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


# 7.24
# 답은 3 나오지만 백준 제출시 틀림.
b_num_list = []
check_list = [[0 for _ in range(5)] for _ in range(5)]

for _ in range(5):
    b_num_list.append(list(map(int, input().split())))

# 빙고확인 check_bingo
def check_bingo(ls):
    cnt_row = 0
    cnt = 0
    # 1. cnt_row
    for i in range(5):
        for ii in range(5):
            if ls[i][ii] == 0:
                cnt_row += 1
            # print("cnt_row")
            # print(ls)
        if cnt_row == 5:
            # print("Cr")
            cnt += 1
    # 2. cnt_col
    cnt_col = 0
    for j in range(5):
        for jj in range(5):
            if ls[j][jj] == 0:
                cnt_col += 1
            # print("cnt_col")
            # print(ls)
        if cnt_col == 5:
            # print("Cc")
            cnt += 1
    # 3. cnt_lr_dg
    cnt_lr_dg = 0
    for k in range(5):
        if ls[k][k] == 0:
            cnt_lr_dg += 1
            # print("cnt_lr")
            # print(ls)
    if cnt_lr_dg == 5:
        # print("Clr")
        cnt += 1

    # 4. cnt_rl_dg
    cnt_rl_dg = 0
    for n in range(5):
        if ls[n][4 - n] == 0:
            cnt_rl_dg += 1
            # print("cnt_rl")
            # print(ls)
    if cnt_rl_dg == 5:
        # print("Crl")
        cnt += 1

    return cnt

cnt = 0

for x in range(5):
    a = list(map(int, input().split()))
    # num_list.append(a)
    for k in range(5):
        for y in range(5):
            for z in range(5):
                if b_num_list[y][z] == a[k]:
                    b_num_list[y][z] = 0
                    # print("yes")

    cnt_tot = check_bingo(b_num_list)
    cnt += cnt_tot
    # print(cnt_tot)
    if cnt >= 3:
        print(x + 1)
        break


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 31 19:48:29 2021

@author: jeanb
"""

import pandas as pd
import xlrd
from  matplotlib import pyplot as plt
import math
#import mglearn
#from sklearn.model_selection import train_test_split
#from sklearn.neighbors import KNeighborsRegressor
import numpy as np
from mpl_toolkits.mplot3d import Axes3D #to plot in 3D
import mpmath as mp

#------------------------------------------------------------------------------
                            #LECTURE DU FICHIER EXCEL

print("PARTIE 1 : Resprésentation graphique des données")
#Lecture du fichier excel
document = xlrd.open_workbook("Data_table_3.xlsx")
fichier = "Data_table_3.xlsx"
sheet = "Sheet1"
df = pd.read_excel(io=fichier, sheet_name=sheet)

#------------------------------------------------------------------------------
                            #CREATION D'UNE BDD OU S'ENTRAINER

ligne_debut = 1
ligne_fin = 6000
ligne = ligne_fin - ligne_debut

df_new = df[['id', 'referenceyear', 'tot_assets', 'capital', 'capital_surplus',
             'paidincapital', 'tot_deposits', 'cash', 'comm_portfolio',
             'securities', 'tot_credit']]

#df_data = df_new.head(ligne)
df_data = df_new[ligne_debut:ligne_fin]

print('------------------------------------')
print("Données à utiliser : \n{}".format(df_data))

df_new = df[['f1']]

#df_resultat = df_new.head(ligne)
df_resultat = df_new[ligne_debut:ligne_fin]

print('------------------------------------')
print("Faillit ou non des banques : \n{}".format(df_resultat))

#------------------------------------------------------------------------------
                            #CREATION DES DONNEES DE TRAINING ET DE TEST

#Choix du nombre de lignes qui vont etre sélectionnée -------------------------
calcul = 0.75*ligne
resultat = int(round(calcul))
#resultat = 75
fin = ligne_fin

#Initialisation des paramètres ------------------------------------------------
capital_ratio_1 = (df_data['capital'])/df_data['tot_assets']
df_data['capital_ratio'] = capital_ratio_1

liquid_ratio_1 = df_data['cash']/df_data['tot_assets']
df_data['liquidity_ratio'] = liquid_ratio_1

#Replace the nan values by 0
df_data.fillna(value=0, inplace = True)
df_resultat.fillna(value=0, inplace = True)

#Training data ----------------------------------------------------------------
Training =  np.array([df_data['referenceyear'][0:resultat],
                      df_data['capital_ratio'][0:resultat],
                      df_data['liquidity_ratio'][0:resultat]])

#plt.plot(Training[0], Training[1], label='Total assets')
plt.scatter(Training[0], Training[1], label='Capital Ratio')
plt.scatter(Training[0], Training[2], label='liquidity ratio')
#plt.plot(Training[0], Training[7], label='real_capital_ratio')
#plt.plot(Training[0], Training[8], label='balence commerciale')
plt.legend()

#Test data --------------------------------------------------------------------
Test = np.array([df_data['referenceyear'][resultat:fin],
                      df_data['capital_ratio'][resultat:fin],
                      df_data['liquidity_ratio'][resultat:fin]])

#Training matrice -------------------------------------------------------------
Xtrain = Training
Xtrain = Xtrain.T
Ytrain = np.array([df_resultat['f1'][0:resultat]])
Ytrain = Ytrain.T

#Test matrice -----------------------------------------------------------------
Xtest = Test
Xtest = Xtest.T
Ytest = np.array([df_resultat['f1'][resultat:fin]])
Ytest = Ytest.T

#Ajout de la colonne de 1 à la matrice Xtrain ---------------------------------
p = np.ones([len(Xtrain),1])
Xtrain = np.append(p, Xtrain, axis = 1)

#Ajout de la colonne de 1 à la matrice Xtest---------------------------------
p = np.ones([len(Xtest),1])
Xtest = np.append(p, Xtest, axis = 1)

#------------------------------------------------------------------------------
#--------------------------------DEFINITION FONCTIONS CFS----------------------

#Fonction hypothèse
def Hypothese(X, Theta):
    return X.dot(Theta)

#Fonction CFS
def CFS(X, Y):
    p1 = np.dot(X.T,X)
    p2 = np.dot(X.T, Y)
    #Theta = np.linalg.pinv(p1).dot(p2)
    Theta =  np.linalg.pinv(p1)
    Theta = Theta.dot(p2)
    #Theta = Theta[~np.isnan(Theta)]
    return Theta

#Fonction Erreur
def Erreur(x,y,theta):
    ypred = np.dot(x,theta)
    I = len(y)
    # boucle for pour parcourir les matrices
    for i in range (I):
        erreur = (1/I) * np.sum(np.square(ypred-y))  #MSE (mean square error)
    return erreur

#------------------------------------------------------------------------------
#------------------------------PARAMETRES OPTIMAUX-----------------------------

Theta_F = CFS(Xtrain, Ytrain)

print(Theta_F)

#Prédiction des données de training--------------------------------------------
Yprediction = Hypothese(Xtrain, Theta_F)
error = Erreur(Xtrain, Ytrain, Theta_F)
print("Erreur : ", error)

#Affichage des données---------------------------------------------------------
fig1 = plt.figure()
ax1 = fig1.gca(projection='3d')
ax1.scatter3D(Xtrain[:,2], Xtrain[:,3], Ytrain, color= 'green')
ax1.scatter3D(Xtrain[:,2], Xtrain[:,3], Yprediction, color= 'red')
ax1.set_xlabel('Capital Ratio', fontweight = 'bold')
ax1.set_ylabel('Liquidity ratio', fontweight = 'bold')
ax1.set_zlabel('Bankruptcy probability', fontweight = 'bold')
plt.show()

#☻Prediction des données de test-----------------------------------------------
#Yprediction2 = Hypothese(Xtest, Theta_F)
#error2 = Erreur(Xtest, Ytest, Theta_F)
#print("Erreur : ", error2)
#------------------------------------------------------------------------------

#Classe de regression logistique-----------------------------------------------
    #Appel permettant la résolution direct pour tout autre type de fichier

class LogisticRegression:

    #On instancie les paramètres propres à la régression
        #lr = alpha = précision
        #num_iter = nomre d'iterations !!ATENTION : Possible overfitting!!
        #fit intercept : ici il faut calculer le point d'interception
        #verbose : suite au traitement de beaucoup de données et de nombreuses itérations
   def __init__(self, lr = 0.01, num_iter = 100000, fit_intercept = True, verbose = False):
      self.lr = lr
      self.num_iter = num_iter
      self.fit_intercept = fit_intercept
      self.verbose = verbose

      #Ajout de la colonne de 1 à Xpar concatenate
   def __add_intercept(self, X):
      intercept = np.ones((X.shape[0], 1))
      return np.concatenate((intercept, X), axis=1)

    #Fonction Sigmoid
   def Sigmoid(self, z):
      return 1 / (1 + np.exp(-z))

    #Fonction erreur
   def Erreur(self, h, y):
      return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()

    #Normalisation des données
   def fit(self, X, y):
      if self.fit_intercept:
        X = self.__add_intercept(X)
        self.theta = np.zeros(X.shape[1])
        for i in range(self.num_iter):
           z = np.dot(X, self.theta)
           h = self.Sigmoid(z)
           gradient = np.dot(X.T, (h - y)) / y.size #gradient : permet de faire des 'boucles' afin de trouver la valeur de Theta pour laquelle la fonction de coût est égale à 0
           self.theta -= self.lr * gradient

           z = np.dot(X, self.theta)
           h = self.Sigmoid(z)
           loss = self.Erreur(h, y)

           if(self.verbose ==True and i % 10000 == 0):
              print(f'loss: {loss} \t')

    #Retourne la valeur exacte de la valeur prédite
   def predict_prob(self, X):
       if self.fit_intercept:
           X = self.__add_intercept(X)
           return self.Sigmoid(np.dot(X, self.theta))

        #Arrondie la prédiction
   def predict(self, X):
      return self.predict_prob(X).round()

#Variables --------------------------------------------------------------------
model = LogisticRegression()
model = model.fit(Xtrain, Ytrain)
preds = model.predict(Xtrain)


# Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
#
# If the fractional part is repeating, enclose the repeating part in parentheses.
#
# For example,
#
# Given numerator = 1, denominator = 2, return "0.5".
# Given numerator = 2, denominator = 1, return "2".
# Given numerator = 2, denominator = 3, return "0.(6)".
# Credits:
# Special thanks to @Shangrila for adding this problem and creating all test cases.

class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
        if denominator == 0:
            return "error"

        rslt = ['' if numerator * denominator >= 0 else '-']

        numerator, denominator = abs(numerator), abs(denominator)
        quotient, remainder = divmod(numerator, denominator)

        rslt.append(str(quotient))

        if remainder == 0:
            return  "".join(rslt)
        else:
            rslt.append('.')

        remainderCache = {}
        while remainder not in remainderCache and remainder != 0:
            remainderCache[remainder] = len(rslt)
            quotient, remainder = divmod(remainder * 10, denominator)
            rslt.append(str(quotient))

        if remainder in remainderCache:
            rslt.insert(remainderCache[remainder], '(')
            rslt.append(')')

        return  "".join(rslt)

#         print("{:-^30}".format("center"))
#         n, remainder = divmod(abs(numerator), abs(denominator))
#         sign = '-' if numerator*denominator < 0 else ''
#         result = [sign+str(n), '.']
#         stack = []
#         print stack
#         while remainder not in stack:
#             stack.append(remainder)
#             print stack
#             n, remainder = divmod(remainder*10, abs(denominator))
#             print n, remainder
#             result.append(str(n))
#
#         print result
#         idx = stack.index(remainder)
#         result.insert(idx+2, '(')
#         result.append(')')
#         print result
#         return ''.join(result).replace('(0)', '').rstrip('.')


from agent import *
from layout import *
import matplotlib.pyplot as plt
size = 10
num_snakes = 1
# players = 1
players = [RandomPlayer(0)]
gui_size = 600

# game = Game(size, num_snakes, players, gui=None, display=True, max_turns=100)
# gui = Gui(game, gui_size)
# game.play(True, terminate=False)

population_size = 100
num_generations = 500
num_trails = 1
window_size = 10   #Board seen by the agent NxN
hidden_size = 50   #Brain SIze neurons
board_size = 15
counter = []
agent = Player(population_size, num_generations, num_trails, window_size, hidden_size, board_size, counter, mutation_chance=0.2, mutation_size=0.3)
agent.evolve()
x = list(range(num_generations))
plt.plot(x, counter)
plt.xlabel('Generations')
plt.ylabel('Max Score')
plt.show()


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

import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate

if __name__ == "__main__":
    from_address = ""
    to_address   = ["", ""] #複数に送る場合はリスト型
    cc_address   = ["", ""]
    bcc_address  = ["", ""]

    charset = "ISO-2022-JP"
    subject = u"メールの件名です"
    text    = u"メールの本文です"

    msg = MIMEText(text.encode(charset),"plain",charset)
    msg["Subject"] = Header(subject,charset)
    msg["From"]    = from_address
    msg["To"]      = ",".join(to_address) #ここは "," 区切りでひとつに
    msg["cc"]      = ",".join(cc_address) #ccの場合も区切りでひとつに
    #bcc についてはメールヘッダに記述しないので項目なし
    msg["Date"]    = formatdate(localtime=True)

    to_addrs = to_address + cc_address + bcc_address
    #メールの送信先を一つのリスト型にまとめる bcc
    #は宛先にのみに含めヘッダに入れない

    smtp = smtplib.SMTP() #引数を省略すると localhost:25
    smtp.connect()
    #上記コマンドの引数を省略した場合初期化を明示する必要がある
    smtp.sendmail(from_address, to_addrs, msg.as_string())
    smtp.close()


# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell
import time
from utils import get_logger
from data_helper import batch_iter
import numpy as np
from utils import focal_loss

class BiLSTM_Model(object):
    def __init__(self, args, tag2label, model_w2v, paths, config):
        self.batch_size = args['batch_size']
        self.epoch_num = args['epoch']
        self.hidden_dim = args['hidden_dim']
        self.embedding_dim = args['embedding_dim']
        self.dropout_keep_prob = args['dropout']
        self.lr_ = args['lr']
        # 学习率自动衰减
        self.global_step = tf.Variable(0)
        self.lr = tf.train.exponential_decay(self.lr_, self.global_step, decay_steps=4,
                                             decay_rate=0.98, staircase=False)
        # 词向量矩阵，添加一行全0向量，对应没出现过的词<UNK>
        self.embeddings = np.r_[model_w2v.wv.vectors, [[0] * self.embedding_dim]]
        self.tag2label = tag2label
        self.num_tags = len(tag2label)
        self.shuffle = args['shuffle']
        self.model_path = paths['model_path']
        self.summary_path = paths['summary_path']
        self.logger = get_logger(paths['log_path'])
        self.result_path = paths['result_path']
        self.config = config

    def build_graph(self):
        """
        构建TensorFlow网络结构
        可以添加attention层去优化
        :return:
        """
        self.add_placeholders()
        self.lookup_layer_op()
        self.biLSTM_layer_op()
        self.accuracy_op()
        self.loss_op()
        self.trainstep_op()
        self.init_op()

    def add_placeholders(self):
        """
        使用tf的占位符，初始化3个属性
        :return:
        """
        self.word2ids = tf.placeholder(tf.int32, shape=[None, None], name="word2ids")
        self.labels = tf.placeholder(tf.int32, shape=[None, None], name="labels")
        self.dropout_pl = tf.placeholder(dtype=tf.float32, shape=[], name="dropout")

    def lookup_layer_op(self):
        """
        在预训练的词向量矩阵中寻找max_len个词向量，一个word_id对应一个词向量，id数即为词向量矩阵的第几行
        预训练词向量矩阵是一个可优化的点
        """
        with tf.variable_scope("words"):
            _word_embeddings = tf.Variable(self.embeddings,
                                           dtype=tf.float32,
                                           name="_word_embeddings")
            word_embeddings = tf.nn.embedding_lookup(params=_word_embeddings,
                                                     ids=self.word2ids,
                                                     name="word_embeddings")
        self.word_embeddings = tf.nn.dropout(word_embeddings, self.dropout_pl)

    def biLSTM_layer_op(self):
        with tf.variable_scope("bi-lstm"):
            # 前向lstm
            cell_fw = LSTMCell(self.hidden_dim)
            # 反向lstm
            cell_bw = LSTMCell(self.hidden_dim)
            (output_fw_seq, output_bw_seq), _ = tf.nn.bidirectional_dynamic_rnn(
                cell_fw=cell_fw,
                cell_bw=cell_bw,
                inputs=self.word_embeddings,
                dtype=tf.float32)

            output = tf.concat([output_fw_seq, output_bw_seq], axis=-1)

            # 将词向量取平均，维度变化：[batch_size, max_len, hidden_dim] -> [batch_size, hidden_dim]
            # 即将max_len个hidden_dim维的词向量合并为一个
            output = tf.reduce_sum(output, axis=1)
            output = tf.reshape(output, [-1, 2 * self.hidden_dim])
            output = tf.nn.dropout(output, self.dropout_pl)

        with tf.variable_scope("proj"):
            W = tf.get_variable(name="W",
                                shape=[2 * self.hidden_dim, self.num_tags],
                                initializer=tf.contrib.layers.xavier_initializer(),
                                dtype=tf.float32)

            b = tf.get_variable(name="b",
                                shape=[self.num_tags],
                                initializer=tf.zeros_initializer(),
                                dtype=tf.float32)

            pred = tf.matmul(output, W) + b
            self.logits = tf.nn.dropout(pred, self.dropout_pl)

    def loss_op(self):
        """
        损失函数，可尝试替换其他损失函数去优化，如focal loss
        """
        losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.labels)
        self.loss = tf.reduce_mean(losses)
        tf.summary.scalar("loss", self.loss)

    def accuracy_op(self):
        self.prediction = tf.cast(tf.argmax(self.logits, axis=1), tf.int32)
        correct_prediction = tf.equal(self.prediction, tf.cast(tf.argmax(self.labels, axis=1), tf.int32))
        self.correct_num = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
        self.acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="acc")

    def trainstep_op(self):
        with tf.variable_scope("train_step"):
            self.global_step = tf.Variable(0, name="global_step", trainable=False)
            optim = tf.train.AdamOptimizer(learning_rate=self.lr)
            self.train_op = optim.minimize(self.loss)

    def init_op(self):
        """变量初始化"""
        self.init_op = tf.global_variables_initializer()

    def add_summary(self, sess):
        """
        打印概览
        :param sess:
        :return:
        """
        self.merged = tf.summary.merge_all()
        self.file_writer = tf.summary.FileWriter(self.summary_path, sess.graph)

    def train(self, train, dev):
        """
        训练入口
        :param train:训练集
        :param dev: 验证集
        :return:
        """
        saver = tf.train.Saver(tf.global_variables())

        with tf.Session(config=self.config) as sess:
            sess.run(self.init_op)
            self.add_summary(sess)

            for epoch in range(self.epoch_num):
                self.run_one_epoch(sess, train, dev, epoch, saver)

    def test(self, test):
        """
        测试入口
        :param test:测试集
        :return:
        """
        saver = tf.train.Saver()
        with tf.Session(config=self.config) as sess:
            self.logger.info('=========== testing ===========')
            saver.restore(sess, self.model_path)
            self.dev_one_epoch(sess=sess, dev=test)

    def demo(self, demo_sent):
        """
        测试一条文本，返回值可根据需求更改
        """
        saver = tf.train.Saver()
        with tf.Session(config=self.config) as sess:
            saver.restore(sess, self.model_path)
            y_pred = self.predict_one(sess, demo_sent)[0]
            label = self.tag2label[str(y_pred)]
            return label

    def run_one_epoch(self, sess, train, dev, epoch, saver):
        """
        训练1个opoch
        :param sess:session
        :param train:训练集
        :param dev:验证集
        :param epoch:当前epoch
        :param saver:tf模型保存对象
        :return:
        """
        num_batches = (len(train[0]) + self.batch_size - 1) // self.batch_size
        start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        batches = batch_iter(train, self.batch_size)
        avg_loss = 0
        avg_acc = 0
        for step, (seqs, labels) in enumerate(batches):
            step_num = epoch * num_batches + step + 1
            feed_dict = self.get_feed_dict(seqs, labels, self.dropout_keep_prob)
            _, loss_train, acc_train, summary, step_num_ = sess.run(
                [self.train_op, self.loss, self.acc, self.merged, self.global_step],
                feed_dict=feed_dict)
            avg_loss += loss_train / num_batches
            avg_acc += acc_train / num_batches
            self.file_writer.add_summary(summary, step_num)
        self.logger.info(
            '{} epoch {}, loss: {:.4}, acc: {:.4}'.format(start_time, epoch + 1, avg_loss, avg_acc))
        saver.save(sess, self.model_path, global_step=epoch + 1)

        self.logger.info('===========validation / test===========')
        self.dev_one_epoch(sess, dev, epoch)

    def get_feed_dict(self, seqs, labels=None, dropout=None):
        """
        获取tf网络模型需要“喂”的数据
        :param seqs: 文本
        :param labels:
        :param dropout:
        :return: feed_dict
        """
        feed_dict = {self.word2ids: seqs}
        if labels is not None:
            feed_dict[self.labels] = labels
        if dropout is not None:
            feed_dict[self.dropout_pl] = dropout

        return feed_dict

    def dev_one_epoch(self, sess, dev, epoch=None):
        """
        :param sess:
        :param dev:
        :param epoch:
        :return:
        """
        num_batches = (len(dev[0]) + self.batch_size - 1) // self.batch_size
        avg_acc = 0
        for seqs, labels in batch_iter(dev, self.batch_size):
            feed_dict = self.get_feed_dict(seqs, labels, 1.0)
            acc = sess.run(self.acc, feed_dict=feed_dict)
            avg_acc += acc / num_batches
        if epoch is not None:
            self.logger.info('epoch {}, dev acc : {:.4}'.format(epoch + 1, avg_acc))
        else:
            self.logger.info('Test acc : {:.4}'.format(avg_acc))

    def predict_one(self, sess, seqs):
        """
        预测一条
        :param sess:
        :param seqs:
        :return y_pred: 预测标签对应的id
        """
        seqs = np.array([seqs])
        feed_dict = self.get_feed_dict(seqs=seqs, dropout=1.0)
        y_pred = sess.run(self.prediction, feed_dict=feed_dict)

        return y_pred


from libs import *

def Smoothening_Transformation(training_image):
    """
    1) A smoothening operation
    """
    #Gaussian smoothing the image using Gaussian Low pass filter
    smoothing = cv2.GaussianBlur(training_image,(5,5),0)
    """
    2) A color domain transformation
    """
    # moving image in Lab mode
    from skimage import color, io
    lab=color.rgb2lab(smoothing, illuminant='D65', observer='2')
    return lab

def Normalise_ResidualCalc(lab):
    """
    3) A normalization operation
    """
    #splitting La*b* color space
    L,A,B=cv2.split(lab)
    #cv2.imshow("L_Channel",L)

    #Local normalization of luminance channel
    float_lumn = L.astype(np.float32) / 255.0

    blur = cv2.GaussianBlur(float_lumn, (0, 0), sigmaX=2, sigmaY=2)
    num = float_lumn - blur

    blur = cv2.GaussianBlur(num*num, (0, 0), sigmaX=20, sigmaY=20)
    den = cv2.pow(blur, 0.5)

    luminance = num / den

    cv2.normalize(luminance, dst=luminance, alpha=0.0, beta=1.0, norm_type=cv2.NORM_MINMAX)

    """

    4) A spatial residual calculation

    """

    #find fourier spectrum

    dft = cv2.dft(np.float32(luminance),flags = cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)

    #converted to polar coordinates
    mag=cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])
    ang=cv2.phase(dft_shift[:,:,0],dft_shift[:,:,1])
    #mag,ang=cv2.cartToPolar(dft_shift[:,:,0],dft_shift[:,:,1])

    # logarithmic image
    # Apply log transformation method
    c = 255 / np.log(1 + np.max(mag))
    log_image = c * (np.log(mag + 1))

    # Specify the data type so that
    # float value will be converted to int
    log_image = np.array(log_image, dtype = np.float32)

    smooth_log_image=cv2.blur(log_image,(5,5),0)

    #Residual
    residual=log_image-smooth_log_image

    x, y = cv2.polarToCart(residual, ang)

    rows, cols = x.shape
    crow,ccol = int(rows/2) , int(cols/2)

    # create a mask first, center square is 1, remaining all zeros
    mask = np.zeros((rows,cols,2),np.float32)
    dft = np.zeros((rows,cols,2),np.float32)
    mask[crow-30:crow+30, ccol-30:ccol+30] = 1
    dft[:,:,0]=x
    dft[:,:,1]=y

    # apply mask and inverse DFT
    fshift = dft*mask
    f_ishift = np.fft.ifftshift(fshift)
    img_back = cv2.idft(f_ishift)
    img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
    # Applying Gaussian LPF and normalize
    smooth_img_back=  cv2.GaussianBlur(img_back,(5,5),0)
    cv2.normalize(smooth_img_back,  smooth_img_back, 0.0, 1.0, cv2.NORM_MINMAX)

    # Multiplicative pixel wise pooling
    pool_image=(luminance*smooth_img_back*255.0)
    pool_image = np.array(pool_image, dtype = np.uint8)
    return pool_image


def count_letters(a_string, find_consonants):

    #And we still need a counter:
    count = 0

    #But this time, we'll check what we're looking for
    #first. If we're looking for consonants...
    if find_consonants:

        #...then we loop through looking for consonants:
        for character in a_string:
            if character in "bcdfghjklmnpqrstvwxyz":
                count += 1

    #If we weren't looking for consonants:
    else:

        #...then we loop through looking for vowels:
        for character in a_string:
            if character in "aeiou":
                count += 1

    #Either way, we return the result when we're done:
    return count
a_string = "up with the white and gold"

print(count_letters(a_string, True))
print(count_letters(a_string, False))

5.2  Control Structures/4 Functions/24 VowelsAndConsonants2.py


import warnings

import iris

def rename_unknown(cube, field, filename):

    # rename unknown grib phenomena
    if isinstance(field, iris.fileformats.grib.GribWrapper):
        if field.edition == 1:
            cube.rename("{} table {} item {}".format(field.centre, field.table2Version,
                                                     field.indicatorOfParameter))
        elif field.edition == 2:
            cube.rename("{} d{} c{} n{}".format(field.centre, field.discipline,
                                                field.parameterCategory,
                                                field.parameterNumber))
    else:
        warnings.warn("This callback deos not yet handle type {}".format(type(field)))


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

got = pd.read_csv("train.csv")
gottest = pd.read_csv("test.csv")

from sklearn.linear_model import LinearRegression
reg = LinearRegression()

labels = got['bestSoldierPerc']
train1 = got.drop(['soldierId', 'shipId','attackId','bestSoldierPerc'],axis=1)

x_train , y_train = train1 , labels

reg.fit(x_train,y_train)

gottest1 =gottest.drop(['Unnamed: 0','index','soldierId', 'shipId','attackId'],axis =1)
x_test,y_test = gottest1,labels
y_test = reg.predict(x_test)
y_test

gottest.insert(26,"bestSoldierPerc",value = y_test)
gottest = gottest.drop([''])

#from sklearn import preprocessing
#import numpy as np
#min_max_scaler = preprocessing.MinMaxScaler()
#y_test1 = pd.DataFrame(y_test)
#x_scaled = min_max_scaler.fit_transform(y_test1)
#x_scaled = np.array(x_scaled)
#gottest.insert(27,"bestSoldierPerc1",value = y_test)
#df_normalized = pd.DataFrame(x_scaled)
#df_normalized

gottest = gottest.drop(['Unnamed: 0'],axis = 1)

gottest.to_csv("gottest.csv")


import requests
from bs4 import BeautifulSoup
import csv

# URL của trang web bạn muốn trích xuất dữ liệu
url = "https://cafef.vn/doc-nhanh/trang-2.chn"

# Sử dụng requests để lấy nội dung của trang web
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Tạo danh sách để lưu dữ liệu
data = []

# Tìm tất cả các mục có class "item expandable"
items = soup.find_all('div', class_='item expandable')

# Duyệt qua từng mục và trích xuất thông tin
for item in items:
    time = item.find('div', class_='timeTitle time-ago')['title']
    title = item.find('a', class_='news-title')['title']
    link = item.find('a', class_='news-title')['href']
    content = item.find('div', class_='abs').text.strip()
    data.append([time, title, link, content])

# Lưu dữ liệu vào tệp CSV
with open('C:\\Hai\\OK\\cafe.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(['Time', 'Title', 'Link', 'Content'])  # Viết tiêu đề cho cột
    csv_writer.writerows(data)

print("Dữ liệu đã được trích xuất và lưu vào cafe.csv")


#!/usr/bin/python

from socket import *
import pyfiglet
import random
from termcolor import colored

def scanner(ports):
	global host
	global sock
	sock = socket(AF_INET, SOCK_STREAM)
	sock.settimeout(0.5)
	if (host[:4] == "http"):
		host = sock.gethostbyname(host)
	try:
		sock.connect((host, ports))
		print (colored("[+]port " + str(ports) + " open", 'green'))
	except:
		print (colored("[-]port " + str(ports) + " closed", 'red'))

def banner():
	fonts = ["banner","big","bubble","digital","emboss","emboss2","future","letter","mini","pagga","script","shadow","slant","small","smblock"]
	ran_font = random.choice(fonts)
	colors = ["grey","red","green","yellow","blue","magenta","cyan","white"]
	ran_color = random.choice(colors)
	banner = pyfiglet.figlet_format("PORT\nSCAN",font = ran_font)
	print (colored(banner, ran_color))

def main():
	global host
	global sock
	host = input("[*] Enter host: ")
	port_range = input("[*] Enter range to scan: ")
	port_range = port_range.split(",")

	for ports in range(int(port_range[0]) , int(port_range[1]) + 1):
		try:
			scanner(ports)
		except:
			sock.close()
			return()

	sock.close()


from typing import Optional, Union  # noqa F401
import flask  # noqa F401

from pathlib import Path
import os

import pyjson5 as jsonc
import yaml

from hidebound.core.database import Database
from hidebound.server.api import API
import hidebound.core.config as hbc
import hidebound.core.tools as hbt
# ------------------------------------------------------------------------------

# inheriting from Singleton breaks init and init_app tests
class HideboundExtension:
    def __init__(self, app=None):
        # type: (Optional[flask.Flask]) -> None
        '''
        Initialize flask extension.

        Args:
            app (flask.Flask, optional): Flask app.
        '''
        if app is not None:
            self.init_app(app)

    def get_config(self, app):
        # type: (flask.Flask) -> dict
        '''
        Get config from envirnment variables or config file.

        Args:
            app (flask.Flask): Flask app.

        Returns:
            dict: Database config.
        '''
        config_path = os.environ.get('HIDEBOUND_CONFIG_FILEPATH', None)
        if config_path is not None:
            config = self._get_config_from_file(config_path)

        else:
            app.config.from_prefixed_env('HIDEBOUND')
            config = self._get_config_from_env(app)

        config = hbc.Config(config).to_native()
        return config

    def _get_config_from_file(self, filepath):
        # type: (Union[str, Path]) -> dict
        '''
        Get config from envirnment variables or config file.

        Args:
            filepath (str or Path): Filepath of hidebound config.

        Raises:
            FileNotFoundError: If HIDEBOUND_CONFIG_FILEPATH is set to a file
                that does not end in json, yml or yaml.

        Returns:
            dict: Database config.
        '''
        fp = Path(filepath)
        ext = fp.suffix.lower().lstrip('.')
        exts = ['json', 'yml', 'yaml']
        if ext not in exts:
            msg = 'Hidebound config files must end in one of these extensions: '
            msg += f'{exts}. Given file: {fp.as_posix()}.'
            raise FileNotFoundError(msg)

        with open(filepath) as f:
            if ext in ['yml', 'yaml']:
                return yaml.safe_load(f)
            return jsonc.load(f)

    def _get_config_from_env(self, app):
        # type: (flask.Flask) -> dict
        '''
        Get config from environment variables.

        Args:
            app (flask.Flask): Flask app.

        Returns:
            dict: Database config.
        '''
        dask = dict(
            cluster_type=app.config.get('DASK_CLUSTER_TYPE'),
            num_partitions=app.config.get('DASK_NUM_PARTITIONS'),
            local_num_workers=app.config.get('DASK_LOCAL_NUM_WORKERS'),
            local_threads_per_worker=app.config.get('DASK_LOCAL_THREADS_PER_WORKER'),
            local_multiprocessing=hbt.str_to_bool(
                app.config.get('DASK_LOCAL_MULTIPROCESSING', 'True')
            ),
            gateway_address=app.config.get('DASK_GATEWAY_ADDRESS'),
            gateway_proxy_address=app.config.get('DASK_GATEWAY_PROXY_ADDRESS'),
            gateway_public_address=app.config.get('DASK_GATEWAY_PUBLIC_ADDRESS'),
            gateway_auth_type=app.config.get('DASK_GATEWAY_AUTH_TYPE'),
            gateway_api_token=app.config.get('DASK_GATEWAY_API_TOKEN'),
            gateway_cluster_options=yaml.safe_load(
                str(app.config.get('DASK_GATEWAY_CLUSTER_OPTIONS', '[]'))
            ),
            gateway_shutdown_on_close=hbt.str_to_bool(
                app.config.get('DASK_GATEWAY_SHUTDOWN_ON_CLOSE', 'True')
            ),
        )
        return dict(
            ingress_directory=app.config.get('INGRESS_DIRECTORY'),
            staging_directory=app.config.get('STAGING_DIRECTORY'),
            include_regex=app.config.get('INCLUDE_REGEX', ''),
            exclude_regex=app.config.get('EXCLUDE_REGEX', r'\.DS_Store'),
            write_mode=app.config.get('WRITE_MODE', 'copy'),
            redact_regex=app.config.get('REDACT_REGEX', '(_key|_id|_token|url)$'),
            redact_hash=hbt.str_to_bool(app.config.get('REDACT_HASH', 'False')),
            specification_files=yaml.safe_load(
                str(app.config.get('SPECIFICATION_FILES', '[]'))
            ),
            workflow=yaml.safe_load(str(app.config.get(
                'WORKFLOW',
                '["delete", "update", "create", "export"]',
            ))),
            dask=dask,
            exporters=yaml.safe_load(str(app.config.get('EXPORTERS', '{}'))),
            webhooks=yaml.safe_load(str(app.config.get('WEBHOOKS', '[]'))),
        )

    def init_app(self, app):
        # type: (flask.Flask) -> None
        '''
        Add endpoints and error handlers to given app.

        Args:
            app (Flask): Flask app.
        '''
        app.extensions['hidebound'] = self
        app.register_blueprint(API)
        if not app.config['TESTING']:
            self.config = self.get_config(app)
            self.database = Database.from_config(self.config)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/7/7 11:08
# @Author  : chenshuhua
# @File    : testsome.py
import datetime

# import TimezoneFinder as TimezoneFinder
import pytz
from tzwhere import tzwhere

def convert(seconds):

    # seconds = seconds % (24 * 3600)
    #
    # hour = seconds // 3600
    #
    # seconds %= 3600
    #
    # minutes = seconds // 60
    #
    # seconds %= 60
    #
    # return "%02d:%02d:%02d" % (hour, minutes, seconds) #formatting

    return str(datetime.timedelta(seconds=seconds))

def timez(longitude,latitude):
    tz = tzwhere.tzwhere()
    time_zone = tz.tzNameAt(longitude,latitude)
    # tf = TimezoneFinder()
    print("地区:{}".format(time_zone))
    # time = pytz.timezone(tf.timezone_at(lng=longitude, lat=latitude)).localize(
    #     datetime.datetime(2022, 7, 8)).strftime('%z')

    # # invert sign and return in 'Etc/GMT' format
    # if time[0] == '-':
    #     time_zone = 'Etc/GMT+' + time[2]
    # else:
    #     time_zone = 'Etc/GMT-' + time[2]

if __name__ == '__main__':
    timez(31.230416,121.473701)
    print(convert(75780))
    print(convert(39540))
    print(convert(56760))