import os
import sys
import pandas as pd

def obtain_time_taken_for_plot(scale, partition, log_level):
    output_dir = f"../deepola/wake/outputs/scale={scale}/partition={partition}"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    result = []
    for query_no in range(1,23):
        try:
            log_file = open(f'../deepola/wake/logs/scale={scale}/partition={partition}/q{query_no}-{log_level}.log','r').readlines()
        except:
            continue
        for l in log_file:
            if "Query Took" in l:
                result.append({
                    'query_no': f'q{query_no}',
                    'time': float(l.strip().split(':')[-1].strip()[:-1])
                })
    df = pd.DataFrame(result)
    print(f"Wrote to file: {output_dir}/result.csv")
    df.to_csv(f"{output_dir}/result.csv", index=False)
    return df

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python3 obtain-time-taken.py <scale=50> <partition=512M>")
        exit(1)
    scale = sys.argv[1]
    partition = sys.argv[2]
    log_level = sys.argv[3]
    print(obtain_time_taken_for_plot(scale,partition,log_level))


import os

import pandas as pd

# Helpers for configuration files
from polite.appdirs import site_data_dir
from polite.paths import Directory
from polite.configuration import ReadINI

DIR_PATH = os.path.dirname(__file__)

def get_root_configuration(root_config_name="install.ini"):

    """Pick the necessary paths to configure the external files for the wave
    and tidal packages."""

    # Get the root path from the site data path.
    root_config_dir = site_data_dir("DTOcean Installation", "DTOcean")
    configdir = Directory(root_config_dir)

    ini_reader = ReadINI(configdir, root_config_name)
    config = ini_reader.get_config()

    return config

def get_include_path():

    root_config = get_root_configuration()
    root_path = root_config["InstallSettings"]["InstallPath"]
    include_path = root_config["InstallSettings"]["IncludePath"]

    full_path = os.path.join(root_path, include_path)

    return full_path

def get_operations_template(template_name="operations_time_OLC.xlsx"):

    template_path = os.path.join(DIR_PATH, "config", template_name)
    template_df = pd.read_excel(template_path)

    return template_df


from django import forms

from .models import Vendor, Demand, DemandForcast

class VendorForm(forms.ModelForm):
    # order   = forms.IntegerField(widget=forms.TextInput())
    class Meta:
        model = Vendor
        fields = [
            'monthly_order'
]

class DemandForm(forms.ModelForm):
	class Meta:
		model=Demand
		fields = [
			'new_style',
			'new_flavour',
			'discount',
			'marketing',
		]

class ForcastForm(forms.ModelForm):
	class Meta:
		model=DemandForcast
		fields = [
		'demand_forcast'

		]


''' Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2. For 3 ≤
a ≤ 1000, find ∑r_max '''

def main():
    ''' Brute-force '''
    total = 0
    for a in range(3, 1001):
        r_max = 0
        for n in range(1, a*2):
            r_max = max(r_max, (pow(a-1, n, a*a) + pow(a+1, n, a*a)) % (a*a))
        total += r_max
    print(total)

if __name__ == "__main__":
    main()


import random
import os
import cv2
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import albumentations as A
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from albumentations.pytorch import ToTensorV2

from Training.configurations import BATCH_SIZE, DATAPATH, DEVICE, SEED
from Training.path_constants import PROCESSED_DATA
from Training.dataset import ImageFolder

TRANSFORM = A.Compose([
    A.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225], max_pixel_value = 255,),
    ToTensorV2()
])
# Apply the SEED
def seed_all(SEED_VALUE = SEED):
    random.seed(SEED_VALUE)
    os.environ['PYTHONHASHSEED'] = str(SEED_VALUE)
    np.random.seed(SEED_VALUE)
    torch.manual_seed(SEED_VALUE)
    torch.cuda.manual_seed(SEED_VALUE)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = True

def get_data_loaders(data_path = DATAPATH):
    df = pd.read_csv(data_path)
    train_data, test_data  = train_test_split(df, test_size = 0.2, random_state = SEED, stratify = df.hasTable)
    train_dataset = ImageFolder(train_data, isTrain = True, transform = None)
    test_dataset = ImageFolder(test_data, isTrain = False, transform = None)
    train_loader =  DataLoader(train_dataset, batch_size = BATCH_SIZE, shuffle = True, num_workers = 4, pin_memory = True)
    test_loader =  DataLoader(test_dataset, batch_size = 8, shuffle = False, num_workers = 4, pin_memory = True)
    return train_loader, test_loader

# Save Checkpoint
def save_checkpoint(state, filename = f"{PROCESSED_DATA}/model_checkpoint.pth.tar"):
    torch.save(state, filename)
    print("Checkpoint Saved at: ", filename)

# Load the checkpoint we saved
def load_checkpoint(checkpoint, model, optimizer = None):
    print("Loading checkpoint...")
    model.load_state_dict(checkpoint['state_dict'])
    if optimizer is not None:
        optimizer.load_state_dict(checkpoint['optimizer'])
    last_epoch = checkpoint['epoch']
    tr_metrics = checkpoint['train_metrics']
    te_metrics = checkpoint['test_metrics']
    return last_epoch, tr_metrics, te_metrics

def write_summary(writer, tr_metrics, te_metrics, epoch):
    writer.add_scalar("Table Loss/Train", tr_metrics['table_loss'], global_step = epoch)
    writer.add_scalar("Table Loss/Test", te_metrics['table_loss'], global_step = epoch)
    writer.add_scalar("Table Acc/Train", tr_metrics['table_acc'], global_step = epoch)
    writer.add_scalar("Table Acc/Test", te_metrics['table_acc'], global_step = epoch)
    writer.add_scalar("Table F1/Train", tr_metrics['table_f1'], global_step = epoch)
    writer.add_scalar("Table F1/Test", te_metrics['table_f1'], global_step = epoch)
    writer.add_scalar("Table Precision/Train", tr_metrics['table_precision'], global_step = epoch)
    writer.add_scalar("Table Precision/Test", te_metrics['table_precision'], global_step = epoch)
    writer.add_scalar("Table Recall/Train", tr_metrics['table_recall'], global_step = epoch)
    writer.add_scalar("Table Recall/Test", te_metrics['table_recall'], global_step = epoch)
    writer.add_scalar("Column Loss/Train", tr_metrics['column_loss'], global_step = epoch)
    writer.add_scalar("Column Loss/Test", te_metrics['column_loss'], global_step = epoch)
    writer.add_scalar("Column Acc/Train", tr_metrics['col_acc'], global_step = epoch)
    writer.add_scalar("Column Acc/Test", te_metrics['col_acc'], global_step = epoch)
    writer.add_scalar("Column F1/Train", tr_metrics['col_f1'], global_step = epoch)
    writer.add_scalar("Column F1/Test", te_metrics['col_f1'], global_step = epoch)
    writer.add_scalar("Column Precision/Train", tr_metrics['col_precision'], global_step = epoch)
    writer.add_scalar("Column Precision/Test", te_metrics['col_precision'], global_step = epoch)
    writer.add_scalar("Column Recall/Train", tr_metrics['col_recall'], global_step = epoch)
    writer.add_scalar("Column Recall/Test", te_metrics['col_recall'], global_step = epoch)

def display_metrics(epoch, tr_metrics, te_metrics):
    print(f"Epoch: {epoch} \n\
        Table Loss -- Train: {tr_metrics['table_loss']:.3f} Test: {te_metrics['table_loss']:.3f}\n\
        Table Acc -- Train: {tr_metrics['table_acc']:.3f} Test: {te_metrics['table_acc']:.3f}\n\
        Table F1 -- Train: {tr_metrics['table_f1']:.3f} Test: {te_metrics['table_f1']:.3f}\n\
        Table Precision -- Train: {tr_metrics['table_precision']:.3f} Test: {te_metrics['table_precision']:.3f}\n\
        Table Recall -- Train: {tr_metrics['table_recall']:.3f} Test: {te_metrics['table_recall']:.3f}\n\
        \n\
        Col Loss -- Train: {tr_metrics['column_loss']:.3f} Test: {te_metrics['column_loss']:.3f}\n\
        Col Acc -- Train: {tr_metrics['col_acc']:.3f} Test: {te_metrics['col_acc']:.3f}\n\
        Col F1 -- Train: {tr_metrics['col_f1']:.3f} Test: {te_metrics['col_f1']:.3f}\n\
        Col Precision -- Train: {tr_metrics['col_precision']:.3f} Test: {te_metrics['col_precision']:.3f}\n\
        Col Recall -- Train: {tr_metrics['col_recall']:.3f} Test: {te_metrics['col_recall']:.3f}\n"
    )

def compute_metrics(ground_truth, prediction, threshold = 0.5):
    # Ref: https://stackoverflow.com/a/56649983
    ground_truth = ground_truth.int()
    prediction = (torch.sigmoid(prediction) > threshold).int()
    TP = torch.sum(prediction[ground_truth == 1] == 1)
    TN = torch.sum(prediction[ground_truth == 0] == 0)
    FP = torch.sum(prediction[ground_truth == 1] == 0)
    FN = torch.sum(prediction[ground_truth == 0] == 1)
    acc = (TP + TN) / (TP + TN + FP+ FN)
    precision = TP / (FP + TP + 1e-4)
    recall = TP / (FN + TP + 1e-4)
    f1 = 2 * precision * recall / (precision + recall + 1e-4)
    metrics = {
        'acc': acc.item(),
        'f1': f1.item(),
        'precision':precision.item(),
        'recall': recall.item()
    }
    return metrics

def display(image, table, column, title = 'Original'):
    f, ax  = plt.subplots(1, 3, figsize = (15, 8))
    ax[0].imshow(image)
    ax[0].set_title(f'{title} Image')
    ax[1].imshow(table)
    ax[1].set_title(f'{title} Table Mask')
    ax[2].imshow(column)
    ax[2].set_title(f'{title} Column Mask')
    plt.show()

def display_prediction(image, table = None, table_image = None, no_: bool = False):
  if no_:
    f1, ax  = plt.subplots(1, 1, figsize = (7, 5))
    ax.imshow(image)
    ax.set_title('Original Image')
    f1.suptitle('No Tables Detected')
  else:
    f2, ax  = plt.subplots(1, 3, figsize = (15, 8))
    ax[0].imshow(image)
    ax[0].set_title('Original Image')
    ax[1].imshow(table)
    ax[1].set_title('Image with Predicted Table')
    ax[2].imshow(table_image)
    ax[2].set_title('Predicted Table Example')
  plt.show()

def get_TableMasks(test_image, model, transform = TRANSFORM, device = DEVICE):
    image = transform(image = test_image)["image"]
    # Get predictions
    model.eval()
    with torch.no_grad():
        image = image.to(device).unsqueeze(0)
        # With torch.cuda.amp.autocast():
        table_out, column_out  = model(image)
        table_out = torch.sigmoid(table_out)
        column_out = torch.sigmoid(column_out)
    # Remove gradients
    table_out = (table_out.cpu().detach().numpy().squeeze(0).transpose(1, 2, 0) > 0.5).astype(int)
    column_out = (column_out.cpu().detach().numpy().squeeze(0).transpose(1, 2, 0) > 0.5).astype(int)
    # Return masks
    return table_out, column_out

