from inpladesys.datatypes import Segment, Segmentation
from typing import List
import numpy as np
from inpladesys.datatypes.dataset import Dataset
from collections import Counter
from sklearn.model_selection import train_test_split
import time
import scipy.stats as st

def generate_segmentation(preprocessed_documents: List[List[tuple]], documents_features: List[np.ndarray],
                          document_label_lists, documents, task=None) -> List[Segmentation]:
    assert len(documents_features) == len(preprocessed_documents)
    segmentations = []
    for i in range(len(documents_features)):
        preprocessed_doc_tokens = preprocessed_documents[i]
        doc_features = documents_features[i]
        assert doc_features.shape[0] == len(preprocessed_doc_tokens)
        labels = document_label_lists[i]
        segments = []
        for k in range(doc_features.shape[0]):
            prep_token = preprocessed_doc_tokens[k]
            segments.append(Segment(offset=prep_token[1],
                                    length=prep_token[2] - prep_token[1],
                                    author=labels[k]))
        segmentations.append(Segmentation(author_count=max(labels) + 1,
                                          segments=segments,
                                          max_repairable_error=60,
                                          document_length=len(documents[i])))
    if task == 'a':
        for segmentation in segmentations:
            fix_segmentation_labels_for_plagiarism_detection(segmentation)

    return segmentations

def fix_segmentation_labels_for_plagiarism_detection(segmentation, plagiarism_majority=False):
    # the majority label should be 0 (original author)
    assert segmentation.author_count == 2
    author_segments = segmentation.by_author[0]
    plagiarism_segments = segmentation.by_author[1]
    author_len = sum(s.length for s in author_segments)
    plagiarism_len = sum(s.length for s in plagiarism_segments)
    swap = author_len < plagiarism_len
    if plagiarism_majority:
        swap = not swap
    if swap:
        for s in segmentation:
            s.author = 1 - s.author
        segmentation.by_author[0] = plagiarism_segments
        segmentation.by_author[1] = author_segments

def custom_train_test_split(preprocessed_documents: List[List[tuple]], documents_features: List[np.ndarray],
                            dataset: Dataset, train_size, random_state):
    # indices of every document
    indices_of_docs = [i for i in range(len(preprocessed_documents))]

    i_train, i_test = train_test_split(indices_of_docs, train_size=train_size, random_state=random_state)

    prep_docs_train = [preprocessed_documents[i] for i in i_train]
    prep_docs_test = [preprocessed_documents[i] for i in i_test]

    doc_features_train = [documents_features[i] for i in i_train]
    doc_features_test = [documents_features[i] for i in i_test]

    author_counts_train = [dataset.segmentations[i].author_count for i in i_train]
    author_counts_test = [dataset.segmentations[i].author_count for i in i_test]

    dataset_train = Dataset([dataset.documents[i] for i in i_train],
                            [dataset.segmentations[i] for i in i_train])

    dataset_test = Dataset([dataset.documents[i] for i in i_test],
                           [dataset.segmentations[i] for i in i_test])

    return prep_docs_train, prep_docs_test, \
           doc_features_train, doc_features_test, \
           author_counts_train, author_counts_test, \
           dataset_train, dataset_test

def find_cluster_for_noisy_samples(predicted_labels, context_size=10):
    start = time.time()
    len_ = len(predicted_labels)
    counter = Counter(predicted_labels)
    noisy = counter[-1]
    unclustered_label = 0
    if -1 in counter.keys():
        if len(counter.most_common()) == 1:
            predicted_labels[:] = unclustered_label
        else:
            for i in range(len_):
                if predicted_labels[i] == -1:
                    left_diff = i - context_size
                    left = left_diff if left_diff >= 0 else 0
                    right_diff = i + context_size
                    right = right_diff if right_diff < len_ else len_
                    counter = Counter(predicted_labels[left:right])
                    if -1 in counter.keys():
                        if len(counter.most_common()) == 1:
                            predicted_labels[left:right] = unclustered_label
                        else:
                            found, curr = 0, 0
                            while found == 0:
                                if counter.most_common()[curr][0] != -1:
                                    predicted_labels[i] = counter.most_common()[curr][0]
                                    found = 1
                                curr += 1
    # print('Noisy labels reclustered in {}'.format(time.time()-start))
    return noisy

def perform_confidence_interval_test(samples: List, c_interval=0.95, p_normal_threshold=0.05):
    n = len(samples)
    #  https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.stats.normaltest.html
    #  https://stackoverflow.com/questions/12838993/scipy-normaltest-how-is-it-used
    z, p_val = st.normaltest(samples, nan_policy='raise')
    if p_val < p_normal_threshold:
        print('A given sample is not from normal distribution: '
              'p_val = {} < threshold = {}'.format(p_val, p_normal_threshold))
        print('The confidence intervals cannot be calculated.')
    else:
        sem = st.sem(samples)
        mean = np.mean(samples)
        interval = st.t.interval(c_interval, n-1, loc=mean, scale=sem)  #  https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data/34474255#34474255
        print('Mean:', mean)
        print('Standard error:', sem)
        print('{}% confidence interval: {}\n'.format(c_interval * 100, interval))


"""Methods for playing the game from the value iteration agent."""

from DeepQLearningAgent import *
from QLearningAgent import *
from DoubleQLearningAgent import *
episodes = 100

def play_q(env: JoypadSpace, args, actions):
    """Play the game using the Q-learning agent."""
    agent: QLearningAgent = QLearningAgent(env)

    for _ in range(episodes):

        environment = None
        if actions is None:
            actions = env.action_space.n
        else:
            environment = SkipFrame(JoypadSpace(gym.make(args.env)), skip=5)
            state = environment.reset()

        done = False
        _, _, _, info, = environment.step(0)
        _, _, _, info, = environment.step(0)
        _, _, _, info, = environment.step(0)

        state = agent.make_state(info)
        while not done:
            action = agent.get_action(state)

            _, _, done, info = environment.step(action)
            state = agent.make_state(info)

            environment.render()

        # close the environment
        env.close()

def play_double_q(env: JoypadSpace, args, actions):
    """Play the game using the Q-learning agent."""
    agent: DoubleQLearningAgent = DoubleQLearningAgent(env, actions)
    for _ in range(episodes):

        environment = None
        if actions is None:
            actions = env.action_space.n
        else:
            environment = JoypadSpace(gym.make(args.env), actions)
            environment.reset()

        done = False
        _, _, _, info, = environment.step(0)
        state = agent.make_state(info)
        while not done:
            if done:
                _ = environment.reset()

            action = agent.get_action(state)
            _, _, done, info = environment.step(action)
            state = agent.make_state(info)
            environment.render()

        # close the environment
        try:
            env.close()
        except:
            pass


#!/bin/python3

import os
import sys

#
# Complete the getMoneySpent function below.
#
def getMoneySpent(keyboards, drives, b):
    keyboards = sorted([each_keyboards for each_keyboards in keyboards if each_keyboards < b], reverse = True)
    drives = sorted([each_drives for each_drives in drives if each_drives < b], reverse = True)
    result = set()
    for each_keyboards in keyboards:
        for each_drives in drives:
            if each_keyboards + each_drives <= b:
                result.add(each_keyboards + each_drives)
    if len(result) != 0:
        return max(result)
    return (-1)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    bnm = input().split()

    b = int(bnm[0])

    n = int(bnm[1])

    m = int(bnm[2])

    keyboards = list(map(int, input().rstrip().split()))

    drives = list(map(int, input().rstrip().split()))

    #
    # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
    #

    moneySpent = getMoneySpent(keyboards, drives, b)

    fptr.write(str(moneySpent) + '\n')

    fptr.close()


from pymongo import MongoClient
import time

client = MongoClient('localhost', 27017)
db = client['sahamyab']
series_collection = db['tweets']

start_time = time.time()
series_collection.update_many(
              {'hashtags':{'$in': ['فولاد', 'شستا', 'شبندر'] }},
              {'$set':{'gov': True }})

end_time = time.time()
delta_time = end_time - start_time
print(delta_time)

NoSQL Databases (Cassandra, MongoDB, Neo4j, Elasticsearch)/MongoDB/1000 twiits/game3_2.py


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

from __future__ import division
from __future__ import print_function

import ojfdb
#import ojfresult
#import ojfpostproc
import towercal
import yawcal
import bladecal
import ojf_freeyaw

def rebuild_symlink_database():
    # first, rebuild the symlink list: all files in one folder
    # this includes the sweep cases as well
    path_db = 'database/'
    data_source_root = 'data/raw/'
    ojfdb.make_symlinks_all(path_db, data_source_root)

    # convert the database index to csv/DataFrame_hdf5/xls. Based on the file
    # name other usefull selection columns are created
    ojfdb.convert_pkl_index_df(path_db, db_id='symlinks_all')

    # create a stastistics database
    # create a dashboard plot for all the cases
    ojfdb.build_stats_db(path_db, 'symlinks_all', calibrate=True, dashplot=True,
                         dataframe=True, resample=True, continue_build=True,
                         save_df=True, save_df_csv=True)

    # only rebuild the statistics database
    ojfdb.build_stats_db(path_db, 'symlinks_all', calibrate=True, dashplot=False,
                         dataframe=True, resample=True, continue_build=False,
                         save_df=False, save_df_csv=False)

    # add the freeyaw control stair cases to the stats collection
    ojf_freeyaw.add_yawcontrol_stair_steps()

def rebuild_calibration_data():
    """
    Rebuild the calibration data based on the raw calibration measurements.
    """

    towercal.all_tower_calibrations()
    yawcal.all_yawlaser_calibrations()

    # bladecall fails currently for the stair detection in April
    bladecal.all_blade_calibrations()

if __name__ == '__main__':

    dummy=None

    path_db = 'database/'
    data_source_root = 'data/raw/'


from collections import deque

#올바른 괄호열인지 판단 하는 함수
def isCorrect(p):
    lst = [] #문자열의 문자를 하나하나 담을 lst
    for i in range(len(p)):
        if p[i] == '(': # 만약 열린 괄호이면 리스트에 넣는다.
            lst.append(p[i])
        elif p[i] == ')': # 만약 닫힌 괄호라면
            if len(lst) == 0: # 닫힌 괄호인데 lst가 빈 상태라면
                return False # 올바른 문자열이 아니다.
            lst.pop() # lst에 있는 열린 괄호를 하나 뽑는다.
    if len(lst): # lst에 열린 괄호가 남은 상태라면 올바른 문자열이 아니다.
        return False
    return True

def solution(p): #p는 균형잡힌 문자(열린 괄호와 닫힌 괄호가 같다.)
    #종료 조건 -> 빈 문자열이라면 빈 문자열 반환
    if p == "" or isCorrect(p): # 또는 문자열이 처음부터 올바른 문자열이라면 그대로 반환
        return p
    length = len(p) # 문자열의 길이를 담는다.
    u = ""
    v = ""
    q = deque([p[0]]) # 문자열의 첫 번째 괄호를 큐에 넣는다.
    idx = 0    # 문자열의 첫 번째 괄호를 큐에 넣고 index는 0으로 초기화(p에서 인덱스 0을 가리킴)

    # 균형잡힌 문자열이 끝난 지점을 idx로 찾아나가는 작업
    while q:
        if q[-1] == p[idx + 1]: #만약 큐에 있는 괄호와 같은 괄호라면
            q.append(p[idx + 1]) #큐에 집어넣는다.
            idx += 1 # 현재 index를 다음 index로 업데이트
        else: # 큐에 있는 괄호와 다른 괄호라면
            q.pop() # 큐에 있는 괄호 하나를 제거
            idx += 1 # index 업데이트

    #인덱스를 기준으로 u와 v를 나누기
    u = p[:idx + 1] # u는 더 이상 분리할 수 없는 균형잡힌 문자열을 담고 있다.
    v = p[idx + 1:] # 나머지 열은 v에 담기

    #만약 u가 '올바른 괄호 문자열'이라면 -> 즉 u의 시작 문자열이 열린 괄호라면(u가 균형잡힌 문자열이므로) v에 대하여 1단계부터 다시 수행

    if u[0] == '(':
        return u + solution(v)

    else: #그렇지 않다면(u가 올바른 괄호가 아니라면)
        answer = ""
        p = solution(v)
        #u의 앞 뒤 문자 제거하고 괄호 뒤집기
        u = list(u)
        u[0] = ""
        u[-1] = ""
        u = ''.join(u) #u를 다시 문자열로 변경
        if u != "":
            for i in range(len(u)):
                if u[i] == '(':
                    u = list(u)
                    u[i] = ')'
                    u = ''.join(u)
                else:
                    u = list(u)
                    u[i] = '('
                    u = ''.join(u)

        answer += "(" + p + ")" + u
        return answer


