from matplotlib import pyplot as plt
import numpy as np
from skimage import data, util, transform, feature, measure, filters, metrics
from skimage import io
from skimage.io import imsave as sk_imsave
import cv2

def match_locations(img0, img1, coords0, coords1, radius=5, sigma=8):
    """Match image locations using SSD minimization.

    Areas from `img0` are matched with areas from `img1`. These areas
    are defined as patches located around pixels with Gaussian
    weights.

    Parameters:
    -----------
    img0, img1 : 2D array
        Input images.
    coords0 : (2, m) array_like
        Centers of the reference patches in `img0`.
    coords1 : (2, n) array_like
        Centers of the candidate patches in `img1`.
    radius : int
        Radius of the considered patches.
    sigma : float
        Standard deviation of the Gaussian kernel centered over the patches.

    Returns:
    --------
    match_coords: (2, m) array
        The points in `coords1` that are the closest corresponding matches to
        those in `coords0` as determined by the (Gaussian weighted) sum of
        squared differences between patches surrounding each point.
    """
    y, x = np.mgrid[-radius:radius + 1, -radius:radius + 1]
    weights = np.exp(-0.5 * (x ** 2 + y ** 2) / sigma ** 2)
    weights /= 2 * np.pi * sigma * sigma

    match_list = []
    for r0, c0 in coords0:
        roi0 = img0[r0 - radius:r0 + radius + 1, c0 - radius:c0 + radius + 1]
        roi1_list = [img1[r1 - radius:r1 + radius + 1,
                          c1 - radius:c1 + radius + 1] for r1, c1 in coords1]
        # sum of squared differences
        ssd_list = [np.sum(weights * (roi0 - roi1) ** 2) for roi1 in roi1_list]
        match_list.append(coords1[np.argmin(ssd_list)])

    return np.array(match_list)

startNo = 0
endNo = 6

imageNumbers = np.arange(startNo + 1, endNo + 1)

differenceImages = [io.imread(r"rotatedCross\%s_D.tif" % str(startNo)).astype(np.float32)]
intensityImages = [io.imread(r"rotatedCross\%s_I.tif" % str(startNo)).astype(np.float32)]

for i in imageNumbers:

    differenceImg = io.imread(r"rotatedCross\%s_D.tif" % str(i))
    intensityImg = io.imread(r"rotatedCross\%s_I.tif" % str(i))

    differenceImages = differenceImages + [differenceImg]
    intensityImages = intensityImages + [intensityImg]

initialIntensityImages = intensityImages
initialDifferenceImages = differenceImages

imageStack = []

initialAvg = np.nanmean(differenceImages[0])
initialStd = np.nanstd(differenceImages[0])

for image in differenceImages:
    avg = np.nanmean(image)
    std = np.nanstd(image)

    newImage = initialAvg + ((image - avg) * (initialStd / std))
    np.clip(newImage, -1, 1)

    image = newImage
    image = (image + 1)/2
    image = image * 255
    image = np.array(image, dtype="uint8")
    #image = cv2.medianBlur(image, 5)
    #image = np.clip(image, 110, 150)
    #image = cv2.equalizeHist(image)
    #image = (image-np.nanmin(image))/(np.nanmax(image)-np.nanmin(image))
    #image = image * 255
    #image = np.array(image, dtype="uint8")

    imageStack = imageStack + [image]
#imageStack = standardizeStack(imageStack)

differenceImages = imageStack
print("no of images")
print(len(differenceImages))

initialAvg = np.nanmean(intensityImages[0])
initialStd = np.nanstd(intensityImages[0])
imageStack = []

for image in intensityImages:
    print("looping")
    avg = np.nanmean(image)
    std = np.nanstd(image)

    image = (image-np.nanmin(image))/(np.nanmax(image)-np.nanmin(image)) #renormalises - after contrast adjust so shows
    image = image * 255

    newImage = initialAvg + ((image - avg) * (initialStd / std))

    np.clip(newImage, 0, 255)
    image = np.array(newImage, dtype = "uint8")
    image = cv2.medianBlur(image, 5)

    image = np.array(image, dtype="uint8")

    imageStack = imageStack + [image]

intensityImages = imageStack

img_list = differenceImages

min_dist = 5
corner_list = [feature.corner_peaks(
    feature.corner_harris(img, sigma=7), threshold_rel=0.001, min_distance=min_dist, )
               for img in img_list]

img0 = img_list[0]
coords0 = corner_list[0]
matching_corners = [match_locations(img0, img1, coords0, coords1, min_dist)
                    for img1, coords1 in zip(img_list, corner_list)]

for dst in matching_corners:
    print("printing dst")
    print(dst)

src = np.array(coords0)
trfm_list = []
for dst in matching_corners:
    trfm_list = trfm_list + [measure.ransac((dst, src),
                            transform.EuclideanTransform, min_samples=3,
                            residual_threshold=50, max_trials=500)[0]]
print("trfm_list")
print(trfm_list)

fig, ax_list = plt.subplots(6, 2, figsize=(6, 9), sharex=True, sharey=True)
for idx, (im, trfm, (ax0, ax1)) in enumerate(zip(img_list, trfm_list,
                                                 ax_list)):
    ax0.imshow(im, cmap="gray")
    ax1.imshow(transform.warp(im, trfm), cmap="gray", vmin = 0.4, vmax = 0.55)

    if idx == 0:
        ax0.set_title("initial")
        #ax0.set_ylabel(f"Reference Image\n(PSNR={psnr_ref:.2f})")
        ax1.set_title("corrected")

    ax0.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])
    ax1.set_axis_off()

fig.tight_layout()
plt.show()

All Code - Everything Dumped/imageStitchingAttempt.py


import re

from django.utils.cache import add_never_cache_headers

class NoCacheMiddleware(object):
    """Add No-cache headers to all responses if detect IE UA"""

    IE_DETECTION_RE = [
        re.compile('Trident/.*rv:(\d+\.\d*)'),
        re.compile('MSIE')
    ]

    @staticmethod
    def process_response(request, response):

        if 'HTTP_USER_AGENT' not in request.META:
            return response

        user_agent = request.META['HTTP_USER_AGENT']
        is_ie = False

        for expr in NoCacheMiddleware.IE_DETECTION_RE:
            if expr.search(user_agent):
                is_ie = True
                break

        if is_ie:
            add_never_cache_headers(response)

        return response


from http import HTTPStatus
from app.models.animies_models import Animes
from flask import jsonify, request
from psycopg2.errors import UndefinedColumn
from psycopg2.errors import UniqueViolation
from psycopg2.errors import UndefinedTable

def create():
    data = request.get_json()
    try:
        new_data = Animes(**data)
        result = Animes.create_anime(new_data.__dict__)
    except UniqueViolation:
        return {"error": "anime is already exists"}, HTTPStatus.UNPROCESSABLE_ENTITY
    except KeyError as e:
        return {"required_keys": ["anime", "released_date", "seasons"], "missing_keys": e.args}, HTTPStatus.UNPROCESSABLE_ENTITY

    new_result = Animes.serialized_animes(result)

    return new_result, HTTPStatus.CREATED

def get_all_animes():

    try:
        result = Animes.get_animes()
        data = Animes.serialized_animes(result, lista=True)
    except UndefinedTable:
        return jsonify([]), HTTPStatus.OK

    return {"data": data}, HTTPStatus.OK

def get_one_by_id_anime(id):

    try:
        data = Animes.get_animes_by_id(id)
        result = Animes.serialized_animes(data)
    except (TypeError, UndefinedTable):
        return {"error": "Not Found"}, HTTPStatus.NOT_FOUND

    return {"data": [result]}, HTTPStatus.OK

def update(id):
    get = request.get_json()
    try:
        data = Animes.update_animes(get, id)
        data_serialized = Animes.serialized_animes(data)
    except UniqueViolation:
        return {"error": "anime is already exists"}, HTTPStatus.UNPROCESSABLE_ENTITY
    except UndefinedColumn as e:
        text = str(e.args).split('"')[1]
        return {"available_keys": ["anime", "released_date", "seasons"], "wrong_keys_sended": [f"{text}"]}, HTTPStatus.UNPROCESSABLE_ENTITY
    except (UndefinedTable, TypeError):
        return {"error": "Not Found"}, HTTPStatus.NOT_FOUND
    except KeyError as e:
        text = str(e.args).replace("(", "").replace(")", "").replace(",", "").replace("'", "")
        return {"available_keys": ["anime", "released_date", "seasons"], "wrong_keys_sended": [f"{text}"]}, HTTPStatus.UNPROCESSABLE_ENTITY

    return data_serialized, HTTPStatus.OK

def delete(id):
    try:
        deleted = Animes.deleted_animes(id)
        if not deleted:
            return {"error": "Not Found"}, HTTPStatus.NOT_FOUND
    except UndefinedTable:
        return {"error": "Not Found"}, HTTPStatus.NOT_FOUND

    return "", HTTPStatus.NO_CONTENT


import sys, os, io, atexit
input = lambda : sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s : stdout.write(s.encode("ascii"))
atexit.register(lambda : os.write(1, stdout.getvalue()))
import math
N = int(input())
arr = list(map(int, input().split()))
money = int(input())

if sum(arr) <= money:
    print(max(arr))
else:
    start = 0
    end = money
    answer = 0
    while start <= end:
        mid = ( start + end ) // 2
        sum_money = 0
        for i in arr:
            if i < mid:
                sum_money += i
            else:
                sum_money += mid

        if sum_money <= money:
            start = mid + 1
            answer = mid
        else:
            end = mid - 1
    print(answer)


# %%
# We are importing everything we need for this example:
import os.path as op
import shutil
import csv
import os

import mne
import mne_bids

from mne_bids import write_raw_bids, BIDSPath, print_dir_tree
from mne_bids.stats import count_events
import json
import numpy as np
import matplotlib.pyplot as plt

def convert_to_bids(raw, ica_component=None, ica_topo_figs=None, ica_dict=None, bad_channel_dict=None, sub_id='06', ses='LittlePrince',
                    task='Reading', run=1, bids_root='derivative/preproc',
                    dataset_name='Novel Reading', dataset_type='derivative',
                    author='Xinyu Mou, Cuilin He, Liwei Tan', line_freq=50):
    '''
    :param raw: the pre-processed raw data which you want to save into BIDS format
    :param ica_component: The ICA components when you pre-process the data
    :param ica_topo_figs: Topography of ICA components
    :param ica_dict: This is a dict containing information of the ICA components, It should
           satisfy the following format: {'shape': np.ndarray, 'exclude': list}
           The first value represents the shape of the ICA components: (n_components, time_length)
           The second value represents the excluded ICA components when pre-processing the data
    :param bad_channel_dict: a dict containing information of the marked bad channel when pre-processing
           the data. It should satisfy the following format: {'bad channel': list}
    :param sub_id: The id of the subject you are processing
    :param ses: The session of the current data
    :param run: the run of the current data
    :param bids_root: The root of your dataset
    :param dataset_name: The name of the dataset, which will be saved in the dataset_description.json
    :param dataset_type: The type of the dataset, can be 'raw' or 'derivative', which will be saved in the dataset_description.json
    :param author: The author of the dataset, which will be saved in the dataset_description.json
    :param line_freq: line frequency of your raw data, normally 50 in China

    This function convert a raw eeg to BIDS format with some sidecar files. The EEG data will be
    saved following BrainVision format to satisfy the requirement of BIDS. Make sure that information in the
    data will not be lost when converting the data format.

    The parameter ica_component, ica_dict, bad_channel_dict are optional.
    '''
    raw.info["line_freq"] = line_freq  # specify power line frequency as required by BIDS

    # save files in need, including information about coordinate system, JSON of the eeg, channel information, ...
    bids_path = BIDSPath(subject=sub_id, session=ses, task=task, run=run, root=bids_root)
    basename = str(bids_path.basename)

    events, event_id = mne.events_from_annotations(raw)
    write_raw_bids(raw, bids_path, format='BrainVision', allow_preload=True, overwrite=True)

    fpath = bids_path.fpath
    eeg_file_directory = str(fpath.parent)

    ica_component_path = eeg_file_directory + '/' + basename + '_ica_components.npy'
    ica_topo_path = eeg_file_directory + '/' + basename + '_ica_components_topography'
    ica_json_path = eeg_file_directory + '/' + basename + '_ica_components.json'
    bad_channel_path = eeg_file_directory + '/' + basename + '_bad_channels.json'

    # save ICA components
    if ica_component is not None:
        np.save(ica_component_path, ica_component)

    # save ICA component JSON file
    if ica_dict is not None:
        ica_component_json = json.dumps(ica_dict, sort_keys=False, indent=4, separators=(',', ': '))
        f = open(ica_json_path, 'w')
        f.write(ica_component_json)

    # save bad channel record JSON file
    if bad_channel_dict is not None:
        bad_channel_json = json.dumps(bad_channel_dict, sort_keys=False, indent=4, separators=(',', ': '))
        f = open(bad_channel_path, 'w')
        f.write(bad_channel_json)

    if ica_topo_figs is not None:
        fig_num = 1
        if isinstance(ica_topo_figs, list):
            for topo in ica_topo_figs:
                if fig_num < 10:
                    fig_num_str = str(0) + str(fig_num)
                else:
                    fig_num_str = str(fig_num)
                topo.savefig(ica_topo_path + '_' + fig_num_str + '.png')
                fig_num += 1
        else:
            ica_topo_figs.savefig(ica_topo_path + '.png')

    print_dir_tree(bids_root)

    readme = op.join(bids_root, "README")
    with open(readme, "r", encoding="utf-8-sig") as fid:
        text = fid.read()
    print(text)

    mne_bids.make_dataset_description(path=bids_root, name=dataset_name, dataset_type=dataset_type,
                                      authors=author, overwrite=True)