def fixMasks(image, table_mask, column_mask):
    """ Fix Table Bounding Box to get better OCR predictions """
    table_mask = table_mask.reshape(1024, 1024).astype(np.uint8)
    column_mask = column_mask.reshape(1024, 1024).astype(np.uint8)
    # Get contours of the mask to get number of tables
    contours, table_heirarchy = cv2.findContours(table_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    table_contours = []
    # Ref: https://www.pyimagesearch.com/2015/02/09/removing-contours-image-using-python-opencv/
    # Remove bad contours
    for c in contours:
        # if the contour is bad, draw it on the mask
        if cv2.contourArea(c) > 2000:
            table_contours.append(c)
    if len(table_contours) == 0:
        return None
    # Ref : https://docs.opencv.org/4.5.2/da/d0c/tutorial_bounding_rects_circles.html
    # Get bounding box for the contour
    table_bound_rect = [None] * len(table_contours)
    for i, c in enumerate(table_contours):
        polygon = cv2.approxPolyDP(c, 3, True)
        table_bound_rect[i] = cv2.boundingRect(polygon)
    # Table bounding Box
    table_bound_rect.sort()
    column_bound_rects = []
    for x, y, w, h in table_bound_rect:
        column_mask_crop = column_mask[y : y + h, x : x + w]
        # Get contours of the mask to get number of tables
        contours, column_heirarchy = cv2.findContours(column_mask_crop, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # Get bounding box for the contour
        bound_rect = [None] * len(contours)
        for i, c in enumerate(contours):
            polygon = cv2.approxPolyDP(c, 3, True)
            bound_rect[i] = cv2.boundingRect(polygon)
            # Adjusting columns as per table coordinates
            bound_rect[i] = (bound_rect[i][0] + x, bound_rect[i][1] + y, bound_rect[i][2], bound_rect[i][3])
        column_bound_rects.append(bound_rect)
    image = image[...,0].reshape(1024, 1024).astype(np.uint8)
    # Draw bounding boxes
    color = (0, 255, 0)
    thickness = 4
    for x, y, w, h in table_bound_rect:
        image = cv2.rectangle(image, (x, y),(x + w, y + h), color, thickness)
    return image, table_bound_rect, column_bound_rects


import argparse

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

import util.io
import util.plot

from plot_results_lprob import get_sim, ed, get_samples_snl
from plot_results_mmd import get_true_samples

def make_plots(samples, sim, sim_name):
    """
    Makes all plots.
    """

    n_dim = samples.shape[1]
    n_bins = int(np.sqrt(samples.shape[0]))
    lims = np.asarray(sim.get_disp_lims())
    lims = np.tile(lims, [n_dim, 1]) if lims.ndim == 1 else lims
    true_ps, _ = sim.get_ground_truth()

    if sim_name == 'hh':
        ii = sim.Model().ps_order_in_plot
        true_ps = true_ps[ii]
        samples = samples[:, ii]
        lims = lims[ii]

    for i in xrange(n_dim):
        for j in xrange(i, n_dim):

            if i == j:

                fig, ax = plt.subplots(1, 1)
                ax.hist(samples[:, i], bins=n_bins, normed=True, rasterized=True)
                ax.set_xlim(lims[i])
                ax.set_ylim([0.0, ax.get_ylim()[1]])
                ax.tick_params(axis='x', which='both', top=False, bottom=False, labelbottom=False)
                ax.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
                ax.vlines(true_ps[i], 0, ax.get_ylim()[1], color='r')

            else:

                fig, ax = plt.subplots(1, 1)
                ax.scatter(samples[:, j], samples[:, i], c='k', s=3, marker='o', cmap='binary', edgecolors='none', rasterized=True)
                ax.tick_params(axis='x', which='both', top=False, bottom=False, labelbottom=False)
                ax.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
                ax.set_xlim(lims[j])
                ax.set_ylim(lims[i])
                ax.scatter(true_ps[j], true_ps[i], c='r', s=12, marker='o', edgecolors='none')

def plot_results(sim_name):
    """
    Plots posterior for a given simulator.
    """

    sim = get_sim(sim_name)

    matplotlib.rc('text', usetex=True)
    matplotlib.rc('font', size=16)

    for exp_desc in ed.parse(util.io.load_txt('exps/{0}_seq.txt'.format(sim_name))):

        if isinstance(exp_desc.inf, ed.SNL_Descriptor):

            samples = get_samples_snl(exp_desc, sim)[-1]
            make_plots(samples, sim, sim_name)

    if sim_name == 'gauss':

        samples = get_true_samples()
        make_plots(samples, sim, sim_name)

    plt.show()

def main():

    parser = argparse.ArgumentParser(description='Plotting the posteriors for SNL.')
    parser.add_argument('sim', type=str, choices=['gauss', 'mg1', 'lv', 'hh'], help='simulator')
    args = parser.parse_args()

    plot_results(args.sim)

if __name__ == '__main__':
    main()


import math

if __name__ == "__main__":
    """
    概要
    最小公倍数を出力する

    解法
    最小公倍数
    A * B = 最大公約数 * 最小公倍数
    最小公倍数 = A * B / 最大公約数
    12 * 18 = 6 * 36

    URL
    https://atcoder.jp/contests/abc148/tasks/abc148_c

    入力例
    2 3

    出力例
    6

    """
    A, B = map(int, input().split())
    gcd = math.gcd(A, B)
    lcm = A * B // gcd
    print(lcm)


import psycopg2
import configparser
import os.path
from psycopg2.extras import Json
from utils.env_config import EnvConfig

def table_exists(con, table_str):

    exists = False
    try:
        cur = con.cursor()
        cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')")
        exists = cur.fetchone()[0]
        if exists:
            columns = get_table_col_names(con, table_str)
            print("Table {} exists with columns: {}".format(table_str, columns))

        cur.close()
    except psycopg2.Error as e:
        print(e)
    return exists

def get_table_col_names(con, table_str):
    col_names = []
    try:
        cur = con.cursor()
        cur.execute("select * from " + table_str + " LIMIT 0")
        for desc in cur.description:
            col_names.append(desc[0])
        cur.close()
    except psycopg2.Error as e:
        print(e)

    return col_names

class GearMoodPS:
    def __init__(self):
        config = EnvConfig()
        try:
            self.conn = psycopg2.connect(
                "dbname='" + config.get_value("DatabaseSection","database.dbname") +
                "' user='" + config.get_value("DatabaseSection","database.user") +
                "' host='" + config.get_value("DatabaseSection","database.host") +
                "' password='" + config.get_value("DatabaseSection","database.password") +"'")
        except:
            print("Unexpected error:")
            raise
        table_exists(self.conn, "shake")
        table_exists(self.conn, "sentence")

    def save_shakedown(self, shakedown):
        cur = self.conn.cursor()
        cur.execute("INSERT INTO shake (submission_id, subreddit_id, title, data) " +
                    "VALUES (%s, %s, %s, %s) " +
                    "ON Conflict (submission_id) DO UPDATE SET data = %s",
                    (shakedown["id"], shakedown["subreddit_id"],
                    shakedown["title"], Json(shakedown), Json(shakedown)))
        #print("Shakedown {} : {}".format(shakedown["title"], "https://www.reddit.com/" + shakedown["id"]))
        self.conn.commit()
        cur.close()

    def get_shakedown(self, submission_id):
        cur = self.conn.cursor()
        sql = "SELECT * FROM shake where submission_id = %s;"
        data = (submission_id, )
        cur.execute(sql,data)
        results = cur.fetchone()
        cur.close()
        return results

    def get_all_shakedowns(self):
        cur = self.conn.cursor()
        cur.execut("SELECT * FROM test;")
        result = cur.fetchall()
        print("result: {}".format(self))
        cur.close()
        return result

    def save_sentence(self, submission_id, cut_sentences):
        cur = self.conn.cursor()
        for cut_sentence in cut_sentences:
            cur.execute("INSERT INTO cut_sentence (submission_id, words, sentence) " +
                        "VALUES (%s, %s, %s)",
                        #"ON Conflict (submission_id) DO UPDATE SET words = %s, sentence = %s",
                        (submission_id, Json(cut_sentence["words"]), cut_sentence["sentence"]))
        self.conn.commit()
        cur.close()

if __name__ == '__main__':
    GearMoodPS()


import streamlit as st

st.title("201921054 임채민")

st.header("201921054 임채민")
st.subheader("과제")
st.text("폐루프 함수=G(s) = 100 / (s^2 + 5s + 6)")

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

s1 = signal.lti([100],[1,5,6])

frequencies = np.logspace(-2,2,500)

w, mag, phase= s1. bode(frequencies)

plt.figure()
plt.subplot(2,1,1)
plt.semilogx(w,mag)
plt.title('Bode plot of G(s)=100/(s+2)(s+3)')
plt.ylabel('Magnitude [dB]')

plt.subplot(2,1,2)
plt.semilogx(w,phase)
plt.ylabel('Phase [degrees]')
plt.xlabel('Frequency [Hz]')

st.pyplot(plt)


import os
import json
import time
from kafka import KafkaConsumer, KafkaProducer

KAFKA_BROKER_URL = os.environ.get('KAFKA_BROKER_URL')
FROM_TOPIC = os.environ.get('FROM_TOPIC')
TO_TOPIC = os.environ.get("TO_TOPIC")
WINDOW_SIZE = os.environ.get("WINDOW_SIZE")
THROTTLE_LIMIT = os.environ.get("THROTTLE_LIMIT_PER_MIN")
METRIC_TOPIC = os.environ.get("METRIC_TOPIC")
METRIC_CYCLE = os.environ.get("METRIC_CYCLE")

sliding_window = {}
blacklist = []

def put_sliding_window(ip_ts: dict):
    """
    Takes a dict of form {"IP": str, "TS": int}
    Puts into a sliding window dict of lists that counts
    the number of timestamps in a certain period. If that
    count exceeds the threshold, the IP address is "blacklisted"
    and added to the blacklist list and the IP is posted to a
    kafka topic called logs.blacklist

    :param ip_ts: dict of form {"IP": str, "TS": ts}
    :return: None if not new blacklisted IP or dict of form
        {
            "IP": str,
            "Req_Per_Min_Exceeded": int
        }
        if the IP address is newly blacklisted
    """
    ip = ip_ts["IP"]
    ts = ip_ts["TS"]

    # If IP is already blacklisted, ignore it
    if ip in blacklist:
        return None

    # IF IP is new, add it to sliding window keys
    if ip not in sliding_window.keys():
        sliding_window[ip] = {'ts': [ts],
                              'count': 1}

    # Otherwise, add timestamp to sliding window
    # And slide the window as necessary, keeping
    # track of count
    else:
        while sliding_window[ip]['ts'] != [] \
                and ts - (int(WINDOW_SIZE)*60) > sliding_window[ip]['ts'][0]:
            del sliding_window[ip]['ts'][0]
            sliding_window[ip]['count'] -= 1
        sliding_window[ip]['ts'].append(ts)
        sliding_window[ip]['count'] += 1

        # If the count exceeds the THROTTLE_LIMIT,
        # return the IP address to be sent to logs.blacklist
        if sliding_window[ip]['count'] \
                >= int(THROTTLE_LIMIT) * int(WINDOW_SIZE):
            blacklist.append(ip)
            return {
                "IP": ip,
                "Req_Per_Min_Exceeded": int(THROTTLE_LIMIT)
            }

    return None

if __name__ == '__main__':
    consumer = KafkaConsumer(
        FROM_TOPIC,
        bootstrap_servers=KAFKA_BROKER_URL,
        value_deserializer=lambda value: json.loads(value),
        consumer_timeout_ms=5000
    )
    producer = KafkaProducer(
        bootstrap_servers=KAFKA_BROKER_URL,
        value_serializer=lambda value: json.dumps(value).encode(),
    )

    # Metric initialization
    count = 0
    blacklisted = 0
    start = time.time()

    for message in consumer:

        # Metric Increments
        count += 1

        # Transform and Publish Data
        transaction: dict = put_sliding_window(message.value)
        if transaction:
            blacklisted += 1
            producer.send(TO_TOPIC, value=transaction)

        # Metric Aggregation
        if count >= int(METRIC_CYCLE):
            metrics = {
                "processed_per_second": count /(time.time() - start),
                "records_processed": count,
                "blacklisted_ips": blacklisted,
                "end_ts": time.time()
            }
            producer.send(METRIC_TOPIC, value=metrics)
            count = 0
            blacklisted = 0
            start = time.time()


n, k, m = input('\nВведіть розмір матриці у форматі n*n: ')
print()
matrix = []
count = 1
for i in range(int(n)):
    matrix_1 = []
    for j in range(int(m)):
        if count != 3:
            matrix_1.append(input(f'Введіть {count}-е слово для матриці: '))
        else:
            matrix_1.append(input(f'Введіть {count}-є слово для матриці: '))
        count += 1
    matrix.append(matrix_1)

print('\nВаша матриця:')
for i in range(int(n)):
    for j in range(int(m)):
        print(matrix[i][j], end=' ')
    print()
input('\nPress ENTER to exit')


from time import sleep
findAlpha = list('abcdefghijklmnopqrstuvwxyz')
for x in range(26):
    findAlpha[x] = findAlpha[x].upper()

class Piece():
    def __init__(self, colour, position):
        self.position = position
        self.colour = colour

    def checkKill(self, dest):  # check if the move is killing a piece of the opponent.
        colour = self.colour
        position = self.position
        src_x = findAlpha.uppercase.index(position[0])
        src_y = position[1]
        self.dest = dest
        dest_x = dest[0]
        dest_y = dest[1]
        if colour == "R":
            if dest_x > src_x:  # check if the destination move is 2 boxes away in the x and y direction
                if dest_x - 2 == src_x and dest_y - 2 == src_y:
                    return True
                else:
                    return False
            elif dest_x < src_x:
                if dest_x + 2 == src_x and dest_y - 2 == src_y:
                    return True
                else:
                    return False
        elif colour == "B":
            if dest_x > src_x:
                if dest_x - 2 == src_x and dest_y + 2 == src_y:
                    return True
                else:
                    return False
            elif dest_x < src_x:
                if dest_x + 2 == src_x and dest_y + 2 == src_y:
                    return True
                else:
                    return False

    def checkLegal(self, dest):  # check if the move being made is a legal move.
        colour = self.colour
        position = self.position
        src_x = findAlpha.uppercase.index(position[0])  # index of letter
        src_y = position[1]
        self.dest = dest
        dest_x = dest[0]
        dest_y = dest[1]
        columnNum = src_x + 1  # cartesian row number
        rowNum = src_y
        if checkKill(dest) == False:
            if colour == "R":
                if columnNum >= 2 and columnNum <= 7:  # check if its in in the center portion of the board
                    for i in [-1, 1]:
                        if type(layout[x + i][y + 1]) != Piece:
                            return True
                        else:
                            return False
                elif columnNum == 1:  # check if its on left/right edges
                    if type(layout[x + 1][y + 1]) != Piece:
                        return True
                    else:
                        return False
                elif columnNum == 8:
                    if type(layout[x - 1][y + 1]) != Piece:
                        return True
                    else:
                        return False
            if colour == "B":
                if columnNum >= 2 and columnNum <= 7:
                    for i in [-1, 1]:
                        if type(layout[x + i][y - 1]) != Piece:
                            return True
                        else:
                            return False
                elif columnNum == 1:
                    if type(layout[x + 1][y - 1]) != Piece:
                        return True
                    else:
                        return False
                elif columnNum == 8:
                    if type(layout[x - 1][y - 1]) != Piece:
                        return True
                    else:
                        return False

    def move(self, dest, layout):
        self.position = dest
        Board.updateDataStructure(layout)

class Board():
    layout = []
    num_co = [t for t in range(1, 9)]
    alpha_co = ["A", "B", "C", "D", "E", "F", "G", "H"]

    def __init__(self):
        pass

    def createBoard(self):
        blank = True
        start = 0
        end = 8
        for yCo in Board.num_co[0:3]:
            for xCo in range(0, 8):
                if blank == False:
                    Board.layout.append(Piece("R", (Board.alpha_co[xCo] + str(yCo))))
                    blank = True
                elif blank == True:
                    Board.layout.append(Board.alpha_co[xCo] + str(yCo))
                    blank = False
            blank = not blank
        for yCo in Board.num_co[3:5]:
            for xCo in range(0, 8):
                Board.layout.append(Board.alpha_co[xCo] + str(yCo))
        for yCo in Board.num_co[5:8]:
            for xCo in range(0, 8):
                if blank == False:
                    Board.layout.append(Piece("B", (Board.alpha_co[xCo] + str(yCo))))
                    blank = True
                elif blank == True:
                    Board.layout.append(Board.alpha_co[xCo] + str(yCo))
                    blank = False
            blank = not blank
        return Board.layout

    def createDataStructure(self, layout):
        print()
        print()
        temp = []
        layout_temp = []
        for i in Board.alpha_co:
            for j in layout:
                if type(j) == Piece:
                    if j.position[0] == i:
                        temp.append(j)
                else:
                    if j[0] == i:
                        temp.append(j)
            layout_temp.append(temp)
            temp = []
        print(layout_temp)
        return layout_temp

    def updateDataStructure(layout):
        updated = False
        temp = []
        loop1 = True
        while not updated:
            for x in range(0, len(layout)):
                for y in range(0, len(layout[x])):
                    current_pos = findAlpha[x] + str(y + 1)
                    current_obj = layout[x][y]
                    if (x, y) != (8, 8) and loop1 == True:
                        if type(current_obj) == Piece:
                            if current_obj.position != current_pos:
                                temp.append(current_obj)
                                updated = False
                                layout[x][y] = current_pos

                    else:
                        for item in temp:
                            if item.position == current_pos:
                                layout[x][y] = item
                                temp.remove(item)
                                if len(temp) == 0:
                                    updated = True
            loop1 = False

    def printLayout(self, layout):
        temp = []
        final = []
        count = 0
        for w in Board.num_co:
            for x in layout:
                for y in x:
                    if type(y) == Piece:
                        if y.position[1] == str(w):
                            temp.append(y.colour)
                    else:
                        if y[1] == str(w):
                            temp.append("X")
            final.append(temp)
            temp = []
        for t in reversed(final):
            print(" ".join(t))

board = Board()
pieces = board.createBoard()
layout = board.createDataStructure(pieces)
board.printLayout(layout)
print()
print()
layout[1][2].move('A5', layout)
board.printLayout(layout)


import argparse
import os
import aiohttp
import asyncio
import time
import multiprocessing
from aiohttp import web
from retry import retry
from fake_useragent import UserAgent
from urllib import parse
from rich.console import Console
from rich.progress import (BarColumn, DownloadColumn, Progress, TextColumn,
                        TimeRemainingColumn, TransferSpeedColumn, TaskID)
console = Console()
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)

async def total(url: str, session: aiohttp.ClientSession, header: dict) -> int:
    """_summary_

    Args:
        url (str): _description_
        session (aiohttp.ClientSession): _description_
        header (dict): _description_

    Returns:
        int: _description_
    """
    async with session.head(url, headers=header, timeout=aiohttp.ClientTimeout(total=60)) as req:
        print(req.headers)
        return int(req.headers.get('content-length'))

async def split(filesize: int, num_threads: int) -> list[tuple[int, int]]:
    """Split file size

    Args:
        filesize (int): The file size.
        num_threads (int): The number of threads.

    Returns:
        list[tuple[int, int]]: Chucks.
    """
    chunk_size: int = filesize // num_threads
    parts: dict[tuple[int, int]] = []
    for i in range(num_threads):
        start: int = chunk_size * i
        end: int = start + chunk_size - 1 if i < num_threads - 1 else filesize
        parts.append((start, end))
    print(parts)
    return parts

async def main(url: str, retry_nums: int, coros: int, semaphores: int) -> None:
    """_summary_

    Args:
        url (str): _description_
        retry_nums (int): _description_
    """
    main_dir: str = os.path.split(os.path.abspath(__file__))[0]
    download_dir: str = os.path.join(os.path.dirname(main_dir), "Downloaded files\\")
    download_file: str = os.path.join(download_dir, os.path.normpath(os.path.basename(parse.urlparse(url).path)))
    user_agent: str = UserAgent().random
    semaphore = asyncio.Semaphore(semaphores)
    f = open(download_file, "wb")
    @retry(tries=retry_nums)
    async def start_download(start: int, end: int, session: aiohttp.ClientSession) -> None:
        """_summary_

        Args:
            start (int): _description_
            end (int): _description_
            session (aiohttp.ClientSession): _description_
        """
        progress.start_task(task_id)
        f.seek(start)
        _headers: dict = {'User-Agent': user_agent, 'Range': f'bytes={start}-{end}'}
        Timeout: aiohttp.ClientTimeout = aiohttp.ClientTimeout(total=100000**10)
        async with semaphore:
            async with session.get(url, headers=_headers, timeout=Timeout) as req:
                async for chunk in req.content.iter_chunked((end-start)//10):
                        f.write(chunk)
                        progress.update(task_id, advance=len(chunk))
    with Progress(
        TextColumn("[bold blue]{task.fields[filename]}", justify="right"),
        BarColumn(bar_width=None),
        "[progress.percentage]{task.percentage:>3.1f}%",
        " ",
        DownloadColumn(),
        " ",
        TransferSpeedColumn(),
        " eta ",
        TimeRemainingColumn(),
) as progress:
        task_id: TaskID = progress.add_task("Download file:", filename=os.path.split(download_file)[1], start=False)
        tasks: dict = []
        async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
            _total = await asyncio.create_task(total(url, session, {'User-Agent': user_agent}))
            progress.update(task_id, total=_total)
            parts = await asyncio.create_task(split(_total, coros))
            print(len(parts))
            for part in parts:
                start, end = part
                tasks.append(asyncio.create_task(start_download(start, end, session)))
            tasks_a = await asyncio.gather(*tasks)
    f.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="A downloader.")
    parser.add_argument('-U', '--url', type=str, required=True)
    parser.add_argument('--retry-nums', type=int, required=False, default=3)
    parser.add_argument('-C', "--concurrent-nums",type=int, required=False, default=multiprocessing.cpu_count()*2+2)
    parser.add_argument('-S', "--semaphores",type=int, required=False, default=3)
    arg = parser.parse_args()
    start = time.perf_counter()
    asyncio.run(main(arg.url, arg.retry_nums, arg.concurrent_nums, arg.semaphores))
    end = time.perf_counter()
    print(end - start)


from .functions import get_namespace_by_classname
from .PhpFileAnalyzer import PhpFileAnalyzer
from lxml import etree as xml

class GraphMLExporter:

    def __init__(self):
        self.xmlns_namespace = "http://graphml.graphdrawing.org/xmlns"
        self.xsi_namespace = "http://www.w3.org/2001/XMLSchema-instance"
        self.ygraphml_namespace = "http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"
        self.y_namespace = "http://www.yworks.com/xml/graphml"
        self.nsmap = {None : self.xmlns_namespace}

        self.xmlns = "{%s}" % self.xmlns_namespace
        self.xsi   = "{%s}" % self.xsi_namespace
        self.y     = "{%s}" % self.y_namespace

    def exportClassGraphhToFile(
        self,
        plugin,
        storage,
        classes,
        filePath,
        depth=0,
        classesExcluded=[],
        options = {}
    ):

        ### FETCH NODES AND EDGES BY DEPTH

        allNodes = []
        allEdges = []

        cleanedClasses = []
        for className in classes:
            className = self.__clearClassName(className)
            cleanedClasses.append(className)
        classes = cleanedClasses

        cleanedClassesExcluded = []
        for className in classesExcluded:
            className = self.__clearClassName(className)
            cleanedClassesExcluded.append(className)
        classesExcluded = cleanedClassesExcluded

        if depth > 0:
            lastAddedClasses = classes
            while depth > 0:
                classesToAdd = []
                for className in lastAddedClasses:
                    if className not in classesExcluded:
                        nodes, edges = self._fetchRelatedEdges(className, plugin, storage, options)
                        allNodes += nodes
                        allEdges += edges
                        for node in nodes:
                            nodeClassName, nodeType = node.split('@')
                            classesToAdd.append(nodeClassName)
                classes += classesToAdd
                classes = list(set(classes))
                lastAddedClasses = list(set(classesToAdd))
                depth -= 1
            nodes = allNodes
            edges = allEdges

        else:
            nodes = []
            edges = [] # TODO: fill edges from nodes
            for nodeFullClassName in list(set(classes)):
                nodeNamespace, nodeClassName = get_namespace_by_classname(nodeFullClassName)
                classType = storage.get_class_type(nodeNamespace, nodeClassName)
                nodes.append(nodeFullClassName + "@" + classType)

        ### INIT XML

        # http://lxml.de/tutorial.html

        xmlns_namespace = "http://graphml.graphdrawing.org/xmlns"
        xsi_namespace = "http://www.w3.org/2001/XMLSchema-instance"
        ygraphml_namespace = "http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"
        nsmap = {None : xmlns_namespace}

        xmlns = "{%s}" % xmlns_namespace
        xsi   = "{%s}" % xsi_namespace

        tree = xml.ElementTree()

        graphmlXml = xml.Element(self.xmlns + "graphml", nsmap=self.nsmap)
        graphmlXml.set(self.xsi + "schemaLocation", self.xmlns_namespace + " " + self.ygraphml_namespace)

        tree._setroot(graphmlXml)

        graphXml = xml.SubElement(graphmlXml, self.xmlns + "graph", edgedefault="directed")
        graphXml.set("id", "G")

        for keyAttributes in [
            {"for": "graph", "id": "d0", "attr.type": "string", "attr.name": "description"},
            {"for": "node",  "id": "d1", "attr.type": "string", "attr.name": "url"},
            {"for": "node",  "id": "d2", "attr.type": "string", "attr.name": "description"},
            {"for": "node",  "id": "d3", "yfiles.type": "nodegraphics"},
            {"for": "edge",  "id": "d4", "attr.type": "string", "attr.name": "url"},
            {"for": "edge",  "id": "d5", "attr.type": "string", "attr.name": "description"},
            {"for": "edge",  "id": "d6", "yfiles.type": "edgegraphics"}
        ]:
            keyXml = xml.Element("key")
            for key, value in keyAttributes.items():
                keyXml.set(key, value)
            graphmlXml.append(keyXml)

        ### WRITE NODES AND EDGES TO XML

        classToNodeIndexMap = {}
        counter = 0
        for node in nodes:
            fullClassName, classType = node.split("@")
            if fullClassName not in classToNodeIndexMap:
                classToNodeIndexMap[fullClassName] = counter
                namespace, className = get_namespace_by_classname(fullClassName)

                headerText = className + "\n" + namespace

                if classType != "class":
                    headerText = "<<" + classType + ">>\n" + headerText

                bodyText = ""

                if "contain_methods" not in options or options["contain_methods"]:
                    for methodName in storage.get_all_class_methods(namespace, className):
                        methodData = storage.get_method(namespace, className, methodName)
                        visibility, is_static, methodFilePath, line, column, doccomment, returnType = methodData
                        methodPrefix = "+"
                        if visibility == "protected":
                            methodPrefix = "#"
                        if visibility == "private":
                            methodPrefix = "-"
                        methodReturnTypeDef = ""
                        if returnType != None:
                            methodReturnTypeDef = " : " + returnType
                        bodyText += methodPrefix + " " + methodName + "()" + methodReturnTypeDef + "\n"

                if "contain_members" not in options or options["contain_members"]:
                    for memberName in storage.get_all_class_members(namespace, className):
                        memberData = storage.get_member(namespace, className, memberName)
                        visibility, is_static, memberFilePath, line, column, doccomment, typeHint = memberData
                        memberPrefix = "+"
                        if visibility == "protected":
                            memberPrefix = "#"
                        if visibility == "private":
                            memberPrefix = "-"
                        memberTypeDef = ""
                        if typeHint != None:
                            memberTypeDef = " : " + typeHint
                        bodyText += memberPrefix + " " + memberName + memberTypeDef + "\n"

                classFilePath, classLine, classColumn = storage.get_class_position(namespace, className)

                self._writeNodeXml(counter, headerText, bodyText, classType, graphXml, classFilePath)
                counter += 1

        edgeToIdMap = {}
        counter = 0
        for edge in edges:
            if edge not in edgeToIdMap:
                edgeToIdMap[edge] = counter
                sourceClassName, edgeType, targetClassName = edge.split("-")

                sourceIndex = classToNodeIndexMap[sourceClassName]
                targetIndex = classToNodeIndexMap[targetClassName]

                self._writeEdgeXml(counter, sourceIndex, targetIndex, edgeType, graphXml)
                counter += 1

        tree.write(filePath)

    def _writeNodeXml(self, index, headerText, bodyText, nodeType, graphXml, url=None):
        nodeXml = xml.SubElement(graphXml, "node")
        nodeXml.set("id", "n"+str(index))

        if url != None:
            urlDataXml = xml.Element("data", key="d1")
            urlDataXml.text = url
            nodeXml.append(urlDataXml)

        nodeXml.append(xml.Element("data", key="d2"))
        nodeGraphicsDataXml = xml.SubElement(nodeXml, "data", key="d3")

        lineCount = 0
        highestColumnCount = 0
        for line in headerText.split("\n"):
            lineCount += 1
            if len(line) > highestColumnCount:
                highestColumnCount = len(line)
        for line in bodyText.split("\n"):
            lineCount += 1
            if len(line) > highestColumnCount:
                highestColumnCount = len(line)

        yGenericNodeXml = xml.SubElement(
            nodeGraphicsDataXml,
            self.y + "GenericNode",
            configuration="com.yworks.entityRelationship.big_entity"
        )

        nodeWidth  = 10 + (highestColumnCount * 7)
        nodeHeight = 10 + (lineCount * 14)

        if nodeType == "interface":
            foregroundColor = "#E8F7F7"
            backgroundColor = "#B7E3E3"

        elif nodeType == "trait":
            foregroundColor = "#F2F7E8"
            backgroundColor = "#D3E3B7"

        else:
            foregroundColor = "#E8EEF7"
            backgroundColor = "#B7C9E3"

        yGeometryXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "Geometry",
            height=str(nodeHeight),
            width=str(nodeWidth),
            x="0.0",
            y="0.0"
        )

        yFillXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "Fill",
            color=foregroundColor,
            color2=backgroundColor,
            transparent="false"
        )

        yBorderStyleXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "BorderStyle",
            color="#000000",
            type="line",
            width="1.0"
        )

        yNodeLabelHeaderXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "NodeLabel",
            alignment="center",
            autoSizePolicy="content",
            backgroundColor=backgroundColor,
            configuration="com.yworks.entityRelationship.label.name",
            fontFamily="Monospace",
            fontSize="12",
            fontStyle="plain",
            hasLineColor="false",
            height="31.9375",
            modelName="internal",
            modelPosition="t",
            textColor="#000000",
            visible="true",
            width="137.880859375",
            x="16.5595703125",
            y="4.0"
        )

        yNodeLabelHeaderXml.text = headerText

        yNodeLabelBodyXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "NodeLabel",
            alignment="left",
            autoSizePolicy="content",
            configuration="com.yworks.entityRelationship.label.attributes",
            fontFamily="Monospace",
            fontSize="12",
            fontStyle="plain",
            hasBackgroundColor="false",
            hasLineColor="false",
            height="4.0",
            modelName="custom",
            textColor="#000000",
            visible="true",
            width="4.0",
            x="2.0",
            y="43.9375"
        )

        yNodeLabelBodyXml.text = bodyText

        yLabelModelXml = xml.SubElement(
            yNodeLabelBodyXml,
            self.y + "LabelModel"
        )

        yErdAttributesNodeLabelModelXml = xml.SubElement(
            yLabelModelXml,
            self.y + "ErdAttributesNodeLabelModel"
        )

        yModelParameterXml = xml.SubElement(
            yNodeLabelBodyXml,
            self.y + "ModelParameter"
        )

        yErdAttributesNodeLabelModelParameterXml = xml.SubElement(
            yModelParameterXml,
            self.y + "ErdAttributesNodeLabelModelParameter"
        )

        yStylePropertiesXml = xml.SubElement(
            yGenericNodeXml,
            self.y + "StyleProperties"
        )

        yPropertyXml = xml.SubElement(
            yStylePropertiesXml,
            self.y + "Property",
            name="y.view.ShadowNodePainter.SHADOW_PAINTING",
            value="true"
        )
        yPropertyXml.set("class", "java.lang.Boolean")

    def _writeEdgeXml(self, index, sourceIndex, targetIndex, edgeType, graphXml):
        edgeXml = xml.SubElement(
            graphXml,
            "edge",
            id="e"+str(index),
            source="n"+str(sourceIndex),
            target="n"+str(targetIndex)
        )

        edgeXml.append(xml.Element("data", key="d4"))
        edgeXml.append(xml.Element("data", key="d5"))

        edgeGraphicsDataXml = xml.SubElement(edgeXml, "data", key="d6")

        yPolyLineEdgeXml = xml.SubElement(edgeGraphicsDataXml, self.y + "PolyLineEdge")

        if edgeType == "generalization":
            lineColor = "#000000"
            lineType = "line"
            sourceArrow = "none"
            targetArrow = "white_delta"

        elif edgeType == "implementation":
            lineColor = "#000000"
            lineType = "dashed"
            sourceArrow = "none"
            targetArrow = "white_delta"

        elif edgeType == "composition":
            lineColor = "#000000"
            lineType = "line"
            sourceArrow = "diamond"
            targetArrow = "none"

        else: # association
            lineColor = "#aaaaaa"
            lineType = "line"
            sourceArrow = "none"
            targetArrow = "short"

        yPathXml = xml.SubElement(
            yPolyLineEdgeXml,
            self.y + "Path",
            sx="0.0",
            sy="0.0",
            tx="0.0",
            ty="0.0"
        )
        yLineStyleXml = xml.SubElement(
            yPolyLineEdgeXml,
            self.y + "LineStyle",
            color=lineColor,
            type=lineType,
            width="1.0"
        )
        yArrowsXml = xml.SubElement(
            yPolyLineEdgeXml,
            self.y + "Arrows",
            source=sourceArrow,
            target=targetArrow
        )
        yBendStyleXml = xml.SubElement(
            yPolyLineEdgeXml,
            self.y + "BendStyle",
            smoothed="false"
        )

    def _calculateCoupling(self, nodes, edges):
        couplingByNode = {}
        for node in nodes:
            nodeClassName, nodeType = node.split('@')
            coupling = 0
            for edge in edges:
                edgeBaseClass, edgeTargetClass, edgeType = edge.split("-")
                if edgeBaseClass == nodeClassName or edgeTargetClass == nodeClassName:
                    coupling += 1
            couplingByNode[node] = coupling
        return couplingByNode

    def _fetchRelatedEdges(self, fullClassName, plugin, storage, options={}):
        nodes = []
        edges = []

        fullClassName = self.__clearClassName(fullClassName)

        internalTypes = ["string", "array", "int", "float", "object", "bool"]

        if len(fullClassName) > 0:
            namespace, className = get_namespace_by_classname(fullClassName)

            classes = [fullClassName]

            ### INTERFACES

            interfacesImplemented = []

            if "include_interfaces" not in options or options["include_interfaces"]:
                interfaces = storage.get_class_interfaces(namespace, className)
                for interface in interfaces:
                    interface = self.__clearClassName(interface)
                    interfacesImplemented.append(interface)
                    classes.append(interface)
                    edges.append(fullClassName + "-implementation-" + interface)

            ### PARENT / CHILDREN

            if "include_parental_inheritance" not in options or options["include_parental_inheritance"]:
                parentClassName = storage.get_class_parent(namespace, className)
                if parentClassName != None:
                    parentClassName = self.__clearClassName(parentClassName)
                    classes.append(parentClassName)
                    edges.append(fullClassName + "-generalization-" + parentClassName)

            if "include_children_inheritance" not in options or options["include_children_inheritance"]:
                children = storage.get_class_children(fullClassName)
                for childClassName in children:
                    childClassName = self.__clearClassName(childClassName)
                    if childClassName not in interfacesImplemented:
                        classes.append(childClassName)
                        edges.append(childClassName + "-generalization-" + fullClassName)

            ### COMPOSITIONS & AGGREGATIONS

            if "include_has_a_composition" not in options or options["include_has_a_composition"]:
                members = storage.get_all_class_members(namespace, className)
                for memberName in members:
                    memberData = storage.get_member(namespace, className, memberName)
                    typeHint = memberData[6]
                    if typeHint != None and len(typeHint) > 0 and typeHint not in internalTypes:
                        typeHint = self.__clearClassName(typeHint)
                        classes.append(typeHint)
                        edges.append(fullClassName + "-composition-" + typeHint)
                methods = storage.get_all_class_methods(namespace, className)
                for methodName in methods:
                    methodData = storage.get_method(namespace, className, methodName)
                    returnType = methodData[6]
                    if returnType != None and len(returnType) > 0 and returnType not in internalTypes:
                        returnType = self.__clearClassName(returnType)
                        classes.append(returnType)
                        edges.append(fullClassName + "-composition-" + returnType)

            if "include_is_part_of_composition" not in options or options["include_is_part_of_composition"]:
                members = storage.get_members_by_type_hint(namespace, className)
                for memberNamespace, memberClassname, memberName in members:
                    memberFullClassname = memberNamespace + "\\" + memberClassname
                    memberFullClassname = self.__clearClassName(memberFullClassname)
                    classes.append(memberFullClassname)
                    edges.append(memberFullClassname + "-composition-" + fullClassName)

            ### REFERENCES

            if "include_uses_references" not in options or options["include_uses_references"]:
                uses = storage.get_class_uses(fullClassName)
                for usingFilePath, line, column, usingClassName, functionName in uses:
                    usingClassName = self.__clearClassName(usingClassName)
                    classes.append(usingClassName)
                    edges.append(usingClassName + "-association-" + fullClassName)

            if "include_usedby_references" not in options or options["include_usedby_references"]:
                uses = storage.get_class_uses_by_class(fullClassName)
                for usingFilePath, line, column, userClassName, functionName in uses:
                    userClassName = self.__clearClassName(userClassName)
                    classes.append(userClassName)
                    edges.append(fullClassName + "-association-" + userClassName)

            ### BUILD NODES FROM CLASSES

            for nodeFullClassName in list(set(classes)):
                nodeNamespace, nodeClassName = get_namespace_by_classname(nodeFullClassName)
                classType = storage.get_class_type(nodeNamespace, nodeClassName)
                nodes.append(nodeFullClassName + "@" + classType)

        return [nodes, edges]

    def __clearClassName(self, className):
        if className != None and len(className) > 0 and className[0] != "\\":
            className = "\\" + className
        return className


