text:
import torch
from torch.utils.tensorboard import SummaryWriter

import mmcv
from mmcv.runner import load_checkpoint, init_dist, get_dist_info, build_optimizer, set_random_seed
from mmcv import Config, DictAction
from mmaction.models import build_recognizer
from mmaction.datasets import build_dataset, build_dataloader

import argparse
import os.path as osp
import copy
import sys, os
from tqdm import tqdm
from scipy.io import savemat

def blockPrint():
    sys.stdout = open(os.devnull, 'w')

def args_parser():
    parser = argparse.ArgumentParser(description="Arguments for train dataloader")
    parser.add_argument('--output_mat', help='File name for saved .mat file (TCN)')
    parser.add_argument("--model_checkpoint", type=str, help="Location to model (.pth) file")
    parser.add_argument("--model_config", type=str, help="Locationto config file")
    parser.add_argument("--annotation_file", type=str, help="Path to annotation file")
    parser.add_argument("--data_prefix", type=str, help="Data location prefix")
    parser.add_argument("--batch_size", default=3, type=int, help="Batch size")
    parser.add_argument("--epoch", default=5, type=int, help="")
    parser.add_argument('--work-dir', help='the dir to save logs and models')
    parser.add_argument(
        '--resume-from', help='the checkpoint file to resume from')
    parser.add_argument(
        '--validate',
        action='store_true',
        help='whether to evaluate the checkpoint during training')
    parser.add_argument(
        '--test-last',
        action='store_true',
        help='whether to test the checkpoint after training')
    parser.add_argument(
        '--test-best',
        action='store_true',
        help=('whether to test the best checkpoint (if applicable) after '
              'training'))
    group_gpus = parser.add_mutually_exclusive_group()
    group_gpus.add_argument(
        '--gpus',
        type=int,
        help='number of gpus to use '
             '(only applicable to non-distributed training)')
    group_gpus.add_argument(
        '--gpu-ids',
        type=int,
        nargs='+',
        help='ids of gpus to use '
             '(only applicable to non-distributed training)')
    parser.add_argument('--seed', type=int, default=None, help='random seed')
    parser.add_argument(
        '--deterministic',
        action='store_true',
        help='whether to set deterministic options for CUDNN backend.')
    parser.add_argument(
        '--cfg-options',
        nargs='+',
        action=DictAction,
        default={},
        help='override some settings in the used config, the key-value pair '
             'in xxx=yyy format will be merged into config file. For example, '
             "'--cfg-options model.backbone.depth=18 model.backbone.with_cp=True'")
    parser.add_argument(
        '--launcher',
        choices=['none', 'pytorch', 'slurm', 'mpi'],
        default='none',
        help='job launcher')
    parser.add_argument('--local_rank', type=int, default=0)
    parser.add_argument('--feature_extraction', action='store_true')
    args = parser.parse_args()
    return args

def prepare_model(cfg, args, checkpoint_path, device=torch.device('cuda:0')):

    model = build_recognizer(cfg.model,
                             train_cfg=cfg.get('train_cfg'),
                             test_cfg=cfg.get('test_cfg'))

    if checkpoint_path is not None:
        load_checkpoint(model, checkpoint_path, map_location=device, strict=False)

    model.cfg = cfg
    model.to(device)
    model.cls_head.fc_cls = torch.nn.Linear(in_features=768, out_features=10, bias=True)
    for param in model.parameters():
        param.requires_grad = False
    if not args.feature_extraction:
        #for param in model.backbone.layers[-1].parameters():
        #    param.requires_grad = True
        for param in model.cls_head.parameters():
            param.requires_grad = True
    else:
        model.eval()
    return model.cuda()

def prepare_dataloader(cfg, shuffle):
    datasets = [build_dataset(cfg.data.train)]

    val_dataset = copy.deepcopy(cfg.data.val)
    datasets.append(build_dataset(val_dataset))
    dataloader_setting = dict(
        videos_per_gpu=cfg.data.get('videos_per_gpu', 1) // cfg.optimizer_config.get('update_interval', 1),
        workers_per_gpu=cfg.data.get('workers_per_gpu', 1),
        num_gpus=len(cfg.gpu_ids),
        shuffle=,
        dist=True,
        seed=cfg.seed)
    dataloader_setting = dict(dataloader_setting,
                              **cfg.data.get('train_dataloader', {}))
    data_loaders = [
        build_dataloader(ds, **dataloader_setting) for ds in datasets
    ]

    return data_loaders[0]

def train_model(model,
                dataloader,
                cfg,
                distributed=False,
                validate=False,
                test=dict(test_best=False, test_last=False)):

    optimizer = build_optimizer(model, cfg.optimizer)
    writer = SummaryWriter()
    #print(iter(dataloader)
    blockPrint()
    for ep in tqdm(range(10)):
        running_loss = 0
        for (batch_idx, batch) in enumerate(dataloader):
            optimizer.zero_grad()
            batch["imgs"], batch["label"] = batch["imgs"].cuda(), batch["label"].cuda()
            loss = model(return_loss=True, **batch)
            loss["loss_cls"].backward()
            optimizer.step()
            running_loss += loss["loss_cls"].item()
            if batch_idx % 50 ==0:
                writer.add_scalar("Loss/Train", running_loss/50, ep*batch_idx/50)
                running_loss = 0

def extract_feature(model, dataloader):
    newModel = model.backbone
    outputs = {}
    for (batch_idx, batch) in tqdm(enumerate(dataloader)):
        batch["imgs"], batch["label"] = batch["imgs"].cuda(), batch["label"].cuda()
        batch["imgs"] = batch["imgs"].reshape((-1,) + batch["imgs"].shape[2:])
        output = newModel(batch["imgs"])
        label = batch["label"][0].item()
        if label not in outputs:
            outputs[label] = output
        else:
            outputs[label] = torch.cat([outputs[label], output], dim=0)
    return outputs