import numpy as np
from skimage.color import rgb2gray

def extractFeatures(im, c, patch_radius):
    r = patch_radius
    img = rgb2gray(im)
    img = np.pad(img, pad_width = r,mode='constant')
    cx = c[1,:].astype(int)
    cy = c[0,:].astype(int)
    d = (2*r+1)
    d2 = d//2
    f = []
    for x in range(0,len(cx)):
        x1 = cx[x] - d2
        x2 = cx[x] + d2
        y1 = cy[x] - d2
        y2 = cy[x] + d2
        patch = img[x1:x2, y1:y2]
        feature = patch.reshape(-1)
        f.append(feature)
    return f


with open("second_file.txt", "a") as f1:
    f1.write("Dowlony tekst\n")
    f1.write("Inny dowolny tekst\n")

try:
    path = input("Provide path to the file: ")
    with open(path, "r") as f2:
        print(f2.read())
except Exception as e:
    print(f"{e} -->> file does not exist")


from typing import List

def exist(board: List[List[str]], word: str) -> bool:
    num_rows = len(board)
    num_cols = len(board[0])

    def dfs(r, c, i):
        if i == len(word):
            return True

        if (r < 0 or c < 0 or r >= len(num_rows) or c >= len(num_cols)
                or board[r][c] != word[i] or board[r][c] == 0):
            return False

        temp = board[r][c]
        board[r][c] = 0

        i += 1
        result = (dfs(r, c + 1, i) or
                  dfs(r, c - 1, i) or
                  dfs(r + 1, c, i) or
                  dfs(r - 1, c, i))

        board[r][c] = temp

        return result

    for r in range(num_rows):
        for c in range(num_cols):
            if dfs(r, c, 0):
                return True

    return False


import requests
from bs4 import BeautifulSoup
if __name__ == '__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    }
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
    page_text = requests.get(url=url,headers=headers).text
    soup = BeautifulSoup(page_text,'lxml')
    li_list = soup.select('.book-mulu > ul > li')
    fp = open('./sanguo.txt','w',encoding='utf-8')
    for li in li_list:
        title = li.a.string
        detail = 'https://www.shicimingju.com' + li.a['href']
        detail_page_text = requests.get(url = detail,headers=headers).content.decode('utf-8')
        detail_soup = BeautifulSoup(detail_page_text,'lxml')
        detail_li_list = detail_soup.find('div',class_ = 'chapter_content').text
        fp.write(title+':'+detail_li_list+'\n')
        print("{}已成功下载".format(title))

第三章/bs4案例1：三国演义小说.py

bs4案例1：三国演义小说.py


'''
Created on Jul. 9, 2022

@author: Anmol Nagpal
'''

import numpy as np

class Solution:
    def checkValid(self, matrix: List[List[int]]) -> bool:
        n = len(matrix[0])
        standard = [i for i in range(1, n + 1)]
        for i in range(n):
            if len(set(standard).symmetric_difference(set(matrix[i]))) != 0:
                return False
        transpose = np.array(matrix)
        transpose = transpose.T
        for i in range(n):
            if len(set(standard).symmetric_difference(set(transpose[i]))) != 0:
                return False
        return True


n = int(input())
m = list(input())
f = list(input())

same = 0
for i in range(len(m)):
  if m[i] == f[i]:
    same += 1

if same > n:
  print(n + (len(m) - same))
else:
  print(same + (len(m) - n))


"""
ASV benchmarks for irradiance.py
"""

import pandas as pd
import pvlib
from packaging.version import Version
from functools import partial

def set_weather_data(obj):
    obj.times = pd.date_range(start='20180601', freq='1min',
                              periods=14400)
    obj.poa = pd.Series(1000, index=obj.times)
    obj.tamb = pd.Series(20, index=obj.times)
    obj.wind_speed = pd.Series(2, index=obj.times)

class SAPM:

    def setup(self):
        set_weather_data(self)
        if Version(pvlib.__version__) >= Version('0.7.0'):
            kwargs = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS['sapm']
            kwargs = kwargs['open_rack_glass_glass']
            self.sapm_cell_wrapper = partial(pvlib.temperature.sapm_cell,
                                             **kwargs)
        else:
            sapm_celltemp = pvlib.pvsystem.sapm_celltemp

            def sapm_cell_wrapper(poa_global, temp_air, wind_speed):
                # just swap order; model params are provided by default
                return sapm_celltemp(poa_global, wind_speed, temp_air)
            self.sapm_cell_wrapper = sapm_cell_wrapper

    def time_sapm_cell(self):
        # use version-appropriate wrapper
        self.sapm_cell_wrapper(self.poa, self.tamb, self.wind_speed)

class Fuentes:

    def setup(self):
        if Version(pvlib.__version__) < Version('0.8.0'):
            raise NotImplementedError

        set_weather_data(self)

    def time_fuentes(self):
        pvlib.temperature.fuentes(self.poa, self.tamb, self.wind_speed,
                                  noct_installed=45)


# import requests
import aiohttp

from ...core.exceptions import BadRequest

INTERNAL_API_URL = 'https://sandbox-con.kakao.com/admin/internal-api/hello-mis/'

async def request_krew_info_from_ldap_id(ldap_id):
    async with aiohttp.ClientSession() as session:
        async with session.get(url=INTERNAL_API_URL, params={'name': ldap_id}) as response:
            response_json = await response.json()

    if 'error' in response_json:
        raise BadRequest()

    return response_json


print()
print(" ************************************* ")
print(" **  AoC 2022_01: Calorie Counting  ** ")
print(" ************************************* ")
print()

filename = "01.input"
with open(filename) as file:
    lines = file.read().splitlines()

elves = [0]

def part_one():
    elf = 0
    for line in lines:
        if line == '':
            elf += 1
            elves.append(0)
        else:
            elves[elf] += int(line)
    return max(elves)

def part_two():
    strongest_elves = sorted(elves)[-3:]
    return sum(strongest_elves)

print("Part 1: ", part_one())
print("Part 2: ", part_two())


import sys

input = lambda: sys.stdin.readline().strip()
read = lambda: map(int, input().split())

def solve():
    t, = read()

    for _ in range(t):

        n, = read()
        a = list(read())
        neg = res = 0
        smallest_abs = float('inf')
        for c in a:
            smallest_abs = min(smallest_abs, abs(c))
            if c < 0:
                neg += 1
            res += abs(c)
        if neg % 2 == 0:
            print(res)
        else:
            print(res-smallest_abs*2)

# 5
# 4
# -1 -1 -1 1
# 6
# -1 1 -1 1 1 1
# 4
# -1 1 0 1
# 4
# 0 1 -1 1
# 6
# -1 1 -1 1 -1 1
# 6
# -1 1 -1 1 -1 0

if __name__ == '__main__':
    solve()


import math
import numpy as np
import matplotlib.pyplot as plt
from random import gauss
import matplotlib as mpl
from matplotlib.colors import ListedColormap
import seaborn as sns

# boundary condition
def BC(x, y):
    if x < -1:
        x = -2 - x
    else:
        if x > 1:
            x = 2 - x
    if y < -1:
        y = -2 - y
    else:
        if y > 1:
            y = 2 - y
    return x, y