#Indra Ratna
#CS-UY 1114
#05 Oct 2018
#Lab 5
#Problem 9
dec = int(input("Enter decimal number: "))
remain = ""
x = dec
while(x>0):
    remain+=str(x%2)
    # remain = str(x%2) + remain
    x=x//2
remain=remain[::-1]
print("The binary representation of "+str(dec)+ " is "+remain)


import ranger.api
from ranger.api.commands import *
from os import getenv

class z(Command):
    """:z
    Uses .z file to set the current directory.
    """
    def execute(self):

        # location of .z file
        z_loc = getenv("HOME")+"/.config/.z"
        with open(z_loc,"r") as fobj:
            flists = fobj.readlines()

        # user given directory
        req = self.args[1]
        directories = []
        for i in flists:
            if req in i:
                directories.append(i.split("|")[0])

        try:
            #  smallest(length) directory will be the directory required
            self.fm.execute_console("cd " + min(directories,key=lambda x: len(x)))
        except Exception as e:
            raise Exception("Directory not found")


# -*- coding: utf-8 -*-
"""
Created on Thu Aug 12 16:18:31 2021

@author: Jagriti
"""

"""The dataset we will be using is the CIFAR-10 dataset, which consists
 of 60,000 32x32 color images in 10 classes, with 6000 images per class.
 There are 50000 training images and 10000 test images.

 https://arxiv.org/pdf/1412.6806.pdf     """