def main():
    args = args_parser()

    cfg = Config.fromfile(args.model_config)

    if cfg.get('cudnn_benchmark', False):
        torch.backends.cudnn.benchmark = True
    cfg.model.backbone.pretrained = None
    if args.work_dir is not None:
        # update configs according to CLI args if args.work_dir is not None
        cfg.work_dir = args.work_dir
    elif cfg.get('work_dir', None) is None:
        # use config filename as default work_dir if cfg.work_dir is None
        cfg.work_dir = osp.join('./work_dirs',
                                osp.splitext(osp.basename(args.config))[0])
    if args.resume_from is not None:
        cfg.resume_from = args.resume_from
    if args.gpu_ids is not None:
        cfg.gpu_ids = args.gpu_ids
    else:
        cfg.gpu_ids = range(1) if args.gpus is None else range(args.gpus)

        # init distributed env first, since logger depends on the dist info.
    if args.launcher == 'none':
        distributed = False
    else:
        distributed = True
        init_dist(args.launcher, **cfg.dist_params)
        _, world_size = get_dist_info()
        cfg.gpu_ids = range(world_size)

        # The flag is used to determine whether it is omnisource training
    cfg.setdefault('omnisource', False)

    # The flag is used to register module's hooks
    cfg.setdefault('module_hooks', [])

    # create work_dir
    mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
    if args.seed is not None:
        set_random_seed(args.seed, deterministic=args.deterministic)
    cfg.seed = args.seed
    dataloader = prepare_dataloader(cfg, args.annotation_file, args.data_prefix, args.batch_size)

    model = prepare_model(cfg, args, args.model_checkpoint)

    if args.feature_extraction:
        mat_dict = {}
        X = None
        Y = None
        outputs = extract_feature(model, dataloader)
        for label in outputs:
            x = outputs[label].permute(0, 2,1,3,4)
            x = x.reshape(x.shape[0]*x.shape[1], x.shape[2]*x.shape[3]*x.shape[4])
            y = torch.tensor([label]*x.shape[0], dtype=torch.float32)
            if X is None:
                X = x
                Y = y
            else:
                X = torch.cat([X, x], dim=0)
                Y = torch.cat([Y, y], dim=0)
        X = X.detach().cpu().numpy()
        Y = Y.detach().cpu().numpy()
        mat_dict = {"X":X, "Y":Y}
        savemat('test.mat', mat_dict, oned_as='row')
    else:
        train_model(model,
                dataloader,
                cfg)

if __name__ == '__main__':
    main()

max_stars_repo_name: vinayakShenoy/Video-Swin-Transformer

max_issues_repo_name: vinayakShenoy/Video-Swin-Transformer

max_forks_repo_name: vinayakShenoy/Video-Swin-Transformer

reason: from scipy


text:
import cv2
import os, sys, json
import numpy as np
from pycocotools.coco import COCO
from pycocotools import mask as maskUtils
from skimage import measure
from tqdm import tqdm

"专门用于调用处理coco数据相关的脚本"
file_path = os.path.abspath(__file__)
sys.path.append(os.path.abspath(os.path.join(file_path, "..", "..", "..")))
from code_aculat.utils.coco_tools import annToMask, MyEncoder

def get_zero_boundry(image):
    row, col = image.shape[:2]
    vertical_line = image[:, int(col / 2), :]
    horizontal_line = image[int(row / 2), :, :]

    v_value = np.where(vertical_line > 0)[0]
    ymin, ymax = v_value[0], v_value[-1]

    h_value = np.where(horizontal_line > 0)[0]
    xmin, xmax = h_value[0], h_value[-1]

    return xmin, xmax, ymin, ymax

def main():
    "去除图片外围的0填充像素,并更新json标注"

    json_path = r"/home/data1/yw/copy_paste_empty/500_aug/hrsc_104_tv_raw_trans/Json/99.json"
    image_dir = "/home/data1/yw/copy_paste_empty/500_aug/hrsc_104_tv_raw_trans/Images"
    out_image_dir = os.path.join(os.path.dirname(image_dir), "new_%s" % os.path.basename(image_dir))
    os.makedirs(out_image_dir, exist_ok=True)

    json_save_path = os.path.join(os.path.dirname(json_path), "new_%s" % os.path.basename(json_path))
    coco = COCO(json_path)
    imgids = coco.getImgIds()  # 获取所有的image id

    new_images = []
    new_anns = []

    for imgid in tqdm(imgids):
        image_info = coco.loadImgs(imgid)[0]
        image_path = os.path.join(image_dir, image_info['file_name'])

        # process image array
        img_arr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
        xmin, xmax, ymin, ymax = get_zero_boundry(img_arr)
        img_arr = img_arr[ymin:ymax + 1, xmin:xmax + 1]

        # process image info
        old_height = image_info['height']
        old_width = image_info['width']

        image_info['height'] = img_arr.shape[0]
        image_info['width'] = img_arr.shape[1]

        new_images.append(image_info)
        cv2.imencode(".%s" % image_info['file_name'].split('.')[-1], img_arr)[1].tofile(
            os.path.join(out_image_dir, image_info['file_name']))

        ann_ids = coco.get_ann_ids(img_ids=image_info['id'])
        anns = coco.loadAnns(ann_ids)

        # update annotaions
        for ann in anns:
            new_mask = annToMask(ann, old_height, old_width)
            new_mask = new_mask[ymin:ymax + 1, xmin:xmax + 1]
            contours = measure.find_contours(new_mask, 0.5)  # must use np.flip with this method

            if len(contours) > 1:
                new_cont = []
                for ic in range(len(contours)):
                    if len(contours[ic]) > 20:
                        new_cont.append(contours[ic])
                contours = new_cont

            assert len(contours) == 1
            contours = np.flip(contours[0], axis=1)
            segmentation = [contours.ravel().tolist()]

            fortran_bina = np.asfortranarray(new_mask)
            encoded_bina = maskUtils.encode(fortran_bina)

            bina_bbox = maskUtils.toBbox(encoded_bina)

            ann["segmentation"] = segmentation
            ann["bbox"] = bina_bbox.tolist()

            new_anns.append(ann)

    with open(json_path, 'r') as f:
        jf = json.load(f)
        cate_list = jf['categories']

    new_coco_json = {'images': new_images, 'annotations': new_anns, 'categories': cate_list}

    with open(json_save_path, 'w') as  f:
        json.dump(new_coco_json, f, cls=MyEncoder)

ext: py

reason: import numpy


text:
from pyautocad import Autocad,APoint,ACAD
import numpy as np
import pyptlist
import random
import time

acad=Autocad(create_if_not_exists=True)

def getpoint():#从cad中获得点
    acad.doc.SetVariable('pdmode', 2)
    n = acad.doc.Utility.GetInteger('请输入点的个数(至少3个):')
    if n < 3:
        acad.prompt('输入点数量有误，程序终止')
        return
    ptlist = []
    for i in range(n):
        prompt1 = "请输入第%d/%d个点" % (i + 1, n)
        acad.prompt(prompt1)
        while True:  # 遇到呼叫错误，不断重复尝试。
            try:
                pt = acad.doc.Utility.GetPoint()
            except Exception:
                time.sleep(0.2)
                acad.doc.Regen(ACAD.acActiveViewport)
                #acad.prompt(prompt1)
                print('呼叫错误，重试')
            else:
                break
        time.sleep(0.1)
        pt = APoint(pt)
        acad.model.AddPoint(pt)
        ptlist.append(pt)
    while True:
        closed = acad.doc.Utility.GetString(0, '\n曲线是否闭合Y(闭合)/N(不闭合)?默认Y')
        if closed == '' or closed.lower() == 'y':
            tagclosed = True
            break
        elif closed.lower() == 'n':
            tagclosed = False
            break
        else:
            acad.prompt('输入有误，请重新输入！')
    return ptlist,tagclosed