# for easier setting, I put all the code into a class, developed by York and The Kite
class CMM3(object):
    def __init__(self):
        # ----------------------------------------
        # init conditions / interface
        # time set, "h" is a step time
        self.time_max = 0.4
        self.h = 0.05
        # diffusivity
        self.D = 0.01
        # domain size
        self.x_min = -1
        self.x_max = 1
        self.y_min = -1
        self.y_max = 1
        # number of axial gridlines and total grids
        self.Nx = 64
        self.Ny = 64
        self.grids = self.Nx * self.Ny
        # number of particles
        self.Np = 65536
        # init velocity
        self.vel = 0
        # -----------------------------------------
        # for temp particle position data save
        self.x_blue = []
        self.y_blue = []
        self.x_red = []
        self.y_red = []
        # figure and save the interval of the gridlines
        self.ivl_grid_y = (self.y_max - self.y_min) / self.Ny
        self.ivl_grid_x = (self.x_max - self.x_min) / self.Nx
        # data0 is set to count and save the number of red particles and blue particles
        self.data0 = np.zeros((self.Nx, self.Ny, 2))
        # data is set to figure the proportion of blue particles in each grid
        self.data = np.zeros((self.Nx, self.Ny))

    # the func below is extends the classical Euler method
    def Euler_method(self, Xp):
        # create a gauss random dx
        r = gauss(0, 1)
        # equation 6
        # 'r' is random numbers with the standard Gaussian probability
        # 'vel' is the (known) velocity components evaluated at the particle position
        Xp += self.vel * self.h + math.sqrt(2 * self.D) * math.sqrt(self.h) * r
        return Xp

    # this func is used to update the particles after a step time, the movement of each particle is built by York,
    def go_a_step(self):
        for i in range(len(self.x_blue)):
            self.x_blue[i] = self.Euler_method(self.x_blue[i])
            self.y_blue[i] = self.Euler_method(self.y_blue[i])
            # use the boundary condition above
            self.x_blue[i], self.y_blue[i] = BC(self.x_blue[i], self.y_blue[i])
        for i in range(len(self.x_red)):
            self.x_red[i] = self.Euler_method(self.x_red[i])
            self.y_red[i] = self.Euler_method(self.y_red[i])
            # use the boundary condition above
            self.x_red[i], self.y_red[i] = BC(self.x_red[i], self.y_red[i])

    # this func is used to setup the particles in one traverse, built by York
    def setup(self):
        # to reset the coordinates and quantities for the circulation in main()
        self.x_blue = []
        self.y_blue = []
        self.x_red = []
        self.y_red = []
        # use np.random to init the particles
        for i in range(self.Np):
            # temp val for a random particle
            tx = np.random.uniform(self.x_min, self.x_max)
            ty = np.random.uniform(self.y_min, self.y_max)
            ivl_xs = math.ceil((tx - self.x_min) / self.ivl_grid_x) - 1
            ivl_ys = math.ceil((ty - self.y_min) / self.ivl_grid_y) - 1
            # select the color of this particle and count each color in data0
            if math.sqrt(math.pow(tx, 2) + math.pow(ty, 2)) < 0.3:
                self.x_blue.append(tx)
                self.y_blue.append(ty)
                self.data0[ivl_xs][ivl_ys][0] += 1
            else:
                self.x_red.append(tx)
                self.y_red.append(ty)
                self.data0[ivl_xs][ivl_ys][1] += 1

    def grid(self):
        # to locate which grid is the new red particle in and add it to data0[1]
        for i in range(len(self.x_blue)):
            ivl_xs = math.ceil((self.x_blue[i] - self.x_min) / self.ivl_grid_x) - 1
            ivl_ys = math.ceil((self.y_blue[i] - self.y_min) / self.ivl_grid_y) - 1
            self.data0[ivl_xs][ivl_ys][0] += 1
        # to locate which grid is the new red particle in and add it to data0[1]
        for i in range(len(self.x_red)):
            ivl_xs = math.ceil((self.x_red[i] - self.x_min) / self.ivl_grid_x) - 1
            ivl_ys = math.ceil((self.y_red[i] - self.y_min) / self.ivl_grid_y) - 1
            self.data0[ivl_xs][ivl_ys][1] += 1
        # transfer the data0 into data by calculating the proportion of blue particles in each grid
        for i in range(self.Nx):
            for j in range(self.Ny):
                self.data[i][j] = self.data0[i][j][0] / (self.data0[i][j][0] + self.data0[i][j][1])

    # show1 and show2 are made by The Kite
    # the visualization of particle form
    def show1(self):
        # set the figure and pass in the coordinates of blue and red particles
        plt.figure(figsize=(10, 8))
        plt.scatter(self.x_blue, self.y_blue, s=1, c='b')
        plt.scatter(self.x_red, self.y_red, s=1, c='r')
        # set the layout of axis and title
        plt.title("2D problem", fontname='Arial', fontsize=30, weight='bold')
        plt.xlabel("x", fontname='Arial', fontsize=20, weight='bold')
        plt.ylabel("y", fontname='Arial', fontsize=20, weight='bold')
        plt.xlim([-1, 1])
        plt.ylim([-1, 1])
        plt.xticks([-1 + i * 0.5 for i in range(5)])
        plt.yticks([-1 + i * 0.5 for i in range(5)])
        # set the parameters of the colorbar in particle form and create it
        cmap = ListedColormap(["red", "blue"])
        norm = mpl.colors.Normalize(vmin=0, vmax=1)
        plt.colorbar(
            mpl.cm.ScalarMappable(cmap=cmap, norm=norm)
        )
        # show
        plt.show()

    # the visualization of grid form
    def show2(self, colors):
        # pass in data and create the heatmap
        sns_plot = sns.heatmap(self.data, vmin=0, vmax=1, cmap=colors)
        # set the layout of axis and title
        plt.title("2D problem", fontname='Arial', fontsize=30, weight='bold')
        sns_plot.set_xlabel("x", fontname='Arial', fontsize=20, weight='bold')
        sns_plot.set_ylabel("y", fontname='Arial', fontsize=20, weight='bold')
        plt.axis('off')
        # show
        plt.show()

    '''
    # This code is built by York, and used to test
    def show(self):
        plt.scatter(self.x_red, self.y_red, s=0.5, color='red')
        plt.scatter(self.x_blue, self.y_blue, s=0.5, color='blue')
        plt.xlabel("x")
        plt.ylabel("y")
        plt.show()
    '''

    # main code for this class
    def main(self):
        # the defination of colorbar of gird form
        colors1 = [(r, g, b) for (r, g, b) in zip(np.linspace(1, 0.8, 7), np.linspace(0, 0, 7), np.linspace(0, 0.9, 7))]
        colors2 = [(r, g, b) for (r, g, b) in zip(np.linspace(0.7, 0, 6), np.linspace(0, 1, 6), np.linspace(1, 0, 6))]
        colors3 = [(r, g, b) for (r, g, b) in zip(np.linspace(0, 0, 7), np.linspace(0.7, 0, 7), np.linspace(0, 1, 7))]
        colors = colors1 + colors2 + colors3

        print("This is CMM3 group's project of 2D probelms")
        while True:
            choice = int(input("for particle press 0,for grid press 1,press anything to quit\n"))
            # the visualization of particle form
            if choice == 0:
                # setup the init list of particles
                self.setup()
                # show the first graph when t = 0
                self.show1()
                # cycle in Classic Euler Method step by step
                for i in range(int(self.time_max / self.h)):
                    self.data = np.zeros((self.Nx, self.Ny))
                    self.go_a_step()
                    self.show1()
                # after the iteration recreate data0 and data
                self.data0 = np.zeros((self.Nx, self.Ny, 2))
                self.data = np.zeros((self.Nx, self.Ny))
            # the visualization of grid form
            elif choice == 1:
                # setup the init list of particles, data0 and data
                self.setup()
                # show the first graph when t = 0, data0 and data
                self.grid()
                self.show2(colors)
                # cycle in Classic Euler Method step by step
                for i in range(int(self.time_max / self.h)):
                    self.data = np.zeros((self.Nx, self.Ny))
                    self.go_a_step()
                    self.grid()
                    self.show2(colors)
                # after the iteration recreate data0 and data
                self.data0 = np.zeros((self.Nx, self.Ny, 2))
                self.data = np.zeros((self.Nx, self.Ny))
            # quit the project
            else:
                return

# main code for the whole project
if __name__ == '__main__':
    # build a instance
    Project = CMM3()
    # to run main code
    Project.main()


# -*- coding: utf-8 -*-
"""
Created on Sun Nov  1 13:21:19 2020

Lineares Gleichungssystem LGS Ax = b direkt mit Gauss-Algorithmus lösen und Determinante von A berechnen

MIT SPALTENPIVOTISIERUNG

@author: IT19ta_WIN / zahlesev@students.zhaw.ch
"""

import numpy as np

"""==================== INPUT ===================="""
A = np.array([[   4,  -1,  -5],
               [-12,   4,  17],
               [ 32, -10, -41]],
              dtype=np.float64)
b = np.array([-5, 19, -39], dtype=np.float64)

A = np.array([[1e-5, 1e-5], [2, 3]], dtype=np.float64)
b = np.array([1e-5, 1], dtype=np.float64)

show_steps = True  # Ob die Zwischenresultate ausgegeben werden sollen
number_format = "{b:8.2f}"  # Formatierung der Zahl bei der Ausgabe von Matrizen
"""==============================================="""

def gauss_solve(A, b):

    if A.shape[0] != A.shape[1]:
        raise Exception('A is not a quadratic matrix!')

    if A.shape[0] != b.shape[0]:
        raise Exception('b has not the same length as the dimensions of A.')

    # Copy input variables so that external data is not altered, and
    # to ensure that concurrent processes don't alter local data.
    R = np.copy(A)
    v = np.copy(b)

    # Recursively create upper triangle matrix, and apply operations to b.
    row_inversion_count = create_upper_triangle_matrix(R, v, 0)

    # Determine solution by reverse-solving with triangle matrix.
    x = reverse_solve(R, v)

    # Calculate determinant as product of diagonal elements
    det = (-1) ** row_inversion_count
    for row in range(R.shape[0]):
        det *= R[row, row]

    return R, det, x

def create_upper_triangle_matrix(R, v, row_inversion_count):
    if show_steps:
        print("Betrachte jetzt Sub-Matrix der Grösse " + str(len(R)) + ":")
        print_extended_matrix(R, v)

    if R.shape[0] == 1 and R.shape[1] == 1:
        return 0

    # If largest value in column is not in first row, switch rows to improve condition / reduce error
    row_inversion_count += switch_rows_for_column_pivoting(R, v)

    # Create zeros in first column
    for row in range(1, R.shape[0]):
        factor = -(R[row, 0] / R[0, 0])

        # Add first row times factor to current row
        R[row, :] = R[row, :] + (factor * R[0, :])
        v[row] = v[row] + (factor * v[0])

        if show_steps:
            print("Erzeuge 0 in Zeile " + str(row + 1) + ":")
            print_extended_matrix(R, v)

    # Repeat process on sub-matrix
    row_inversion_count = create_upper_triangle_matrix(R[1:, 1:], v[1:], row_inversion_count)

    return row_inversion_count

def switch_rows_for_column_pivoting(R, v):
    row_inversion_count = 0

    pivot = 0
    pivot_row = 0

    for row in range(R.shape[0]):
        if abs(R[row, 0]) > pivot:
            pivot = abs(R[row, 0])
            pivot_row = row

    if pivot == 0:
        raise Exception('All elements in first column are zero. System has no single solution.')

    if pivot_row > 0:
        # Switch pivot row with first row
        r_copy = np.copy(R)
        R[0, :] = r_copy[pivot_row, :]
        R[pivot_row, :] = r_copy[0, :]

        v_copy = np.copy(v)
        v[0] = v_copy[pivot_row]
        v[pivot_row] = v_copy[0]

        row_inversion_count += 1
        if show_steps:
            print("|Pivot| ist " + str(pivot) + " --> Vertausche Zeile 1 mit Zeile " + str(pivot_row + 1) + ".")
            print_extended_matrix(R, v)

    else:
        if show_steps:
            print("Keine Zeilenvertauschungen notwendig!")

    return row_inversion_count

def reverse_solve(R, v):
    size = R.shape[0]
    x = np.zeros(size)

    # Start at last row and continue towards first row
    for row in range(size - 1, -1, -1):
        x[row] = - (1 / R[row, row]) * (-v[row] + np.sum(R[row, row + 1:] * x[row + 1:]))

    return x

def print_extended_matrix(R, v):
    out = ""

    for row in range(R.shape[0]):
        lbracket = "|"
        rbracket = "|"

        if row == 0: lbracket = "/"; rbracket = "\\";
        if row == R.shape[0] - 1: lbracket = "\\"; rbracket = "/"
        if R.shape[0] == 1: lbracket = "("; rbracket = ")"

        out += lbracket
        out += " "

        for col in range(R.shape[1]):
            out += number_format.format(b=R[row, col])
            out += " "

        out += "| "
        out += number_format.format(b=v[row])
        out += " "
        out += rbracket
        out += "\n"

    print(out)

"""
MAIN PROGRAM
"""
R, det, x = gauss_solve(A, b)

print("\nDeterminante von A:", str(det))
print("\nObere Dreiecksmatrix:")
print(R)
print('\nLösung des Gleichungssystems ist: ')
for i in range(len(x)):
    print("x{a} = {b:5.2f}".format(a=i, b=x[i]), end='\t')

print("\n\nLösung mit numpy.linalg.solve: x = " + str(np.linalg.solve(A, b)))


import torch
import torch.nn as nn
import torch.nn.functional as F

def weights_init(m):

    classname = m.__class__.__name__

    if hasattr(m, 'weight') and classname.find('Conv') != -1:
        nn.init.normal_(m.weight.data, 0.0, 0.02)
        if hasattr(m, "bias") and m.bias is not None:
            nn.init.constant_(m.bias.data, 0.0)

    elif classname.find('BatchNorm2d') != -1:
        nn.init.normal_(m.weight.data, 1.0, 0.02)
        nn.init.constant_(m.bias.data, 0.0)

# ------
# ResNet
# ------
class ResidualBlock(nn.Module):

    def __init__(self, in_channels):
        super(ResidualBlock, self).__init__()

        self.block = nn.Sequential(
            nn.ReflectionPad2d(1),
            nn.Conv2d(in_channels, in_channels, 3),
            nn.InstanceNorm2d(in_channels),
            nn.ReLU(inplace=True),
            nn.ReflectionPad2d(1),
            nn.Conv2d(in_channels, in_channels, 3),
            nn.InstanceNorm2d(in_channels)
        )

    def forward(self, x):

        return x + self.block(x)

# ---------
# Generator
# ---------
class ResnetGenerator(nn.Module):

    def __init__(self, channels, num_residual_blocks):
        super(ResnetGenerator, self).__init__()

        # Initial convolution block
        out_channels = 64
        layers = [
            nn.ReflectionPad2d(channels),
            nn.Conv2d(channels, out_channels, 7),
            nn.InstanceNorm2d(out_channels),
            nn.ReLU(inplace=True)
        ]
        in_channels = out_channels

        # Downsampling
        for _ in range(2):

            out_channels *= 2
            layers += [
                nn.Conv2d(in_channels, out_channels, 3, 2, 1),
                nn.InstanceNorm2d(out_channels),
                nn.ReLU(inplace=True)
            ]
            in_channels = out_channels

        # Residual blocks
        for _ in range(num_residual_blocks):

            layers += [ResidualBlock(out_channels)]

        # Upsampling
        for _ in range(2):

            out_channels //= 2
            layers += [
                nn.Upsample(scale_factor=2),
                nn.Conv2d(in_channels, out_channels, 3, 1, 1),
                nn.InstanceNorm2d(out_channels),
                nn.ReLU(inplace=True)
            ]
            in_channels = out_channels

        # Output_layer
        layers += [
            nn.ReflectionPad2d(channels),
            nn.Conv2d(out_channels, channels, 7),
            nn.Tanh()
        ]

        self.block = nn.Sequential(*layers)

    def forward(self, x):
        return self.block(x)