from keras.datasets import cifar10
data= cifar10.load_data()
(X_train, y_train), (X_test, y_test) = data

"""-----------------------------------------------------------------"""
# DETERMINE DATASET CHARACTERISTICS
print('Training Images: {}'.format(X_train.shape))
print('Testing Images: {}'.format(X_test.shape))

import matplotlib.pyplot as plt

# create a grid of 3x3 images
for i in range(0,9):
    plt.subplot(330 + 1 + i)
    img = X_train[i]
    plt.imshow(img)

plt.show()

"""-----------------------------------------------------------------"""
#PREPROCESSING THE DATASET
# fix random seed for reproducibility
import numpy as np
seed = 6
np.random.seed(seed)

# normalize the inputs
X_train = X_train / X_train.max()
X_test = X_test / X_test.max()

"""-----------------------------------------------------------------"""
"""The class labels are a single integer value (0-9).
 What we really want is a one-hot vector of length ten.
 For example, the class label of 6 should be denoted as
 [0, 0, 0, 0, 0, 0, 1, 0, 0, 0].
 We can accomplish this using the np_utils.to_categorical() function """

from keras.utils import np_utils
Y_train = np_utils.to_categorical(y_train)
Y_test = np_utils.to_categorical(y_test)
num_classes = Y_test.shape[1]