def job1():
    ptlist,tagclosed=getpoint()
    myptlist=pyptlist.Polygon(ptlist)
    coor=myptlist.Akima(tagclosed)
    en=acad.model.AddLightWeightPolyline(np.float_(coor))
    en.Color=ACAD.acBlue

def job2():
    ptlist,tagclosed=getpoint()
    myptlist = pyptlist.Polygon(ptlist)
    coor = myptlist.Poly2interpolation(tagclosed)
    en = acad.model.AddLightWeightPolyline(np.float_(coor))
    en.Color = ACAD.acRed

def jobcombine():
    ptlist,tagclosed=getpoint()
    myptlist=pyptlist.Polygon(ptlist)
    coor=myptlist.Akima(tagclosed)
    en=acad.model.AddLightWeightPolyline(np.float_(coor))
    en.Color=ACAD.acBlue
    coor = myptlist.Poly2interpolation(tagclosed)
    en = acad.model.AddLightWeightPolyline(np.float_(coor))
    en.Color = ACAD.acRed

if __name__=="__main__":
    jobcombine()


text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy.spatial import Delaunay
from quadtree.point import Point
from quadtree.utils import find_children, get_neighbor_of_greater_or_equal_size, Direction, deeper, DEBUG_MODE, is_inside_polygon, node_is_inside_polygon, contains