import tkinter as tk
import random
import time

class Ball:
    def __init__(self, _x, _y, _r, vx, vy, a_x=0, a_y=0, color='black'):
        self.x_acceleration = a_x
        self.y_acceleration = a_y
        self.v_x = vx
        self.v_y = vy
        self.x = _x
        self.y = _y
        self.r = _r
        self.ball = c.create_oval(_x - _r, _y - _r, _x + _r, _y + _r, fill=color, width=0)

    def ball_move(self):
        last_x = self.x
        last_y = self.y
        self.x += self.v_x
        self.y += self.v_y
        self.v_x += self.x_acceleration
        self.v_y += self.y_acceleration
        c.move(self.ball, self.x - last_x, self.y - last_y)

    def collision_with_ball(self, ball, enother_ball):
        if True:  # условие соударения с шаром
            return True
        else:
            return False

    def collision_with_wall(self, ball, wall):
        d_x = 0
        d_y = 0
        if wall == 'right':
            if ball.x + ball.r - d_x > WW:  # условие столкновения со стеной
                return True
            else:
                return False
        elif wall == 'left':
            if ball.x + ball.r + d_x < 100:  # условие столкновения со стеной
                return True
            else:
                return False
        elif wall == 'up':
            if ball.y + ball.r + d_y < 100:  # условие столкновения со стеной
                return True
            else:
                return False
        else:
            if ball.y + ball.r - d_y > WH:  # условие столкновения со стеной
                return True
            else:
                return False

class Field(Ball):
    def __init__(self):
        Ball.__init__(self, 0, 0, 0, 0, 0)
        self.balls = []
        c.bind('<Button-1>', self.click)

    def click(self, event):
        global score, score_text
        try:
            for i in range(len(self.balls)):
                if (self.balls[i].x - event.x) ** 2 + (self.balls[i].y - event.y) ** 2 < self.balls[i].r ** 2:
                    c.delete(self.balls[i].ball)
                    del self.balls[i]
                    score += 1
                    c.delete(score_text)
                    score_text = c.create_text(1450, 10, text=str(score), font='Verdana 14')
        except IndexError:
            pass

    def generation_of_ball(self):
        x = random.randrange(100, 700)
        y = random.randrange(100, 500)
        r = random.randrange(30, 50)
        d_x = random.randrange(-10, 10)
        d_y = random.randrange(-10, 10)
        a_x = random.randrange(-2, 2)
        a_y = random.randrange(-2, 2)
        self.balls.append(Ball(x, y, r, d_x, d_y, a_x, a_y, random.choice(colors)))

    def collision_handling(self):
        for i in range(len(self.balls) - 1):
            for j in range(i, len(self.balls)):
                if self.collision_with_ball(self.balls[i], self.balls[j]):
                    pass
                    """ написать функцию соударения шаров """
            if self.collision_with_wall(self.balls[i], 'right'):
                self.balls[i].v_x *= -1
            if self.collision_with_wall(self.balls[i], 'left'):
                self.balls[i].v_x *= -1
            if self.collision_with_wall(self.balls[i], 'up'):
                self.balls[i].v_y *= -1
            if self.collision_with_wall(self.balls[i], 'down'):
                self.balls[i].v_y *= -1
        try:
            if self.collision_with_wall(self.balls[-1], 'right'):
                self.balls[-1].v_x *= -1
            if self.collision_with_wall(self.balls[-1], 'left'):
                self.balls[-1].v_x *= -1
            if self.collision_with_wall(self.balls[-1], 'up'):
                self.balls[-1].v_y *= -1
            if self.collision_with_wall(self.balls[-1], 'down'):
                self.balls[-1].v_y *= -1
        except IndexError:
            pass

    def movement(self):
        for i in self.balls:
            i.ball_move()

def update_table(name, score):
    flag = True
    q = 1
    a = []
    table = open("Best_Players.txt")
    for line in table:
        a.append((int(line.split(' | ')[2]), line.split(' | ')[1]))
    table.close()
    for i in range(len(a)):
        if a[i][1] == name:
            a[i] = (score, name)
            flag = False
    if flag:
        a.append((score, name))
    a.sort(key=lambda x: x[0], reverse=True)
    table = open("Best_Players.txt", 'w')
    for i in a:
        table.write(str(q) + ' | ' + i[1] + ' | ' + str(i[0]) + '\n')
        q += 1
    table.close()

WW = 1500
WH = 800
root = tk.Tk()
root.geometry('1500x800+0+0')
c = tk.Canvas(root, width=WW, height=WH, bg='white')
c.pack()
colors = ['black', 'yellow', 'green', 'blue']

f = Field()
for i in range(10):
    f.generation_of_ball()
score = 0
speed = 0
iteration = 0
score_text = c.create_text(1450, 10, text=str(score), font='Verdana 14')
name = input('Enter your name: ')

def upd():
    try:
        table = open("Best_Players.txt")
    except FileNotFoundError:
        table = open("Best_Players.txt", 'w')
        table.write('1' + ' | ' + ' Vasya' + ' | ' + '666' + '\n' + '2' + ' | ' + ' Gosha' + ' | ' + '103' + '\n')
        table.close()
    global speed, iteration, name, score
    f.collision_handling()
    f.movement()
    if len(f.balls) > 40 or len(f.balls) == 7:
        update_table(name, score)
        exit()
    if score > 5 and speed == 0:
        speed = 2
    elif score > 10 and speed == 2:
        speed = 3
    elif score > 20 and speed == 3:
        speed = 5
    elif score > 40 and speed == 5:
        speed = 8
    if speed and iteration % 50 * speed == 0:
        iteration = 0
        f.generation_of_ball()
    root.after(40, upd)
    iteration += 1

upd()
tk.mainloop()


from heapq import heappop, heappush, heapify
def solution(scoville, K):
    answer = 0
    heapify(scoville)
    while scoville[0] < K and len(scoville) >= 2:
        first = heappop(scoville)
        second = heappop(scoville)
        heappush(scoville, first+(second*2))
        answer += 1

    if scoville[0] < K:
        return -1

    return answer


pkgname = "rxvt-unicode"
pkgver = "9.31"
pkgrel = 1
build_style = "gnu_configure"
configure_args = [
    "--with-terminfo=/usr/share/terminfo",
    "--with-term=rxvt-unicode-256color",
    "--enable-256-color",
    "--enable-font-styles",
    "--enable-keepscrolling",
    "--enable-startup-notification",
    "--enable-selectionscrolling",
    "--enable-smart-resize",
    "--enable-transparency",
    "--enable-combining",
    "--enable-unicode3",
    "--enable-pixbuf",
    "--enable-frills",
    "--enable-xim",
    "--disable-perl",
]
hostmakedepends = ["pkgconf"]
makedepends = [
    "xorgproto",
    "libxrender-devel",
    "libxft-devel",
    "libxt-devel",
    "libsm-devel",
    "libptytty-devel",
    "fontconfig-devel",
    "gdk-pixbuf-devel",
    "startup-notification-devel",
]
depends = [f"rxvt-unicode-terminfo={pkgver}-r{pkgrel}"]
pkgdesc = "Terminal emulator supporting Xft fonts and Unicode"
maintainer = "q66 <q66@chimera-linux.org>"
license = "GPL-3.0-or-later"
url = "http://software.schmorp.de/pkg/rxvt-unicode.html"
source = f"http://dist.schmorp.de/{pkgname}/{pkgname}-{pkgver}.tar.bz2"
sha256 = "aaa13fcbc149fe0f3f391f933279580f74a96fd312d6ed06b8ff03c2d46672e8"
hardening = ["vis", "!cfi"]

def init_configure(self):
    self.make_install_env[
        "TERMINFO"
    ] = f"{self.chroot_destdir}/usr/share/terminfo"

def pre_install(self):
    self.make_install_env[
        "TERMINFO"
    ] = f"{self.chroot_destdir}/usr/share/terminfo"

    self.install_dir("usr/share/terminfo")

def post_install(self):
    self.install_file("doc/etc/rxvt-unicode.terminfo", "usr/share/terminfo/r")
    self.install_file(self.files_path / f"{pkgname}.png", "usr/share/pixmaps")
    self.install_file(
        self.files_path / f"{pkgname}.desktop", "usr/share/applications"
    )

@subpackage("rxvt-unicode-terminfo")
def _tinfo(self):
    self.pkgdesc = f"{pkgdesc} (terminfo data)"

    return ["usr/share/terminfo"]

configure_gen = []


def main():
    print("This program will calculate your BMI and tell whether it's above, below, or within the healthy range.")
    weight = int(input("What is your weight in pounds?"))
    height = int(input("What is your height?"))
    finalheight = height ** 2
    bmi = (weight * 720) / finalheight
    finalbmi = str(bmi)
    if bmi < 19:
        finalbmi = "below"
    if bmi >= 19 and bmi <= 25:
        finalbmi = "within"
    if bmi > 25:
        finalbmi = "over"
    print("Your bmi is", finalbmi, "the healthy range.")

main()


from flask import (g, abort, get_flashed_messages, request, flash, redirect,
                   url_for)

from sqlalchemy.sql import functions

from buddyup.app import app
from buddyup.database import (Course, Visit, User, BuddyInvitation,
                              Location, Major, Event, Language, db)
from buddyup.templating import render_template
from buddyup.util import form_get, check_empty
from functools import wraps

def admin_required(f):
    @wraps(f)
    def func(*args, **kwargs):
        if g.user and g.user.user_name == app.config.get("ADMIN_USER", u""):
            return f(*args, **kwargs)
        else:
            abort(403)
    return func

@app.route("/admin")
@admin_required
def admin_dashboard():
    variables = {}
    variables['group_count'] = Event.query.count()
    variables['unique_visits'] = Visit.query.count()
    query = db.session.query(functions.sum(Visit.requests))
    variables['total_visits'] = query.scalar()
    variables['total_groups'] = Event.query.count()
    variables['total_invites'] = BuddyInvitation.query.count()
    # Maybe only count users who have logged in?
    variables['total_users'] = User.query.count()
    variables['courses'] = Course.query.order_by(Course.name).all()
    variables['majors'] = Major.query.order_by(Major.name).all()
    variables['locations'] = Location.query.order_by(Location.name).all()
    variables['languages'] = Language.query.order_by(Language.name).all()
    return render_template('admin/dashboard.html', **variables)

@app.route("/admin/course/add", methods=['POST'])
@admin_required
def admin_add_course():
    name = form_get('name')
    check_empty(name, "Course Name")
    instructor = form_get('instructor')
    check_empty(instructor, "Professor Name")
    if not get_flashed_messages():
        course = Course(name=name, instructor=instructor)
        db.session.add(course)
        db.session.commit()
        flash("Added Course " + name)
    return redirect(url_for('admin_dashboard'))
    #return render_template('admin/dashboard.html', **get_stats())

@app.route("/admin/course/delete", methods=['POST'])
@admin_required
def admin_delete_course():
    course_ids = map(int, request.form.getlist('courses'))
    for course_id in course_ids:
        Course.query.filter_by(id=course_id).delete()
    db.session.commit()
    flash('Course deleted')
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/location/add", methods=['POST'])
@admin_required
def admin_add_location():
    name = form_get('location')
    check_empty(name, "Location Name")
    if not get_flashed_messages():
        loc = Location(name=name)
        db.session.add(loc)
        db.session.commit()
        flash("Added Course " + name)
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/location/delete", methods=['POST'])
@admin_required
def admin_delete_location():
    location_ids = map(int, request.form.getlist('location'))
    for location_id in location_ids:
        Location.query.filter_by(id=location_id).delete()
    db.session.commit()
    flash('Location deleted')
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/major/add", methods=['POST'])
@admin_required
def admin_add_major():
    name = form_get('major')
    check_empty(name, "Major Name")
    if not get_flashed_messages():
        major = Major(name=name)
        db.session.add(major)
        db.session.commit()
        flash("Added Course " + name)
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/major/delete", methods=['POST'])
@admin_required
def admin_delete_major():
    major_ids = map(int, request.form.getlist('majors'))
    for major_id in major_ids:
        Major.query.filter_by(id=major_id).delete()
    db.session.commit()
    flash('Majors deleted')
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/language/add", methods=['POST'])
@admin_required
def admin_add_language():
    name = form_get('language')
    check_empty(name, "Language Name")
    if not get_flashed_messages():
        language = Language(name=name)
        db.session.add(language)
        db.session.commit()
        flash("Added Language " + name)
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/language/delete", methods=['POST'])
@admin_required
def admin_delete_language():
    language_ids = map(int, request.form.getlist('languages'))
    for language_id in language_ids:
        Language.query.filter_by(id=language_id).delete()
    db.session.commit()
    flash('Languages deleted')
    return redirect(url_for('admin_dashboard'))