"""-----------------------------------------------------------------"""
#BUILDING CNN

""" The three base networks used for classification on CIFAR-10 and CIFAR-100.

Input 32 × 32 RGB image
MODEL C

3 × 3 conv. 96 ReLU
3 × 3 conv. 96 ReLU
3 × 3 max-pooling stride 2

3 × 3 conv. 192 ReLU
3 × 3 conv. 192 ReLU
3 × 3 max-pooling stride 2

3 × 3 conv. 192 ReLU
1 × 1 conv. 192 ReLU
1 × 1 conv. 10 ReLU
global averaging over 6 × 6 spatial dimensions
10 or 100-way softmax

"""

from keras.models import Sequential
from keras.layers import Dropout, Activation, Conv2D, GlobalAveragePooling2D

def allcnn(weights=None):
    # dDEFINING SEQUENTIAL MODEL
    model = Sequential()

    # add model layers - Convolution2D, Activation, Dropout
    model.add(Conv2D(96, (3, 3), padding = 'same', input_shape=(32, 32, 3)))
    model.add(Activation('relu'))
    model.add(Conv2D(96, (3, 3), padding = 'same'))
    model.add(Activation('relu'))
    model.add(Conv2D(96, (3, 3), padding = 'same', strides = (2,2)))
    model.add(Dropout(0.5))  #TO PREVENT OVERFITTING

    model.add(Conv2D(192, (3, 3), padding = 'same'))
    model.add(Activation('relu'))
    model.add(Conv2D(192, (3, 3), padding = 'same'))
    model.add(Activation('relu'))
    model.add(Conv2D(192, (3, 3), padding = 'same', strides = (2,2)))
    model.add(Dropout(0.5))

    model.add(Conv2D(192, (3, 3), padding = 'same'))
    model.add(Activation('relu'))
    model.add(Conv2D(192, (1, 1), padding = 'valid'))
    model.add(Activation('relu'))
    model.add(Conv2D(10, (1, 1), padding = 'valid'))

    # add GlobalAveragePooling2D layer with Softmax activation
    model.add(GlobalAveragePooling2D())
    model.add(Activation('softmax'))

    # load the weights
    if weights:
        model.load_weights(weights)

    return model

"""-----------------------------------------------------------------"""
#DEFINING HYPERPARAMETERS
learning_rate = 0.01
weight_decay = 1e-6
momentum = 0.9

model = allcnn()