# -------------
# Discriminator
# -------------
class Discriminator(nn.Module):

    def __init__(self, in_channels):
        super(Discriminator, self).__init__()

        def discriminator_block(in_chs, out_chs, IN=True):

            layers = [nn.Conv2d(in_chs, out_chs, 4, 2, 1)]
            if IN:
                layers.append(nn.InstanceNorm2d(out_chs))
            layers.append(nn.LeakyReLU(0.2, inplace=True))

            return layers

        self.blocks = nn.Sequential(
            *discriminator_block(in_channels, 64, IN=False),
            *discriminator_block(64, 128),
            *discriminator_block(128, 256),
            *discriminator_block(256, 512),
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(512, 1, 4, padding=1)
        )

    def forward(self, img):

        return self.blocks(img)


from typing import Any, List, Tuple, Dict, Union, Optional, cast
from warnings import warn
import numpy as np
import pandas as pd
from scipy import sparse
from scipy.sparse import linalg
from chemicalc.reference_spectra import ReferenceSpectra, alpha_el
from chemicalc.instruments import InstConfig

def init_crlb_df(reference: ReferenceSpectra) -> pd.DataFrame:
    """
    Initialized CRLB dataframe with indices corresponding to all the labels included

    :param ReferenceSpectra reference: Reference star object (used to identify stellar labels)
    :return pd.DataFrame: Empty CRLB dataframe
    """
    if not isinstance(reference, ReferenceSpectra):
        raise TypeError(
            "reference must be a chemicalc.reference_spectra.ReferenceSpectra object"
        )
    return pd.DataFrame(index=reference.labels.index)

def calc_crlb(
    reference: ReferenceSpectra,
    instruments: Union[InstConfig, List[InstConfig]],
    pixel_corr: Optional[List[float]] = None,
    priors: Optional[Dict["str", float]] = None,
    bias_grad: Optional[pd.DataFrame] = None,
    use_alpha: bool = False,
    output_fisher: bool = False,
    chunk_size: int = 10000,
) -> Union[pd.DataFrame, Tuple[pd.DataFrame, pd.DataFrame]]:
    """
    Calculates the Fisher Information Matrix and Cramer-Rao Lower Bound from spectral gradients

    :param ReferenceSpectra reference: Reference star object
    :param Union[InstConfig,List[InstConfig]] instruments: Instrument object or list of instrument objects
    :param Optional[List[float]] pixel_corr: Correlation of adjacent pixels.
                                             This may considerably slow down the computation.
    :param Optional[Dict[str,float]] priors: 1-sigma Gaussian priors for labels
    :param Optional[pd.DataFrame] bias_grad: Gradient of the bias matrix
    :param bool use_alpha: If true, uses bulk alpha gradients and zeros gradients of individual alpha elements
                           (see chemicalc.reference_spectra.alpha_el)
    :param bool output_fisher: If true, outputs Fisher information matrix
    :param int chunk_size: Number of pixels to break spectra into. Helps with memory usage for large spectra.
    :return Union[pd.DataFrame, Tuple[pd.DataFrame, np.ndarray]]: DataFrame of CRLBs.
                                                                  If output_fisher=True, also returns FIM
    """
    if not isinstance(reference, ReferenceSpectra):
        raise TypeError(
            "reference must be a chemicalc.reference_spectra.ReferenceSpectra object"
        )
    if not isinstance(instruments, list):
        instruments = [instruments]
    if chunk_size is not None:
        if chunk_size < 1000:
            warn(
                f"chunk_size of {chunk_size} seems a little small...This may lead to numerical errors",
                UserWarning,
            )
    fisher_mat = np.zeros((reference.nlabels, reference.nlabels))
    for instrument in instruments:
        if not isinstance(instrument, InstConfig):
            raise TypeError(
                "instruments must be chemicalc.instruments.InstConfig objects"
            )
        if instrument.name not in reference.gradients.keys():
            raise KeyError(
                f"Reference star does not have gradients for {instrument.name}"
            )
        grad_backup = reference.gradients[instrument.name].copy()
        if use_alpha and "alpha" not in reference.labels.index:
            raise ValueError("alpha not included in reference file")
        elif use_alpha:
            reference.zero_gradients(name=instrument.name, labels=alpha_el)
        elif not use_alpha and "alpha" in reference.labels.index:
            reference.zero_gradients(name=instrument.name, labels=["alpha"])
        grad = reference.gradients[instrument.name].values
        reference.gradients[instrument.name] = grad_backup
        flux_var = instrument.snr ** (-2)
        if chunk_size is not None:
            n_chunks = int(np.ceil(grad.shape[1] / chunk_size))
        else:
            chunk_size = grad.shape[1]
            n_chunks = 1
        for i in range(n_chunks):
            grad_tmp = grad[:, i * chunk_size : (i + 1) * chunk_size]
            flux_var_tmp = flux_var[i * chunk_size : (i + 1) * chunk_size]
            if pixel_corr:
                flux_covar = sparse.diags(flux_var_tmp, format="csc")
                for k, covar_factor in enumerate(pixel_corr):
                    j = k + 1
                    flux_covar += covar_factor * sparse.diags(
                        flux_var_tmp[:-j], j
                    ) + covar_factor * sparse.diags(flux_var_tmp[j:], -j)
                flux_covar_inv = linalg.inv(flux_covar).todense()
            else:
                flux_covar_inv = np.diag(flux_var_tmp ** -1)
            fisher_mat += grad_tmp.dot(flux_covar_inv).dot(grad_tmp.T)
    diag_val = np.abs(np.diag(fisher_mat)) < 1.0
    fisher_mat[diag_val, :] = 0.0
    fisher_mat[:, diag_val] = 0.0
    fisher_mat[diag_val, diag_val] = 10.0 ** -6
    fisher_df = pd.DataFrame(
        fisher_mat, columns=reference.labels.index, index=reference.labels.index
    )
    if priors:
        if not isinstance(priors, dict):
            raise TypeError("priors must be None or a dictionary of {label: prior}")
        for label in priors:
            prior = priors[label]
            if not isinstance(prior, (int, float)):
                raise TypeError("prior dict entries must be int, or float")
            if label not in reference.labels.index:
                raise KeyError(f"{label} is not included in reference")
            if prior is None:
                continue
            if label == "Teff":
                prior /= 100
            if prior == 0:
                fisher_df.loc[label, :] = 0
                fisher_df.loc[:, label] = 0
                fisher_df.loc[label, label] = 1e-6
            else:
                fisher_df.loc[label, label] += prior ** (-2)
    if bias_grad is not None:
        warn(
            "Calculating the biased CRLB is an experimental feature and has not been thoroughly tested.",
            UserWarning,
        )
        I = np.eye(fisher_df.shape[0])
        D = bias_grad
        crlb = pd.DataFrame(
            np.sqrt(np.diag(((I + D).dot(np.linalg.pinv(fisher_df))).dot((I + D).T))),
            index=reference.labels.index,
        )
    else:
        crlb = pd.DataFrame(
            np.sqrt(np.diag(np.linalg.pinv(fisher_df))), index=reference.labels.index
        )
    if output_fisher:
        return crlb, fisher_df
    else:
        return crlb

def sort_crlb(
    crlb: pd.DataFrame,
    cutoff: float,
    sort_by: str = "default",
    fancy_labels: bool = False,
) -> pd.DataFrame:
    """
    Sorts CRLB dataframe by decreasing precision of labels and removes labels with precisions worse than cutoff.

    :param pd.DataFrame crlb: dataframe of CRLBs
    :param float cutoff: Cutoff precision of labels
    :param str sort_by: Name of dataframe column to sort labels by.
                        'default' uses the column with the most labels recovered below the cutoff.
                        'alphabetical' sorts elemental labels alphabetically.
                        'atomic_number' sorts the elements by the order they appear on the periodic table.
    :param bool fancy_labels: Replaces Teff, logg, and v_micro with math-formatted labels (for plotting).
    :return pd.DataFrame: Sorted CRLB dataframe
    """
    # ToDo: Thoroughly check that sorting works as expected
    if not isinstance(crlb, pd.DataFrame):
        raise TypeError("crlb must be pd.DataFrame")
    if not isinstance(cutoff, (int, float)):
        raise TypeError("cutoff must be int or float")
    if not isinstance(sort_by, str):
        raise TypeError(f"sort_by must be str in {list(crlb.columns)}, 'default', 'alphabetical', or 'atomic_number'")
    crlb_temp = crlb[:3].copy()
    crlb[crlb > cutoff] = np.NaN
    crlb[:3] = crlb_temp
    valid_ele = np.concatenate(
            [crlb.index[:3], crlb.index[3:][np.min(crlb[3:], axis=1) < cutoff]]
        )
    if sort_by == "atomic_number":
        valid_ele_sorted = valid_ele
    elif sort_by == "alphabetical":
        valid_ele_sorted = np.concatenate([valid_ele[:3], sorted(valid_ele[3:])])
    else:
        if sort_by == "default":
            sort_by_index = np.sum(pd.isna(crlb)).idxmin()
        else:
            if sort_by in list(crlb.columns):
                sort_by_index = sort_by
            else:
                raise KeyError(
                    f"{sort_by} not in crlb \n Try 'default', 'atomic_number', 'alphabetical', or one of {list(crlb.columns)}"
                )
        valid_ele_sorted = np.concatenate(
            [crlb.index[:3], crlb.loc[valid_ele][3:].sort_values(sort_by_index).index]
        )
    crlb = crlb.loc[valid_ele_sorted]
    if len(crlb.index) == 3:
        warn(f"No elements w/ CRLBs < cutoff ({cutoff})", UserWarning)
    if fancy_labels:
        crlb.index = [r"$T_{eff}$ (100 K)", r"$\log(g)$", r"$v_{micro}$ (km/s)"] + list(
            crlb.index[3:]
        )
    return crlb


'''
< 퀵 정렬 >
'''
arr = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]

def quick(arr, start, end):
    if end - start < 1:
        return
    pivot = arr[start]
    i, j = 0, 0
    while True:
        for x in range(start + 1, end + 1):
            if pivot < arr[x]:
                i = x
                break
        for x in range(end, start, -1):
            if pivot > arr[x]:
                j = x
                break
        if i != 0 and j != 0:
            if i > j:
                arr[start], arr[j] = arr[j], arr[start]
                break
            arr[i], arr[j] = arr[j], arr[i]
        elif i == 0:
            arr[start:end] = arr[start+1:end+1]
            arr[end] = pivot
            j = end - 1
            break
        elif j == 0:
            j = start
            break
    quick(arr, start, j)
    quick(arr, j + 1, end)

quick(arr, 0, len(arr) - 1)
print(arr)

'''
'''
arr = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]

def quick(arr, start, end):
    if start >= end:
        return
    pivot = start
    left = start + 1
    right = end
    while left <= right:
        while left <= right and arr[left] <= arr[pivot]:
            left += 1

        while left <= right and arr[right] >= arr[pivot]:
            right -= 1

        if left > right:
            arr[right], arr[pivot] = arr[pivot], arr[right]
        else:
            arr[left], arr[right] = arr[right], arr[left]

    quick(arr, start, right - 1)
    quick(arr, right + 1, end)

quick(arr, 0, len(arr) - 1)
print(arr)
'''
'''
arr = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]

def quick(arr):
    print(arr)
    if len(arr) <= 1:
        return arr

    pivot = arr[0]
    tail = arr[1:]

    left_side = [x for x in tail if x <= pivot]
    right_side = [x for x in tail if x > pivot]

    return quick(left_side) + [pivot] + quick(right_side)

print(quick(arr))