@app.route("/admin/users")
@admin_required
def admin_user_management():
    users = User.query.all()
    return render_template('admin/userManagement.html', users=users)

@app.route("/admin/forums")
@admin_required
def admin_forum_management():
    pass

@app.route("/admin/stats")
@admin_required
def admin_stats():
    variables = {}
    variables['group_count'] = Event.query.count()
    variables['unique_visits'] = Visit.query.count()
    # This requires something with func.sum. Not sure what.
    variables['total_visits'] = Visit.query.sum(Visit.requests)
    variables['total_groups'] = Event.query.count()
    variables['total_invites'] = BuddyInvitation.query.count()
    # Maybe only count users who have logged in?
    variables['total_users'] = User.query.filter(User.activated == True).count()

    render_template('admin_stats.html', **variables)


# -*- coding: utf-8 -*-
"""
Created on Mo 12 Sept  2 13:15:51 2022

@author: FKAM
"""

import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objs as go
#import altair as alt
#from bokeh.plotting import figure

def list_ext(uploads, radio3):
    list_ = []
    header_default = ["date [YYYYMMDD]",
                          "time [HHMMSS]",
                          "X [m]",
                          "Y [m]",
                          "Z [m]",
                          "Drain nr. [-]",
                          "Job nr. [-]",
                          "Base unit [-]",
                          "Operator [-]",
                          "Stitcher type [-]",
                          "Stitcher length [m]",
                          "Stitcher ballast [ton]",
                          "Drain type [-]",
                          "Anchoring [-]",
                          "Pattern type [0=square/1=triang.]",
                          "Pattern distance [m]",
                          "Pattern heading [deg]",
                          "Pattern X-position [m]",
                          "Pattern Y-position [m]",
                          "Prescribed depth [m]",
                          "Max. depth [m]",
                          "Pull back [m]",
                          "Cum. drain length [m]",
                          "Duration [s]",
                          "Max. force [kN]",
                          "Stitcher angle [deg]",
                          "ok",
                          "new roll",
                          "canceled",
                          "Log interval [m]",
                          "Data nr. [-]",
                          "Force [kN]"]
    df_default = pd.DataFrame(columns=header_default)

    for file_ in uploads:
        for headerline in file_:
            headerline = str(headerline)
            if '#date' in headerline:
                break
        headerline = headerline[:-3]
        headerlist = headerline.replace("b'#", "").split(',')

        if 'Remarks' in headerlist:
            headerlist.remove('Remarks')
            headerlist.remove('')
            for index, item in enumerate(headerlist):
                if ' [ok' in item:
                    headerlist[index] = 'ok'
                if 'canceled]' in item:
                    headerlist[index] = 'canceled'

        df = pd.read_csv(file_, index_col=False, header=None)

        nums = list(range(len(headerlist)))
        headerdict = dict(zip(nums, headerlist))
        df = df.rename(columns=headerdict)
        df = df.rename(columns={' Drain nr. [-]' : 'Drain nr. [-]'})

        force_1_loc = df.columns.get_loc('Force [kN]')
        df_force = df.iloc[:, force_1_loc+1:-1]
        for col in range(len(df_force.columns)):
            df_force = df_force.rename(columns={df_force.columns[col] : f'Force_{col+2}'})

        if radio3 == 'Default columns (recommended)':

            if not header_default == headerlist:
                df = pd.concat([df_default, df])

            for col in df.columns:
                if col not in header_default:
                    df = df.drop([col], axis=1)
        elif radio3 == 'Columns from file':
            for col in df.columns:
                if type(col) == int:
                    df = df.drop([col], axis=1)

        df = pd.concat([df, df_force], axis=1)

        #####
        list_.append(df)

    ### Sort list_ on df with most columns ##
    a = max([x.shape[1] for x in list_])
    indexa = [x.shape[1] for x in list_].index(a)
    longest = list_[indexa]
    del list_[indexa]
    list_.insert(0, longest)

    return list_, headerlist

def convert(list_, headerlist, wp_calc_method, fixed_nr):

    frame = pd.concat(list_, axis=0, ignore_index=True)

        ## Rename columns ##
    nums = list(range(len(headerlist)))
    headerdict = dict(zip(nums, headerlist))
    frame = frame.rename(columns=headerdict)

    frame = frame.sort_values(['Base unit [-]', 'date [YYYYMMDD]', 'time [HHMMSS]'])

        ## Add date and time columns ##
    #date_text = frame['date [YYYYMMDD]']
    frame['date [YYYYMMDD]'] = pd.to_datetime(frame['date [YYYYMMDD]'], format='%Y%m%d').dt.date
    frame['time [HHMMSS]'] = frame['time [HHMMSS]'].astype(int)
    for pvd in frame.index:
        if len(str(frame.loc[pvd, 'time [HHMMSS]'])) < 6:
            frame.loc[pvd, 'time [HHMMSS]'] = (6 - len(str(frame.loc[pvd, 'time [HHMMSS]']))) * '0' + str(frame.loc[pvd, 'time [HHMMSS]'])
    time_text = frame['time [HHMMSS]'].copy()
    frame['time [HHMMSS]'] = pd.to_datetime(frame['time [HHMMSS]'], format='%H%M%S').dt.time

        ## Cable tension + wp thickness ##
    if wp_calc_method == 'No':
        wp_frame = 0
    else:
        wp_thickness = [100]*len(frame)

        for pvd in range(len(frame)):

            keys = list(frame)
            force1 = keys.index('Force [kN]')
            force_df = frame.iloc[:, force1:]
            force_pvd =  force_df.loc[pvd,:].values.tolist()

            force_pvd = [i for i in force_pvd if i != 0]    #remove zeros
            force_pvd = force_pvd[2:-3]                     #remove first 2 and last 2 values

            if len(force_pvd) > 0:
                cable_tension = min(force_pvd)
                if wp_calc_method == 'Lowest force plus fixed number':
                    cutoff = cable_tension + fixed_nr
                elif wp_calc_method == 'Manual choice':
                    cutoff = fixed_nr
                else:
                    cutoff = 0

                cable_tension_index = force_pvd.index(cable_tension)
                force_pvd = force_pvd[:cable_tension_index]

                wp = (sum(i > cutoff for i in force_pvd) + 2) * frame['Log interval [m]'][pvd]
                wp_thickness[pvd] = wp

        wp_frame = frame[['X [m]', 'Y [m]']]
        wp_frame['wp [m]'] = wp_thickness

        wp_frame['csx'] = [528374]*len(frame)
        wp_frame['csy'] = [507360]*len(frame)

    tofloat = ['Z [m]',
               'Drain nr. [-]',
               'Max. depth [m]',
               'Max. force [kN]',
               'Prescribed depth [m]',
               'Stitcher angle [deg]']

    for col in tofloat:
        if col in frame.columns:
            frame[col] = frame[col].astype(float)
        else:
            continue
    return frame, time_text

def show_delay(frame_filtered, delta, start_time, end_time, date, base_unit):

    time_text = frame_filtered['time_text']
    time_text = pd.concat([start_time, time_text, end_time])
    time_text = list(pd.to_datetime(time_text, format='%H%M%S'))

    start = time_text[:-1].copy()
    end = time_text[1:].copy()

    fig, ax = plt.subplots(figsize=[18,3], facecolor='white')
    periods = []
    for pvd in range(len(start)):
        periods.append((start[pvd], end[pvd] - start[pvd]))

    periods_op = [tup for tup in periods if tup[1] <= np.timedelta64(int(delta), 's')]
    periods_delay = [tup for tup in periods if tup[1] > np.timedelta64(int(delta), 's')]

    ax.broken_barh(
        periods_delay,
        (0.1, 0.2),
        color='#FF6861',
        #edgecolor="black"
    )

    ax.broken_barh(
        periods_op,
        (-0.1, 0.2),
        color='green',
        # edgecolor="black"
    )

    ax.set_yticks([0, 0.2])
    ax.set_yticklabels(['Operational', 'Delay'])
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    fig.suptitle(f'{date} - {base_unit}', fontsize=20)
    ax.grid(linestyle="--")
    fig.autofmt_xdate()
    st.write(fig)

    total_op = total_delay = datetime.timedelta()
    for pvd in periods_op:
        total_op += pvd[1]
    for pvd in periods_delay:
        total_delay += pvd[1]
    st.write('Operational time: ', str((datetime.datetime.min + total_op).time()))
    st.write('Delay time: ', str((datetime.datetime.min + total_delay).time()))

    st.write('Efficiency: ', str(round(100 * total_op.total_seconds() / (total_op.total_seconds() + total_delay.total_seconds()))), '%')

    fn = f'{date} - {base_unit}.png'
    img = io.BytesIO()
    plt.savefig(img, format='png')

    st.download_button(
       label='Download as image',
       data=img,
       file_name=fn,
       mime='image/png'
    )

def show_preview(frame):

    scale = ["date [YYYYMMDD]",
                          "time [HHMMSS]",
                          "Z [m]",
                          "Drain nr. [-]",
                          "Base unit [-]",
                          "Operator [-]",
                          "Stitcher type [-]",
                          "Prescribed depth [m]",
                          "Max. depth [m]",
                          "Max. force [kN]",
                          "Stitcher angle [deg]"]

    choose_scale = st.selectbox('Choose plot parameter:',
                         scale,
                         help='Choose from the list what you want to plot in the figure below', index=8)

    frame.columns[10] == choose_scale
    if choose_scale in frame.columns:
        fig = px.scatter(data_frame = frame,
                         x=frame['X [m]'],
                         y=frame['Y [m]'],
                         color=choose_scale,
                         color_continuous_scale='turbo')

        fig.update_yaxes(scaleanchor='x', scaleratio=1)
        st.write(fig)
    else:
        st.write(f'{choose_scale} not found')

    # from streamlit_plotly_events import plotly_events
    # clickedPoint = plotly_events(fig, key="line")
    # st.write(f"Clicked Point: {clickedPoint}")

def show_wp(wp_frame, cs):
    # st.write('**Working platform thickness:**')
    # #fig1 = go.Figure()
    # fig1 = px.scatter(data_frame = wp_frame,
    #                  x=wp_frame['X [m]'],
    #                  y=wp_frame['Y [m]'],
    #                  color='wp [m]',
    #                  color_continuous_scale='turbo',
    #                  range_color=[0,5])

    # fig1.update_yaxes(scaleanchor='x', scaleratio=1)
    # st.write(fig1)

    st.write('**Working platform thickness:**')
    fig1 = go.Figure()
    fig1.add_trace(go.Scatter(x=wp_frame['X [m]'],
                              y=wp_frame['Y [m]'],
                              mode='markers',
                              name='PVD points',
                              marker_color=wp_frame['wp [m]']))

    x = [507360, 507460]
    y = [cs, cs]
    fig1.add_trace(go.Scatter(x=x, y=y,
                              mode='lines',
                              name='Cross section'))

    fig1.update_yaxes(scaleanchor='x', scaleratio=1)
    st.write(fig1)

    #st.write(fig1)
    # fig3 = go.Figure(data=fig1.data + fig2.data)
    # st.write(fig3)


from __future__ import print_function
import numpy as np
import ad3.factor_graph as fg
import time

def test_random_instance(n):
    costs = np.random.rand(n)
    budget = np.sum(costs) * np.random.rand()
    scores = np.random.randn(n)

    tic = time.clock()
    x = solve_lp_knapsack_ad3(scores, costs, budget)
    toc = time.clock()
    print('ad3: {:.2f}'.format(toc - tic))

    try:
        tic = time.clock()
        x_gold = solve_lp_knapsack_lpsolve(scores, costs, budget)
        toc = time.clock()
        print('lpsolve: {:.2f}'.format(toc - tic))
        res = x - x_gold
        assert np.linalg.norm(res) < 1e-6

    except ImportError:
        print('lpsolve not available')

def solve_lp_knapsack_ad3(scores, costs, budget):
    factor_graph = fg.PFactorGraph()
    binary_variables = []
    for i in range(len(scores)):
        binary_variable = factor_graph.create_binary_variable()
        binary_variable.set_log_potential(scores[i])
        binary_variables.append(binary_variable)

    factor_graph.create_factor_knapsack(binary_variables, costs=costs,
                                        budget=budget)

    # Run AD3.
    _, posteriors, _, _ = factor_graph.solve()
    return posteriors