class Mesh():
    def __init__(self, qtree):
        self.qtree = qtree
        self.triangles = []
        self.pts_inside_contour = []
        self.nodes_inside_polygon = []

    def mesh_generation(self):
        c = find_children(self.qtree.root)

        for u in c:
            d = u.depth
            dN = deeper(get_neighbor_of_greater_or_equal_size(u, Direction.N))
            dS = deeper(get_neighbor_of_greater_or_equal_size(u, Direction.S))
            dW = deeper(get_neighbor_of_greater_or_equal_size(u, Direction.W))
            dE = deeper(get_neighbor_of_greater_or_equal_size(u, Direction.E))

            x, y = u.x0, u.y0
            w_, h_ = u.width, u.height
            #print(d, dN, dS, dW, dE)
            # Padrao #1 -------------------------
            if d>=dN and d>=dS and d>=dW and d>=dE:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x, y + h_])
                # triangle 2
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])

            # Padrao #2 -------------------------
            if dW>d and d>=dN and d>=dS and d>=dE:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])
            if dE>d and d>=dN and d>=dS and d>=dW:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 2
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x, y + h_])
                # triangle 3
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
            if dN>d and d>=dW and d>=dS and d>=dE:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x, y + h_])
                # triangle 2
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
            if dS>d and d>=dN and d>=dW and d>=dE:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 2
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 3
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])

            # Padrao #3 -------------------------
            if dN>d and dW>d and d>=dS and d>=dE: #----1
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x, y + h_/2.])
                # triangle 3
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x, y + h_])
                # triangle 4
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 5
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
                # triangle 6
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
            if dN>d and dE>d and d>=dS and d>=dW: #----2
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 4
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y+ h_/2.])
                self.triangles.append([x, y + h_])
                # triangle 5
                self.triangles.append([x, y + h_])
                self.triangles.append([x + w_/2., y+ h_/2.])
                self.triangles.append([x + w_, y + h_])
                # triangle 6
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y+ h_/2.])
                self.triangles.append([x + w_, y + h_/2.])
            if dS>d and dE>d and d>=dW and d>=dN: #----3
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x, y + h_])
                # triangle 2
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])
                # triangle 5
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 5
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
            if dS>d and dW>d and d>=dN and d>=dE: #----4
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 5
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 6
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])

            # Padrao #4 -------------------------
            if dW>d and dE>d and d>=dS and d>=dN:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 5
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 6
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_/2.])
            if dN>d and dS>d and d>=dW and d>=dE:
                # triangle 1
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 2
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 5
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])
                # triangle 6
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x + w_/2., y + h_/2.])

            # Padrao #5 -------------------------
            if dW>d and dN>d and dS>d and d>=dE:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_/2., y])
                # triangle 4
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_, y])
                # triangle 5
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])
            if dW>d and dN>d and dE>d and d>=dS:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 4
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 5
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x + w_, y + h_/2.])
            if dN>d and dE>d and dS>d and d>=dW:
                # triangle 1
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 2
                self.triangles.append([x, y])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 5
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x + w_, y + h_/2.])
            if dW>d and dE>d and dS>d and d>=dN:
                # triangle 1
                self.triangles.append([x, y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x, y + h_/2.])
                # triangle 2
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x, y + h_/2.])
                # triangle 3
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 4
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 5
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])

            # Padrao #6 -------------------------
            if dW>d and dN>d and dS>d and dE>d:
                # triangle 1
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x, y + h_/2.])
                self.triangles.append([x, y])
                # triangle 2
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x, y + h_/2.])
                # triangle 3
                self.triangles.append([x + w_/2., y])
                self.triangles.append([x + w_, y])
                self.triangles.append([x + w_, y + h_/2.])
                # triangle 4
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_, y + h_])
                self.triangles.append([x + w_/2., y + h_])
                # triangle 5
                self.triangles.append([x + w_, y + h_/2.])
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_/2.])
                # triangle 6
                self.triangles.append([x + w_/2., y + h_])
                self.triangles.append([x, y + h_])
                self.triangles.append([x, y + h_/2.])

            else:
                if DEBUG_MODE:
                    print('warning! Not case found triangulation..')

    def mesh_generation_v2(self):
        c = find_children(self.qtree.root)

        xx_ = [point.x for point in self.qtree.points]
        yy_ = [point.y for point in self.qtree.points]
        polygon_ = list(zip(xx_, yy_))
        pt_countour = []

        for u in c:
            d = u.depth
            NN = get_neighbor_of_greater_or_equal_size(u, Direction.N)
            NS = get_neighbor_of_greater_or_equal_size(u, Direction.S)
            NW = get_neighbor_of_greater_or_equal_size(u, Direction.W)
            NE = get_neighbor_of_greater_or_equal_size(u, Direction.E)

            dN = deeper(NN)
            dS = deeper(NS)
            dW = deeper(NW)
            dE = deeper(NE)

            x, y = u.x0, u.y0
            w_, h_ = u.width, u.height

            if is_inside_polygon(polygon_, [x,y]) and is_inside_polygon(polygon_, [x+w_,y]) and is_inside_polygon(polygon_, [x,y+h_]) and is_inside_polygon(polygon_, [x+w_,y+h_]) and len(u.points)==0:
                self.nodes_inside_polygon.append(u)

                # Puntos de contorno
                if not node_is_inside_polygon(NN, polygon_):
                    pt_countour.append([x,y])
                    pt_countour.append([x+w_,y])
                if not node_is_inside_polygon(NS, polygon_):
                    pt_countour.append([x,y+h_])
                    pt_countour.append([x+w_,y+h_])
                if not node_is_inside_polygon(NW, polygon_):
                    pt_countour.append([x,y])
                    pt_countour.append([x,y+h_])
                if not node_is_inside_polygon(NE, polygon_):
                    pt_countour.append([x+w_,y])
                    pt_countour.append([x+w_,y+h_])

                #print(d, dN, dS, dW, dE)
                # Padrao #1 -------------------------
                if d>=dN and d>=dS and d>=dW and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x, y + h_])
                    # triangle 2
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])

                # Padrao #2 -------------------------
                if dW>d and d>=dN and d>=dS and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])
                if dE>d and d>=dN and d>=dS and d>=dW:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x, y + h_])
                    # triangle 3
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                if dN>d and d>=dW and d>=dS and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x, y + h_])
                    # triangle 2
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                if dS>d and d>=dN and d>=dW and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 2
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 3
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])

                # Padrao #3 -------------------------
                if dN>d and dW>d and d>=dS and d>=dE: #----1
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x, y + h_])
                    # triangle 4
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 5
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                    # triangle 6
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                if dN>d and dE>d and d>=dS and d>=dW: #----2
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 4
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y+ h_/2.])
                    self.triangles.append([x, y + h_])
                    # triangle 5
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x + w_/2., y+ h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    # triangle 6
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y+ h_/2.])
                    self.triangles.append([x + w_, y + h_/2.])
                if dS>d and dE>d and d>=dW and d>=dN: #----3
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x, y + h_])
                    # triangle 2
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])
                    # triangle 5
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                if dS>d and dW>d and d>=dN and d>=dE: #----4
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 5
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 6
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])

                # Padrao #4 -------------------------
                if dW>d and dE>d and d>=dS and d>=dN:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 5
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 6
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                if dN>d and dS>d and d>=dW and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 2
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])
                    # triangle 6
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x + w_/2., y + h_/2.])

                # Padrao #5 -------------------------
                if dW>d and dN>d and dS>d and d>=dE:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_/2., y])
                    # triangle 4
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_, y])
                    # triangle 5
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])
                if dW>d and dN>d and dE>d and d>=dS:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 4
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x + w_, y + h_/2.])
                if dN>d and dE>d and dS>d and d>=dW:
                    # triangle 1
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 2
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x + w_, y + h_/2.])
                if dW>d and dE>d and dS>d and d>=dN:
                    # triangle 1
                    self.triangles.append([x, y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 2
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 4
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])

                # Padrao #6 -------------------------
                if dW>d and dN>d and dS>d and dE>d:
                    # triangle 1
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x, y + h_/2.])
                    self.triangles.append([x, y])
                    # triangle 2
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 3
                    self.triangles.append([x + w_/2., y])
                    self.triangles.append([x + w_, y])
                    self.triangles.append([x + w_, y + h_/2.])
                    # triangle 4
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_, y + h_])
                    self.triangles.append([x + w_/2., y + h_])
                    # triangle 5
                    self.triangles.append([x + w_, y + h_/2.])
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_/2.])
                    # triangle 6
                    self.triangles.append([x + w_/2., y + h_])
                    self.triangles.append([x, y + h_])
                    self.triangles.append([x, y + h_/2.])

                else:
                    if DEBUG_MODE:
                        print('warning! Not case found triangulation..')
        # Remover puntos repetido
        seen = set()
        #print(pt_countour)
        for a,b in pt_countour:
            if (a,b) not in seen:
                self.pts_inside_contour.append([a,b])
            seen.add((a,b))

    def draw_delaunay(self):
        points = []

        xx_ = [point.x for point in self.qtree.points]
        yy_ = [point.y for point in self.qtree.points]
        polygon_ = list(zip(xx_, yy_))

        for pt in self.qtree.points:
            points.append([pt.x, pt.y])
        for pt in self.pts_inside_contour:
            points.append(pt)

        points = np.array(points)
        tri = Delaunay(points)

        # Remover triangulos que estan fuera del polygono original
        tri_v2 = []
        for i1, i2, i3 in  tri.simplices:
            c_x = (points[i1][0] + points[i2][0] + points[i3][0])/3.0
            c_y = (points[i1][1] + points[i2][1] + points[i3][1])/3.0
            if is_inside_polygon(polygon_, [c_x, c_y]):
                # Remover triangulos que estan dentro de self.nodes_inside_polygon
                add = True
                for el in self.nodes_inside_polygon:
                    x, y = el.x0, el.y0
                    w_, h_ = el.width, el.height
                    if contains(x, y, w_, h_, [Point(c_x, c_y)]):
                        add = False
                        break
                if add:
                    tri_v2.append([i1, i2, i3])

        print(tri_v2)
        plt.triplot(points[:,0], points[:,1], tri_v2)
        plt.plot(points[:,0], points[:,1], 'go')

    def draw(self, w, h, plot_points=True):
        _ = plt.figure(figsize=(12, 8))

        plt.figure()
        ax = plt.subplot()
        ax.set_xlim(0, w)
        ax.set_ylim(h, 0)

        i = 0
        while i<len(self.triangles):
            tri = []
            for _ in range(3):
                tri.append(self.triangles[i])
                i += 1
            t1 = plt.Polygon(tri, fill=False, edgecolor='black', lw=0.5)
            plt.gcf().gca().add_patch(t1)

        if plot_points:
            # plots the points as red dots
            xx = [point.x for point in self.qtree.points]
            yy = [point.y for point in self.qtree.points]
            plt.plot(xx, yy, 'ro')

            xx_ = [x for x,y in self.pts_inside_contour]
            yy_ = [y for x,y in self.pts_inside_contour]
            plt.plot(xx_, yy_, 'bo')

            plt.gcf().gca().add_patch(patches.Polygon(list(zip(xx,yy)), fill=False, color='b'))

            self.draw_delaunay()

        plt.show()

reason: import numpy,from scipy


text:
import argparse
from scipy.sparse import load_npz
from numpy import save as save_npy

parser = argparse.ArgumentParser(description='.npz to .npy converter')
parser.add_argument("path", help="data file path")
args = parser.parse_args()