import fitz
import tkinter as tk
from tkinter import filedialog
def pdf_image(pdfPath, imgPath, zoom_x, zoom_y, rotation_angle):
    # 打开PDF文件
    pdf = fitz.open(pdfPath)
    # 逐页读取PDF
    for pg in range(0, pdf.page_count):
        page = pdf[pg]
        # 设置缩放和旋转系数
        trans = fitz.Matrix(zoom_x, zoom_y).prerotate(rotation_angle)
        pm = page.get_pixmap(matrix=trans, alpha=False)
        # 开始写图像
        pm._writeIMG(imgPath + str(pg) + ".png",format=1,jpg_quality=100)
    pdf.close()
def select_files():
    root = tk.Tk()
    root.withdraw()
    file_paths = filedialog.askopenfilenames(title="选择要提取的PDF文件", filetypes=[("PDF Files", "*.pdf")])
    return file_paths
input_file=select_files()
print("filename:{}".format(str(input_file)))
pdf_image(input_file[0]
          , r"images/", 10, 10, 0)


from django.shortcuts import render
from django.http import HttpResponse
from .models import Customers, Records

# Create your views here.

def index(request):
    return render(request,"index.html")

def customers(request):
    datas=Customers.objects.all()
    return render(request,"customers.html",{'datas':datas})

def transfer(request,id):
    costm=Customers.objects.get(id=id)
    recivers=Customers.objects.all().exclude(name=costm.name)
    return render(request,"transfer.html",{'costm':costm,'recivers':recivers})

def submission(request):
    vari = Records()
    vari.sender_name=request.POST.get('name')
    vari.resiver_name=request.POST.get('reciver')
    vari.transfer_balance=request.POST.get('balance')
    vari.save()
    send=Customers.objects.get(name=vari.sender_name)
    reci=Customers.objects.get(name=vari.resiver_name)
    send.balance=int(send.balance)-int(vari.transfer_balance)
    reci.balance=int(reci.balance)+int(vari.transfer_balance)
    send.save()
    reci.save()
    return HttpResponse("Transfer Successful")


import re

pattern = r"(^\$[A-Z][a-z][a-z]+\$:\s\[\d+\]\|\[\d+\]\|\[\d+\]\|$)|(^\%[A-Z][a-z][a-z]+\%:\s\[\d+\]\|\[\d+\]\|\[\d+\]\|$)"

lines = int(input())

for line in range(lines):
    text = input()
    matches = re.findall(pattern, text)
    if not matches:
        print("Valid message not found!")
    else:
        tag, numbers = text.split(":")
        tag = tag[1:-1]
        numbers = numbers.strip().split("|")[:-1]
        decrypted_message = []
        for number in numbers:
            number = int(number[1:-1])
            decrypted_message.append(chr(number))
        print(f"{tag}: {''.join(decrypted_message)}")

01. Fundamentals/00. Exams/Message Decrypter.py


__author__ = 'Neil Butcher'

import sqlite3
from Events import MultipleEventsSavingObject
from Rota_System.Roles import GlobalRoleList, Role
from Rota_System.StandardTimes import StandardEventTimes
from Rota_System.Worker import Worker
from Duration import DurationSavingObject
from Error import DatabaseSaveLoadError
import time
from datetime import datetime

class InstitutionSavingObject(object):
    '''
    classdocs
    '''

    def __init__(self, institution, filename=None):
        if filename:
            self._filename = filename
        else:
            self._filename = institution.name + '.db'

        self._institution = institution
        self._connection = sqlite3.connect(self._filename, detect_types=sqlite3.PARSE_DECLTYPES)

    def load(self):

        self.loadRoles()
        self.loadTimes()
        self.loadPopulation()
        self.loadTemplates()
        self.loadDurations()

    def createTables(self):
        with self._connection:
            self._createRolesTables()
            self._createPopulationTables()
            self._createTimesTable()
        MultipleEventsSavingObject(None, self._filename, None).beginNew()
        DurationSavingObject(None, self._filename).beginNew()

    def populateTables(self):
        with self._connection:
            self._populateRolesTables()
            self._populatePopulationTables()
            self._populateTimesTable()
        e = MultipleEventsSavingObject(self._institution.templates, self._filename, None)
        d = DurationSavingObject(self._institution.durations, self._filename)
        e.populateTables()
        d.populateTables()

    def loadTemplates(self):
        MultipleEventsSavingObject(None, self._filename, None).loadEvents(self._institution)

    def loadDurations(self):
        if self._personCacheDict:
            DurationSavingObject(None, self._filename).loadTables(self._institution, self._personCacheDict)
        else:
            raise DatabaseSaveLoadError('The population must be loaded before appointments can be loaded')

    def loadTimes(self):
        with self._connection:
            self._loadInTimesTable()

    def loadRoles(self):
        with self._connection:
            self._loadInRolesTables()

    def loadPopulation(self):
        with self._connection:
            self._loadInRolesTables()
            self._loadInPopulationTables()

    def _createRolesTables(self):
        _c = self._connection.cursor()
        try:
            _c.execute('''DROP TABLE Roles''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE Roles
             (description TEXT NOT NULL, priority INTEGER, code TEXT,PRIMARY KEY (description))''')
        try:
            _c.execute('''DROP TABLE RolesCompatibility''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE RolesCompatibility
             (role1Description TEXT NOT NULL, role2Description TEXT NOT NULL)''')

    @staticmethod
    def roleTupple(role):
        return role.description, role.priority, role.code

    def _populateRolesTables(self):
        _c = self._connection.cursor()
        _c.execute('''DELETE FROM Roles''')
        roleTupples = map(self.roleTupple, GlobalRoleList.roles)
        _c.executemany('INSERT INTO Roles VALUES (?,?,?)', roleTupples)

        _c.execute('''DELETE FROM RolesCompatibility''')
        for role1 in GlobalRoleList.roles:
            for role2 in role1.compatibilities.roles:
                _c.execute('INSERT INTO RolesCompatibility VALUES (?,?)', (role1.description, role2.description))

    def _loadInRolesTables(self):
        _c = self._connection.cursor()
        GlobalRoleList.clear()
        for row in _c.execute('SELECT * FROM Roles ORDER BY priority'):
            GlobalRoleList.add_role(Role(row[0], row[2], row[1]))

        for row in _c.execute('SELECT * FROM RolesCompatibility'):
            role1 = GlobalRoleList.role_from_desc(row[0])
            role2 = GlobalRoleList.role_from_desc(row[1])
            role1.compatibilities.add(role2)

    def _createPopulationTables(self):
        _c = self._connection.cursor()
        try:
            _c.execute('''DROP TABLE Population''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE Population
             (name TEXT NOT NULL, address TEXT, email TEXT, phone TEXT,PRIMARY KEY (name))''')
        try:
            _c.execute('''DROP TABLE PopulationAvailability''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE PopulationAvailability
             (personName TEXT NOT NULL, unavailableDate date NOT NULL)''')
        self._connection.commit()
        try:
            _c.execute('''DROP TABLE PopulationQualifications''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE PopulationQualifications
             (personName TEXT NOT NULL, qualification TEXT NOT NULL)''')

    @staticmethod
    def personTupple(person):
        return person.name, person.address, person.email, person.phone_number

    def _populatePopulationTables(self):
        _c = self._connection.cursor()
        _c.execute('''DELETE FROM Population''')
        tupples = map(self.personTupple, self._institution.people)
        _c.executemany('INSERT INTO Population VALUES (?,?,?,?)', tupples)

        _c.execute('''DELETE FROM PopulationAvailability''')
        _c.execute('''DELETE FROM PopulationQualifications''')
        for person in self._institution.people:
            for date in person.blacklisted_dates():
                _c.execute('INSERT INTO PopulationAvailability VALUES (?,?)', (person.name, date))
            for role in person.roles():
                _c.execute('INSERT INTO PopulationQualifications VALUES (?,?)', (person.name, role.description))

    def _loadInPopulationTables(self):
        _c = self._connection.cursor()
        self._institution.people = []
        personCacheDict = {'Name': 'PersonObject'}
        for row in _c.execute('SELECT * FROM Population ORDER BY name'):
            p = Worker()
            p.name = row[0]
            p.address = row[1]
            p.email = row[2]
            p.phoneNumber = row[3]
            self._institution.people.append(p)
            personCacheDict[p.name] = p

        for row in _c.execute('SELECT * FROM PopulationAvailability'):
            personCacheDict[row[0]].blacklist_date(row[1])

        for row in _c.execute('SELECT * FROM PopulationQualifications'):
            r = GlobalRoleList.role_from_desc(row[1])
            personCacheDict[row[0]].roles().add(r)

        self._personCacheDict = personCacheDict

    def _createTimesTable(self):
        _c = self._connection.cursor()
        try:
            _c.execute('''DROP TABLE StandardEventTimes''')
        except sqlite3.OperationalError:
            pass
        _c.execute('''CREATE TABLE StandardEventTimes
             (name TEXT NOT NULL, time TEXT,PRIMARY KEY (name))''')

    @staticmethod
    def timeTupple(item):
        return item[0], item[1].strftime("%H:%M")

    def _populateTimesTable(self):
        _c = self._connection.cursor()
        _c.execute('''DELETE FROM StandardEventTimes''')
        timeTupples = map(self.timeTupple, StandardEventTimes)
        _c.executemany('INSERT INTO StandardEventTimes VALUES (?,?)', timeTupples)

    def _loadInTimesTable(self):
        _c = self._connection.cursor()
        StandardEventTimes[:] = []
        for row in _c.execute('SELECT * FROM StandardEventTimes'):
            t = (datetime(*time.strptime(row[1], "%H:%M")[0:6])).time()
            StandardEventTimes.append((row[0], t))


'''
This file converts an outdated 1.15 model file into one that works with 1.16.
To use, place this script in a directory with 1 or more outdated Java model files, and each
will have a copy of it created with correct functions and structure.

Note: You must fix textureWidth and textureSize manually
'''

import glob, os

def formatLine(line, indent):
  out = ""
  for i in range(indent):
    out += "    "
  out += line.strip() + "\n"
  return out

for file in glob.glob("*.java"):
  readFrom = open(file, "r")
  outFile = open(file[0:-5]+"_out.txt", "w")
  break

pos = 0
inFile = list(readFrom)

# Skip over start of file
while ("public" not in inFile[pos]):
  pos += 1

className = inFile[pos].split()[2]
pos += 1

# Read the private variables
while ("public" not in inFile[pos]):
  outFile.write(formatLine(inFile[pos], 1))
  pos += 1

# Add the className
outFile.write(formatLine("public " + className + "() {", 2))
pos += 1

width, height = inFile[pos:pos+2]

width = width.split()[-1][0:-1]
height = height.split()[-1][0:-1]
pos += 2

while ("}" not in inFile[pos]):

  line = inFile[pos]
  if ("bb_main" in line):
    outFile.write(formatLine(line, 3))
    outFile.write(
      formatLine("bb_main.setTexSize(" + width + ", " + height + ")", 3)
    )
  elif ("setRotationPoint" in line):
    outFile.write(
      formatLine(line.replace("setRotationPoint", "setPos"), 3)
    )
  elif ("setTextureOffset" in line):
    outFile.write(
      formatLine(line.replace("setTextureOffset", "texOffs"), 3)
    )
  elif ("setRotationAngle" in line):
    obj = line.strip()[17:-2]
    modelName, x, y, z = obj.split(", ")
    outFile.write(formatLine(modelName + ".xRot = " + x + ";", 3))
    outFile.write(formatLine(modelName + ".yRot = " + y + ";", 3))
    outFile.write(formatLine(modelName + ".zRot = " + z + ";", 3))

  else:
    outFile.write(formatLine(inFile[pos], 3))
  pos += 1

readFrom.close()
outFile.close()

print("Conversion complete!")


from dataclasses import dataclass
from . import *

@mark.copyfiles(('fileA',2), ('fileA2',3))
def test_comparefilecontents(copiedtestfiles, filesopen):
    pathsandhandles = zip(
        (copiedtestfiles.paths['fileA'] + copiedtestfiles.paths['fileA2']),
        (copiedtestfiles.handles['fileA'] + copiedtestfiles.handles['fileA2'])
    )
    filestocompare = {frozenset(
        BufferedIOFile(path_handle[0], handle=path_handle[1]) for path_handle in pathsandhandles
    )}
    identicalfiles = comparefilecontents(filestocompare)
    assert identicalfiles == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA']),
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA2'])
    }