def solve_lp_knapsack_gurobi(scores, costs, budget):
    from gurobipy import Model, LinExpr, GRB

    n = len(scores)

    # Create a new model.
    m = Model("lp_knapsack")

    # Create variables.
    for i in range(n):
        m.addVar(lb=0.0, ub=1.0)
    m.update()
    vars = m.getVars()

    # Set objective.
    obj = LinExpr()
    for i in range(n):
        obj += scores[i] * vars[i]
    m.setObjective(obj, GRB.MAXIMIZE)

    # Add constraint.
    expr = LinExpr()
    for i in range(n):
        expr += costs[i] * vars[i]
    m.addConstr(expr, GRB.LESS_EQUAL, budget)

    # Optimize.
    m.optimize()
    assert m.status == GRB.OPTIMAL
    x = np.zeros(n)
    for i in range(n):
        x[i] = vars[i].x

    return x

def solve_lp_knapsack_lpsolve(scores, costs, budget):
    import lpsolve55 as lps

    relax = True
    n = len(scores)

    lp = lps.lpsolve('make_lp', 0, n)
    # Set verbosity level. 3 = only warnings and errors.
    lps.lpsolve('set_verbose', lp, 3)
    lps.lpsolve('set_obj_fn', lp, -scores)

    lps.lpsolve('add_constraint', lp, costs, lps.LE, budget)

    lps.lpsolve('set_lowbo', lp, np.zeros(n))
    lps.lpsolve('set_upbo', lp, np.ones(n))

    if not relax:
        lps.lpsolve('set_int', lp, [True] * n)
    else:
        lps.lpsolve('set_int', lp, [False] * n)

    # Solve the ILP, and call the debugger if something went wrong.
    ret = lps.lpsolve('solve', lp)
    assert ret == 0

    # Retrieve solution and return
    x, _ = lps.lpsolve('get_variables', lp)
    x = np.array(x)

    return x

if __name__ == "__main__":
    n = 100
    test_random_instance(n)


from django.shortcuts import render, redirect
from .models import Aricle
from .forms import ArticleForm

def new(request):
    if request.method == 'POST':
        article_form = ArticleForm(request.POST)
        if article_form.is_valid():
            article = article_form.save()
            return redirect('blog:detail', article.id)
    elif request.method == 'GET':
        article_form = ArticleForm()

    context = {
        'article_form' : article_form,
    }
    return render(request, 'blog/form_new.html', context)


from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import json
import string
import re

ps = PorterStemmer()

punctuation = list(string.punctuation)
stop = stopwords.words('english') + punctuation + ['rt', '#rt', '#follow', 'via', 'donald', 'trump', '…', "trump's",
                                                   'new']
emoticons_str = r"""
    (?:
        [:=;] # Eyes
        [oO\-]? # Nose (optional)
        [D\)\]\(\]/\\OpP] # Mouth
    )"""

regex_str = [
    emoticons_str,
    r'<[^>]+>', # HTML tags
    r'(?:@[\w_]+)', # @-mentions
    r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags
    r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs
    r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers
    r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and '
    r'(?:[\w_]+)', # other words
    r'(?:\S)' # anything else
]

tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE)
emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE)

def tokenize(s):
    return tokens_re.findall(s)

def preprocess(s, lowercase=True): #what does lowercase=True do?
    tokens = tokenize(s)
    if lowercase:
        tokens = [token if emoticon_re.search(token) else ps.stem(token.lower()) for token in tokens]
    return tokens

def normalize_text():
    with open('Tweets.json', 'r') as f:
        for line in f:
            try:
                tweet = json.loads(line) # load it as Python dict
                tokens = preprocess(tweet['text'])
                print([w for w in tokens if not w in stop])
            except BaseException as e:
                continue

normalize_text()


# Qus: https://leetcode.com/problems/maximal-network-rank/
# time complexity O(N**2)
class Solution(object):
    def maximalNetworkRank(self, n, roads):
        """
        :type n: int
        :type roads: List[List[int]]
        :rtype: int
        """

        graph = {}

        for i in range(n):
            graph[i] = set()

        for u,v in roads:

            graph[u].add(v)
            graph[v].add(u)

        ans = 0

        for u in graph:

            for v in graph:

                if(u!=v):
                    # print u,v,len(graph[u]) + len(graph[v])
                    count = len(graph[u]) + len(graph[v])

                    if(v in graph[u]):
                        count -= 1 # remove the common edge if exist between two nodes

                    ans = max(ans,count)
        return ans

Leetcode Everyday challenge/Maximal Network Rank.py


# pxy7896@foxmail.com
# 2020/8/1

__doc__ = """
获取中公教育每日一练内容；获取国务院政府工作报告。
"""

import requests
from bs4 import BeautifulSoup
import os

# 服务器反爬虫机制会判断客户端请求头中的User-Agent是否来源于真实浏览器，所以，我们使用Requests经常会指定UA伪装成浏览器发起请求
headers = {'user-agent': 'Mozilla/5.0'}

# 写文件
def writedoc(raw_ss, i, ii):
    # 打开文件
    # 编码为utf-8
    start = raw_ss.find("模拟试题")
    end = raw_ss.find("免责声明")
    ss = raw_ss[start+5: end-5]
    with open("result\\第" + str(ii) + "页.txt", 'a', encoding='utf-8') as f:
        # 写文件
        f.write(ss + "\n\n")
    #print("问题" + str(i) + "文件写入完成" + "\n")

# 根据详细页面url获取目标字符串
def geturl(url):
    # 请求详细页面
    r = requests.get(url, headers=headers)
    # 改编码
    r.encoding = "GB2312"
    soup = BeautifulSoup(r.text, "html.parser")
    # 找出类名为 info-zi mb15 下的所有p标签
    #ans = soup.find_all(["p", ".info-zi mb15"])
    ans = soup.find_all(["p", ".offcn_shocont"])
    # 用来储存最后需要写入文件的字符串
    mlist = ""
    for tag in ans:
        # 获取p标签下的string内容，并进行目标字符串拼接
        mlist = mlist + str(tag.string)
    # 返回目标字符串
    return mlist

# 获取目标网址第几页
def getalldoc(ii):
    #string_ans_li = []
    if ii == 1:
        testurl = "http://www.offcn.com/mianshi/mryl/"
    else:
    # 字符串拼接成目标网址
        testurl = "http://www.offcn.com/mianshi/mryl/" + str(ii) + ".html"
    # 使用request去get目标网址
    res = requests.get(testurl, headers=headers)
    # 更改网页编码--------不改会乱码
    res.encoding = "GB2312"
    # 创建一个BeautifulSoup对象
    soup = BeautifulSoup(res.text, "html.parser")
    # 找出目标网址中所有的small标签
    # 函数返回的是一个list
    ans = soup.find_all("a")
    # 用于标识问题
    cnt = 1
    # 先创建目录
    # 如果需要分页爬取，那么路径只要写到对应就好了
    #mkdir("result\\第" + str(ii) + "页\\")
    for tag in ans:
        # 获取a标签下的href网址
        #string_ans = str(tag.a.get("href"))
        string_ans = str(tag.get("href"))
        if string_ans.find("/mianshi/2020/") == -1 and string_ans.find("/mianshi/2019/") == -1 and string_ans.find("/mianshi/2020/") == -1:
            continue
        #string_ans_li.append(string_ans)
        # 请求详细页面
        # 返回我们需要的字符串数据
        string_write = geturl(string_ans)
        # 写文件到磁盘
        writedoc(string_write, cnt, ii)
        cnt = cnt + 1
    #print("第", ii, "页写入完成")
    #return string_ans_li

"""
def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        return False
"""

def getall():
    for i in range(1, 10, 1):
        getalldoc(i)
        #print(ss)
        print(str(i) + " end!")
        #break

def get_gov(testurl, file):
    res = requests.get(testurl, headers=headers)
    # 更改网页编码--------不改会乱码
    res.encoding = "utf-8"
    # 创建一个BeautifulSoup对象
    soup = BeautifulSoup(res.text, "html.parser")
    ans = soup.find_all([["p","h5"], "conlun2_box_text"])
    # 用来储存最后需要写入文件的字符串
    mlist = ""
    for tag in ans:
        # 获取p标签下的string内容，并进行目标字符串拼接
        s = str(tag.string)
        if s == 'None': continue
        mlist = mlist + s + "\n"
    # 返回目标字符串
    with open(file, "a+") as file:
        file.write(mlist)

if __name__ == "__main__":
    #getall()
    get_gov("http://www.gov.cn/guowuyuan/zfgzbg.htm","gov-2020.txt")
    get_gov("http://www.gov.cn/guowuyuan/2019zfgzbg.htm","gov-2019.txt")

获取某网站每日一练.py

获取某网站每日一练.py


from collections import deque

GENERATOR = 0
MICROCHIP = 1

floors = [[] for _ in range(4)]
elev = 0
elems = dict()

def is_safe(arrangement):
    floors, _ = arrangement
    for floor in floors:
        chips = set()
        hasg = False
        for e in floor:
            if e & 1 == MICROCHIP:
                chips.add(e >> 1)
        for e in floor:
            if e & 1 == GENERATOR:
                if e >> 1 in chips:
                    chips.remove(e >> 1)
                hasg = True
        if len(chips) > 0 and hasg:
            return False
    return True

def moves(arrangement):
    res = []
    floors, elev = arrangement
    nelevs = []
    if elev > 0:
        nelevs.append(elev-1)
    if elev < 3:
        nelevs.append(elev+1)
    for nelev in nelevs:
        ne = len(floors[elev])
        for i in range(ne):
            for j in range(i, ne):
                cand = [list(x) for x in floors]
                cand[nelev].append(floors[elev][i])
                cand[elev][i] = None
                if j != i:
                    cand[nelev].append(floors[elev][j])
                    cand[elev][j] = None
                    cand[elev].remove(None)
                cand[elev].remove(None)
                for k, _ in enumerate(cand):
                    cand[k].sort()
                    cand[k] = tuple(cand[k])
                narr = (tuple(cand), nelev)
                if is_safe(narr):
                    res.append(narr)
    return res

def append(lst, e):
    e0, e1 = e
    if not e0 in elems:
        elems[e0] = len(elems)
    e0 = elems[e0]
    if e1 == 'generator':
        e1 = GENERATOR
    else:
        e1 = MICROCHIP
    lst.append(2*e0+e1)

with open('day11/input.txt') as h:
    for i, line in enumerate(h):
        line = line.strip('.\n')
        words = line.split()
        for j, word in enumerate(words):
            word = word.strip(',')
            if word == 'generator':
                append(floors[i], (words[j-1], word))
            elif word == 'microchip':
                append(floors[i], (words[j-1][:-11], word))
        if i == 0:
            append(floors[i], ('elerium', 'generator'))
            append(floors[i], ('elerium', 'microchip'))
            append(floors[i], ('dilithium', 'generator'))
            append(floors[i], ('dilithium', 'microchip'))
        floors[i].sort()
        floors[i] = tuple(floors[i])
floors = tuple(floors)

initial = (floors, elev)
final = [[list(x) for x in floors], 3]
for i in range(3):
    final[0][3].extend(final[0][i])
    final[0][i] = []
for i in range(4):
    final[0][i].sort()
    final[0][i] = tuple(final[0][i])
final[0] = tuple(final[0])
final = tuple(final)

qfront = deque([(initial, 0)])
qback = deque([(final, 0)])
sfront, sback = {initial: 0}, {final: 0}
dfront, dback = 0, 0
cont = True
while cont:
    while len(qfront) > 0 and qfront[0][1] == dfront:
        arr, _ = qfront.popleft()
        for narr in moves(arr):
            if narr in sback:
                print(dfront + sback[narr] + 1)
                cont = False
                break
            if narr in sfront:
                continue
            sfront[narr] = dfront + 1
            qfront.append((narr, dfront + 1))
        if not cont:
            break
    if not cont:
        break
    dfront += 1
    while len(qback) > 0 and qback[0][1] == dback:
        arr, _ = qback.popleft()
        for narr in moves(arr):
            if narr in sfront:
                print(sfront[narr] + dback + 1)
                cont = False
                break
            if narr in sback:
                continue
            sback[narr] = dback + 1
            qback.append((narr, dback + 1))
        if not cont:
            break
    dback += 1


# Author: Trevor Sherrard
# Since: Feb. 21, 2022
# Purpose: This file contains functionallity needed to run inference on a single image

import cv2
import numpy as np
import tensorflow as tf
import keras

# declare file paths
model_file_loc = "../../models/saved_unet_model.h5"
test_image_loc = "../../dataset/semantic_drone_dataset/original_images/000.jpg"