npz = load_npz(args.path)
npy = npz.toarray()

save_npy(args.path.replace('.npz', '.npy'), npy)
print('Done')

max_stars_repo_name: ikulab/matrix-converer

reason: from numpy,from scipy


text:
"""
Reference
- https://medium.com/data-science-everywhere/ml-series-day-6-pandas-for-beginners-part-1-4aacad767d1c
"""
#%%

# Importing Pandas
import pandas as pd
print(pd.__version__)

#%%
#cars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
#Creating an empty Series
s = pd.Series()
s

#%%
# From List
list1 = [12,24,32]
s4 = pd.Series(list1)
s4

#%%

#with custom index values
s5 = pd.Series(list1, index = ['Peter', 'John', 'Mathew'])
s5

#%%
# From NumPy Array
import numpy as np
arr = np.array([12,24,32])
s = pd.Series(arr)
s2 = pd.Series(arr,index = ['Peter', 'John', 'Mathew'])
s
#%%
# From Python Dictionary
dict1 = {'Peter':12, 'John':24, 'Mathew':32}
s3 = pd.Series(dict1)
s3

# %%
#Retrieving data using position
s2[0]

# %%
#retrieve the first three element
s2[:3]

# %%
#retrieve the last three element
s2[-3:]

# %%
# Using label
s2['Peter']
s2[['Peter', 'John', 'Mathew']]

# %%
# axes
## Returns the list of the labels of the series
print(s2.axes)

# %%
# ndim
# Returns dimension of the object.
print(s2.ndim)

# %%

max_stars_repo_name: aTechGuide/machine-learning

max_issues_repo_name: kamranalinitb/machine-learning

max_forks_repo_name: kamranalinitb/machine-learning


text:
import copy
import numpy as np

def get_coords(cams_eop):
    grid = cams_eop.data["PM2_5"].squeeze()
    bbox = cams_eop.bbox
    X = bbox.min_x, bbox.max_x
    Y = bbox.min_y, bbox.max_y

    coords = []
    positions = []
    for i in range(grid.shape[0]):
        for j in range(grid.shape[1]):
            if not np.isnan(grid[i, j]):
                x = X[0] * (1 - j / (grid.shape[1] - 1)) + \
                    X[1] * (j / (grid.shape[1]-1))
                y = Y[0] * (1 - i / (grid.shape[0] - 1)) + \
                    Y[1] * (i / (grid.shape[0]-1))
                coords.append((x, y))
                positions.append((i, j))

    return coords, positions

def _get_point(lat, lon, grid, bbox):
    min_x, max_x, min_y, max_y = bbox.min_x, bbox.max_x, bbox.min_y, bbox.max_y

    delta_x = max_x - min_x
    deltas_x = np.arange(grid.shape[1]) * delta_x / (grid.shape[1]-1)
    coords_x = min_x + deltas_x
    x_ind = np.argmin(np.abs(coords_x-lon))

    delta_y = max_y - min_y
    deltas_y = np.arange(grid.shape[0]) * delta_y / (grid.shape[0]-1)
    coords_y = min_y + deltas_y[::-1]
    y_ind = np.argmin(np.abs(coords_y-lat))

    return y_ind, x_ind

def get_point(gt_row, eop, key):
    lat, lon = gt_row[["SITE_LATIT", "SITE_LONGI"]]

    grid = eop.data[key[0] if isinstance(key, list) else key][0]
    eop = copy.deepcopy(eop)

    coords = _get_point(lat, lon, grid, eop.bbox)
    y_ind, x_ind = coords

    if isinstance(key, list):
        return {k: eop.data[k][:, y_ind, x_ind] for k in key}, coords
    else:
        data = eop.data[key]
        value = data[:, y_ind, x_ind]
        return value, coords

def get_patch(gt_row, eop, patch_size):
    lat, lon = gt_row[["SITE_LATIT", "SITE_LONGI"]]
    grid = eop.mask_timeless['CORINE'][..., 0]

    coords = _get_point(lat, lon, grid, eop.bbox)
    y_ind, x_ind = coords

    patch = grid[y_ind-patch_size:y_ind+1+patch_size,
                 x_ind-patch_size:x_ind+1+patch_size]
    return patch

def _get_patch(lat, lon, grid, bbox, patch_size):
    coords = _get_point(lat, lon, grid, bbox)
    y_ind, x_ind = coords
    patch = grid[y_ind-patch_size:y_ind+1+patch_size,
                 x_ind-patch_size:x_ind+1+patch_size]
    return patch


text:
from fba.utils.torch_utils import mask2torch
import torch
import tqdm
import numpy as np
import enum
from fba import logger, utils
from fba import build_generator, build_discriminator
from fba.engine.checkpointer import load_checkpoint, get_closest_ckpt

def build_trained_generator(cfg, global_step=None):
    try:
        ckpt_path = get_closest_ckpt(cfg.checkpoint_dir, global_step)
    except FileNotFoundError as e:
        if cfg.checkpoint_url is None:
            raise e
        ckpt_path = utils.download_file(cfg.checkpoint_url)
    ckpt = load_checkpoint(ckpt_path)
    global_step = ckpt["global_step"] if "global_step" in ckpt else None
    ckpt = ckpt["EMA_generator"]

    g = build_generator(cfg)
    g.eval()
    g.load_state_dict(ckpt)
    print(f"Generator loaded, num parameters: {utils.num_parameters(g)/1e6}M")
    return g, global_step

def build_trained_discriminator(cfg, global_step=None):
    ckpt_path = get_closest_ckpt(cfg.checkpoint_dir, global_step)
    ckpt = load_checkpoint(ckpt_path)["D"]

    d = build_discriminator(cfg)
    d.load_state_dict(ckpt)
    return d, ckpt_path

class TruncationStrategy(enum.Enum):
    NONE = None
    W_CLAMP = "W_CLAMP"
    W_INTERPOLATE = "W_INTERPOLATE"
    Z_CLAMP = "Z_CLAMP"
    Z_INTERPOLATE = "Z_INTERPOLATE"