@mark.copyfiles(('fileA',2), ('fileA2',1), ('fileB', 4))
def test_comparefilecontents_filehasnoduplicate(copiedtestfiles, filesopen):
    pathsandhandles = zip(
        (copiedtestfiles.paths['fileA'] + copiedtestfiles.paths['fileA2'] + copiedtestfiles.paths['fileB']),
        (copiedtestfiles.handles['fileA'] + copiedtestfiles.handles['fileA2'] + copiedtestfiles.handles['fileB'])
    )
    filestocompare = {frozenset(
        BufferedIOFile(path_handle[0], handle=path_handle[1]) for path_handle in pathsandhandles
    )}
    identicalfiles = comparefilecontents(filestocompare)
    assert identicalfiles == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA']),
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileB'])
    }

@mark.copyfiles(('fileA',2), ('fileB', 1), ('fileA2', 1))
@mark.linkfiles(('fileA',1))
def test_instantiatefrompath(copiedtestfiles):
    duplicatefiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert any((
        duplicatefiles.duplicates == {frozenset((
                                BufferedIOFile(copiedtestfiles.paths['fileA'][1]),
                                BufferedIOFile(copiedtestfiles.paths['fileA'][0])
                                ))
                            },
        duplicatefiles.duplicates == {frozenset((
                                BufferedIOFile(copiedtestfiles.paths['fileA'][1]),
                                BufferedIOFile(copiedtestfiles.paths['fileA'][2])
                                ))
                            }
    )), f'Following files identified as duplicates: {duplicatefiles.duplicates}'

@mark.copyfiles(('fileA',2), ('fileA2',1), ('fileB', 4))
def test_instantiatefrompath_multipleduplicatefiles(copiedtestfiles):
    identicalfiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert identicalfiles.duplicates == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA']),
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileB'])
    }

@mark.copyfiles(('fileA',2), ('fileA2',1), ('fileB', 4))
def test_instantiatefrompath_zerosizefile(copiedtestfiles):
    with open(copiedtestfiles.root / Path("file0"), 'w'): pass
    identicalfiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert identicalfiles.duplicates == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA']),
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileB'])
    }

@mark.copyfiles(('fileA',2))
def test_multiplezerosizefiles(copiedtestfiles):
    zerolengthfilepaths = (
        copiedtestfiles.root / Path("file00"),
        copiedtestfiles.root / Path("file01")
    )

    for path in zerolengthfilepaths:
        with open(path, 'w'): pass

    identicalfiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert identicalfiles.duplicates == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileA'])
    }

@mark.copyfiles(('fileA',2))
def test_instantiate_dropsymlinks(copiedtestfiles):
    fileA = copiedtestfiles.paths['fileA'][0]
    symlink = copiedtestfiles.root / Path('linktoA.txt')
    with skipon(OSError, lambda e: e.winerror == 1314, 'SymLinks not available on Windows without DevMode enabled'):
        symlink.symlink_to(fileA)
    duplicatefiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert duplicatefiles.duplicates == {frozenset(path for path in copiedtestfiles.paths['fileA'])}, f'Following files identified as duplicates: {duplicatefiles.duplicates}'

@mark.copyfiles(('fileA',1), ('fileB',2))
@mark.linkfiles(('fileA',2))
def test_somefilesalreadyprocessed(copiedtestfiles):
    identicalfiles = DuplicateFiles.frompaths(copiedtestfiles.root)
    assert identicalfiles.duplicates == {
        frozenset(BufferedIOFile(path) for path in copiedtestfiles.paths['fileB'])
    }

@mark.copyfiles(
    set1 = (('fileA',1), ('fileB',2)),
    set2 = (('fileA2',2), ('fileB',2))
    )
def test_nocommonroot(copiedtestfiles):
    identicalfiles = DuplicateFiles.frompaths(
        copiedtestfiles['set1'].root,
        copiedtestfiles['set2'].root
    )

    fileA2 = frozenset(
        BufferedIOFile(path)
        for path
        in copiedtestfiles['set2'].paths['fileA2']
    )

    fileB = frozenset(
        BufferedIOFile(path)
        for path
        in copiedtestfiles['set1'].paths['fileB'] + copiedtestfiles['set2'].paths['fileB']
    )

    assert identicalfiles.duplicates == {fileA2, fileB}

@mark.copyfiles(
    set1 = (('fileA',1), ('fileB',2)),
    set2 = (('fileA2',2), ('fileB',2))
    )
def test_differentfilesystems(copiedtestfiles):

    class _Path(Path):
        def stat(self):
            @dataclass
            class _fakestat():
                st_dev: int
            return _fakestat(st_dev=uuid1())

    with raises(InvalidFileSystemError):
        _ = DuplicateFiles.frompaths(
            _Path(copiedtestfiles['set1'].root),
            _Path(copiedtestfiles['set2'].root)
        )


from Queue import Queue

class Stack:
    def __init__(self, limit):
        self.q1 = Queue(limit)
        self.q2 = Queue(limit)
        self.limit = limit
        self.curr_size = 0

    def push(self, x):
        self.curr_size += 1
        self.q2.enqueue(x)

        while not self.q1.isEmpty():
            self.q2.enqueue(self.q1.dequeue())
        # swap the names of two queues
        self.q1, self.q2 = self.q2, self.q1

    def pop_(self):
        if (self.q1.isEmpty()):
            print("Stack Underflow")
            return
        self.curr_size -= 1
        return self.q1.dequeue()

    def size(self):
        return self.curr_size

    def display(self):
        print("Stack:")
        for elem in self.q1.queue[::-1]:
            print("\t", elem)

if __name__ == '__main__':
    stack = Stack(3)
    print("POP called:", end="\n\t")
    stack.pop_()
    stack.push(5)
    stack.push(4)
    stack.push(3)
    stack.display()
    print('POP: ', stack.pop_())
    stack.display()

data/Algorithms/Stack using two Queues 1.py


from persistent.dict import PersistentDict
from persistent import Persistent

from zope.schema._field import Choice
from zope.schema._field import Date
from zope.schema import TextLine, Bool
from zope.schema import Int
from zope.location.location import Location
from zope.location.location import locate
from zope.html.field import HtmlFragment
from zope.interface import Interface
from zope.interface import implements
from zope.interface import implementer
from zope.component import adapts
from zope.component import adapter
from zope.container.btree import BTreeContainer
from zope.container.ordered import OrderedContainer
from zope.lifecycleevent.interfaces import IObjectRemovedEvent
from zope.schema.vocabulary import SimpleVocabulary
from zope.schema.vocabulary import SimpleTerm

import z3c.form.field

from schooltool.app.app import InitBase, StartUpBase
from schooltool.app.interfaces import ISchoolToolApplication
from schooltool.basicperson.interfaces import IEnumFieldDescription
from schooltool.basicperson.interfaces import IIntFieldDescription
from schooltool.basicperson.interfaces import IDemographicsFields
from schooltool.basicperson.interfaces import IBasicPerson
from schooltool.basicperson.interfaces import IDemographics
from schooltool.basicperson.interfaces import IFieldDescription
from schooltool.common import SchoolToolMessage as _

class IDemographicsForm(Interface):
    """Interface for fields that are supposed to get stored in person demographics."""

class PersonDemographicsDataContainer(BTreeContainer):
    """Storage for demographics information for all persons."""

class InvalidKeyError(Exception):
    """Key is not in demographics fields."""

class PersonDemographicsData(PersistentDict):
    """Storage for demographics information for a person."""

    def isValidKey(self, key):
        app = ISchoolToolApplication(None)
        demographics_fields = IDemographicsFields(app)
        return key in demographics_fields

    def __repr__(self):
        return '%s: %s' % (
            object.__repr__(self),
            super(PersonDemographicsData, self).__repr__())

    def __setitem__(self, key, v):
        if not self.isValidKey(key):
            raise InvalidKeyError(key)
        super(PersonDemographicsData, self).__setitem__(key, v)

    def __getitem__(self, key):
        if key not in self and self.isValidKey(key):
            self[key] = None
        return super(PersonDemographicsData, self).__getitem__(key)

@adapter(IBasicPerson)
@implementer(IDemographics)
def getPersonDemographics(person):
    app = ISchoolToolApplication(None)
    pdc = app['schooltool.basicperson.demographics_data']
    demographics = pdc.get(person.username, None)
    if demographics is None:
        pdc[person.username] = demographics = PersonDemographicsData()
    return demographics

@adapter(IBasicPerson, IObjectRemovedEvent)
def removePersonDemographicsSubscriber(person, event):
    app = ISchoolToolApplication(None)
    pdc = app['schooltool.basicperson.demographics_data']
    demographics = pdc.get(person.username, None)
    if demographics is not None:
        del pdc[person.username]

class DemographicsFormAdapter(object):
    implements(IDemographicsForm)
    adapts(IBasicPerson)

    def __init__(self, context):
        self.__dict__['context'] = context
        self.__dict__['demographics'] = IDemographics(self.context)

    def __setattr__(self, name, value):
        self.demographics[name] = value

    def __getattr__(self, name):
        return self.demographics.get(name, None)

class DemographicsFields(OrderedContainer):
    implements(IDemographicsFields)

    def filter_key(self, key):
        """Return the subset of fields whose limited_keys list is either
           empty, or it contains the key passed."""
        result = []
        for field in self.values():
            if not field.limit_keys or key in field.limit_keys:
                result.append(field)
        return result

    def filter_keys(self, keys):
        """Return the subset of fields whose limited_keys list is either
           empty, or it contains one of the keys passed."""
        result = []
        for field in self.values():
            limit_keys = field.limit_keys
            if not limit_keys or [key for key in keys if key in limit_keys]:
                result.append(field)
        return result

def setUpDefaultDemographics(app):
    dfs = DemographicsFields()
    app['schooltool.basicperson.demographics_fields'] = dfs
    locate(dfs, app, 'schooltool.basicperson.demographics_fields')
    dfs['ID'] = TextFieldDescription('ID', _('ID'))
    dfs['ethnicity'] = EnumFieldDescription('ethnicity', _('Ethnicity'))
    dfs['ethnicity'].items = [_('American Indian or Alaska Native'),
                              _('Asian'),
                              _('Black or African American'),
                              _('Native Hawaiian or Other Pacific Islander'),
                              _('White')]
    dfs['language'] = TextFieldDescription('language', _('Language'))
    dfs['placeofbirth'] = TextFieldDescription('placeofbirth', _('Place of birth'))
    dfs['citizenship'] = TextFieldDescription('citizenship', _('Citizenship'))

class DemographicsAppStartup(StartUpBase):
    def __call__(self):
        if 'schooltool.basicperson.demographics_fields' not in self.app:
            setUpDefaultDemographics(self.app)
        if 'schooltool.basicperson.demographics_data' not in self.app:
            self.app['schooltool.basicperson.demographics_data'] = PersonDemographicsDataContainer()

class DemographicsInit(InitBase):
    def __call__(self):
        setUpDefaultDemographics(self.app)
        self.app['schooltool.basicperson.demographics_data'] = PersonDemographicsDataContainer()

@implementer(IDemographicsFields)
@adapter(ISchoolToolApplication)
def getDemographicsFields(app):
    return app['schooltool.basicperson.demographics_fields']

class FieldDescription(Persistent, Location):
    implements(IFieldDescription)
    limit_keys = []
    description = None

    def __init__(self, name, title, required=False, limit_keys=[],
                 description=None):
        self.name, self.title, self.required, self.limit_keys = (name,
            title, required, limit_keys)
        self.description = description

    def setUpField(self, form_field):
        form_field.description = self.description
        form_field.required = self.required
        form_field.__name__ = str(self.__name__)
        form_field.interface = IDemographicsForm
        return z3c.form.field.Fields(form_field)

# XXX: IMHO all IDNA conversions should be replaced by punycode.
#      64 max length limitation simply breaks things too often.
class IDNAVocabulary(SimpleVocabulary):

    def createTerm(cls, *args):
        """Create a single term from data.

        Encode the value using idna encoding so it would look sane in
        the form if it's ascii, but still work if it uses unicode.
        """
        value = args[0]
        token = value.encode('idna')
        title = value
        return SimpleTerm(value, token, title)
    createTerm = classmethod(createTerm)