# declare goal image sizes
img_height = 800
img_width = 1200

def preprocess_image(img_file):
    def func(img_file):
        img_file = img_file.decode()
        img = cv2.imread(img_file, cv2.IMREAD_COLOR)
        img = cv2.resize(img, (img_width, img_height))
        img = img / 255.0
        img = img.astype(np.float32)
        return img

    image = tf.convert_to_tensor(tf.numpy_function(func, [img_file], [tf.float32]))
    image = tf.reshape(image, (img_height, img_width, 3))
    return image

def load_image_as_dataset(img_file):
    dataset = tf.data.Dataset.from_tensor_slices(img_file)
    dataset = dataset.map(preprocess_image)
    dataset = dataset.batch(1)
    return dataset

def run_inference(image_loc):
    # load image
    dataset = load_image_as_dataset([image_loc])

    # load model
    model = keras.models.load_model(model_file_loc)

    # run inference
    pred = model.predict(dataset)

    # extract results
    predictions = np.argmax(pred, axis=3)
    single_channel_pred = predictions[0]
    single_channel_pred = single_channel_pred.astype("uint8")

    # show mono mask image
    cv2.imshow("test", single_channel_pred)
    cv2.waitKey(0)

if(__name__ == "__main__"):
    run_inference(test_image_loc)


import cupy
import cupyx.scipy.fft

from cupy import _core
from cupy._core import _routines_math as _math
from cupy._core import fusion
from cupy.lib import stride_tricks

import numpy

_dot_kernel = _core.ReductionKernel(
    'T x1, T x2',
    'T y',
    'x1 * x2',
    'a + b',
    'y = a',
    '0',
    'dot_product'
)

def _choose_conv_method(in1, in2, mode):
    if in1.ndim != 1 or in2.ndim != 1:
        raise NotImplementedError('Only 1d inputs are supported currently')

    if in1.dtype.kind in 'bui' or in2.dtype.kind in 'bui':
        return 'direct'

    if _fftconv_faster(in1, in2, mode):
        return 'fft'

    return 'direct'

def _fftconv_faster(x, h, mode):
    """
    .. seealso:: :func: `scipy.signal._signaltools._fftconv_faster`

    """
    # TODO(Dahlia-Chehata): replace with GPU-based constants.
    return True

def convolve(a, v, mode='full'):
    """Returns the discrete, linear convolution of two one-dimensional sequences.

    Args:
        a (cupy.ndarray): first 1-dimensional input.
        v (cupy.ndarray): second 1-dimensional input.
        mode (str, optional): `valid`, `same`, `full`

    Returns:
        cupy.ndarray: Discrete, linear convolution of a and v.

    .. seealso:: :func:`numpy.convolve`

    """  # NOQA
    if a.size == 0:
        raise ValueError('a cannot be empty')
    if v.size == 0:
        raise ValueError('v cannot be empty')
    if v.ndim > 1:
        raise ValueError('v cannot be multidimensional array')
    if v.size > a.size:
        a, v = v, a
    a = a.ravel()
    v = v.ravel()

    method = _choose_conv_method(a, v, mode)
    if method == 'direct':
        out = _dot_convolve(a, v, mode)
    elif method == 'fft':
        out = _fft_convolve(a, v, mode)
    else:
        raise ValueError('Unsupported method')
    return out

def _fft_convolve(a1, a2, mode):

    offset = 0
    if a1.shape[-1] < a2.shape[-1]:
        a1, a2 = a2, a1
        offset = 1 - a2.shape[-1] % 2

    # if either of them is complex, the dtype after multiplication will also be
    if a1.dtype.kind == 'c' or a2.dtype.kind == 'c':
        fft, ifft = cupy.fft.fft, cupy.fft.ifft
    else:
        fft, ifft = cupy.fft.rfft, cupy.fft.irfft

    dtype = cupy.result_type(a1, a2)
    n1, n2 = a1.shape[-1], a2.shape[-1]
    out_size = cupyx.scipy.fft.next_fast_len(n1 + n2 - 1)
    fa1 = fft(a1, out_size)
    fa2 = fft(a2, out_size)
    out = ifft(fa1 * fa2, out_size)

    if mode == 'full':
        start, end = 0, n1 + n2 - 1
    elif mode == 'same':
        start = (n2 - 1) // 2 + offset
        end = start + n1
    elif mode == 'valid':
        start, end = n2 - 1, n1
    else:
        raise ValueError(
            'acceptable mode flags are `valid`, `same`, or `full`.')

    out = out[..., start:end]

    if dtype.kind in 'iu':
        out = cupy.around(out)

    return out.astype(dtype, copy=False)

def _dot_convolve(a1, a2, mode):

    offset = 0
    if a1.size < a2.size:
        a1, a2 = a2, a1
        offset = 1 - a2.size % 2

    dtype = cupy.result_type(a1, a2)
    n1, n2 = a1.size, a2.size
    a1 = a1.astype(dtype, copy=False)
    a2 = a2.astype(dtype, copy=False)

    if mode == 'full':
        out_size = n1 + n2 - 1
        a1 = cupy.pad(a1, n2 - 1)
    elif mode == 'same':
        out_size = n1
        pad_size = (n2 - 1) // 2 + offset
        a1 = cupy.pad(a1, (n2 - 1 - pad_size, pad_size))
    elif mode == 'valid':
        out_size = n1 - n2 + 1

    stride = a1.strides[0]
    a1 = stride_tricks.as_strided(a1, (out_size, n2), (stride, stride))
    output = _dot_kernel(a1, a2[::-1], axis=1)
    return output

def clip(a, a_min, a_max, out=None):
    """Clips the values of an array to a given interval.

    This is equivalent to ``maximum(minimum(a, a_max), a_min)``, while this
    function is more efficient.

    Args:
        a (cupy.ndarray): The source array.
        a_min (scalar, cupy.ndarray or None): The left side of the interval.
            When it is ``None``, it is ignored.
        a_max (scalar, cupy.ndarray or None): The right side of the interval.
            When it is ``None``, it is ignored.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: Clipped array.

    .. seealso:: :func:`numpy.clip`

    Notes
    -----
    When `a_min` is greater than `a_max`, `clip` returns an
    array in which all values are equal to `a_max`.
    """
    if fusion._is_fusing():
        return fusion._call_ufunc(_math.clip,
                                  a, a_min, a_max, out=out)

    # TODO(okuta): check type
    return a.clip(a_min, a_max, out=out)

# sqrt_fixed is deprecated.
# numpy.sqrt is fixed in numpy 1.11.2.
sqrt = sqrt_fixed = _core.sqrt

cbrt = _core.create_ufunc(
    'cupy_cbrt',
    ('e->e', 'f->f', 'd->d'),
    'out0 = cbrt(in0)',
    doc='''Elementwise cube root function.

    .. seealso:: :data:`numpy.cbrt`

    ''')

square = _core.create_ufunc(
    'cupy_square',
    ('b->b', 'B->B', 'h->h', 'H->H', 'i->i', 'I->I', 'l->l', 'L->L', 'q->q',
     'Q->Q', 'e->e', 'f->f', 'd->d', 'F->F', 'D->D'),
    'out0 = in0 * in0',
    doc='''Elementwise square function.

    .. seealso:: :data:`numpy.square`

    ''')

absolute = _core.absolute

fabs = _core.create_ufunc(
    'cupy_fabs',
    ('e->e', 'f->f', 'd->d'),
    'out0 = abs(in0)',
    doc='''Calculates absolute values element-wise.
    Only real values are handled.

    .. seealso:: :data:`numpy.fabs`

    ''')

_unsigned_sign = 'out0 = in0 > 0'
_complex_sign = '''
if (in0.real() == 0) {
  out0 = (in0.imag() > 0) - (in0.imag() < 0);
} else {
  out0 = (in0.real() > 0) - (in0.real() < 0);
}
'''
sign = _core.create_ufunc(
    'cupy_sign',
    ('b->b', ('B->B', _unsigned_sign), 'h->h', ('H->H', _unsigned_sign),
     'i->i', ('I->I', _unsigned_sign), 'l->l', ('L->L', _unsigned_sign),
     'q->q', ('Q->Q', _unsigned_sign), 'e->e', 'f->f', 'd->d',
     ('F->F', _complex_sign), ('D->D', _complex_sign)),
    'out0 = (in0 > 0) - (in0 < 0)',
    doc='''Elementwise sign function.

    It returns -1, 0, or 1 depending on the sign of the input.

    .. seealso:: :data:`numpy.sign`

    ''')

heaviside = _core.create_ufunc(
    'cupy_heaviside',
    ('ee->e', 'ff->f', 'dd->d'),
    '''
    if (isnan(in0)) {
        out0 = in0;
    } else if (in0 == 0) {
        out0 = in1;
    } else {
        out0 = (in0 > 0);
    }
    ''',
    doc='''Compute the Heaviside step function.

    .. seealso:: :data:`numpy.heaviside`

    '''
)

_float_preamble = '''
#ifndef NAN
#define NAN __int_as_float(0x7fffffff)
#endif
'''
_float_maximum = ('out0 = (isnan(in0) | isnan(in1)) ? out0_type(NAN) : '
                  'out0_type(max(in0, in1))')
maximum = _core.create_ufunc(
    'cupy_maximum',
    ('??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
     'LL->L', 'qq->q', 'QQ->Q',
     ('ee->e', _float_maximum),
     ('ff->f', _float_maximum),
     ('dd->d', _float_maximum),
     ('FF->F', _float_maximum),
     ('DD->D', _float_maximum)),
    'out0 = max(in0, in1)',
    preamble=_float_preamble,
    doc='''Takes the maximum of two arrays elementwise.

    If NaN appears, it returns the NaN.

    .. seealso:: :data:`numpy.maximum`

    ''',
    cutensor_op=('OP_MAX', 1, 1), scatter_op='max')

_float_minimum = ('out0 = (isnan(in0) | isnan(in1)) ? out0_type(NAN) : '
                  'out0_type(min(in0, in1))')
minimum = _core.create_ufunc(
    'cupy_minimum',
    ('??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
     'LL->L', 'qq->q', 'QQ->Q',
     ('ee->e', _float_minimum),
     ('ff->f', _float_minimum),
     ('dd->d', _float_minimum),
     ('FF->F', _float_minimum),
     ('DD->D', _float_minimum)),
    'out0 = min(in0, in1)',
    preamble=_float_preamble,
    doc='''Takes the minimum of two arrays elementwise.

    If NaN appears, it returns the NaN.

    .. seealso:: :data:`numpy.minimum`

    ''',
    cutensor_op=('OP_MIN', 1, 1), scatter_op='min')

fmax = _core.create_ufunc(
    'cupy_fmax',
    ('??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
     'LL->L', 'qq->q', 'QQ->Q',
     ('ee->e', 'out0 = fmax(in0, in1)'),
     ('ff->f', 'out0 = fmax(in0, in1)'),
     ('dd->d', 'out0 = fmax(in0, in1)'),
     'FF->F', 'DD->D'),
    'out0 = max(in0, in1)',
    doc='''Takes the maximum of two arrays elementwise.

    If NaN appears, it returns the other operand.

    .. seealso:: :data:`numpy.fmax`

    ''')

fmin = _core.create_ufunc(
    'cupy_fmin',
    ('??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
     'LL->L', 'qq->q', 'QQ->Q',
     ('ee->e', 'out0 = fmin(in0, in1)'),
     ('ff->f', 'out0 = fmin(in0, in1)'),
     ('dd->d', 'out0 = fmin(in0, in1)'),
     'FF->F', 'DD->D'),
    'out0 = min(in0, in1)',
    doc='''Takes the minimum of two arrays elementwise.

    If NaN appears, it returns the other operand.

    .. seealso:: :data:`numpy.fmin`

    ''')

_nan_to_num_preamble = '''
template <class T>
__device__ T nan_to_num(T x, T nan, T posinf, T neginf) {
    if (isnan(x))
        return nan;
    if (isinf(x))
        return x > 0 ? posinf : neginf;
    return x;
}

template <class T>
__device__ complex<T> nan_to_num(complex<T> x, T nan, T posinf, T neginf) {
    T re = nan_to_num(x.real(), nan, posinf, neginf);
    T im = nan_to_num(x.imag(), nan, posinf, neginf);
    return complex<T>(re, im);
}
'''