# DEFINING OPTIMIZER & COMPILING THE MODEL
from keras.optimizers import SGD #stochaistic gradient descent
sgd = SGD(lr=learning_rate, decay=weight_decay, momentum=momentum, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

print (model.summary())

"""batch size simply means you're going to run 32 images.
And then after those 32 images you can update the loss or update the
parameters instead of updating them individually after every single image."""

model.fit(X_train, Y_train, validation_data=(X_test, Y_test),
          epochs=350, batch_size=32, verbose = 1)

"""-----------------------------------------------------------------"""
#PREDICTIONS

classes = range(0,10)

names = ['airplane',
        'automobile',
        'bird',
        'cat',
        'deer',
        'dog',
        'frog',
        'horse',
        'ship',
        'truck']

# zip the names and classes to make a dictionary of class_labels
class_labels = dict(zip(classes, names))

# generate batch of 9 images to predict
batch = X_test[100:109]
labels = np.argmax(Y_test[100:109],axis=-1)

# make predictions
predictions = model.predict(batch, verbose = 1)

# convert class probabilities to class labels
class_result = np.argmax(predictions,axis=-1)

# create a grid of 3x3 images
fig, axs = plt.subplots(3, 3, figsize = (15, 6))
fig.subplots_adjust(hspace = 1)
axs = axs.flatten()

for i, img in enumerate(batch):

    # determine label for each prediction, set title
    for key, value in class_labels.items():
        if class_result[i] == key:
            title = 'Prediction: {}\nActual: {}'.format(class_labels[key], class_labels[labels[i]])
            axs[i].set_title(title)
            axs[i].axes.get_xaxis().set_visible(False)
            axs[i].axes.get_yaxis().set_visible(False)

    # plot the image
    axs[i].imshow(img)

plt.show()


from rest_framework.decorators import action
from rest_framework.generics import RetrieveAPIView
from rest_framework import viewsets, status, generics
from rest_framework.response import Response

from .serializers import *

class CategoryView(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = Category.objects.all()

        title = self.request.query_params.get('title')
        if title:
            queryset = queryset.filter(title__icontains=title)
        return queryset

class RegionView(viewsets.ModelViewSet):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer

    def get_queryset(self):
        queryset = Region.objects.all()

        state = self.request.query_params.get('state')
        city = self.request.query_params.get('city')
        if state:
            queryset = queryset.filter(state__icontains=state)
        if city:
            queryset = queryset.filter(city__icontains=city)
        return queryset

class VacancyViewSet(viewsets.ModelViewSet):
    serializer_class = VacancySerializer
    queryset = Vacancy.objects.all()
    basename = 'vacancy'

    def get_queryset(self):
        queryset = Vacancy.objects.all()

        title = self.request.query_params.get('title')
        salary = self.request.query_params.get('salary')
        state = self.request.query_params.get('state')
        if state:
            queryset = queryset.filter(state=state)
        if salary:
            queryset = queryset.filter(salary__icontains=salary)
        if title:
            queryset = queryset.filter(title__icontains=title)
        return queryset

    @action(detail=True, methods=['get'])
    def count(self, request, pk=None):
        instance = self.get_object()
        instance.count += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=status.HTTP_200_OK)

class CompanyView(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer

class TopVacancyView(viewsets.ModelViewSet):
    queryset = TopVacancy.objects.all()
    serializer_class = TopVacancySerializer


import pandas as pd
from core.models import City
from django.contrib.gis.geos import Point
from django.core.management.base import BaseCommand

tmp_data_city = pd.read_csv(
    'core/management/commands/city.csv', sep=',', encoding="utf-8"
)
tmp_data_city['city'] = tmp_data_city['city'].fillna(tmp_data_city['region'])

class Command(BaseCommand):
    help = 'The Zen of Python'

    def handle(self, **options):
        cities = [
            City(
                name=row['city'],
                location=Point(row['geo_lon'], row['geo_lat']),
            )
            for _, row in tmp_data_city.iterrows()
        ]

        City.objects.bulk_create(cities, ignore_conflicts=True)


import random

f = open('../data/data3.in', 'w', encoding='utf-8')
N = 100000
f.write("{}\n".format(10*N))
array = list(range(N))
random.shuffle(array)
for i in array:
  f.write("A {}\n".format(i))

for i in range(9*N):
  f.write("C {}\n".format(random.randint(1,int(N/10000))))

f.close()


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

"""The setup script."""

from setuptools import setup, find_packages

with open("README.rst") as readme_file:
    readme = readme_file.read()

with open("HISTORY.rst") as history_file:
    history = history_file.read()

requirements = [
    "Click>=7.1",
    "pysnmp>=4.4",
    "psycopg2>=2.8",
    "sqlalchemy>=1.3",
    "yattag>=1.14",
]

setup_requirements = [
    "pytest-runner",
]

test_requirements = [
    "pytest",
]

setup(
    author="Krys Lawrence",
    author_email="krys.lawrence@cbsa-asfc.gc.ca",
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Intended Audience :: Developers",
        "Natural Language :: English",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
    ],
    description="Test code for an SNMP adapter for LabView.",
    entry_points={
        "console_scripts": [
            "snmp_adapter=snmp_adapter.__main__:main",
        ],
    },
    install_requires=requirements,
    long_description=readme + "\n\n" + history,
    include_package_data=True,
    keywords="snmp_adapter",
    name="snmp_adapter",
    packages=find_packages(include=["snmp_adapter"]),
    setup_requires=setup_requirements,
    test_suite="tests",
    tests_require=test_requirements,
    url="https://github.com/justkrys/snmp_adapter",
    version="0.1.0",
    zip_safe=False,
)


import re, string, datetime, operator

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

VIDEO_PREFIX = "/video/hgtv.ca"

NAME = L('Title')

ART             = 'art-default.jpg'
ICON            = 'icon-default.png'

HGTV_PARAMS         = ["HmHUZlCuIXO_ymAAPiwCpTCNZ3iIF1EG", "z/HGTV%20Player%20-%20Video%20Center"]

FEED_LIST    = "http://feeds.theplatform.com/ps/JSON/PortalService/2.2/getCategoryList?PID=%s&startIndex=1&endIndex=500&query=hasReleases&query=CustomText|PlayerTag|%s&field=airdate&field=fullTitle&field=author&field=description&field=PID&field=thumbnailURL&field=title&contentCustomField=title&field=ID&field=parent"

FEEDS_LIST    = "http://feeds.theplatform.com/ps/JSON/PortalService/2.2/getReleaseList?PID=%s&startIndex=1&endIndex=500&query=categoryIDs|%s&query=BitrateEqualOrGreaterThan|400000&query=BitrateLessThan|601000&sortField=airdate&sortDescending=true&field=airdate&field=author&field=description&field=length&field=PID&field=thumbnailURL&field=title&contentCustomField=title"

DIRECT_FEED = "http://release.theplatform.com/content.select?format=SMIL&pid=%s&UserName=Unknown&Embedded=True&TrackBrowser=True&Tracking=True&TrackLocation=True"

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

def Start():
    Plugin.AddPrefixHandler(VIDEO_PREFIX, MainMenu, L('VideoTitle'), ICON, ART)

    Plugin.AddViewGroup("InfoList", viewMode="InfoList", mediaType="items")
    Plugin.AddViewGroup("List", viewMode="List", mediaType="items")

    MediaContainer.art = R(ART)
    MediaContainer.title1 = NAME
    DirectoryItem.thumb = R(ICON)

####################################################################################################
def MainMenu():
    dir = MediaContainer(viewGroup="List")
    shows_with_seasons = {}
    shows_without_seasons = {}

    network = HGTV_PARAMS

    content = JSON.ObjectFromURL(FEED_LIST % (network[0], network[1]))
    for item in content['items']:
        if "Full Episodes" in item['parent']:
            title = item['title']
            id = item['ID']
            if re.search("Season", title):
                show, season = title.split("Season")
                show = show.rstrip().split(":")[0].rstrip()
                if not(show in shows_with_seasons):
                    shows_with_seasons[show] = ""
                    dir.Append(Function(DirectoryItem(SeasonsPage, show), network=network))
            else:
                if not(title in shows_without_seasons):
                    shows_without_seasons[title] = []
                shows_without_seasons[title].append(Function(DirectoryItem(VideosPage, title), pid=network[0], id=id))

    for show in shows_without_seasons:
        if not(show in shows_with_seasons) and len([added_show for added_show in shows_with_seasons if show in added_show or added_show in show]) == 0:
            for item in shows_without_seasons[show]:
                dir.Append(item)

    dir.Sort('title')

    return dir

####################################################################################################
def VideoPlayer(sender, pid):

    videosmil = HTTP.Request(DIRECT_FEED % pid).content
    player = videosmil.split("ref src")
    player = player[2].split('"')
    #Log(player)
    if ".mp4" in player[1]:
        player = player[1].replace(".mp4", "")
        try:
            clip = player.split(";")
            clip = "mp4:" + clip[4]
        except:
            clip = player.split("/video/")
            player = player.split("/video/")[0]
            clip = "mp4:/video/" + clip[-1]
    else:
        player = player[1].replace(".flv", "")
        try:
            clip = player.split(";")
            clip = clip[4]
        except:
            clip = player.split("/video/")
            player = player.split("/video/")[0]
            clip = "/video/" + clip[-1]

    #Log(player)
    #Log(clip)
    return Redirect(RTMPVideoItem(player, clip))

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

def VideosPage(sender, pid, id):

    dir = MediaContainer(title2=sender.itemTitle, viewGroup="InfoList", art=sender.art)
    pageUrl = FEEDS_LIST % (pid, id)
    feeds = JSON.ObjectFromURL(pageUrl)
    #Log(feeds)

    for item in feeds['items']:
        title = item['title']
        pid = item['PID']
        summary =  item['description'].replace('In Full:', '')
        duration = item['length']
        thumb = item['thumbnailURL']
        airdate = int(item['airdate'])/1000
        subtitle = 'Originally Aired: ' + datetime.datetime.fromtimestamp(airdate).strftime('%a %b %d, %Y')
        dir.Append(Function(VideoItem(VideoPlayer, title=title, subtitle=subtitle, summary=summary, thumb=thumb, duration=duration), pid=pid))

    dir.Sort('title')

    return dir

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

def SeasonsPage(sender, network):
    dir = MediaContainer(title2=sender.itemTitle, viewGroup="List", art=sender.art)
    content = JSON.ObjectFromURL(FEED_LIST % (network[0], network[1]))
    for item in content['items']:
        if "Full Episodes" in item['parent'] and sender.itemTitle in item['title']:
            title = item['title'].split(sender.itemTitle)[-1].split(":")[-1].lstrip()
            id = item['ID']
            #thumb = item['thumbnailURL']
            dir.Append(Function(DirectoryItem(VideosPage, title, thumb=sender.thumb), pid=network[0], id=id))
    dir.Sort('title')
    return dir

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


from elasticsearch import Elasticsearch

es = Elasticsearch('http://localhost:9200')

resp = es.search(index="starwars-characters", query={"match_all": {}})

#print(resp)

print("Got %d Hits:" % resp['hits']['total']['value'])
for hit in resp['hits']['hits']:
    print("%(name)s" % hit["_source"])


class updaterVPN:

    def updateFILE(self,url,port,status,path_vpn):
        successful = ""
        msg = ""
        if status:
            try:
                PATH = path_vpn
                with open(PATH,'r',encoding='utf-8') as f:
                    data = f.readlines()
                    print("[+] Actual URL: " + data[3])
            except Exception:
                successful = False
                pass

            f_url = data[3].split(" ")[1]
            f_port = data[3].split(" ")[2]
            successful = True

            if f_url == url and f_port == port:
                msg = "[+] Nothing to Do"

                print(msg)
            else:
                data[3] = "remote {} {} \n".format(url,port)
                with open(PATH, 'w', encoding='utf-8') as file:
                    file.writelines(data)
                msg = "[+] File Updated: " + data[3]
                print(msg)
        return {
            'msg' : msg,
            'status' : successful
        }


#!/usr/bin/env python
# license removed for brevity

import rospy
from kortex_driver.msg import JointSpeed
from kortex_driver.srv import SendJointSpeedsCommandRequest, SendJointSpeedsCommand
import math

if __name__=='__main__':
  rospy.init_node('gen3_test')
  rospy.wait_for_service('/my_gen3/base/send_joint_speeds_command')
  srv_joint_speeds= rospy.ServiceProxy('/my_gen3/base/send_joint_speeds_command', SendJointSpeedsCommand)
  joint_names= ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'joint_6', 'joint_7']

  speed_req = SendJointSpeedsCommandRequest()
  #NOTE: JointSpeed/value is in DEGREES per second.
  #cf. https://github.com/Kinovarobotics/kortex/blob/master/api_cpp/doc/markdown/messages/Base/JointSpeed.md
  rad2deg= lambda q:q/math.pi*180.0
  for jidx,jname in enumerate(joint_names):
    joint_speed= JointSpeed()
    joint_speed.joint_identifier= jidx
    joint_speed.value= 0.0
    speed_req.input.joint_speeds.append(joint_speed)

  t0= rospy.Time.now()
  rate= rospy.Rate(200)

  try:
    while not rospy.is_shutdown():

      t= (rospy.Time.now()-t0).to_sec()
      for joint_speed in speed_req.input.joint_speeds:
        #NOTE: JointSpeed/value is in DEGREES per second.
        if joint_speed.joint_identifier == 3:
          joint_speed.value= -1.0
        else:
          # joint_speed.value= rad2deg(0.5*math.sin(math.pi*t))
          joint_speed.value= 0
      srv_joint_speeds.call(speed_req)
      rate.sleep()

  except KeyboardInterrupt:
      print('Interrupted')

  finally:
    #To make sure the robot stops:
    speed_req= SendJointSpeedsCommandRequest()
    for jidx,jname in enumerate(joint_names):
      joint_speed= JointSpeed()
      joint_speed.joint_identifier= jidx
      joint_speed.value= 0.0
      speed_req.input.joint_speeds.append(joint_speed)
    srv_joint_speeds.call(speed_req)


"""
Unsharp masking
"""
import skimage.io as io
import numpy as np
import cv2

# read image
name = input('Enter image name : ')
filename, filetype = name.split('.')
original_image = io.imread(name)

# get image height, image width
information = original_image.shape
height = information[0]
width = information[1]

'''
Average filter
'''
n = 3
div = pow(n,2)

def avg_get_pixel(i, j):
    if (i > height-1 or j > width-1 or i < 0 or j < 0):
        return 0
    else:
        return original_image[i][j]

def avg_filter(i, j):
    sum = 0
    mask = [[i-1, j-1], [i-1, j], [i-1, j+1], [i, j-1], [i, j], [i, j+1], [i+1, j-1], [i+1, j], [i+1, j+1]]
    for pixel in mask:
        sum += avg_get_pixel(pixel[0], pixel[1])/div
    return sum