class EnumFieldDescription(FieldDescription):
    implements(IEnumFieldDescription)

    items = []

    def makeField(self):
        return self.setUpField(Choice(
                title=unicode(self.title),
                vocabulary=IDNAVocabulary.fromValues(self.items)
                ))

class DateFieldDescription(FieldDescription):

    def makeField(self):
        return self.setUpField(Date(title=unicode(self.title)))

class TextFieldDescription(FieldDescription):

    def makeField(self):
        return self.setUpField(TextLine(title=unicode(self.title)))

class BoolFieldDescription(FieldDescription):

    def makeField(self):
        return self.setUpField(Bool(title=unicode(self.title)))

class DescriptionFieldDescription(FieldDescription):

    def makeField(self):
        return self.setUpField(HtmlFragment(title=unicode(self.title)))

class IntFieldDescription(FieldDescription):

    implements(IIntFieldDescription)

    min_value = None
    max_value = None

    def makeField(self):
        return self.setUpField(Int(title=unicode(self.title),
                                   min=self.min_value,
                                   max=self.max_value))


from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import telebot
import tzlocal
from settings import BOT_TOKEN, KIDS_GROUP_ID, CONVERSATION_LINK

logging.basicConfig(
    format='%(asctime)s [%(levelname)s] %(message)s',
    level=logging.INFO
)
schedule = BlockingScheduler(timezone=str(tzlocal.get_localzone()))
bot = telebot.TeleBot(BOT_TOKEN)

def instant_message(msg, *args, **kwargs):
    bot.send_message(KIDS_GROUP_ID, msg, *args, **kwargs)
    logging.info(f"Sent instant message '{msg}'")

def first_reminder():
    bot.send_message(
        KIDS_GROUP_ID,
        "*Доброго ранку, друзі\!*\n\n"
        "За 15 хв почнеться наше заняття 👩💻",
        parse_mode="MarkdownV2"
    )
    logging.info("Sent first reminder")

def second_reminder():
    bot.send_message(
        KIDS_GROUP_ID,
        "🔔🔔🔔 Саме час приєднатися до уроку, за 5 хв починаємо\n\n"
        f"[Приєднатися до заняття]({CONVERSATION_LINK})",
        disable_web_page_preview=True,
        parse_mode="MarkdownV2"
    )
    logging.info("Sent second reminder")

def main():
    # instant_message("Доброго ранку! Сподіваюся у всіх все чудово "
    #                 "і побачимося з вами завтра на нашому занятті!")
    schedule.add_job(first_reminder, trigger="cron",
                     day_of_week="Sat", hour=11, minute=15)
    schedule.add_job(second_reminder, trigger="cron",
                     day_of_week="Sat", hour=11, minute=25)
    schedule.start()

if __name__ == "__main__":
    main()


import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import http

_url_re = re.compile(r'''https?://(?:www\.)?teamliquid\.net/video/streams/''')

class Teamliquid(Plugin):
    @classmethod
    def can_handle_url(cls, url):
        return _url_re.match(url)

    def _get_streams(self):
        res = http.get(self.url)

        stream_address_re = re.compile(r'''href\s*=\s*"([^"]+)"\s*>\s*View on''')

        stream_url_match = stream_address_re.search(res.text)
        if stream_url_match:
            stream_url = stream_url_match.group(1)
            self.logger.info("Attempting to play streams from {0}", stream_url)
            return self.session.streams(stream_url)

__plugin__ = Teamliquid


def mix(V,T):
	#V=Volume
	#T=Target Concentration

	tl = 3 #Tolerance
	a = 24 #Stronger Concentration
	b = 5  #Weaker Concentration

	c = a-b #Range
	x = (T-b)/c #Solve
	y = round(V*x,tl) #Amount of a
	z = round(V-y,tl) #Amount of b

	print(f'{V}ml at {T}% strength is:')
	print(f'{y}ml of {a}% acid,')
	print(f'and {z}ml of {b}% vinegar.')

#start
mix(1000,7) #enter desired volume (ml) and concentration (%) here.


import argparse
import sys
import pandas as pd
import numpy as np
import tensorflow as tf

from models import ConvNet_Models
from models import RecurNet_Models
from models import Feed_Forward

from train import Trainer

parser = argparse.ArgumentParser()

# Positional Arguments
parser.add_argument("DATASET_PATH", help="Path to Dataset File (.CSV)", type=str)
parser.add_argument("MODEL", help="Neural Network Model to Train", type=str)
models = ['feed_forward', 'multi_column_cnn', 'simple_rnn', 'bidirectional_rnn', 'vote_multi_column_cnn']

# Optional Arguments
parser.add_argument("--save_model", help="Where to save trained model? Default='model/model.ckpt'", type=str, default='model/model.ckpt')
parser.add_argument("--epochs", help="How many Epochs to train for? Default=10", type=int, default=10)
parser.add_argument("--batch_size", help="What will be the batch Size? Default=128", type=int, default=128)
parser.add_argument("--learning_rate", help="What will be the Learning rate? Default = 0.001", type=float, default=0.001)
parser.add_argument("--feed_forward_architecture", help="If training Feed Forward Network, what will be the Architecture? Specify Number of neurons in each hidden layer EX: [500,500,500]", default="[500,500,500]")

args = parser.parse_args()

if not args.DATASET_PATH or not (args.DATASET_PATH.endswith(".csv")):
    print("No Dataset To Train or Invalid Dataset File!")
    print("'python3 main.py -h' for help")
    sys.exit()
if not args.MODEL or not(args.MODEL in models):
    print("Invalid Model to Train")
    print("USAGE:", models)
    sys.exit()

dataset_path = args.DATASET_PATH
model_to_train = args.MODEL

path_to_save_model = args.save_model
total_epochs = args.epochs
batch_size = args.batch_size
learning_rate = args.learning_rate
architecture = args.feed_forward_architecture

def read_data(dataset_path):
    data = pd.read_csv(dataset_path)
    data = data.values
    values = list(data[:,0])

    labels = []
    for val in values:
        one_hot = np.zeros(10)
        one_hot[val] += 1
        labels.append(np.asarray(one_hot, np.float32))

    images = []
    for val in data:
        images.append(np.asarray(val[1:], np.float32))

    return images, labels

images, labels = read_data(dataset_path)

if model_to_train in ["multi_column_cnn", "vote_multi_column_cnn"]:
    img_w = 28
    img_h = 28
    no_classes = 10
    channels = 1

    x = tf.placeholder("float", [None, img_w, img_h, channels])
    y = tf.placeholder("float", [None, no_classes])

    if model_to_train == "multi_column_cnn":
        model_to_train = ConvNet_Models.Multi_Column_DeepNet()
    else:
        model_to_train = ConvNet_Models.Vote_Multi_Column_DeepNet()

    size = [-1, img_h, img_w, channels]

elif model_to_train in ['simple_rnn', 'bidirectional_rnn']:
    hidden_features = 512
    no_classes = 10
    timesteps = 28
    input_size = 28

    x = tf.placeholder("float", [None, timesteps, input_size])
    y = tf.placeholder("float", [None, no_classes])

    if model_to_train == "simple_rnn":
        model_to_train = RecurNet_Models.Simple_RNN(hidden_features=hidden_features, no_classes=no_classes,
                                                    timesteps=timesteps)
    else:
        model_to_train = RecurNet_Models.Bidirectional_RNN(hidden_features=hidden_features, no_classes=no_classes,
                                                    timesteps=timesteps)

    size = [-1, timesteps, input_size]

elif model_to_train == "feed_forward":
    architecture = architecture.replace("[", '')
    architecture = architecture.replace("]", '')
    architecture = architecture.split(',')

    input_size = 784
    no_classes = 10

    architecture = [int(x) for x in architecture]

    architecture = [784] + architecture + [10]

    size = [-1, input_size]

    x = tf.placeholder("float", [None, input_size])
    y = tf.placeholder("float", [None, no_classes])

    model_to_train = Feed_Forward.Feed_Forward(architecture)

images = np.reshape(images, size)

trainer = Trainer(x, y)

trainer.train_network(x, dataset=[images, labels], model=model_to_train.model,
            learning_rate=learning_rate, save_model_path=path_to_save_model,
            total_epochs=total_epochs, batch_size=batch_size)

#


'''
Calculation files in VASP
'''

from logging import getLogger
import os

from ...IO import read_input as rin

logger = getLogger('cryspy')

def check_input_vasp():
    # ---------- prepare rin.jobfile, POTCAR, INCAR
    calc_inputs = [rin.jobfile, 'POTCAR', 'INCAR']

    # ------ check required files
    for f in calc_inputs:
        if f == 'INCAR':
            fincars = ['INCAR_{}'.format(i) for i in range(1, rin.nstage+1)]
            for ff in fincars:
                if not os.path.isfile('./calc_in/' + ff):
                    logger.error('Could not find ./calc_in/' + ff)
                    raise SystemExit(1)
        else:
            if not os.path.isfile('./calc_in/' + f):
                logger.error('Could not find ./calc_in/' + f)
                raise SystemExit(1)


#Program to multiply two matrices using nested loops
"Computer Programming Tutor_May 20,2021"

#3#3 Matrix A
a = [ [1,2,3],
      [4,5,6],
      [7,8,9]
    ]
#3x3 Matrix B

b = [ [1,2,1],
      [2,4,6],
      [7,2,5]
    ]
#Results is also a 3x3 Matrix C
Matoutput = [ [0,0,0],
              [0,0,0],
              [0,0,0]
              ]
# Multiplying Matrix a by Matrix b
# Iteration through rows of Matrix a
for m in range(len(a)):
    #iteration through columns of Matrix b
    for n in range(len(b[0])):
        #Iteration through rows of Matrix b
        for k in range(len(b)):
            Matoutput[m][n] +=a[m][k]*b[k][n]
for z in Matoutput:
    print(z)

2021-05-21_Python_Program to multiply two matrices using nested loops.py


from django.core.management.base import BaseCommand, CommandError

from main.models import Publication
from collections import defaultdict
import pandas as pd

class Command(BaseCommand):
    help = 'Adds the bio.tools to the publications model'

    def add_arguments(self, parser):
        parser.add_argument('biotoolsid2pmid', default=None)

    def handle(self, *args, **options):
        try:
            biotoolsid2pmid = options['biotoolsid2pmid']
        except:
            raise CommandError('Please provide an biotoolsid2pmid csv')

        df = pd.read_csv(biotoolsid2pmid, sep='\t', names = ["biotoolsID","pmid"])
        pmid2biotoolsid = dict(zip(list(df.pmid), list(df.biotoolsID)))

        to_update = []
        for pub in Publication.objects.all():
            if pmid2biotoolsid:
                if pub.pubmed_id in pmid2biotoolsid:
                    pub.biotools_id = pmid2biotoolsid[pub.pubmed_id]
                    to_update.append(pub)

        Publication.objects.bulk_update(to_update, ["biotools_id"])

        self.stdout.write(self.style.SUCCESS(f'Updated {len(to_update)} publications'))


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

import logging

def get_logger():
    # 设置logger等级
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    # 设置文件流和标准输出流stream
    fh = logging.FileHandler('logger2')
    sh = logging.StreamHandler()
    # 设置文件流的消息格式
    fm = logging.Formatter("%(asctime)s [%(lineno)s] %(message)s")
    fh.setFormatter(fm)
    logger.addHandler(fh)
    # 设置标准输出的消息格式
    sh.setFormatter(fm)
    logger.addHandler(sh)
    return logger

logger = get_logger()
logger.info('info message')
logger.debug('debug message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critial message')

python基础/第三方模块/logging模块/test_如何配置logger可以同时写文件和控制台显示.py

test_如何配置logger可以同时写文件和控制台显示.py


"""
 * Project name(项目名称)：Python函数可变参数
 * Package(包名):
 * File(文件名): test1
 * Author(作者）: mao
 * Author QQ：1296193245
 * GitHub：https://github.com/maomao124/
 * Date(创建日期)： 2022/3/25
 * Time(创建时间)： 20:19
 * Version(版本): 1.0
 * Description(描述)：
 """