_nan_to_num = _core.create_ufunc(
    'cupy_nan_to_num_',
    ('????->?', 'bbbb->b', 'BBBB->B', 'hhhh->h', 'HHHH->H',
     'iiii->i', 'IIII->I', 'llll->l', 'LLLL->L', 'qqqq->q', 'QQQQ->Q',
     ('eeee->e',
      'out0 = nan_to_num(in0, in1, in2, in3)'),
     ('ffff->f',
      'out0 = nan_to_num(in0, in1, in2, in3)'),
     ('dddd->d',
      'out0 = nan_to_num(in0, in1, in2, in3)'),
     ('Ffff->F',
      'out0 = nan_to_num(in0, in1, in2, in3)'),
     ('Dddd->D',
      'out0 = nan_to_num(in0, in1, in2, in3)')),
    'out0 = in0',
    preamble=_nan_to_num_preamble,
    doc='''Elementwise nan_to_num function.

    .. seealso:: :func:`numpy.nan_to_num`

    ''')

def _check_nan_inf(x, dtype, neg=None):
    if dtype.char in 'FD':
        dtype = cupy.dtype(dtype.char.lower())
    if dtype.char not in 'efd':
        x = 0
    elif x is None and neg is not None:
        x = cupy.finfo(dtype).min if neg else cupy.finfo(dtype).max
    elif cupy.isnan(x):
        x = cupy.nan
    elif cupy.isinf(x):
        x = cupy.inf * (-1)**(x < 0)
    return cupy.asanyarray(x, dtype)

def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None):
    """Replace NaN with zero and infinity with large finite numbers (default
    behaviour) or with the numbers defined by the user using the `nan`,
    `posinf` and/or `neginf` keywords.

    .. seealso:: :func:`numpy.nan_to_num`

    """
    if not isinstance(x, cupy.ndarray):
        out = cupy.full((), x)
    else:
        out = cupy.empty_like(x) if copy else x
    dtype = out.dtype
    nan = _check_nan_inf(nan, dtype)
    posinf = _check_nan_inf(posinf, dtype, False)
    neginf = _check_nan_inf(neginf, dtype, True)
    return _nan_to_num(x, nan, posinf, neginf, out=out)

def real_if_close(a, tol=100):
    """If input is complex with all imaginary parts close to zero, return real
    parts.
    "Close to zero" is defined as `tol` * (machine epsilon of the type for
    `a`).

    .. warning::

            This function may synchronize the device.

    .. seealso:: :func:`numpy.real_if_close`
    """
    if not issubclass(a.dtype.type, cupy.complexfloating):
        return a
    if tol > 1:
        f = numpy.finfo(a.dtype.type)
        tol = f.eps * tol
    if cupy.all(cupy.absolute(a.imag) < tol):
        a = a.real
    return a

@cupy._util.memoize(for_each_device=True)
def _get_interp_kernel(is_complex):
    in_params = 'raw V x, raw U idx, '
    in_params += 'raw W fx, raw Y fy, U len, raw Y left, raw Y right'
    out_params = 'Z y'  # output dtype follows NumPy's

    if is_complex:
        preamble = 'typedef double real_t;\n'
    else:
        preamble = 'typedef Z real_t;\n'
    preamble += 'typedef Z value_t;\n'
    preamble += cupy._sorting.search._preamble  # for _isnan

    code = r'''
        U x_idx = idx[i] - 1;

        if ( _isnan<V>(x[i]) ) { y = x[i]; }
        else if (x_idx < 0) { y = left[0]; }
        else if (x[i] == fx[len - 1]) {
            // searchsorted cannot handle both of the boundary points,
            // so we must detect and correct ourselves...
            y = fy[len - 1];
        }
        else if (x_idx >= len - 1) { y = right[0]; }
        else {
            const Z slope = (value_t)(fy[x_idx+1] - fy[x_idx]) / \
                            ((real_t)fx[x_idx+1] - (real_t)fx[x_idx]);
            Z out = slope * ((real_t)x[i] - (real_t)fx[x_idx]) \
                    + (value_t)fy[x_idx];
            if (_isnan<Z>(out)) {
                out = slope * ((real_t)x[i] - (real_t)fx[x_idx+1]) \
                      + (value_t)fy[x_idx+1];
                if (_isnan<Z>(out) && (fy[x_idx] == fy[x_idx+1])) {
                    out = fy[x_idx];
                }
            }
            y = out;
        }
    '''
    return cupy.ElementwiseKernel(
        in_params, out_params, code, 'cupy_interp', preamble=preamble)

def interp(x, xp, fp, left=None, right=None, period=None):
    """ One-dimensional linear interpolation.

    Args:
        x (cupy.ndarray): a 1D array of points on which the interpolation
            is performed.
        xp (cupy.ndarray): a 1D array of points on which the function values
            (``fp``) are known.
        fp (cupy.ndarray): a 1D array containing the function values at the
            the points ``xp``.
        left (float or complex): value to return if ``x < xp[0]``. Default is
            ``fp[0]``.
        right (float or complex): value to return if ``x > xp[-1]``. Default is
            ``fp[-1]``.
        period (None or float): a period for the x-coordinates. Parameters
            ``left`` and ``right`` are ignored if ``period`` is specified.
            Default is ``None``.

    Returns:
        cupy.ndarray: The interpolated values, same shape as ``x``.

    .. note::
        This function may synchronize if ``left`` or ``right`` is not already
        on the device.

    .. seealso:: :func:`numpy.interp`

    """

    if xp.ndim != 1 or fp.ndim != 1:
        raise ValueError('xp and fp must be 1D arrays')
    if xp.size != fp.size:
        raise ValueError('fp and xp are not of the same length')
    if xp.size == 0:
        raise ValueError('array of sample points is empty')
    if not x.flags.c_contiguous:
        raise NotImplementedError('Non-C-contiguous x is currently not '
                                  'supported')
    x_dtype = cupy.common_type(x, xp)
    if not cupy.can_cast(x_dtype, cupy.float64):
        raise TypeError('Cannot cast array data from'
                        ' {} to {} according to the rule \'safe\''
                        .format(x_dtype, cupy.float64))

    if period is not None:
        # The handling of "period" below is modified from NumPy's

        if period == 0:
            raise ValueError("period must be a non-zero value")
        period = abs(period)
        left = None
        right = None

        x = x.astype(cupy.float64)
        xp = xp.astype(cupy.float64)

        # normalizing periodic boundaries
        x %= period
        xp %= period
        asort_xp = cupy.argsort(xp)
        xp = xp[asort_xp]
        fp = fp[asort_xp]
        xp = cupy.concatenate((xp[-1:]-period, xp, xp[0:1]+period))
        fp = cupy.concatenate((fp[-1:], fp, fp[0:1]))
        assert xp.flags.c_contiguous
        assert fp.flags.c_contiguous

    # NumPy always returns float64 or complex128, so we upcast all values
    # on the fly in the kernel
    out_dtype = 'D' if fp.dtype.kind == 'c' else 'd'
    output = cupy.empty(x.shape, dtype=out_dtype)
    idx = cupy.searchsorted(xp, x, side='right')
    left = fp[0] if left is None else cupy.array(left, fp.dtype)
    right = fp[-1] if right is None else cupy.array(right, fp.dtype)
    kern = _get_interp_kernel(out_dtype == 'D')
    kern(x, idx, xp, fp, xp.size, left, right, output)
    return output


import cryptoFunc

choice = input('Please type 1 for encrypt or 2 for decrypt: ')
file = input('Please give me a file name: ')

if choice == '1':
    cryptoFunc.encrypt_file(file)
elif choice == '2':
    cryptoFunc.decrypt_file(file)

print('Successfull')


# 곱하기 혹은 더하기 / p312

input = input()

result = 0
for i in input:
    if i == '0':
        continue
    if i == '1':
        result += 1
        continue
    if result == 0:
        result += int(i)
    else:
        result *= int(i)

print(result)


#Clases y funciones
#classes = []
#for i in range(10):
#    class Dummy:
#        def init(self, _name):
#            self._name = 'Dummy {}'.format(i)
#
#    classes.append(Dummy)

#for item in classes:
#    dummy = item()
#    print(dummy.name)

#print("Hello World")

class Student:

    university = 'Espe'
    class Meta:
        name = 'MetaClass'

    def __init__(self, _id, _name, _age, _carrer, _cell_number):
        self.id = _id
        self.name = _name
        self.age = _age
        self.carrer = _carrer

        class Phone:
            def __init__(self, _number):
                self.number = _number

            def __repr__(self):
                return 'Phone({})'.format(self.number)

        self.phone = Phone(_cell_number)

    def __repr__(self):
        return 'Student ({}, {}, {}, {}, {})'.format(self.id, self.name, self.age, self.carrer, self.phone)

    def say_name(self):
        print('My name is {}'.format(self.name))

student = Student(1, 'Diego', 18, 'Ing Software','0994651465')
student1 = Student(2, 'Edison', 19, 'Ing Software','0990316348')
student.say_name()
student1.say_name()

print(student)
print(student1)

print(Student.Meta.name)

Workshop/First partial/Workshop05/classes and functions.py


import numpy as np
from PIL import Image

rainbow = np.zeros((521,512,3),'uint8')

for i in range(0,256):
    rainbow[:,i,0] = 255-i
    rainbow[:,i,1] = 0+i
for i in range(256,512):
    rainbow[:,i,1] = 255-i
    rainbow[:,i,2] = 0+i

image = Image.fromarray(rainbow)
image.save('rainbow.jpg')


import pandas as pd
import numpy as np
import os, sys
import warnings
import matplotlib.pyplot as plt
import gmplot
from sklearn.cluster import DBSCAN
import random
import json

def remove_invalid_coord(df): #[-90; 90]
	#return df.query('lat >= -90 & lat <= 90').query('lon >= -90 & lat <= 90')
	return df.query('lat != 0 & lon != 0')

def read_data(day='monday', city='chicago', types='crimes'):

	data_file = open('data/{0}/{1}_2018_{2}.csv'.format(day, types, city), 'r')

	crime_list = []

	for line in data_file:
		line = line.strip().split(',')

		item = {}
		item['datetime'] = pd.to_datetime(str(line[0]), format='%Y/%m/%d %H:%M')
		item['month'] = pd.to_datetime(str(line[0]), format='%Y/%m/%d %H:%M').month
		item['hour'] = pd.to_datetime(str(line[0]), format='%Y/%m/%d %H:%M').hour
		item['lat'] = float(line[1])
		item['lon'] = float(line[2])
		item['type'] = line[3].strip()
		item['export'] = 0

		crime_list.append(item)

	df = pd.DataFrame(crime_list)
	df.set_index('datetime', inplace=True)

	return remove_invalid_coord(df)

def read_all_data(city='chicago', types='crimes'):

	df = []

	for day in ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']:

		if len(df) == 0:
			df = read_data(day, city=city, types=types)
		else:
			df = pd.concat([df, read_data(day, city=city, types=types)])

	return df

def see_density():
	# Le os dados
	df = read_all_data()
	#print(df.head())

	df_month_type = df.groupby(['month', 'type']).count()

	#print(min(df_month_type['export']))
	#print(max(df_month_type['export']))

	crimes = df.groupby('type').all().index

	# for c in crimes:

		# df_crime = df.query("type == '%s'" % c)

		# filtered = df_crime.groupby(['month']).count()

		# plt.figure()

		# months = ['', 'Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.',
		# 			'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.']

		# filtered['export'].plot(legend=None, title=c, style='.:')

		# plt.xlabel('Months')
		# plt.ylabel('Quantity of Crimes')
		# plt.xticks(range(13), months, rotation=50)
		# plt.yticks(range(0, 7000, 500), [x for x in range(0, 7000, 500)])

		# if not os.path.exists('density'):
		# 	os.makedirs('density')

		# plt.savefig('density/'+ c + '.pdf', bbox_inches="tight", format='pdf')

		# plt.clf()

	# Export
	df.groupby(['month', 'type']).count()['export'].to_csv('density_austin.csv')

###############################################################################################################

###############################################################################################################

###############################################################################################################

def colors(n):
	ret = []
	for i in range(n):
		r = int(random.random() * 256)
		g = int(random.random() * 256)
		b = int(random.random() * 256)
		r = int(r) % 256
		g = int(g) % 256
		b = int(b) % 256
		ret.append('#{:02X}{:02X}{:02X}'.format(r,g,b))
	return ret

def plot_heat(clusters, day, city, types):

	plt.clf()
	gmap = gmplot.GoogleMapPlotter(clusters.iloc[0]['lat'], clusters.iloc[0]['lon'], 11)

	lats, longs = [], []

	for indx, cluster in clusters.iterrows():
		lats.append(float(cluster['lat']))
		longs.append(float(cluster['lon']))

	gmap.heatmap(lats, longs)

	if not os.path.exists('plottest'):
		os.makedirs('plottest')
	gmap.draw('plottest/{0}_{1}_{2}.html'.format(city, types, day))