avg_image = np.zeros((height, width))
for i in range(height):
    for j in range(width):
        avg_image[i][j] = avg_filter(i, j)

io.imshow(avg_image, cmap='gray')
io.show()

io.imsave(filename + '_average_filter.' + filetype, avg_image.astype(np.uint8))

'''
Median filter
'''
def get_median(array):
    array.sort()
    l = len(array)
    if (l%2 != 0):
        position = (l+1)/2-1
        return array[int(position)]
    else:
        position1 = l/2-1
        position2 = l/2
        return ( int(array[int(position1)]) + int(array[int(position2)]) )/2

def med_get_pixel(i, j):
    if (i > height-1 or j > width-1 or i < 0 or j < 0):
        return -1
    else:
        return original_image[i][j]

def med_filter(i, j):
    values = []
    mask = [[i-1, j-1], [i-1, j], [i-1, j+1], [i, j-1], [i, j], [i, j+1], [i+1, j-1], [i+1, j], [i+1, j+1]]
    for pixel in mask:
        value = med_get_pixel(pixel[0], pixel[1])
        if (value != -1):
            values.append(value)
    return get_median(values)

med_image = np.zeros((height, width))
for i in range(height):
    for j in range(width):
        med_image[i][j] = med_filter(i,j)

io.imshow(med_image, cmap='gray')
io.show()

io.imsave(filename + '_median_filter.' + filetype, med_image.astype(np.uint8))

'''
Unsharp Masking
'''
k = 0.9

# create mask : subtract
mask_average = original_image - avg_image
mask_median = original_image - med_image

io.imshow(mask_average, cmap='gray')
io.show()
io.imshow(mask_median, cmap='gray')
io.show()

# add mask to image
unsharp_average = original_image + k*mask_average
unsharp_median = original_image + k*mask_median
io.imshow(unsharp_average, cmap='gray')
io.show()
io.imshow(unsharp_median, cmap='gray')
io.show()

# scale mask
unsharp_average = 255* ( (unsharp_average-unsharp_average.min()) / (unsharp_average.max() - unsharp_average.min()) )
unsharp_median = 255* ( (unsharp_median-unsharp_median.min()) / (unsharp_median.max() - unsharp_median.min()) )

io.imsave(filename + '_median_unsharp.' + filetype, unsharp_average.astype(np.uint8))
io.imsave(filename + '_average_unsharp.' + filetype, unsharp_median.astype(np.uint8))


"""
@作者: egon老湿
@微信:18611453110
@专栏: https://zhuanlan.zhihu.com/c_1189883314197168128
"""

import random

# print(random.random()) #(0,1)----float    大于0且小于1之间的小数
# print(random.randint(1, 3))  # [1,3]    大于等于1且小于等于3之间的整数

# print(random.randrange(1, 3))  # [1,3)    大于等于1且小于3之间的整数
#
# print(random.choice([111, 'aaa', [4, 5]]))  # 1或者23或者[4,5]
#
# print(random.sample([111, 'aaa', 'ccc','ddd'],2))  # 列表元素任意2个组合
#
# print(random.uniform(1, 3))  # 大于1小于3的小数，如1.927109612082716
#
# item = [1, 3, 5, 7, 9]
# random.shuffle(item)  # 打乱item的顺序,相当于"洗牌"
# print(item)

# 应用：随机验证码

# import random
#
# res=''
# for i in range(6):
#     从26大写字母中随机取出一个=chr(random.randint(65,90))
#     从10个数字中随机取出一个=str(random.randint(0,9))
#
#     随机字符=random.choice([从26大写字母中随机取出一个,从10个数字中随机取出一个])
#     res+=随机字符

import random

def make_code(size=4):
    res=''
    for i in range(size):
        s1=chr(random.randint(65,90))
        s2=str(random.randint(0,9))
        res+=random.choice([s1,s2])
    return res

print(make_code(6))

2函数和模块/函数编程纯小白都能学会/day22-强大的Python标准库/代码/02 random模块.py


class Solution:
    def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
        min_nums = sorted(str(min(nums1)) + str(min(nums2)))

        for num in sorted(nums1):
            if num in nums2:
                return num
            else:
                continue
        return int(''.join(min_nums))

array/Form Smallest Number From Two Digit Arrays(2605).py


import os

def changeLabel(path,path2):

    for r,d,f in os.walk(path):
        for file in f:
            tmp = os.path.join(r,file)
            with open(tmp) as f:
                lines = f.readlines()
                tmp1 = os.path.join(path2,file)
                for i in lines:
                    tmp_line = '0'+i[1:]
                    f2 = open(tmp1,'a')
                    f2.write(tmp_line)
                f2.close()

def k_fold(path,path2,key_value):
    from shutil import copyfile
    # copyfile(path,path2)
    lst = ['flip','Rotation180','Rotation90','Rotation270','shrink']
    for index,flag in enumerate(lst):
        for r,d,f in os.walk(path):
            for file in f:
                if file.split('+')[-1].split('.')[0] == flag:
                    old_path = os.path.join(path,file)
                    flag_file = f'fold{index+1}\\val\\{key_value}'
                    new_path = os.path.join(path2,flag_file,file)
                    copyfile(old_path,new_path)
                else:
                    old_path = os.path.join(path, file)
                    flag_file = f'fold{index+1}\\train\\{key_value}'
                    new_path = os.path.join(path2, flag_file, file)
                    copyfile(old_path, new_path)

path = r'D:\yolo\yolov5-6.2\data\sample\moreChange\newlabels'
path2 = r'D:\yolo\yolov5-6.2\data\sample\moreChange'
path3 = r'D:\yolo\yolov5-6.2\data\sample\moreChange\fold1\val'
k_fold(path,path2,key_value='labels')


import json

states = {
    "Andhra Pradesh": "Hyderabad",
    "Karnataka": "Bengaluru",
    "Maharashtra": "Mumbai",
    "Odisha": "Bhubaneswar",
    "Punjab": "Chandigarh",
    "Tamil Nadu": "Chennai",
    "Uttar Pradesh": "Lucknow"
}

with open('states.json', 'w') as f:
    json.dump(states, f)


#while문의 기본구조
# while 조건식: #조건식이 참인 경우 무한 반복
#     실행문

# a=10
# while a>5:
#     print("참입니다")

#조건을 체크 후 True이면 실행문을 1회 실행시키고
#다시 조건을 체크하러 돌아온다. 그리고 True이면 또 실행
#그러다가 조건이 False가 되면 while문 종료
# a=0
# while a<5:
#     print(str(a)+"반복")
#     a+=1

# 연습문제 1~1000까지만 프린트 되도록 출력
# 연습문제 1~1000까지 모두 더한 값을 출력
# a=1
# total=0
# while a<=1000:
#     total+=a
#     a=a+1
# print(total)

#while문에서 반복을 진행하다가 break를 만나면, 반복문 종료.
#1)if문을 써서 xxx한 조건에 break
# a=1
# total=0
# while True:
#     total+=a
#     if a==100:
#         break
#     a+=1
# print(total)

#continue: 이 구문을 만나면 다시 반복문 조건으로 이동
#하단에 불필요한 로직을 수행하지 않고 다시 조건으로 이동할 수 있게 함

#아래와 같이 코딩하면 무한 반복됨
# a=0
# while a<1000:
#     print("hello")
#     continue
#     a+=1

#continue문을 활용해보자
# a=0
# total=0
# while a<1000:
#     a +=1
#     if a % 2==0:
#         continue
#     total +=a
# print(total)

#2)1~1000중에 홀수만 더해서 출력
# a=0
# total=0
# while a<1000:
#     a +=1
#     if a % 2!=0:
#         total +=a
# print(total)

#로또 번호 생성기
#랜덤의 값을 추출하는 파이썬 라이브러리 =>random
#리스트의 크기가 6개인 리스트를 만들어서 오늘의 로또번호를 만들어보자

# print(random.randint(1,45))
# import random

# a=0
# lista=[]
# while a<6:
#     b= random.randint(1,45)
#     lista.append(b)
#     a+=1
# print(lista)

#for문의 기본 구조
# for 변수 in 반복가능한 자료형(iterable)
#     실행문
# lista=[1,2,3,4,5,6,7,8,9,10]
# for a in lista:  #lista에 있는 자료가 순차적으로 a에 전부 출력이 되는 형식
#     print(a)

# listb=["abc","bcd"]
# for b in listb:
#     print(b)

# #range문법: range(x,y) x이상 y미만
# for a in range(1,101): #100까지 출력하고 싶으면 101로 기재해야함, 왜냐면 y미만이라는 공식이기 때문에
#     print(a)

#range의 의미: iterable객체
# v1=list(range(1,10))
# print(v1)

#range(x,y): x이상, y미만의 숫자를 담은 객체
#range(y): 0이상 y미만의 숫자를 담은 객체

# v1=list(range(10,20))
# #for a in 리스트를 써서 v1의 값을 모두 출력
# for a in v1:
#     print(a)

# #for a in range를 써서 v1[index]의 형태로 v1의 값을 모두 출력
# for a in range(len(v1)):
#     print(v1[a])

# #for a in 리스트 구문으로는 원본리스트 데이터를 변경 할 수 없다.
# lista=[10,20,30,40,50,60]
# lista[5]=100
# # for a in lista:
# #     a=100  #이런 방식으로는 원본의 lista의 값을 변경 할 수 없다.

# for a in range(len(lista)):
#     lista[a]=100
# print(lista)

# #리스트를 만드는 방법중에 리스트 컴프리헨션이라는 방법이 있다.
# #리스트에 0~9까지 담는 방법

# #방법1, 그냥 리스트 생성하는 방법
# lista=[0,1,2,3,4,5,6,7,8,9]

# #방법2
# lista=list(range(10))

# #방법3, 홀수인 값에 2를 곱한 값만을 list로
# lista=[]
# for a in range(10):
#     if a % 2 !=0:
#         lista.append(a*2)

# #방법4: 리스트 컴프리헨션으로 방법3을 표현
# lista= [a*2 for a in range(10) if a % 2 !=0] #장점: 간결하다
# print(lista)

#연습문제 나만의 리스트 만들기
# 리스트의 크기를 키보드로 입력받아 그 크기만큼 임의 숫자를 리스트에 추가하고,
# 리스트의 크기와 값 전체를 출력하라. 모든 값은 키보드로 입력을 받고, list의 크기는
# len() 함수를 통해 구하라. 단, 리스트의 크기는 10 이하로 입력하라.

# [출력화면 예시]
# 리스트의 크기를 정하세요!30
# 리스트의 크기를 10 이하로 다시 할당하세요!9
# 리스트에 값을 할당해 보세요! 1
# 리스트에 값을 할당해 보세요! 2
# …………………………………
# 리스트에 값을 할당해 보세요! 9
# 크기9의 리스트 ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 가 할당 되었어요

# size=int(input("리스트의 사이즈를 입력해주세요"))
# a=0
# lista=[]
# while a < size:
#     value=input("리스트의 값을 입력해주세요")
#     lista.append(value)
#     a+=1
# print("크기", size , "의 리스트", lista, "가 할당 되었어요")

#한 반에 수학점수가 60점이 넘으면 합격, 60점 미만이면 불합격
lista=[90,25,67,45,80]
#위 list가 학생의 번호 순서대로 있을때, 아래와 같이 출력하도록 코딩하여라.
#1번 학생은 합격입니다. 2번 학생을 불합격입니다, ...

#방법1
# num=1
# for i in lista:
#     if i>=60:
#         print("%d 번 학생은 합격입니다" %num)
#     else:
#         print("%d 번 학생은 불합격입니다." %num)
#     num+=1