def f1(*num):
    """
    累加
    :param num:
    :return:
    """
    max1 = 0
    for i in num:
        max1 = max1 + i
    return max1

def f2(data, *num):
    """
    累加
    :param data:
    :param num:
    :return:
    """
    max1 = 0
    for i in num:
        max1 = max1 + i
    return max1 * data

def f3(first, last, **user_info):
    profile = {'first_name': first, 'last_name': last}
    for key, value in user_info.items():
        profile[key] = value
    return profile

if __name__ == '__main__':
    print(f1(1, 2))
    print(f1(1, 2, 5, 6))
    print(f1(1))
    print(f1(1, 2, -3))
    print(f1(1, 2, 7, 8, 9, 3, 1, 7))

    # 函数接收任意数量的非关键字实参
    # 如果函数参数中既要接收已知数量的实参，又要接收任意数量的实参，则必须遵循一个原则，即将接纳任意数量实参的形参放在最后。
    print(f2(3))
    print(f2(2, 1, 1))
    print(f2(2, 4, 5, 3))

    # 函数接收任意数量的关键字实参
    # 如果在调用函数时是以关键字参数的形式传入实参，且数量未知，则需要使函数能够接收任意数量的键值对参数。
    print(f3('albert', 'einstein', location='princeton', field='physics'))


import time

class bankAccount:
    def __init__(self, strName):
        self.name = strName
        self.balance = 0

    def withdraw(self,flAmount):
        if self.balance >= flAmount:
            self.balance -= flAmount
            print("You have withdrawn ${0: .2f} from {1}".format(flAmount, self.name))
        else:
            print("You are broke")

    def deposit(self,flAmount):
        self.balance += flAmount
        print("You have deposited ${0: .2f} into {1}".format(flAmount, self.name))

    def ckBalance(self):
        print("You have ${0: .2f} in {1}".format(self.balance, self.name))

class savingsAcct(bankAccount):
    def __init__(self, strName):
        super().__init__(strName)
        print("You have created savings account: {0}".format(self.name))

class checkingAcct(bankAccount):
    def __init__(self, strName):
        super().__init__(strName)
        print("You have created checking account: {0}".format(self.name))
        self.checkNumber = 1000

    def writeCheck(self, flAmount):
        if self.balance >= flAmount:
            self.balance -= flAmount
            print("You have written a check #{0} ${1: .2f} from {2}".format(self.checkNumber, flAmount, self.name))
            self.checkNumber += 1
        else:
            print("You are broke")

def mainMenu():
    print("$"*80)
    print("$$","  Moseley Bank  ".center(74),"$$")
    print("$"*80)
    print("What do you want to do?")
    print("1. Deposit Money")
    print("2. Withdraw")
    print("3. Write a Check")
    print("4. Check Balance")
    print("5. Add an Account")
    print("6. To exit")
    strTmp = input("Enter Choice Here:")
    return strTmp

def showAccounts(lisAccounts):
    intIndex = 1
    for account in lisAccounts:
        str1 = str(intIndex).ljust(5)
        str2 = str(account.name).ljust(30, ".")
        str3 = "${0}: .2f".format(account.balance).rjust(20, ".")
        print(str1, str2, str3)
        intIndex += 1

def pressEnter():
    input("\nPress Enter/Return to continue...")
    print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n")

def createAccount(lisAccounts):
    strAccountType = input("Do you want a (1) Checking or (2) Savings account? ")
    strAcctName = input("What should the account be called? ")
    if strAccountType == "1":
        lisAccounts.append(checkingAcct(strAcctName))
    elif strAccountType == "2":
        lisAccounts.append(savingsAcct(strAcctName))
    else:
        print("That is not a valid choice")
    showAccounts(lisAccounts)
    return lisAccounts

def makeDeposit(lisAccounts):
    showAccounts(lisAccounts)
    strAccount = input("Which account?")
    strAmount = input("How much?")
    if strAccount.isnumeric() and int (strAccount) <= len(lisAccounts):
        intIndex = int(strAccount) - 1
        lisAccounts[intIndex].deposit(float(strAmount))

def makeWithdraw(lisAccounts):
    showAccounts(lisAccounts)
    strAccount = input("Which account?")
    strAmount = input("How much?")
    if strAccount.isnumeric() and int (strAccount) >= len(lisAccounts):
        intIndex = int(strAccount) - 1
        lisAccounts[intIndex].withdraw(float(strAmount))

def writeChecks(lisAccounts):
    showAccounts(lisAccounts)
    strAccount = input("Which account?")
    strAmount = input("How much?")
    if strAccount.isnumeric() and int (strAccount) >= len(lisAccounts):
        intIndex = int(strAccount) - 1
        lisAccounts[intIndex].writeCheck(float(strAmount))

lisAccounts = []
lisAccounts.append(savingsAcct("Main savings"))
lisAccounts.append(savingsAcct("Main checking"))

while True:
    strMenu = mainMenu()
    if strMenu == "1":
        print("Make a deposit")
        makeDeposit(lisAccounts)
    elif strMenu == "2":
        print("Make a withdrawal")
        makeWithdraw(lisAccounts)
    elif strMenu == "3":
        print("Write a Check")
        writeChecks(lisAccounts)
    elif strMenu == "4":
        print("Check Balances")
        showAccounts(lisAccounts)
    elif strMenu == "5":
        print("Add an Account")
        lisAccounts = createAccount(lisAccounts)
    elif strMenu == "6":
        break
    else:
        print("invalid entry")
        pressEnter()


# IMPORTS
import json
#Read Json
with open('account.json', 'r') as acc1:
    acc = json.load(acc1)

# Input Part and Reading commands
#Get Name
if acc["name"] == "":
    acc["name"] = input("--Please, enter your name:  ")
    with open('account.json', 'w') as acc2:
        json.dump(acc, acc2)
else:
    pass
print(f"--Welcome, {acc['name']}.")
#Get Observation Type
a = input("--[statistics] (1) or [probability] (2)?:  ")
if a=="statistics" or a=="1":
    from statistics_lib.operations import observType
    x = input(f"--Select observation type - {list(observType.keys())}:  ")
    className = observType[x]
    runnerObj = className()
    runnerObj.get_output()
elif a=="probability" or a=="2":
    from probability_lib.operations import distType
    x = input(f"--Select distribution type - {list(distType.keys())}:  ")
    className = distType[x]
    runnerObj = className()
    runnerObj.get_output()
else:
    raise ImportError("You should import correct library!")


import numpy as np
import librosa
import soundfile
import os
import json
import tqdm
import sys

pause_threshold=float(sys.argv[1])

base_path='/home/german/Documentos/Trust/First_Impressions_Dataset/OCEAN_new_structure/'
out_path=base_path+'data/audio_IPU_'+str(pause_threshold)+'/'

if not os.path.exists(out_path):
    os.makedirs(out_path)

with open (base_path+'experiments/audio_lists/all_audio_complete_set.txt') as filename:
    list=filename.read().splitlines()

for file in tqdm.tqdm(list):

    parent_path=out_path+'/'+file.split('/')[0]

    if not os.path.exists(parent_path):
        os.mkdir(parent_path)

    with open (base_path+'data/JSON/'+file+'.JSON') as jsonfile:
        dict=json.load(jsonfile)

    y,fs=librosa.core.load(base_path+'data/audio/'+file+'.wav', sr=None)

    IPU=pause_threshold*fs

    final=np.array([])
    n_segment=0
    n_sub_segment=1

    if 'words' in dict:

        # Creo lista con las palabras reconocidas

        words=[x for x in dict['words'] if 'start' in x.keys()]

        for i in range(len(words)-1):

            start=int(words[i]['start']*fs)
            end=int(words[i]['end']*fs)

            speech=y[start:end]

            pause_end=int(words[i+1]['start']*fs)
            pause_init=int(words[i]['end']*fs)

            no_speech=y[pause_init:pause_end]

            pause_duration=pause_end-pause_init

            if pause_duration < IPU:

                segment=np.append(speech,no_speech)
                final=np.append(final,segment)
                n_sub_segment+=1

            else:
                if n_sub_segment==1:
                    final=speech

                n_segment+=1
                soundfile.write(out_path+'%s_%d.wav'% (file,n_segment),final,fs)

                final=np.array([])
                n_sub_segment=1


import json
from urllib.parse import urlparse

try:
    from json.decoder import JSONDecodeError
except ImportError:
    # json decoder in Python3.4 raises ValueError on invalid json
    JSONDecodeError = ValueError
import logging
import sys
from os import getenv, environ
from socket import gaierror, timeout

from h2.exceptions import ProtocolError
from hypertemp import HTTP20Connection
from hypertemp.http20.exceptions import StreamResetError

from ssl import SSLError

log = logging.getLogger(__name__)

class MaxNumberOfRequestsError(Exception):
    """Thrown when remote peer closes the connection because
    maximum number of requests were served through a single connection.
    """

class Http2Client(object):
    """Base class for an http2 client."""
    _no_conn_err = "No connection with server, call reconnect_to_server()"

    def __init__(self, server_url):
        self._server_url = getenv('ORANGE_EMBEDDING_API_URL', server_url)
        self._server_connection = self._connect_to_server()
        self._max_concurrent_streams = self._read_max_concurrent_streams()

    def reconnect_to_server(self):
        self.disconnect_from_server()
        self._server_connection = self._connect_to_server()
        self._max_concurrent_streams = self._read_max_concurrent_streams()
        return self.is_connected_to_server()

    def disconnect_from_server(self):
        if self._server_connection:
            try:
                self._server_connection.close()
            except (ConnectionError, SSLError):
                log.error("Error when disconnecting from server", exc_info=True)

        self._server_connection = None
        self._max_concurrent_streams = None

    def _connect_to_server(self):
        host = port = proxy = None
        if "http_proxy" in environ:
            proxy = environ["http_proxy"]
        elif "https_proxy" in environ:
            proxy = environ["https_proxy"]
        if proxy is not None:
            url = urlparse(proxy)
            host = url.hostname
            port = url.port
        return HTTP20Connection(host=self._server_url, force_proto='h2',
                                proxy_host=host, proxy_port=port)

    def _read_max_concurrent_streams(self):
        if not self._server_ping_successful():
            return None

        # pylint: disable=protected-access
        max_concurrent_streams = (self._server_connection._conn._obj
                                  .remote_settings.max_concurrent_streams)

        if not max_concurrent_streams <= sys.maxsize:
            return 1

        return max_concurrent_streams

    def is_connected_to_server(self):
        if not self._server_connection:
            return False
        if not self._max_concurrent_streams:
            return False
        return self._server_ping_successful()

    def _server_ping_successful(self):
        try:
            self._server_connection.ping(bytes(8))
        except (OSError, TimeoutError, ConnectionError, gaierror, timeout):
            log.error("Remote server not reachable", exc_info=True)
            return False
        return True

    def _send_request(self, method, url, headers, body_bytes):
        if not self._server_connection or not self._max_concurrent_streams:
            raise ConnectionError(self._no_conn_err)

        try:
            return self._server_connection.request(
                method=method,
                url=url,
                body=body_bytes,
                headers=headers
            )
        except (ConnectionError, BrokenPipeError) as error:
            self.disconnect_from_server()
            log.error("Request sending failed")
            raise error

    def _get_json_response_or_none(self, stream_id):
        if not self._server_connection or not self._max_concurrent_streams:
            raise ConnectionError(self._no_conn_err)

        try:
            response_raw = self._server_connection.get_response(stream_id)
            response_txt = response_raw.read().decode()
            return json.loads(response_txt)

        except JSONDecodeError:
            log.warning("Response skipped (not valid json)", exc_info=True)
            return None

        except StreamResetError:
            log.warning(
                "Response skipped (request didn't reach the server "
                "or was malformed)",
                exc_info=True)
            return None

        except ProtocolError:
            error = MaxNumberOfRequestsError(
                "Maximum number of http2 requests through a single "
                "connection exceeded")
            log.warning(error, exc_info=True)
            raise error

        except OSError:
            self.disconnect_from_server()
            error = ConnectionError("Response receiving failed")
            log.error(error, exc_info=True)
            raise error