def see_distribution():

	city='chicago'
	types='crimes'

	# for day in ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']:
	# 	df = read_data(day, city, types)
	# 	df = df.drop(['type', 'hour', 'month', 'export'], axis=1)
	# 	clustering = DBSCAN(eps=0.001, min_samples=3).fit_predict(df)
	# 	df['cluster'] = clustering
	# 	plot_heat(df.query('cluster != -1'), day, city, types)

	df = read_all_data(city, types)

	df = df.drop(['type', 'hour', 'month', 'export'], axis=1)
	clustering = DBSCAN(eps=0.001, min_samples=3).fit_predict(df)
	df['cluster'] = clustering
	plot_heat(df.query('cluster != -1'), 'all', city, types)

###############################################################################################################

###############################################################################################################

###############################################################################################################

def format_clusters(data):

	clusters = []
	clusters.append([])
	lastid = 0

	data = data.query('cluster > -1')

	for indx, row in data.iterrows():
		if row['cluster'] > lastid:
			clusters.append([])
			lastid = row['cluster']
		clusters[-1].append((row['lat'], row['lon']))

	return clusters

def get_coords(cluster):

	lat, lon = [], []
	for i in cluster:
		lat.append(i[0])
		lon.append(i[1])
	return lat, lon

def plot_dots(clusters, day, city, types, each):

	plt.clf()
	if len(clusters) > 0 and len(clusters[0]) > 0:
		gmap = gmplot.GoogleMapPlotter(float(clusters[0][0][0]), float(clusters[0][0][1]), 11)

		color_list = colors(len(clusters))
		indx = 0
		for cluster in clusters:

			lat, lon = get_coords(cluster)
			gmap.scatter(lat, lon, color_list[indx], edge_width=5, marker=False)
			indx += 1
			#break

		if not os.path.exists('plottest'):
			os.makedirs('plottest')
		gmap.draw('plottest/{0}_{1}_{2}_{3}_dots.html'.format(city, types, day, each))

def load_clusters(day):
		with open(str(os.path.dirname(os.path.abspath(__file__)))+"/clusters/" + str(day) + '.json', "r") as file:
			return json.load(file)

def see_maps():

	city='austin'
	types='crashes'
	day='monday'

	clusters = load_clusters(day)['{0}_2018_{1}'.format(types, city)]['January']['unkown']

	for each in clusters:
		plot_dots(clusters[each], day, city, types, each)

see_distribution()
#see_maps()


# This is just a sample program to show you how to do
# basic image operations using python and the Pillow library.
#
# By Eriya Terada, based on earlier code by Stefan Lee,
#    lightly modified by David Crandall, 2020

# Import the Image and ImageFilter classes from PIL (Pillow)

from PIL import Image, ImageFilter, ImageDraw, ImageFont
import random
import numpy as np
import sys

# Step 3 Convert image to gray scale
def grayscale_pad(image, padding_size):
    im = Image.open(image).convert("L")
    im_width = im.width
    im_height = im.height
    new_width = (2 * padding_size) + im_width
    new_height = (2 * padding_size) + im_height

    # Create a new blank grayscale image with padding
    gray_im = Image.new("L", (new_width, new_height), color=255)

    # Loop over the new image with padding
    for x in range(new_width):
        for y in range(new_height):
            # fill in areas that are not padding
            if x > padding_size and x < new_width - padding_size:
                if y > padding_size and y < new_height - padding_size:
                    # convert the original image to grayscale
                    l_value = im.getpixel((x - padding_size, y - padding_size))
                    gray_im.putpixel((x, y), l_value)

    # Save the image
    gray_im.save("gray.png")
    return gray_im

# Step 4 Convolution with separable kernel
def convolve(image, hx, hy):

    im_width = image.width
    im_height = image.height
    hx_len = len(hx)
    hy_len = len(hy)
    image=np.array(image).astype(np.uint8)

    new_image = np.zeros(image.shape)
    vertimage = np.zeros(image.shape)

    # convolve vertically
    for x in range(im_height-hy_len+1):
        for y in range(im_width):
            row_sum=0
            col_sum=0
            for v in range(hy_len):
                row_sum+=image[x+v][y]*hy[v]
            vertimage[x][y]=row_sum

    # convolve horizontally
    img = Image.fromarray(np.uint8(vertimage * 255))
    for x in range(im_height):
        for y in range(im_width-hx_len+1):
            row_sum=0
            col_sum=0
            for h in range(hx_len):
                col_sum+=vertimage[x][y+h]*hx[h]
            new_image[x][y]=col_sum

    img = Image.fromarray(np.uint8(new_image * 255))
#    img.show()
    return img

# Canny edge detection
def sobel_edge_detection(gray_img):

    gray_img=np.array(gray_img).astype(np.uint8)
    # Sobels filter
    v = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    h = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

    print(gray_img.shape)

    im_height, im_width = gray_img.shape

    new_image_h = np.zeros(gray_img.shape)
    new_image_v = np.zeros(gray_img.shape)
    new_image = np.zeros(gray_img.shape)

    for i in range(0, im_height-3+1):
        for j in range(0, im_width-3+1):
            horizontalGrad=0
            verticalGrad=0
            for x in range(h.shape[0]):
                for y in range(h.shape[1]):
                    horizontalGrad+=h[x][y]*gray_img[i+x,j+y]

            new_image_h[i, j] = abs(horizontalGrad)

            for x in range(v.shape[0]):
                for y in range(v.shape[1]):
                    verticalGrad+=v[x][y]*gray_img[i+x,j+y]

            new_image_v[i, j] = abs(verticalGrad)

            # Edge Magnitude
            edge_mag = np.sqrt(pow(horizontalGrad, 2.0) + pow(verticalGrad, 2.0))
            new_image[i, j] = edge_mag

    img = Image.fromarray(np.uint8(new_image * 255))
    img.show()

    # Create binary edge map
    new_image[new_image!= 0.0]=1
    new_image[new_image== 0.0]=0
    print(new_image.shape)
    return new_image

def get_region_colors(im, t_height, t_width, coordinate):
    # coordinate is the x,y value of where the region starts in the image
    # region_colors is the same size as the template
    region_colors = []
    for i in range(coordinate[0], coordinate[0]+t_height):
        row = []
        for j in range(coordinate[1], coordinate[1]+t_width):
            row.append(im.getpixel((j, i)))
        region_colors.append(row)
    return region_colors

def compareImages(region, template):
    # takes 2 matrices with the color values
    # region and template are the same size
    t_height = len(template)
    t_width = len(template[0])
    total_score = 0

    for i in range(t_height):
        for j in range(t_width):
            region_pixel = region[i][j]
            t_pixel = template[i][j]
            # changed similarity function to use 255 instead of 1 since grayscale values are from 0-255
            pixel_similarity = (region_pixel * t_pixel) + (255-region_pixel) * (255-t_pixel)
            total_score += pixel_similarity
    return total_score

'''
Function to calculate hamming distance i.e. step 5 in the assignment
'''
def hammingDist(im, t_im, combine, color, text_file_list, symbol_type, p, dist):
    im_width = im.width
    im_height = im.height
    t_width = t_im.width
    t_height = t_im.height

    # get the template and it's score to compare with image regions later on
    t_region = get_region_colors(t_im, t_height, t_width, (0,0))
    perfect_score = compareImages(t_region, t_region)

    #t_found = Image.new("L", (im_width, im_height), color=255)

    combine = combine.copy().convert("RGB")
    d = {}
    # loop through the image
    for i in range(im_height-t_height):
        for j in range(im_width-t_width):
            # get image region
            im_region = get_region_colors(im, t_height, t_width, (i, j))
            # score the region
            region_score = compareImages(im_region, t_region)
            # compare the image region score to the template score
            if region_score >= (0.87 * perfect_score):
                max_val = region_score
                it_val = (i,j)
                for y in range(3):
                    for z in range(3):
                        if (i-y,j-z) in d:
                            if d[(i-y,j-z)] >= region_score:
                                max_val = region_score
                                it_val = (i-y,j-z)
                            else:
                                del d[(i-y,j-z)]
                        elif (i-y,j+z) in d:
                            if d[(i-y,j+z)] >= region_score:
                                max_val = region_score
                                it_val = (i-y,j+z)
                            else:
                                del d[(i-y,j+z)]
                d[it_val] = max_val

    for k,v in d.items():
        i,j = k
        region_score = v
        draw = ImageDraw.Draw(combine)
        top_left = (j,i)
        bottom_right = (j + t_width, i + t_height)
        #draw.rectangle(((100, 100), (200, 200)), (0, 255, 0))
        draw.rectangle((top_left, bottom_right), fill=None, outline = color,width=2)
        pitch = '_'

        if symbol_type == 'filled_note':
            for q in range(int(dist/2)):
                if q+i in p:
                    pitch = p[q+i]
                elif i-q in p:
                    pitch = p[i-q]

            font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuLGCSansMono.ttf")
            # font = ImageFont.truetype("/usr/share/fonts/msttcorefonts/arial.ttf")  load_default()
            draw.text((j-10, i-2),pitch,(255,0,0),font=font)

        text_file_list.append([j, i, t_height, t_width, symbol_type, pitch, float(round((region_score/perfect_score*100), 2))])
#    combine.save("step5.png")
    return combine, text_file_list

# Step 6: Template matching using convolution
def template_matching(image, template):
    m=template.shape[0]
    n=template.shape[1]

    F=np.zeros((image.shape))
    D=np.zeros((image.shape))

#    X=np.array(image)
#
#    X[X==0]=np.inf
#    X[X==1]=0

    # Find the coordinates of edges
    v,w=np.where(image!=0)
    loc=np.stack((v,w),axis=1)

    # Find coordinates of whole image
    v1,w1=np.where(image==0)
    loc1=np.stack((v1,w1),axis=1)
    loc2=np.vstack((loc,loc1))

    # Calculate D matrix which stores the distance of each pixel from its nearest edge pixel
    temp=np.zeros(loc.shape[0])
    for i in range(loc2.shape[0]):
        temp=np.sqrt((loc2[i][0]-loc[:,0])**2+(loc2[i][1]-loc[:,1])**2)
        D[loc2[i][0],loc2[i][1]]=np.min(temp)

    img = Image.open(im_name)
    draw = ImageDraw.Draw(img)

    sum=0
    for k in range(0,m):
        for l in range(0,n):
            sum+=(template[k][l])*(template[k][l])
    score=sum

    max_D=np.max(D)

    # Calculate template scoring
    for i in range(0,image.shape[0]-m+1):
        for j in range(0,image.shape[1]-n+1):
            sum=0
            for k in range(0,m):
                for l in range(0,n):
                    sum+=((template[k][l])*((max_D-D[i+k][j+l])/max_D))
            F[i][j]=sum
            if sum>=0.95*score:
                draw.rectangle(((j,i), (j+n,i+m)), fill=None,outline="red")

    img.save("output-6.png")

def hough_line(edge):
    thetas = np.arange(0, 180, 1)
    cos = np.cos(np.deg2rad(theta))
    sin = np.sin(np.deg2rad(theta))

    rho_range = round(math.sqrt(edge.shape[0]*2 + edge.shape[1]*2))
    accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8)

    edge_pixels = np.where(edge == 1)
    coordinates = list(zip(edge_pixels[0], edge_pixels[1]))

    for p in range(len(coordinates)):
        for theta in range(len(theta)):
            rho = int(round(coordinates[p][1] * cos[theta] + coordinates[p][0] * sin[theta]))
            accumulator[rho, t] += 1
    #print(np.max(accumulator))
    return accumulator

def hough(image):

#    im = image.load()
#    im_h, im_w = image.size
#    th_val, r_val = 500, 1200
#    hough_im = Image.new("L", (th_val, r_val), 255)
#    him = hough_im.load()
#    rho = {}
#    rmax = hypot(im_h, im_w)
#    dr = rmax / int(r_val/2)
#    dth = pi / th_val
#    for x in range(im_h):
#        for y in range(im_w):
#            if im[x, y] != 255:
#                for m in range(th_val):
#                    th = dth * m
#                    r = x*cos(th) + y*sin(th)
#                    n = int(r_val/2) + int(r/dr+0.5)
#                    him[m, n] -= 1

    dist = 0
    img = image.convert('L')  #conversion to gray scale
    bw = img.point(lambda x: 0 if x<128 else 255, '1')
    img_bin = np.array(bw).astype(np.uint8)
    x, y = img_bin.shape
    d = {}
    for i in range(0,x):
        d[i] = 0
        for j in range(y):
            if img_bin[i][j]==0:
                d[i] +=1
    l = [k for k,v in d.items() if v > y/2]
    for i in range(0,len(l)-1):
        if l[i]+1 != l[i+1]:
            if dist == 0:
                dist = l[i+1]-l[i]
            elif dist == l[i+1]-l[i]:
                break

    lines = [l[0]]
    p = l[0]
    for i in range(1,len(l)):
        if l[i] - p > dist*2:
            lines.append(l[i])
        p = l[i]

    return dist, lines