def sample_from_G(batch, G, truncation_strategy: TruncationStrategy, truncation_level: float):
    z = torch.randn((batch["img"].shape[0], G.z_channels), device=batch["img"].device)
    has_intermediate_latent = hasattr(G, "style_net") and hasattr(G.style_net, "E_map") and G.style_net.E_map.input_z
    if truncation_strategy in [TruncationStrategy.W_CLAMP, TruncationStrategy.W_INTERPOLATE] and not has_intermediate_latent:
        logger.warn("Setting truncation strategy to Z_CLAMP as the generator has no style net.")
        truncation_strategy = TruncationStrategy.Z_CLAMP
    if truncation_level is None:
        return G(**batch, z=z)
    if truncation_strategy in (TruncationStrategy.W_CLAMP, TruncationStrategy.W_INTERPOLATE):
        w_avg = G.style_net.E_map.get_average_w().repeat(batch["img"].shape[0], 1)
        w = G.style_net.E_map.map_network(z)
        if truncation_strategy == TruncationStrategy.W_INTERPOLATE:
            assert abs(truncation_level) <= 1
            w = w_avg.lerp(w.float(), truncation_level)
        if truncation_strategy == TruncationStrategy.W_CLAMP:
            assert truncation_level >= 0
            w = w.clamp(w_avg-truncation_level, w_avg+truncation_level)
        z = None
    elif truncation_strategy in (TruncationStrategy.Z_CLAMP, TruncationStrategy.Z_INTERPOLATE):
        w = None
        if truncation_strategy == TruncationStrategy.Z_INTERPOLATE:
            z = z*truncation_level
            assert abs(truncation_level) <= 1
        if truncation_strategy == TruncationStrategy.Z_CLAMP:
            assert truncation_level >= 0
            z = z.clamp(-truncation_level, truncation_level)
    else:
        z, w = None, None

    return G(**batch, w=w, z=z)


text:
import matplotlib
import numpy as np

def polyfit (dates, levels, p):

    # dates = matplotlib.dates.date2num(dates)
    p_coeff = np.polyfit(dates,levels,p)
    # p_coeff = np.polyfit(dates-dates[0],levels,p)

    poly = np.poly1d(p_coeff)

    return poly, dates[0]


text:
import numpy as np
import utils

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from english_stemmer import EnglishTokenizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_fscore_support

tweets = None
classifications = None

with open('../corpus/sentiment140/tweets.txt', 'r') as tweets_file:
    tweets = np.array(tweets_file.read().splitlines() )

with open('../corpus/sentiment140/classification.txt', 'r') as classifications_file:
    classifications = np.array(classifications_file.read().splitlines())

population = utils.prepare_entr_tweets(tweets, classifications, 1)
classifier = LogisticRegression(C=2,
                                class_weight='balanced',
                                fit_intercept=True,
                                penalty='l2',
                                warm_start=True)

pipeline = Pipeline([('tfidf', TfidfVectorizer(binary=True,
                                               ngram_range=(1, 1),
                                                smooth_idf=False,
                                                stop_words='english',
                                                sublinear_tf=False,
                                                tokenizer=EnglishTokenizer(),
                                                use_idf=True)),
                     ('clf', classifier)])

pipeline.fit(population['train_tweets'], y=population['train_classif'])

predicted = pipeline.predict(population['val_tweets'])

metrics = precision_recall_fscore_support(population['val_classif'], predicted, average='macro', pos_label=None)

print("\nPrecision:{0}\nRecall:{1}\nF1:{2}\n".format(
        metrics[0], metrics[1], metrics[2]))

print("###############################################################")

population = utils.prepare_entr_tweets(tweets, classifications, 2)
classifier = LogisticRegression(C=2.5,
                                class_weight=None,
                                fit_intercept=True,
                                penalty='l2',
                                warm_start=True)

pipeline = Pipeline([('tfidf', TfidfVectorizer(binary=True,
                                               ngram_range=(1, 2),
                                                smooth_idf=True,
                                                stop_words='english',
                                                sublinear_tf=True,
                                                tokenizer=EnglishTokenizer(),
                                                use_idf=True)),
                     ('clf', classifier)])

pipeline.fit(population['train_tweets'], y=population['train_classif'])

predicted = pipeline.predict(population['val_tweets'])

metrics = precision_recall_fscore_support(population['val_classif'], predicted, average='macro', pos_label=None)

print("\nPrecision:{0}\nRecall:{1}\nF1:{2}\n".format(
        metrics[0], metrics[1], metrics[2]))

max_stars_repo_name: alesanmed/asr-twitter

max_issues_repo_name: alesanmed/asr-twitter

max_forks_repo_name: alesanmed/asr-twitter


text:
from __future__ import print_function
import sys
sys.path.append('..')
import numpy as np
from tqdm import tqdm
import theano
import theano.tensor as T
from load import load_imgs
import argparse
import train_dcgan_utils
import train_dcgan_config
import os
from time import time
from lib import utils

# set parameters and arguments
parser = argparse.ArgumentParser('compute batchnorm statistics for DCGAN model')
parser.add_argument('--model_name', dest='model_name', help='model name', default='shoes_64', type=str)
parser.add_argument('--ext', dest='ext', help='experiment name=model_name+ext', default='', type=str)
parser.add_argument('--data_file', dest='data_file', help='the file that stores the hdf5 data', type=str, default=None)
parser.add_argument('--batch_size', dest='batch_size', help='the number of examples in each batch', type=int, default=128)
parser.add_argument('--num_batches', dest='num_batches', help='number of batches for estimating batchnorm parameters', type=int, default=1000)
parser.add_argument('--cache_dir', dest='cache_dir', help='cache directory that stores models, samples and webpages', type=str, default=None)
args = parser.parse_args()

expr_name = args.model_name + args.ext
npx, n_layers, n_f, nc, nz, niter, niter_decay = getattr(train_dcgan_config, args.model_name)()
num_batches = args.num_batches
batch_size = args.batch_size

if not args.cache_dir:
    args.cache_dir = './cache/%s/' % expr_name

if not args.data_file:
    args.data_file = '../datasets/%s.hdf5' % args.model_name

for arg in vars(args):
    print('[%s] =' % arg, getattr(args, arg))

model_dir = os.path.join(args.cache_dir, 'models')
predict_bn_path = os.path.join(model_dir, 'predict_batchnorm')
ntrain = batch_size * num_batches

# load data
tr_data, te_data, tr_stream, te_stream, ntrain, ntest = load_imgs(ntrain=ntrain, ntest=None, batch_size=batch_size, data_file=args.data_file)

# define theano model
predict_params = train_dcgan_utils.init_predict_params(nz=nz, n_f=n_f, n_layers=n_layers)
print('load predictive model from %s' % model_dir)
train_dcgan_utils.load_model(predict_params, os.path.join(model_dir, 'predict_params'))

x = T.tensor4()
z_p, bn_data = train_dcgan_utils.predict_batchnorm(x, predict_params, n_layers=n_layers)

print('COMPILING...')
t = time()
_estimate_batchnorm = theano.function([x], bn_data)
print('%.2f seconds to compile theano functions' % (time() - t))

nb_sum = []
nb_mean = []
nb_mean_ext = []
num_batches = int(np.floor(ntrain / float(batch_size)))
print('n_batch = %d, batch_size = %d' % (num_batches, batch_size))