#방법2 for i in range로 하는 방법
# for i in range(len(lista)):
#     if lista[i]>=60:
#         print("%d 번 학생은 합격입니다" % (i+1))
#     else:
#         print("%d 번 학생은 불합격입니다." % (i+1))

#for문과 break: for문에서 break문을 반드시 써야 하는 상황
#혈액형이 a형인 고객 선착순 1명만 찾는 상황.
lista=['b','b','ab','a','b','a']
#출력결과: n번째 고객이 이벤트에 당첨되었습니다.
# for i in range(len(lista)):
#     if lista[i] =='a':
#         print(f"{i+1}번째 고객이 당첨되었습니다")
#         break

#방법2
for i in range(len(lista)):
    if lista[i] =='a':
        answer=i+1
        break
print(str(answer) +"번째 고객이 당첨되었습니다")

#for문을 이용한 구구단
#5단 결과 출력:
# 5X1 = 5
# 5X2 = 10 ... 이렇게 나오게 하기

#정답
# for i in range(1,10):
#     print(5 ,"X", i, "=", 5*i)  #print(f"5 X {i} = {5*i}") 이런식으로도 표현 가능

#문제2) 구구단 몇단을 계산해드릴까요?
# while True이용하기
# while True:
#     num=int(input("구구단 몇단을 계산해드릴까요?:"))
#     for i in range(1,10):
#         print(num ,"X", i, "=", num*i)

#2중 for문
#구구단을 5단~9단까지 한꺼번에 출력해보자
# for i in range(5,10):
#     for j in range(1,10):
#         print(i, "X", j, "=", i*j)

#다른 방법2
num=5
while num<10:
    for a in range(1,10):
        print(f"{num} X {a}={num*a}")
    num+=1

#문제
lista=[10,20,30,40]
#lista의[0]와[1]의 자리를 바꾸려면?
num1=lista[0]
lista[0]=lista[1]
lista[1]=num1
print(lista)

'''
lista[0]=lista[1]
lista[1]=lista[0] 이 방법으로는 안됨
'''
#파이썬에서 지원하고 있는 문법
# lista[0],lista[1]=lista[1],lista[0] 이렇게도 표현이 가능하다.

#for문을 이용한 정렬 알고리즘
lista=[93,45,21,30,20,94,66,71,45]
#위 리스트를 어떻게 오름차순 정렬 할 것인가?
#선택정렬: 0번째 인덱스부터 가장 작은 값을 채워나가는 방법
#첫번째 for문은 채워나가야할 index를 의미,
for i in range(len(lista)-1):
    #2번째 for문은 비교의 대상이 되는 index를 의미
    for j in range(i+1,len(lista)):
        if lista[i] > lista[j]:   #자리 change
            # lista[i],lista[j]=lista[j],lista[i] #이렇게 해도 됨
            temp=lista[i]
            lista[i]=lista[j]
            lista[j]=temp
print(lista)

#버블정렬
#직접 배우자


'''
# Module name:
    jdfundindex.py

# Prerequisite:
    Based on Python 3.4
    Need python module requests and bs4

# Purpose:
    Fund index sensor powered by JD

# Author:
    Retroposter retroposter@outlook.com

# Created:
    Sep.8th 2017

# Last Modified:
    Jan.23th 2018
'''

from datetime import datetime, timedelta
import json
import logging
import time

from bs4 import BeautifulSoup
from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout
import requests
import re
import voluptuous as vol

from homeassistant.const import (CONF_LATITUDE, CONF_LONGITUDE, CONF_API_KEY, CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_CELSIUS, ATTR_ATTRIBUTION)
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Fund Index'
ATTRIBUTION = 'Powered by JD'

CONF_UPDATE_INTERVAL = 'update_interval'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_UPDATE_INTERVAL, default=timedelta(hours=1)): (vol.All(cv.time_period, cv.positive_timedelta))
})

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Fund sensor."""
    name = config[CONF_NAME]
    interval = config.get(CONF_UPDATE_INTERVAL)
    index_data = JdFundIndexData(interval)
    index_data.update()
    # If connection failed don't setup platform.
    if index_data.data is None:
        return False
    sensors = [JdFundIndexSensor(index_data, name)]
    add_devices(sensors, True)

class JdFundIndexSensor(Entity):
    def __init__(self, index_data, name):
        """Initialize the sensor."""
        self.index_data = index_data
        self.client_name = name
        self._state = None

    @property
    def name(self):
        """Return the name of the sensor."""
        return self.client_name

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        if self._state < 41:
            return 'mdi:emoticon-sad'
        if self._state < 50:
            return 'mdi:emoticon-neutral'
        if self._state < 61:
            return 'mdi:emoticon-happy'
        return 'mdi:emoticon-excited'

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        return 'Pts'

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        attrs = {}
        attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
        data = self.index_data.data
        if data is None:
            return attrs
        attrs['交易日'] = data['index_date']
        attrs['整体走势'] = data['summary']
        if data['hot_list'] is not None:
            for hot in data['hot_list']:
                attrs[hot['name']] = hot['index']
        return attrs

    def update(self):
        """Get the latest data from He Weather and updates the states."""
        self.index_data.update()
        data = self.index_data.data
        if data is None:
            return
        self._state = data['index']

class JdFundIndexData(object):
    """Get the latest data from JD."""

    def __init__(self, internal):
        self.data = None
        # Apply throttling to methods using configured interval
        self.update = Throttle(internal)(self._update)

    def _update(self):
        timespan = str(time.time())
        resp = None
        try:
            resp = requests.post('https://licai.jd.com//async/financing/getJZBroadCast.action?_dc=' + timespan)
        except (ConnectError, HTTPError, Timeout, ValueError) as error:
            _LOGGER.error('Unable to connect to licai.jd.com. %s', error)
            return
        if resp is None:
            return
        json_data = json.loads(resp.text)
        self.data = {}
        self.data['index'] = json_data['heat']
        self.data['index_date'] = json_data['degreeDateStr'][0:10]
        self.data['summary'] = json_data['shareAdvise']
        self.data['hot_list'] = None

        resp = None
        try:
            resp = requests.post('https://fund.jd.com/topicRecommend.action?t=' + timespan)
        except (ConnectError, HTTPError, Timeout, ValueError) as error:
            _LOGGER.error('Unable to connect to fund.jd.com. %s', error)
            return
        if resp is None:
            return
        json_data = json.loads(resp.text)
        hot_list = []
        for industry in json_data:
            hot = {'name': industry['strategyName'], 'index': industry['degree']}
            hot_list.append(hot)
        self.data['hot_list'] = hot_list


number_of_matrix = int(input("¿Cuantas matrices quieres sumar?: "))

if number_of_matrix > 1:

    rows = int(input("¿Cuantas filas tendrán las matrices?: "))
    columns = int(input("¿Cuantas columnas tendrán las matrices?: "))

    matrix_list = []

    # Llenado de matrices
    for number in range(number_of_matrix):
        matrix = []
        for row in range(rows):
            new_row = []
            for column in range(columns):
                new_row.append(
                    int(input(f"Introduce un elemento para la matriz {number + 1} fila {row}, columna {column}: ")))
            matrix.append(new_row)
        matrix_list.append(matrix)

    # Suma de las matrices
    matrix = []
    for row in range(rows):
        new_row = []
        for column in range(columns):
            sum_matrix = 0
            for matrix_position in range(len(matrix_list)):
                sum_matrix += matrix_list[matrix_position][row][column]
            new_row.append(sum_matrix)
        matrix.append(new_row)
    matrix_list.append(matrix)

    # Imprimir matrices
    for matrix_row in range(rows):
        for matrix_list_position in range(len(matrix_list)):
            if matrix_row != 1:
                print(f"{matrix_list[matrix_list_position][matrix_row]}", end="   ")
            else:
                if matrix_list_position < len(matrix_list) - 2:
                    print(f"{matrix_list[matrix_list_position][matrix_row]}", end=" + ")
                elif matrix_list_position < len(matrix_list) - 1:
                    print(f"{matrix_list[matrix_list_position][matrix_row]}", end=" = ")
                else:
                    print(f"{matrix_list[matrix_list_position][matrix_row]}", end="   ")
        print()

else:
    print("Se necestinas dos o más matrices para realizar la suma.")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Класс: Поиск в коде однострочных комментариев вида '#' и многострочных  вида '=begin ... =end'
"""
import re

class RubyComments:

    def __init__(self,code):
        self._code  = code + '\n'
        self._lines = set()

    @property
    def comment_lines_count(self):
        """ Возвращает количество строк с '#' в self._code """
        # преобразуем результат соответствия регулярного выражения в множество позиций символов
        match_to_set = lambda m: set(range(*m.span()))
        # возвращаем итератор соответствий регулярного выражения в self._code
        re_iter      = lambda expr: re.finditer(expr, self._code)
        code = list(enumerate(match_to_set(m) for m in re_iter('.*\n')))
        for m in re_iter('#(.*\\\s*\n)+.*\n|#.*\n|/\*(\n|.)*?\*/'):
            self._lines |= set(s[0] for s in code if match_to_set(m) & s[1])
        return len(self._lines)


from sklearn.metrics import matthews_corrcoef #计算MCC
from sklearn.metrics import confusion_matrix, accuracy_score, matthews_corrcoef, recall_score, roc_curve, roc_auc_score
from sklearn.metrics.ranking import auc
import pandas  as pd
import matplotlib.pyplot as plt
test_label=pd.read_csv("_label.csv", header=None)
print(test_label.shape)

p=pd.read_csv("test.csv", header=None)
p=p.iloc[:,2]
print(p.shape)
pp=[i>0.5 for i in p]
fpr, tpr, threshold = roc_curve(test_label, p)
roc_auc = auc(fpr, tpr)
print("MCC: %f " %matthews_corrcoef(test_label,pp))
print("AUC",roc_auc)

plt.figure(figsize=(10,10))
plt.plot(fpr, tpr, color='red',lw=2, label='PPIformer :ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve comparison of the models')
'''
#Data  A
Ctest_label=pd.read_csv("_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("test_111_2.csv", header=None)
Cp=Cp.iloc[:,2]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='green',lw=2, label='without Data Augmentation :ROC curve (area = %0.2f)' % roc_auc)##假正率为横坐标，真正率为纵坐标做曲线

'''
#RF
Ctest_label=pd.read_csv("RF_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("RF.csv", header=None)
Cp=Cp.iloc[:,1]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='green',lw=2, label='RF:ROC curve (area = %0.2f)' % roc_auc)##假正率为横坐标，真正率为纵坐标做曲线

#textCNN
Ctest_label=pd.read_csv("CNN_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("CNN2.csv", header=None)
Cp=Cp.iloc[:,2]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='blue',lw=2, label='TextCNN:ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线
#svm
Ctest_label=pd.read_csv("SVM_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("SVM.csv", header=None)
Cp=Cp.iloc[:,0]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='orange',lw=2, label='SVM:ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线

#DNN
Ctest_label=pd.read_csv("DNN_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("DNN2.csv", header=None)
Cp=Cp.iloc[:,2]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='pink',lw=2, label='DNN:ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线
#LR
Ctest_label=pd.read_csv("LR_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("LR.csv", header=None)
Cp=Cp.iloc[:,1]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='yellow',lw=2, label='LR:ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线
#lstm
Ctest_label=pd.read_csv("lstm_label.csv", header=None)
print(Ctest_label.shape)
Cp=pd.read_csv("lstm10.csv", header=None)
Cp=Cp.iloc[:,1]
print(Cp.shape)
fpr, tpr, threshold = roc_curve(Ctest_label, Cp)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, color='purple',lw=2, label='LSTM:ROC curve (area = 0.52)' )
plt.legend(loc=0)
plt.legend(loc="lower right")
plt.show()