def rescale(template,dist):
    temp = Image.open(template).convert("L")
    factor = dist/temp.height
    temp = temp.resize((int(temp.width * factor), int(temp.height * factor)))
    return temp

def pitch(lines,dist):
    p = {}
    j = 1
    for i in lines:
        if j%2 ==0:
            p[i-dist*1.5] = 'D'
            p[i-dist] = 'C'
            p[i-dist*0.5] = 'B'
            p[i] = 'A'
            p[i+dist*0.5] = 'G'
            p[i+dist] = 'F'
            p[i+dist*1.5] = 'E'
            p[i+dist*2] = 'D'
            p[i+dist*2.5] = 'C'
            p[i+dist*3] = 'B'
            p[i+dist*3.5] = 'G'
            p[i+dist*4] = 'F'
            p[i+dist*4.5] = 'E'
        else:
            p[i-dist*0.5] = 'G'
            p[i] = 'F'
            p[i+dist*0.5] = 'E'
            p[i+dist] = 'D'
            p[i+dist*1.5] = 'C'
            p[i+dist*2] = 'B'
            p[i+dist*2.5] = 'A'
            p[i+dist*3] = 'G'
            p[i+dist*3.5] = 'F'
            p[i+dist*4] = 'E'
            p[i+dist*4.5] = 'D'
            p[i+dist*5] = 'B'
        j += 1
    return p

if __name__ == '__main__':
    music_file = sys.argv[1]
    im_name = "../test-images/" + music_file
    template1 = "../test-images/template1.png"
    template2 = "../test-images/template2.png"
    template3 = "../test-images/template3.png"
    template4 = "../test-images/template4.png"
    template5 = "../test-images/template5.png"

    image = Image.open(im_name)
#    finding the scale of the template
    dist, lines = hough(image)
    temp1 = rescale(template1,dist)
    temp2 = rescale(template2,dist*3)
    temp3 = rescale(template3,dist*2.5)
    temp4 = rescale(template4,dist*3)
    temp5 = rescale(template5,dist*8)

    gray_im = image.convert("L")
#    temp1 = Image.open(template1).convert("L")
#    temp2 = Image.open(template2).convert("L")
#    temp3 = Image.open(template3).convert("L")

#    hx=[1,2,1]
#    hy=[1,2,1]
#    image=convolve(gray_im, hx, hy)

#    edge1=sobel_edge_detection(gray_im)
#    edge2=sobel_edge_detection(temp1)

#    template_matching(edge1,edge2)

    result_list = []
    l =[]

    p = pitch(lines,dist)

    result1, result_list = hammingDist(gray_im, temp1, gray_im, "red", result_list, "filled_note", p, dist)
    result2, result_list = hammingDist(gray_im, temp2, result1, "green", result_list, "eighth_rest", p, dist)
    result3, result_list = hammingDist(gray_im, temp3, result2, "blue", result_list, "quarter_rest", p, dist)
    result4, l = hammingDist(gray_im, temp4, result3, "yellow", l, "quarter_rest", p, dist)
    result5, l = hammingDist(gray_im, temp5, result4, "pink", l, "quarter_rest", p, dist)
    text_list = result_list
    np.savetxt("detected.txt", text_list, fmt="%s") # Saving the results in a txt file
    result5.save("detected.png")


import sys
import threading

lastId = 0 #Ids used for object pointers

class aObject:
	def __init__(self, name, value, type):
		global lastId
		self.name = name
		self.value = value
		self.aType = type
		self.id = lastId + 1
		self.attributes = {}
		lastId += 1

class aString(aObject):
	def __init__(self, name, value):
		super().__init__(name, value, "string")
		self.name = name
		self.value = str(value)
		self.aType = "string"

class aNum(aObject):
	def __init__(self, name, value):
		super().__init__(name, value, "number")
		self.name = name
		self.value = value

class aBool(aObject):
	false = aNum("false", 0)
	true = aNum("true", 1)

	def __init__(self, name, value):
		super().__init__(name, value, "bool")
		self.name = name
		self.value = value

class aArray(aObject):
	def __init__(self, name):
		super().__init__(name, [], "array")
		self.name = name
		self.value = []
		self.aType = "array"

class aError(aObject):
	def __init__(self, name):
		super().__init__(name, name, "error_obj")
		self.name = name
		self.aType = "error"
	def aRaise(self, text, ln):
		print("EXCEPTION: " + self.name + ": " + text + " on line " + str(ln) + "\n")
		input("Press enter to exit...\n")
		sys.exit()

class aStream(aObject):
	def act(self, val):
		pass
	def getVal(self):
		return self.id
	def delVal(self):
		pass
	def setVal(self, val):
		self.act(val)
	def __init__(self, name, act):
		super().__init__(name, 0, "stream")
		self.act = act
		self.attributes["act"] = self.act

	value = property(getVal, setVal, delVal, )

TypeErr = aError("TypeError")

def convertObject(obj, newType, ln, attr=None):
		try:
			if newType == "string":
				return aString(obj.name, str(obj.value))
			elif newType == "num":
				return aNum(obj.name, int(obj.value))
			elif newType == "stream":
				return aStream(obj.name, attr["act"])
		except TypeError:
			TypeErr.aRaise("Invalid Value For Type " + obj.type, ln)


def dfs(graph, node, visited, stack):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited, stack)
    stack.append(node)
    return stack

def topological_order(edges, n):
    graph = dict()

    for i in range(1, n+1):
        graph[i] = set()

    for edge in edges:
        graph[edge[0]].add(edge[1])

    visited = set()
    stack = []
    for key in graph.keys():
        if key not in visited:
            order = dfs(graph, key, visited, stack)
    return order[::-1]

n = 5
Edges = [[1,2],[1,3],[2,3],[3,4],[4,2],[3,5]]
# [1, 2, 3, 5, 4]

# n = 5
# Edges = [[1,2],[1,3],[2,3],[4,2],[3,4],[3,5]]
# # [6, 1, 2, 3, 5, 4]

# n=9
# Edges = [[3,2],[3,7],[2,1],[1,7],[1,6],[6,5],[7,6],[7,5],[5,4],[8,9]]

print(topological_order(Edges, n))


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('portfolio', '0006_auto_20160109_0000'),
    ]

    operations = [
        migrations.CreateModel(
            name='Blog',
            fields=[
                ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('content', models.TextField()),
                ('date_ts', models.DateField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


n = int(input('Digite um número: '))
verificador = 1
if (n / 2).is_integer() == False and n != 1 and n != 0:
    verificador = 0
    for c in range(2, n):
        n2 = n / c
        if n2.is_integer():
            verificador = 1
if verificador == 0:
    print('Esse número é primo!')
else:
    print('Esse número não é primo!')


import os
import shutil
import numpy as np
import cv2
import random
import copy

from keras.models import Sequential
from keras.layers.core import Dense, Flatten, Dropout
import tensorflow as tf

def qpixmap_to_array(qtpixmap):
    # qpixmap转换成array
    img = qtpixmap.toImage()
    temp_shape = (img.height(), img.bytesPerLine() * 8 // img.depth())
    temp_shape += (4,)
    ptr = img.bits()
    ptr.setsize(img.byteCount())
    result = np.array(ptr, dtype=np.uint8).reshape(temp_shape)
    result = result[..., :3]

    return result

def img_to_candy(img):
    # 图片转换成灰色,灰色图片转换为轮廓
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_candy = cv2.Canny(img_gray, 100, 200)
    return img_candy

def create_model(input_shape, output_dim, hidden_layer: dict):
    convolutional_layer = hidden_layer.get("convolutional_layer")
    fully_connected_layer = hidden_layer.get("fully_connected_layer")
    # 创建模型
    model = Sequential()
    model.add(Flatten(input_shape=input_shape))

    if convolutional_layer is not None:
        # 待实现
        # 处理卷积层
        pass

    if fully_connected_layer is not None:
        # 处理全连接层
        for index, item in enumerate(fully_connected_layer):
            model.add(Dense(item, activation='relu'))
            model.add(Dropout(0.2))
        model.add(Dense(output_dim, activation='softmax'))

    return model

def model_mutation():
    # 模型变异-变异程度由低到高
    # 1.完全继承/复制-降低lr重训练
    # 2.完全继承/复制-并重训练
    # 3.数量不变,结构重排,并重训练
    # 4.降低5%结构,并重训练
    # 5.增加5%结构,并重训练
    pass

def arr_mutation_rearrange(arr_old: list):
    # 随机重排,比如[1,2,3]排列成[2,1,3]
    arr_new = copy.deepcopy(arr_old)
    random.shuffle(arr_new)
    return arr_new

def arr_mutation_merge(arr_old: list):
    # 合并,层数减少,如[1,2,3]=>[3,3]或[1,5]
    arr_new = copy.deepcopy(arr_old)
    length = len(arr_new)
    if length <= 1:
        return arr_new
    index1, index2 = random.sample(range(0, length), 2)
    arr_new[index1] = arr_new[index1] + arr_new[index2]
    del arr_new[index2]
    return arr_new

def arr_mutation_split(arr_old: list):
    # 分裂,层数增加,如如[3,4]=>[1,3,3]或[2,2,3]等
    arr_new = copy.deepcopy(arr_old)
    index_arr = []
    for i, val in enumerate(arr_new):
        if val > 1:
            index_arr.append(i)
    if len(index_arr) <= 0:
        # 数组中没有可以分裂的
        return arr_new
    index_random = random.sample(index_arr, 1)[0]
    val0 = arr_new[index_random]
    val1 = random.randint(1, val0 - 1)
    val2 = val0 - val1
    del arr_new[index_random]
    arr_new.insert(index_random, val2)
    arr_new.insert(index_random, val1)
    return arr_new

def arr_mutation_increase(arr_old: list):
    arr_new = copy.deepcopy(arr_old)

    length = len(arr_new)
    random_index = random.randint(0, length - 1)
    increase = int(arr_new[random_index] * 0.05)
    if increase == 0:
        increase = 1
    arr_new[random_index] = arr_new[random_index] + increase
    return arr_new

def arr_mutation_decrease(arr_old: list):
    arr_new = copy.deepcopy(arr_old)

    length = len(arr_new)
    random_index = random.randint(0, length - 1)
    decrease = int(arr_new[random_index] * 0.05)
    if decrease == 0:
        decrease = 1
    arr_new[random_index] = arr_new[random_index] - decrease
    if arr_new[random_index] <= 0:
        arr_new[random_index] = 1
    return arr_new

def hidden_layer_mutation(hidden_layer: dict):
    convolutional_layer = hidden_layer.get("convolutional_layer")
    fully_connected_layer = hidden_layer.get("fully_connected_layer")

    return [
        {
            "mutation_type": "origin",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": copy.deepcopy(fully_connected_layer)
        },
        {
            "mutation_type": "mutations_rearrange",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": arr_mutation_rearrange(fully_connected_layer)
        },
        {
            "mutation_type": "mutations_merge",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": arr_mutation_merge(fully_connected_layer)
        },
        {
            "mutation_type": "mutations_split",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": arr_mutation_split(fully_connected_layer)
        },
        {
            "mutation_type": "mutations_increase",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": arr_mutation_increase(fully_connected_layer)
        },
        {
            "mutation_type": "mutations_decrease",
            "convolutional_layer": convolutional_layer,
            "fully_connected_layer": arr_mutation_decrease(fully_connected_layer)
        }
    ]

def model_save(model, model_path):
    # 模型保存
    if not os.path.exists(model_path):
        os.makedirs(model_path)
    tf.saved_model.save(model, model_path)

def model_load(model_path):
    # 模型加载
    if not os.path.exists(model_path):
        print(f"[{model_path}] is not exists ,exit")
        exit(-1)
    model = tf.saved_model.load(model_path)
    return model

def create_folder(folder_path):
    # 删除模型
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

def remove_folder(folder_path):
    # 删除模型
    if os.path.exists(folder_path):
        shutil.rmtree(folder_path)

if __name__ == '__main__':
    a = [100, 101, 102, 103, 104, 105, 106, 107, 108]
    a = [1, 2, 3]
    print(a)
    b = arr_mutation_merge(a)
    c = arr_mutation_split(a)
    print(b)
    print(c)