# first pass
print('first pass: computing mean')
n = 0
for imb, in tqdm(tr_stream.get_epoch_iterator(), total=ntrain / batch_size):
    imb = train_dcgan_utils.transform(imb, nc=nc)
    bn_data = _estimate_batchnorm(imb)

    if n == 0:
        for d in bn_data:
            nb_sum.append(d)
    else:
        for id, d in enumerate(bn_data):
            nb_sum[id] = nb_sum[id] + d
    n = n + 1
    if n >= num_batches:
        break
# compute empirical mean
for id, d_sum in enumerate(nb_sum):
    if d_sum.ndim == 4:
        m = np.mean(d_sum, axis=(0, 2, 3)) / num_batches
        nb_mean.append(m)
        nb_mean_ext.append(np.reshape(m, [1, len(m), 1, 1]))
    if d_sum.ndim == 2:
        m = np.mean(d_sum, axis=0) / num_batches
        nb_mean.append(m)
        nb_mean_ext.append(m)

# second pass
print('second pass: computing variance')
tr_stream.reset()
nb_var_sum = []
n = 0

for imb, in tqdm(tr_stream.get_epoch_iterator(), total=ntrain / batch_size):
    imb = train_dcgan_utils.transform(imb, nc=nc)
    bn_data = _estimate_batchnorm(imb)
    if n == 0:
        for id, d in enumerate(bn_data):
            var = (np.copy(d) - nb_mean_ext[id]) ** 2
            nb_var_sum.append(var)
    else:
        for id, d in enumerate(bn_data):
            var = (np.copy(d) - nb_mean_ext[id]) ** 2
            nb_var_sum[id] = nb_var_sum[id] + var
    n += 1
    if n >= num_batches:
        break

# compute empirical variance
nb_var = []
for id, var_sum in enumerate(nb_var_sum):
    if var_sum.ndim == 4:
        nb_var.append(np.mean(var_sum, axis=(0, 2, 3)) / (num_batches - 1))

    if var_sum.ndim == 2:
        nb_var.append(np.mean(var_sum, axis=0) / (num_batches - 1))

print('saving model to %s' % predict_bn_path)
predict_batchnorm = nb_mean + nb_var
utils.PickleSave(predict_bn_path, predict_batchnorm)

max_stars_repo_name: CosmosHua/iGAN

max_issues_repo_name: CosmosHua/iGAN

max_forks_repo_name: CosmosHua/iGAN

reason: import numpy,import theano


text:
import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr

class TestUseCuDNN(unittest.TestCase):

    @attr.cudnn
    def test_valid_case_combination(self):
        with chainer.using_config('use_cudnn', 'always'):
            self.assertTrue(chainer.should_use_cudnn('==always'))
            self.assertTrue(chainer.should_use_cudnn('>=auto'))

        with chainer.using_config('use_cudnn', 'auto'):
            self.assertFalse(chainer.should_use_cudnn('==always'))
            self.assertTrue(chainer.should_use_cudnn('>=auto'))

        with chainer.using_config('use_cudnn', 'never'):
            self.assertFalse(chainer.should_use_cudnn('==always'))
            self.assertFalse(chainer.should_use_cudnn('>=auto'))

    @unittest.skipIf(cuda.cudnn_enabled, 'cudnn unavailable')
    def test_no_cudnn_available(self):
        with chainer.using_config('use_cudnn', 'always'):
            self.assertFalse(chainer.should_use_cudnn('==always'))
            self.assertFalse(chainer.should_use_cudnn('>=auto'))

    @attr.cudnn
    def test_invalid_level(self):
        self.assertRaises(ValueError, chainer.should_use_cudnn, '==auto')

    @attr.cudnn
    def test_invalid_config(self):
        with chainer.using_config('use_cudnn', True):
            self.assertRaises(ValueError, chainer.should_use_cudnn, '>=auto')

        with chainer.using_config('use_cudnn', False):
            self.assertRaises(ValueError, chainer.should_use_cudnn, '>=auto')

        with chainer.using_config('use_cudnn', 'on'):
            self.assertRaises(ValueError, chainer.should_use_cudnn, '>=auto')

    @attr.cudnn
    def test_higher_version_required(self):
        with chainer.using_config('use_cudnn', 'always'):
            self.assertFalse(chainer.should_use_cudnn(
                '>=auto', cuda.cuda.cudnn.getVersion() + 1))

class TestDtype(unittest.TestCase):

    def test_numpy_dtypes(self):
        for dtype in (numpy.float16, numpy.float32, numpy.float64):
            with chainer.using_config('dtype', dtype):
                self.assertEqual(chainer.get_dtype(), numpy.dtype(dtype))

    def test_specified_dtype(self):
        with chainer.using_config('dtype', numpy.float64):
            dtype = numpy.float16
            self.assertEqual(chainer.get_dtype(dtype), numpy.dtype(dtype))

    def test_mixed16_dtype(self):
        with chainer.using_config('dtype', chainer.mixed16):
            self.assertEqual(chainer.get_dtype(),
                             numpy.dtype(numpy.float16))
            self.assertEqual(chainer.get_dtype(map_mixed16=numpy.float32),
                             numpy.dtype(numpy.float32))

    def test_specified_mixed16_dtype(self):
        with chainer.using_config('dtype', numpy.float64):
            self.assertEqual(chainer.get_dtype(chainer.mixed16),
                             numpy.dtype(numpy.float16))
            self.assertEqual(
                chainer.get_dtype(chainer.mixed16, map_mixed16=numpy.float32),
                numpy.dtype(numpy.float32))

testing.run_module(__name__, __file__)

max_stars_repo_name: zjzh/chainer

max_issues_repo_name: zjzh/chainer

max_forks_repo_name: zjzh/chainer


text:
from typing import Tuple

import numpy as np
from dgps_with_iwvi.models import DGP_VI
from numpy import ndarray
from scipy.special import logsumexp
from scipy.stats import shapiro

def compute_metrics(
    model: DGP_VI, X: ndarray, Y: ndarray, num_samples: int
) -> Tuple[float, float, float]:
    """Computes log likelihood, RMSE and median Shapiro-Wilk value for the given data.

    :param num_samples: number of times to sample the model posterior at each test point
    :returns: (log lik, rmse, median Shapiro-Wilk)
    """
    assert len(X) == len(Y)
    rmse = np.empty(len(X))
    shapiro_W = np.empty(len(X))

    for i, (x, y) in enumerate(zip(X, Y)):
        samples = model.predict_y_samples(x.reshape(1, -1), num_samples)
        Ss = samples[:, :, 0]

        shapiro_W[i] = float(shapiro((Ss - np.average(Ss)) / np.std(Ss))[0])
        rmse[i] = (np.average(Ss) - float(y)) ** 2

    logp = compute_log_likelihood(model, X, Y, n_samples=1000)
    return logp, (np.average(rmse) ** 0.5).item(), np.median(shapiro_W).item()

def compute_log_likelihood(model: DGP_VI, X: ndarray, Y: ndarray, n_samples: int) -> float:
    """Computes the log likelihood of the given data using Monte Carlo sampling."""
    batch_size = 128
    logps_per_batch = []
    for batch_i in range(0, len(X), batch_size):
        xs = X[batch_i : batch_i + batch_size]
        ys = Y[batch_i : batch_i + batch_size]
        # Shape [num samples x batch size x output dimension]
        logp_samples = model.sample_likelihood(xs, ys, n_samples)
        assert logp_samples.shape == (n_samples, xs.shape[0], ys.shape[1])
        # Compute AND probability over the outputs.
        logp_samples = logp_samples.sum(2)
        assert logp_samples.shape == (n_samples, xs.shape[0])
        # Compute the mean in probability space over the samples
        batch_logps = -np.log(n_samples) + logsumexp(logp_samples, axis=0)
        assert batch_logps.shape == (xs.shape[0],)
        logps_per_batch.append(batch_logps)

    return np.concatenate(logps_per_batch).mean().item()

reason: import numpy,from numpy,from scipy


text:
# This script solves Problem #1 of Section 3's exercises in the TFC book
# Updated: 18 Mar 2021
####################################################################################################
# Differential Equation
#   yₓₓ + w^2 y = 0      where   w is the period
#
#   subject to: y(0) = 1, yₓ(0) = 0
####################################################################################################
from tfc import utfc
from tfc.utils import LsClass, egrad, MakePlot
from jax import jit
import jax.numpy as np

import numpy as onp
import tqdm
####################################################################################################

## user defined parameters: ************************************************************************
N = 100 # number of discretization points per TFC step
m = 40  # number of basis function terms
basis = 'CP' # basis function type

xspan = [0., 2.] # time range of problem
Nstep = int(xspan[1]/2) # number of TFC steps

y0  = 1.  # y(x0)  = 1
y0p = 0.  # yₓ(x0) = 0

w = 2.*np.pi

## problem initial conditions: *********************************************************************
if basis == 'CP' or 'LeP':
    nC  = 2
elif basis == 'FS':
    nC  = 1
else:
    nC  = 0
# number of constraints

# length of time for one TFC step
xstep = (xspan[1]-xspan[0])/Nstep
# !!! since this differential equation is not a explicit function of position 'x', I can get
#     away with contructing the tfc class such that x = [0, xstep] an imposing a constant step so
#     that the mapping parameter c = (zf-z0)/(xf-x0) is also constant

## construct univariate tfc class: *****************************************************************
tfc = utfc(N+1, nC, int(m+1), basis = basis, x0=0, xf=xstep)
x = tfc.x
# !!! notice I am using N+1 for the number of points. this is because I will be using the last point
#     of a segment 'n' for the initial conditons of the 'n+1' segment

H = tfc.H
dH = tfc.dH
H0 = H(x[0])
H0p = dH(x[0])

## define tfc constrained expression and derivatives: **********************************************
# switching function
phi1 = lambda x: np.ones_like(x)
phi2 = lambda x: x

# tfc constrained expression
y = lambda x,xi,IC: np.dot(H(x),xi) + phi1(x)*(IC['y0']  - np.dot(H0,xi)) \
                                    + phi2(x)*(IC['y0p'] - np.dot(H0p,xi))
# !!! notice here that the initial conditions are passed as a dictionary (i.e. IC['y0'])
#     this will be important so that the least-squares does not need to be re-JITed

yp = egrad(y)
ypp = egrad(yp)

## define the loss function: ***********************************************************************
#   yₓₓ + w^2 y = 0
L = jit(lambda xi,IC: ypp(x,xi,IC) + w**2*y(x,xi,IC))

## construct the least-squares class: **************************************************************
xi0 = np.zeros(H(x).shape[1])
IC = {'y0': np.array([y0]), 'y0p': np.array([y0p])}

ls = LsClass(xi0,L,timer=True)

## initialize dictionary to record solution: *******************************************************
xSol    = onp.zeros((Nstep,N))
ySol    = onp.zeros_like(xSol)
res     = onp.zeros_like(xSol)
err     = onp.zeros_like(xSol)
time    = onp.zeros(Nstep)

xSol[0,:] = x[:-1]
xFinal = x[-1]
## 'propagation' loop: *****************************************************************************
for i in tqdm.trange(Nstep):
    xi, time[i] = ls.run(xi0,IC)

    # print solution to dictionary
    if i > 0:
        xSol[i,:]    = xFinal + x[:-1]
        xFinal += x[-1]

    # save solution to python dictionary
    ySol[i,:]   = y(x,xi,IC)[:-1]
    res[i,:]    = np.abs(L(xi,IC))[:-1]

    # update initial condtions
    IC['y0']  = y(x,xi,IC)[-1]
    IC['y0p'] = yp(x,xi,IC)[-1]

## compute the error: ******************************************************************************
A = np.sqrt(y0**2 + (y0p/w)**2)
Phi = np.arctan(-y0p/w/y0)
yTrue = A*np.cos(w*xSol+Phi)

err = np.abs(ySol-yTrue)

## print status of run: ****************************************************************************
print('TFC least-squares time[s]: ' +'\t'+ str((time.sum())))
print('Max residual:' +'\t'*3+ str(res.max()))
print('Max error:' +'\t'*3+ str(err.max()))

## plotting: ***************************************************************************************
# figure 1: solution
p1 = MakePlot(r'$x$',r'$y(t)$')
p1.ax[0].plot(xSol.flatten(),ySol.flatten())
p1.ax[0].grid(True)
p1.PartScreen(7.,6.)
p1.show()

# figure 2: residual
p2 = MakePlot(r'$t$',r'$|L(\xi)|$')
p2.ax[0].plot(xSol.flatten(),res.flatten(),'*')
p2.ax[0].grid(True)
p2.ax[0].set_yscale('log')
p2.PartScreen(7.,6.)
p2.show()

# figure 3: error
p3 = MakePlot(r'$t$',r'$|y_{true} - y(t)|$')
p3.ax[0].plot(xSol.flatten(),err.flatten(),'*')
p3.ax[0].grid(True)
p3.ax[0].set_yscale('log')
p3.PartScreen(7.,6.)
p3.show()

max_stars_repo_name: leakec/tfc

max_issues_repo_name: leakec/tfc

max_forks_repo_name: leakec/tfc

reason: import numpy,import jax,from jax