index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
20,001
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/models/__init__.py
|
from . import cycle_gan
def create_model(isTrain):
instance = cycle_gan.CycleGANModel(isTrain)
print("model [%s] was created" % type(instance).__name__)
return instance
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,002
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/gui/notitle.py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: jyroy
import sys
from PyQt5.QtCore import Qt, pyqtSignal, QPoint
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QSpacerItem, QSizePolicy
from PyQt5.QtWidgets import QWidget, QPushButton
# 样式
StyleSheet = """
/*标题栏*/
TitleBar {
background-color: red;
}
/*最小化最大化关闭按钮通用默认背景*/
#buttonMinimum,#buttonMaximum,#buttonClose {
border: none;
background-color: red;
}
/*悬停*/
#buttonMinimum:hover,#buttonMaximum:hover {
background-color: red;
color: white;
}
#buttonClose:hover {
color: white;
}
/*鼠标按下不放*/
#buttonMinimum:pressed,#buttonMaximum:pressed {
background-color: Firebrick;
}
#buttonClose:pressed {
color: white;
background-color: Firebrick;
}
"""
class TitleBar(QWidget):
# 窗口最小化信号
windowMinimumed = pyqtSignal()
# # 窗口最大化信号
# windowMaximumed = pyqtSignal()
# # 窗口还原信号
# windowNormaled = pyqtSignal()
# 窗口关闭信号
windowClosed = pyqtSignal()
# 窗口移动
windowMoved = pyqtSignal(QPoint)
def __init__(self, *args, **kwargs):
super(TitleBar, self).__init__(*args, **kwargs)
# 支持qss设置背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.mPos = None
self.iconSize = 20 # 图标的默认大小
# 布局
layout = QHBoxLayout(self, spacing=0)
layout.setContentsMargins(0, 0, 0, 0)
# 窗口图标
self.iconLabel = QLabel(self)
# self.iconLabel.setScaledContents(True)
layout.addWidget(self.iconLabel)
# 窗口标题
self.titleLabel = QLabel(self)
self.titleLabel.setMargin(2)
layout.addWidget(self.titleLabel)
# 中间伸缩条
layout.addSpacerItem(QSpacerItem(
40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
# 利用Webdings字体来显示图标
font = self.font() or QFont()
font.setFamily('Webdings')
# 最小化按钮
self.buttonMinimum = QPushButton(
'0', self, clicked=self.windowMinimumed.emit, font=font, objectName='buttonMinimum')
layout.addWidget(self.buttonMinimum)
# # 最大化/还原按钮
# self.buttonMaximum = QPushButton(
# '1', self, clicked=self.showMaximized, font=font, objectName='buttonMaximum')
# layout.addWidget(self.buttonMaximum)
# 关闭按钮
self.buttonClose = QPushButton(
'r', self, clicked=self.windowClosed.emit, font=font, objectName='buttonClose')
layout.addWidget(self.buttonClose)
# 初始高度
self.setHeight()
# def showMaximized(self):
# if self.buttonMaximum.text() == '1':
# # 最大化
# self.buttonMaximum.setText('2')
# self.windowMaximumed.emit()
# else: # 还原
# self.buttonMaximum.setText('1')
# self.windowNormaled.emit()
def setHeight(self, height=38):
"""设置标题栏高度"""
self.setMinimumHeight(height)
self.setMaximumHeight(height)
# 设置右边按钮的大小
self.buttonMinimum.setMinimumSize(height, height)
self.buttonMinimum.setMaximumSize(height, height)
# self.buttonMaximum.setMinimumSize(height, height)
# self.buttonMaximum.setMaximumSize(height, height)
self.buttonClose.setMinimumSize(height, height)
self.buttonClose.setMaximumSize(height, height)
def setTitle(self, title):
"""设置标题"""
self.titleLabel.setText(title)
def setIcon(self, icon):
"""设置图标"""
self.iconLabel.setPixmap(icon.pixmap(self.iconSize, self.iconSize))
def setIconSize(self, size):
"""设置图标大小"""
self.iconSize = size
def enterEvent(self, event):
self.setCursor(Qt.ArrowCursor)
super(TitleBar, self).enterEvent(event)
# def mouseDoubleClickEvent(self, event):
# super(TitleBar, self).mouseDoubleClickEvent(event)
# self.showMaximized()
def mousePressEvent(self, event):
"""鼠标点击事件"""
if event.button() == Qt.LeftButton:
self.mPos = event.pos()
event.accept()
def mouseReleaseEvent(self, event):
'''鼠标弹起事件'''
self.mPos = None
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton and self.mPos:
self.windowMoved.emit(self.mapToGlobal(event.pos() - self.mPos))
event.accept()
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,003
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/utils/dataset.py
|
import os
from PIL import Image
import random
import torchvision.transforms as transforms
from utils.params import opt
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
'.tif', '.TIF', '.tiff', '.TIFF',
]
def get_transform(method=Image.BICUBIC):
transform_list = []
# resize
osize = [opt['load_size'], opt['load_size']]
transform_list.append(transforms.Resize(osize, method))
# crop
transform_list.append(transforms.CenterCrop(opt['crop_size']))
# flip
# transform_list.append(transforms.RandomHorizontalFlip())
# convert
transform_list += [transforms.ToTensor()]
transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
return transforms.Compose(transform_list)
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def make_dataset(_dir, max_dataset_size=float("inf")):
images = []
assert os.path.isdir(_dir), '%s is not a valid directory' % _dir
for root, _, fnames in sorted(os.walk(_dir)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(path)
return images[:min(max_dataset_size, len(images))]
class Dataset:
"""
This dataset class can load unaligned/unpaired datasets.
It requires two directories to host training images from domain A '/path/to/data/trainA'
and from domain B '/path/to/data/trainB' respectively.
You can train the model with the dataset flag '--dataroot /path/to/data'.
Similarly, you need to prepare two directories:
'/path/to/data/testA' and '/path/to/data/testB' during test time.
"""
def __init__(self, train_or_test, max_dataset_size=float("inf")):
self.dir_A = os.path.join('.\\data', train_or_test + 'A') # create a path '/path/to/data/trainA'
self.dir_B = os.path.join('.\\data', train_or_test + 'B') # create a path '/path/to/data/trainB'
self.A_paths = sorted(make_dataset(self.dir_A, max_dataset_size)) # load images from '/path/to/data/trainA'
self.B_paths = sorted(make_dataset(self.dir_B, max_dataset_size)) # load images from '/path/to/data/trainB'
self.A_size = len(self.A_paths) # get the size of dataset A
self.B_size = len(self.B_paths) # get the size of dataset B
self.transform_A = get_transform()
self.transform_B = get_transform()
def __getitem__(self, index):
"""Return a data point and its metadata information.
Parameters:
index (int) -- a random integer for data indexing
Returns a dictionary that contains A, B, A_paths and B_paths
A (tensor) -- an image in the input domain
B (tensor) -- its corresponding image in the target domain
A_paths (str) -- image paths
B_paths (str) -- image paths
"""
A_path = self.A_paths[index % self.A_size] # make sure index is within then range
# randomize the index for domain B to avoid fixed pairs.
index_B = random.randint(0, self.B_size - 1)
B_path = self.B_paths[index_B]
A_img = Image.open(A_path).convert('RGB')
B_img = Image.open(B_path).convert('RGB')
# apply image transformation
A = self.transform_A(A_img)
B = self.transform_B(B_img)
return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}
def __len__(self):
"""Return the total number of images in the dataset.
As we have two datasets with potentially different number of images,
we take a maximum of
"""
return max(self.A_size, self.B_size)
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,004
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/models/cycle_gan.py
|
import torch
import itertools
from utils.image_pool import ImagePool
from utils.params import opt
from . import models
from . import gan_loss
import os
from collections import OrderedDict
class CycleGANModel:
def __init__(self, isTrain):
"""Initialize the CycleGAN class.
Parameters:
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
"""
self.save_dir = os.path.join(opt['checkpoints_dir'], opt['name']) # save all the checkpoints to save_dir
self.gpu_ids = opt['gpu_ids']
self.isTrain = isTrain
self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device(
'cpu') # get device name: CPU or GPU
self.optimizers = []
# specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B']
# specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
visual_names_A = ['real_A', 'fake_B', 'rec_A']
visual_names_B = ['real_B', 'fake_A', 'rec_B']
if self.isTrain and opt['lambda_identity'] > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B)
visual_names_A.append('idt_B')
visual_names_B.append('idt_A')
self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B
# specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.
if self.isTrain:
self.model_names = ['G_A', 'G_B', 'D_A', 'D_B']
else: # during test time, only load Gs
self.model_names = ['G_A', 'G_B']
# define networks (both Generators and discriminators)
# The naming is different from those used in the paper.
# Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)
self.netG_A = models.define_G(opt['input_nc'], opt['output_nc'], opt['ngf'],
not opt['no_dropout'], opt['init_gain'], self.gpu_ids)
self.netG_B = models.define_G(opt['output_nc'], opt['input_nc'], opt['ngf'],
not opt['no_dropout'], opt['init_gain'], self.gpu_ids)
if self.isTrain: # define discriminators
self.netD_A = models.define_D(opt['output_nc'], opt['ndf'],
opt['n_layers_D'], opt['init_gain'], self.gpu_ids)
self.netD_B = models.define_D(opt['input_nc'], opt['ndf'],
opt['n_layers_D'], opt['init_gain'], self.gpu_ids)
if self.isTrain:
if opt['lambda_identity'] > 0.0: # only works when input and output images have the same number of channels
assert (opt['input_nc'] == opt['output_nc'])
self.fake_A_pool = ImagePool(opt['pool_size']) # create image buffer to store previously generated images
self.fake_B_pool = ImagePool(opt['pool_size']) # create image buffer to store previously generated images
# define loss functions
self.criterionGAN = gan_loss.GANLoss().to(self.device) # define GAN loss.
self.criterionCycle = torch.nn.L1Loss()
self.criterionIdt = torch.nn.L1Loss()
# initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()),
lr=opt['lr'], betas=(opt['beta1'], 0.999))
self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()),
lr=opt['lr'], betas=(opt['beta1'], 0.999))
self.optimizers.append(self.optimizer_G)
self.optimizers.append(self.optimizer_D)
def set_input(self, _input):
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
Parameters:
_input (dict): include the data itself and its metadata information.
The option 'direction' can be used to swap domain A and domain B.
"""
self.real_A = _input['A'].to(self.device)
self.real_B = _input['B'].to(self.device)
self.image_paths = _input['A_paths']
def forward(self):
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
self.fake_B = self.netG_A(self.real_A) # G_A(A)
self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A))
self.fake_A = self.netG_B(self.real_B) # G_B(B)
self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B))
def backward_D_basic(self, netD, real, fake):
"""Calculate GAN loss for the discriminator
Parameters:
netD (network) -- the discriminator D
real (tensor array) -- real images
fake (tensor array) -- images generated by a generator
Return the discriminator loss.
We also call loss_D.backward() to calculate the gradients.
"""
# Real
pred_real = netD(real)
loss_D_real = self.criterionGAN(pred_real, True)
# Fake
pred_fake = netD(fake.detach())
loss_D_fake = self.criterionGAN(pred_fake, False)
# Combined loss and calculate gradients
loss_D = (loss_D_real + loss_D_fake) * 0.5
loss_D.backward()
return loss_D
def backward_D_A(self):
"""Calculate GAN loss for discriminator D_A"""
fake_B = self.fake_B_pool.query(self.fake_B)
self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B)
def backward_D_B(self):
"""Calculate GAN loss for discriminator D_B"""
fake_A = self.fake_A_pool.query(self.fake_A)
self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A)
def backward_G(self):
"""Calculate the loss for generators G_A and G_B"""
lambda_idt = opt['lambda_identity']
lambda_A = opt['lambda_A']
lambda_B = opt['lambda_B']
# Identity loss
if lambda_idt > 0:
# G_A should be identity if real_B is fed: ||G_A(B) - B||
self.idt_A = self.netG_A(self.real_B)
self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt
# G_B should be identity if real_A is fed: ||G_B(A) - A||
self.idt_B = self.netG_B(self.real_A)
self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt
else:
self.loss_idt_A = 0
self.loss_idt_B = 0
# GAN loss D_A(G_A(A))
self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True)
# GAN loss D_B(G_B(B))
self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True)
# Forward cycle loss || G_B(G_A(A)) - A||
self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A
# Backward cycle loss || G_A(G_B(B)) - B||
self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B
# combined loss and calculate gradients
self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B
self.loss_G.backward()
def optimize_parameters(self):
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
# forward
self.forward() # compute fake images and reconstruction images.
# G_A and G_B
self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs
self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero
self.backward_G() # calculate gradients for G_A and G_B
self.optimizer_G.step() # update G_A and G_B's weights
# D_A and D_B
self.set_requires_grad([self.netD_A, self.netD_B], True)
self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero
self.backward_D_A() # calculate gradients for D_A
self.backward_D_B() # calculate graidents for D_B
self.optimizer_D.step() # update D_A and D_B's weights
def optimize_D_parameters(self):
"""Calculate losses, gradients, and update D network weights"""
# forward
self.forward() # compute fake images and reconstruction images.
# D_A and D_B
self.set_requires_grad([self.netD_A, self.netD_B], True)
self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero
self.backward_D_A() # calculate gradients for D_A
self.backward_D_B() # calculate graidents for D_B
self.optimizer_D.step() # update D_A and D_B's weights
def set_requires_grad(self, nets, requires_grad=False):
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
Parameters:
nets (network list) -- a list of networks
requires_grad (bool) -- whether the networks require gradients or not
"""
if not isinstance(nets, list):
nets = [nets]
for net in nets:
if net is not None:
for param in net.parameters():
param.requires_grad = requires_grad
def setup(self):
"""Load and print networks; create schedulers
Parameters:
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
"""
if self.isTrain:
self.schedulers = [models.get_scheduler(optimizer) for optimizer in self.optimizers]
if not self.isTrain or opt['continue_train']:
load_suffix = 'iter_%d' % opt['load_iter'] if opt['load_iter'] > 0 else opt['epoch']
self.load_networks(load_suffix)
self.print_networks(opt['verbose'])
def load_networks(self, epoch):
"""Load all the networks from the disk.
Parameters:
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
"""
for name in self.model_names:
if isinstance(name, str):
load_filename = '%s_net_%s.pth' % (epoch, name)
load_path = os.path.join(self.save_dir, load_filename)
net = getattr(self, 'net' + name)
if isinstance(net, torch.nn.DataParallel):
net = net.module
print('loading the model from %s' % load_path)
# if you are using PyTorch newer than 0.4 (e.g., built from
# GitHub source), you can remove str() on self.device
state_dict = torch.load(load_path, map_location=str(self.device))
if hasattr(state_dict, '_metadata'):
del state_dict._metadata
# patch InstanceNorm checkpoints prior to 0.4
for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop
self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))
net.load_state_dict(state_dict)
def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):
"""Fix InstanceNorm checkpoints incompatibility (prior to 0.4)"""
key = keys[i]
if i + 1 == len(keys): # at the end, pointing to a parameter/buffer
if module.__class__.__name__.startswith('InstanceNorm') and \
(key == 'running_mean' or key == 'running_var'):
if getattr(module, key) is None:
state_dict.pop('.'.join(keys))
if module.__class__.__name__.startswith('InstanceNorm') and \
(key == 'num_batches_tracked'):
state_dict.pop('.'.join(keys))
else:
self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)
def print_networks(self, verbose):
"""Print the total number of parameters in the network and (if verbose) network architecture
Parameters:
verbose (bool) -- if verbose: print the network architecture
"""
print('---------- Networks initialized -------------')
for name in self.model_names:
if isinstance(name, str):
net = getattr(self, 'net' + name)
num_params = 0
for param in net.parameters():
num_params += param.numel()
if verbose:
print(net)
print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
print('-----------------------------------------------')
def update_learning_rate(self):
"""Update learning rates for all the networks; called at the end of every epoch"""
old_lr = self.optimizers[0].param_groups[0]['lr']
for scheduler in self.schedulers:
scheduler.step()
lr = self.optimizers[0].param_groups[0]['lr']
print('learning rate %.7f -> %.7f' % (old_lr, lr))
def get_current_losses(self):
"""Return traning losses / errors. train.py will print out these errors on console, and save them to a file"""
errors_ret = OrderedDict()
for name in self.loss_names:
if isinstance(name, str):
errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number
return errors_ret
def compute_visuals(self):
"""Calculate additional output images for visdom and HTML visualization"""
pass
def save_networks(self, epoch):
"""Save all the networks to the disk.
Parameters:
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
"""
for name in self.model_names:
if isinstance(name, str):
save_filename = '%s_net_%s.pth' % (epoch, name)
save_path = os.path.join(self.save_dir, save_filename)
net = getattr(self, 'net' + name)
if len(self.gpu_ids) > 0 and torch.cuda.is_available():
torch.save(net.module.cpu().state_dict(), save_path)
net.cuda(self.gpu_ids[0])
else:
torch.save(net.cpu().state_dict(), save_path)
def get_current_visuals(self):
"""Return visualization images. train.py will display these images with visdom, and save the images to a HTML"""
visual_ret = OrderedDict()
for name in self.visual_names:
if isinstance(name, str):
visual_ret[name] = getattr(self, name)
return visual_ret
def test(self):
"""Forward function used in test time.
This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
It also calls <compute_visuals> to produce additional visualization results
"""
with torch.no_grad():
self.forward()
self.compute_visuals()
def get_image_paths(self):
""" Return image paths that are used to load current data"""
return self.image_paths
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,005
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/edge/hed.py
|
import cv2 as cv
import os
import numpy as np
import matplotlib.image as mp
from skimage import img_as_ubyte
from PIL import Image
class CropLayer(object):
def __init__(self, params, blobs):
self.xstart = 0
self.xend = 0
self.ystart = 0
self.yend = 0
# Our layer receives two inputs. We need to crop the first input blob
# to match a shape of the second one (keeping batch size and number of channels)
def getMemoryShapes(self, inputs):
inputShape, targetShape = inputs[0], inputs[1]
batchSize, numChannels = inputShape[0], inputShape[1]
height, width = targetShape[2], targetShape[3]
self.ystart = (inputShape[2] - targetShape[2]) // 2
self.xstart = (inputShape[3] - targetShape[3]) // 2
self.yend = self.ystart + height
self.xend = self.xstart + width
return [[batchSize, numChannels, height, width]]
def forward(self, inputs):
return [inputs[0][:,:,self.ystart:self.yend,self.xstart:self.xend]]
def extract_edge(frame):
# Load the model.
net = cv.dnn.readNet(cv.samples.findFile('deploy.prototxt'), cv.samples.findFile('hed_pretrained_bsds.caffemodel'))
inp = cv.dnn.blobFromImage(frame, scalefactor=1.0, size=(frame.shape[1], frame.shape[0]),
mean=(104.00698793, 116.66876762, 122.67891434),
swapRB=False, crop=False)
net.setInput(inp)
edge = net.forward()
edge = edge[0, 0]
edge = cv.resize(edge, (frame.shape[1], frame.shape[0]))
edge = cv.merge([edge, edge, edge])
frame = frame/2 + frame/2 * edge
return frame
if __name__ == '__main__':
# ! [Register]
cv.dnn_registerLayer('Crop', CropLayer)
# ! [Register]
path = "..\\data\\org_trainA\\" # 图像读取地址
savepath = "..\\data\\trainA\\" # 图像保存地址
filelist = os.listdir(path) # 打开对应的文件夹
for item in filelist:
name = path + item
img = cv.imread(name)
rst = extract_edge(img)
save_name = savepath + item
print(item+' is processed and saved to '+save_name)
cv.imwrite(save_name, rst)
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,006
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/utils/params.py
|
opt = dict( load_size=286, # scale images to this size
crop_size=256, # then crop to this size
batch_size=1, # input batch size
num_threads=1, # treads for loading data
gpu_ids=[0], # id of gpu
lambda_identity=0.5, # use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1
lambda_A=10.0, # weight for cycle loss (A -> B -> A)
lambda_B=10.0, # weight for cycle loss (B -> A -> B)
input_nc=3,
output_nc=3,
ngf=64, # of gen filters in the last conv layer
ndf=64, # of discriminator filters in the first conv layer
no_dropout=False,
init_gain=0.02, # scaling factor for normal, xavier and orthogonal.
pool_size=50, # the size of image buffer that stores previously generated images
lr=0.0002, # initial learning rate for adam
beta1=0.5, # momentum term of adam
display_id=-1, # window id of the web display
no_html=False,
display_winsize=256, # display window size for both visdom and HTML
name='Chinese Painting Style',
display_port=8888, # visdom port of the web display
display_ncols=4, # if positive, display all images in a single visdom web panel with certain number of images per row.
display_server="http://localhost", # visdom server of the web display
display_env='main',
checkpoints_dir='.\\checkpoints',
n_layers_D=3, # only used if netD==n_layers
epoch_count=1,
n_epochs=25,
n_epochs_decay=25,
continue_train=False,
load_iter=0,
epoch='latest',
verbose=False,
print_freq=100, # frequency of showing training results on console
display_freq=400,
update_html_freq=1000, # frequency of saving training results to html
save_latest_freq=5000,
save_by_iter=False,
save_epoch_freq=5,
n_epochs_D=2,
results_dir='./results/',
phase='test',
num_test=500,
aspect_ratio=1.0,
)
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,008
|
matthew-sessions/DS7_Unit3_print4
|
refs/heads/master
|
/aq_dashboard.py
|
from flask import Flask, render_template, request, redirect, url_for
import openaq_py
from get_data import *
from flask_sqlalchemy import SQLAlchemy
import pygal
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
DB = SQLAlchemy(app)
class Record(DB.Model):
id = DB.Column(DB.Integer, primary_key=True)
city = DB.Column(DB.String(30), nullable=False)
datetime = DB.Column(DB.String(25))
value = DB.Column(DB.Float, nullable=False)
def __repr__(self):
return 'TODO - write a nice representation of Records'
def populate_data(city):
try:
User.query.filter(User.name == city).one()
except:
api = openaq_py.OpenAQ()
status, body = api.measurements(city=city, parameter='pm25')
li = [(city,i['date']['utc'], i['value']) for i in body['results']]
for i in li:
put = Record(city=i[0], datetime=str(i[1]), value=i[2])
DB.session.add(put)
DB.session.commit()
@app.route('/')
def root():
"""Base view."""
#li = data_grab()
lii, parameter = drop_downs()
return render_template('home.html', li=[('Los Angeles','Los Angeles')], parameter=parameter)
@app.route('/add/<name>')
def add(name):
name = name.replace('-',' ')
populate_data(name)
return(redirect('/'))
@app.route('/dash/')
def dash():
city = request.args.get('city')
parameter = request.args.get('parameter')
if "8" in city:
city = city.replace("8", " ")
res = data_grab(city, parameter)
line_chart = pygal.Line()
line_chart.x_labels = [i[0] for i in res]
line_chart.add(parameter, [i[1] for i in res])
graph_data = line_chart.render()
return(render_template('graph.html',graph_data = graph_data))
@app.route('/refresh')
def refresh():
"""Pull fresh data from Open AQ and replace existing data."""
DB.drop_all()
DB.create_all()
# TODO Get data from OpenAQ, make Record objects with it, and add to db
DB.session.commit()
return 'Data refreshed!'
if __name__ == '__main__':
app.run(debug=True)
|
{"/aq_dashboard.py": ["/get_data.py"]}
|
20,009
|
matthew-sessions/DS7_Unit3_print4
|
refs/heads/master
|
/get_data.py
|
import openaq_py
def data_grab(city, parameter):
"""Basic fucntion to get the base data"""
api = openaq_py.OpenAQ()
status, body = api.measurements(city=city, parameter=parameter)
li = [(i['date']['utc'], i['value']) for i in body['results']]
return li
def drop_downs():
api = openaq_py.OpenAQ()
stat1, body1 = api.cities()
cities = [(i['city'],i['city'].replace(' ',"8")) for i in body1['results']]
stat2, body2 = api.parameters()
parameters = [(i['name'],i['description'],i['id']) for i in body2['results']]
return(cities,parameters)
|
{"/aq_dashboard.py": ["/get_data.py"]}
|
20,013
|
fatimaavila/linkQueueFlask
|
refs/heads/master
|
/queue.py
|
from linked_list import LinkedList,Node
import __main__
class Queue(LinkedList,Node):
def __repr__(self):
node = self.head
nodes = []
__main__.linksy.clear()
while node is not None:
nodes.append('<a href="'+node.data.split("|")[0]+'" target="_blank">'+node.data.split("|")[1]+'</a>')
__main__.linksy.append(node.data)
node = node.next
nodes.append("")
return "<br>".join(nodes)
def enqueue(self, node):
if self.head == None:
#print("lista vacía en queue")
self.insert_last(node)
else:
##recorrer lista para buscar el ultimo
node2 = self.head
data_ultimo=self.head
while node2 is not None:
data_ultimo=node2
node2 = node2.next
self.insert_after(data_ultimo.data,node)
def dequeue(self):
node = self.head
self.remove(node.data)
|
{"/queue.py": ["/linked_list.py"], "/main.py": ["/linked_list.py", "/queue.py", "/sort.py", "/search.py"]}
|
20,014
|
fatimaavila/linkQueueFlask
|
refs/heads/master
|
/sort.py
|
# Python program for implementation of Selection
def selSort(A):
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if ord(A[min_idx].split("|")[2]) > ord(A[j].split("|")[2]):
min_idx = j
# Swap the found minimum element with
# the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
'''
print ("Sorted array")
for i in range(len(A)):
B = (A[i])
'''
return A
|
{"/queue.py": ["/linked_list.py"], "/main.py": ["/linked_list.py", "/queue.py", "/sort.py", "/search.py"]}
|
20,015
|
fatimaavila/linkQueueFlask
|
refs/heads/master
|
/main.py
|
from flask import Flask, render_template, request
from random import choice
from linked_list import LinkedList, Node
from queue import Queue
from sort import selSort
from search import linearSearch
#from search import linearSearch
web_site = Flask(__name__)
lista2 = Queue()
linksy = []
sorteado = []
def gen_html():
print(lista2)
print(linksy)
sorteado = selSort(linksy)
#todo A_sorted=selSort(sorteado)
#todo format A_sorted
print(" Generar html del array")
html=''
for i in range(len(sorteado)):
html=html + '<a href="'+sorteado[i].split("|")[0]+'" target="_blank">'+sorteado[i].split("|")[1]+'</a><br>'
return html
#--------------------------- main
@web_site.route('/')
def index():
html=gen_html()
return render_template('index.html',lista=lista2,a_sorted=html)
@web_site.route('/user/', defaults={'username': None})
@web_site.route('/user/<username>')
def generate_user(username):
if not username:
username = request.args.get('username')
if not username:
return 'Sorry error something, malformed request.'
return render_template('personal_user.html', user=username)
@web_site.route('/enqueue')
def enqueque():
print(request.args.get("link"))
print(request.args.get('nombre'))
m_link=request.args.get('link')
m_nombre=request.args.get('nombre')
m_prioridad=request.args.get('prioridad')
#linksy.clear()
lista2.enqueue(Node(m_link +'|'+m_nombre+'|'+m_prioridad))
html = gen_html()
return render_template('index.html',lista=lista2, a_sorted=html)
@web_site.route('/dequeue')
def dequeue():
lista2.dequeue()
return render_template('index.html',lista=lista2)
@web_site.route('/search')
def search():
print("--------------------search")
html = gen_html()
print(request.args.get("buscar"))
consulta = request.args.get("buscar")
resultado=linearSearch(linksy,consulta)
print(resultado)
if(resultado == -1):
resultado_text = "No ha ingresado este nombre :("
else:
resultado_text= ' <h4 style = "font-family:courier new,courier,monospace;"> ⬇️ Su resultado ⬇️ </h4> <a href="'+linksy[resultado].split("|")[0]+'" target="_blank">'+linksy[resultado].split("|")[1]+'</a>'
return render_template('index.html',lista=lista2,a_sorted=html,resultado_search=resultado_text)
web_site.run(host='0.0.0.0', port=8080)
|
{"/queue.py": ["/linked_list.py"], "/main.py": ["/linked_list.py", "/queue.py", "/sort.py", "/search.py"]}
|
20,016
|
fatimaavila/linkQueueFlask
|
refs/heads/master
|
/search.py
|
def linearSearch(array, x):
n = len(array)
# Going through array sequencially
for i in range(0, n):
nombre = array[i].split("|")[1]
if (x in nombre):
return i
return -1
|
{"/queue.py": ["/linked_list.py"], "/main.py": ["/linked_list.py", "/queue.py", "/sort.py", "/search.py"]}
|
20,017
|
fatimaavila/linkQueueFlask
|
refs/heads/master
|
/linked_list.py
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return "Data: " + self.data
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return " \u001b[31m --> \u001b[0m ".join(nodes)
def traverse(self):
node = self.head
while node is not None:
print(node.data)
node = node.next
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
def insert_first(self, node):
node.next = self.head
self.head = node
def insert_last(self, node):
if self.head is None:
self.head = node
else:
for current_node in self:
pass
current_node.next = node
def remove(self, node_data):
if self.head is None:
raise Exception("La lista esta vacia")
if self.head.data == node_data:
self.head = self.head.next
return
previous_node = self.head
for node in self:
if node.data == node_data:
previous_node.next = node.next
return
previous_node = node
raise Exception("Nodo no existe en la lista")
def insert_before(self, node_data, new_node):
if self.head is None:
raise Exception("La lista esta vacia")
if self.head.data == node_data:
return self.insert_first(new_node)
previous_node = self.head
for node in self:
if node_data == node.data:
previous_node.next = new_node
new_node.next = node
return
previous_node = node
raise Exception("Nodo objetivo no existe en la lista")
def insert_after(self, node_data, new_node):
if self.head is None:
raise Exception("La lista esta vacia")
for node in self:
if node_data == node.data:
new_node.next = node.next
node.next = new_node
return
raise Exception("Nodo objetivo no existe en la lista")
def reverse(self):
if self.head is None:
raise Exception("La lista esta vacia")
prev = None
node = self.head
while node is not None:
next = node.next
node.next = prev
prev = node
node = next
self.head = prev
|
{"/queue.py": ["/linked_list.py"], "/main.py": ["/linked_list.py", "/queue.py", "/sort.py", "/search.py"]}
|
20,035
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/utils.py
|
from time import sleep
import datetime
def get_timestamp():
"""
Returns a numeric string with a timestamp. It also halts the execution
of the program during 10 micro seconds to ensure that all returned
timestamps are different and unique.
Returns
-------
str
String containing the timestamp. Format isYYYYMMDDHHMMSSmmmmmm.
Example
-------
>>> get_timestamp()
'20181013234913378084'
>>> [get_timestamp(), get_timestamp()]
['20181013235501158401', '20181013235501158583']
"""
sleep(10e-6) # This ensures that there will not exist two equal timestamps.
return datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,036
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_error_band.py
|
import myplotlib as mpl
import numpy as np
def calc_error(y):
return ((y**2)**.5)*.1 + max(y*.01)
x = np.linspace(-1,1)
y = [
x**3,
np.cos(x),
x**2,
np.exp(x),
x,
2*x,
3*(x**2)**.5,
-x,
np.log(x**2)/8,
]
for package in ['plotly']:
fig = mpl.manager.new(
title = f'Fill between with {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
for idx,yy in enumerate(y):
fig.error_band(
x,
yy,
yy + calc_error(yy),
yy - calc_error(yy),
label = f'Function {idx}',
marker = [None,'.','+','o','x'][np.random.randint(4)],
linestyle = ['solid', 'none','dashed','doted'][np.random.randint(3)],
)
mpl.manager.save_all()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,037
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/figure.py
|
import numpy as np
import warnings
from shutil import copyfile
import plotly.graph_objects as go
class MPLFigure:
"""
This class defines the interface to be implemented in the subclasses
and does all the validation of arguments. For example "title" must
be a string, this is validated in this class. How to write the title
in the figure is to be implemented in the respective subclass for
some particular ploting package, not here.
Convention for getting/setting the properties:
- Each property (e.g. title) has to be defined with 3 @property methods,
1) title
2) _title getter
3) _title setter
See the definition of title for implementation details.
"""
DEFAULT_COLORS = [
(255, 59, 59),
(52, 71, 217),
(4, 168, 2),
(224, 146, 0),
(224, 0, 183),
(0, 230, 214),
(140, 0, 0),
(9, 0, 140),
(107, 0, 96),
]
DEFAULT_COLORS = [tuple(np.array(color)/255) for color in DEFAULT_COLORS]
def pick_default_color(self):
# ~ global DEFAULT_COLORS
color = self.DEFAULT_COLORS[0]
self.DEFAULT_COLORS = self.DEFAULT_COLORS[1:] + [self.DEFAULT_COLORS[0]]
return color
def __init__(self):
self._show_title = True
@property
def title(self):
return self._title
@property
def _title(self):
if hasattr(self, '_title_'):
return self._title_
else:
return None
@_title.setter
def _title(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_title> must be a string, but received <{value}> of type {type(value)}.')
self._title_ = value
@property
def show_title(self):
return self._show_title
@property
def _show_title(self):
return self._show_title_
@_show_title.setter
def _show_title(self, value):
if value not in [True, False]:
raise ValueError(f'<_show_title> must be either True or False, received <{value}> of type {type(value)}.')
self._show_title_ = value
@property
def subtitle(self):
return self._subtitle
@property
def _subtitle(self):
if hasattr(self, '_subtitle_'):
return self._subtitle_
else:
return None
@_subtitle.setter
def _subtitle(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_subtitle> must be a string, but received <{value}> of type {type(value)}.')
self._subtitle_ = value
@property
def xlabel(self):
return self._xlabel
@property
def _xlabel(self):
if hasattr(self, '_xlabel_'):
return self._xlabel_
else:
return None
@_xlabel.setter
def _xlabel(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_xlabel> must be a string, but received <{value}> of type {type(value)}.')
self._xlabel_ = value
@property
def ylabel(self):
return self._ylabel
@property
def _ylabel(self):
if hasattr(self, '_ylabel_'):
return self._ylabel_
else:
return None
@_ylabel.setter
def _ylabel(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_ylabel> must be a string, but received <{value}> of type {type(value)}.')
self._ylabel_ = value
@property
def xscale(self):
return self._xscale
@property
def _xscale(self):
if hasattr(self, '_xscale_'):
return self._xscale_
else:
return None
@_xscale.setter
def _xscale(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_xscale> must be a string, but received <{value}> of type {type(value)}.')
self._validate_axis_scale(value)
self._xscale_ = value
@property
def yscale(self):
return self._yscale
@property
def _yscale(self):
if hasattr(self, '_yscale_'):
return self._yscale_
else:
return None
@_yscale.setter
def _yscale(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_yscale> must be a string, but received <{value}> of type {type(value)}.')
self._validate_axis_scale(value)
self._yscale_ = value
@property
def aspect(self):
return self._aspect
@property
def _aspect(self):
if hasattr(self, '_aspect_'):
return self._aspect_
else:
return None
@_aspect.setter
def _aspect(self, value: str):
if not isinstance(value, str):
raise TypeError(f'<_aspect> must be a string, but received <{value}> of type {type(value)}.')
self._validate_aspect(value)
self._aspect_ = value
def set(self, **kwargs):
for key in kwargs.keys():
if not hasattr(self, f'_{key}'):
raise ValueError(f'Cannot set <{key}>, invalid property.')
setattr(self, f'_{key}', kwargs[key])
def show(self):
raise NotImplementedError(f'The <show> method is not implemented yet for the plotting package you are using! (Specifically for the class {self.__class__.__name__}.)')
def save(self, fname=None, *args, **kwargs):
raise NotImplementedError(f'The <save> method is not implemented yet for the plotting package you are using! (Specifically for the class {self.__class__.__name__}.)')
def close(self):
raise NotImplementedError(f'The <close> method is not implemented yet for the plotting package you are using! (Specifically for the class {self.__class__.__name__}.)')
#### Validation methods ↓↓↓↓
"""
This methods validate arguments so we all speak the same language.
"""
def _validate_axis_scale(self, scale: str):
# Assume that <scale> is a string. Raises an error if "scale" is not a valid scale.
valid_scales = ['lin', 'log']
if scale not in valid_scales:
raise ValueError(f'Axis scale must be one of {valid_scales}, received {scale}.')
def _validate_aspect(self, aspect: str):
# Assuming that <aspect> is a string. Raises an error if it is not a valid option.
valid_aspects = ['equal']
if aspect not in valid_aspects:
raise ValueError(f'<aspect> must be one of {valid_aspects}.')
def _validate_xy_are_arrays_of_numbers(self, x):
if not hasattr(x, '__iter__'):
raise TypeError(f'<x> and <y> must be "array-like" objects, e.g. lists, numpy arrays, etc.')
def _validate_color(self, color):
try:
color = tuple(color)
except:
raise TypeError(f'<color> must be an iterable composed of 3 numeric elements specifying RGB. Received {color} of type {type(color)}.')
if len(color) != 3:
raise ValueError(f'<color> must be an iterable composed of 3 numeric elements specifying RGB. Received {color}.')
for rgb in color:
if not 0 <= rgb <= 1:
raise ValueError(f'RGB elements in <color> must be bounded between 0 and 1, received <{color}>.')
def _validate_alpha(self, alpha):
try:
alpha = float(alpha)
except:
raise ValueError(f'<alpha> must be a float number. Received {alpha} of type {type(alpha)}.')
if not 0 <= alpha <= 1:
raise ValueError(f'<alpha> must be bounded between 0 and 1, received <{alpha}>.')
def _validate_linewidth(self, linewidth):
try:
linewidth = float(linewidth)
except:
raise ValueError(f'<linewidth> must be a float number. Received {linewidth} of type {type(linewidth)}.')
def _validate_bins(self, bins):
if isinstance(bins, int) and bins > 0:
return
elif hasattr(bins, '__iter__') and len(bins) > 0:
return
elif isinstance(bins, str):
return
else:
raise TypeError(f'<bins> must be either an integer number, an array of float numbers or a string as defined for the numpy.histogram function, see https://numpy.org/doc/stable/reference/generated/numpy.histogram.html. Received {bins} of type {type(bins)}.')
def _validate_marker(self, marker):
IMPLEMENTED_MARKERS = ['.', '+', 'x', 'o', None]
if marker not in IMPLEMENTED_MARKERS:
raise ValueError(f'<marker> must be one of {IMPLEMENTED_MARKERS}, received "{marker}".')
def _validate_kwargs(self, **kwargs):
if 'marker' in kwargs:
self._validate_marker(kwargs['marker'])
if kwargs.get('label') != None:
if not isinstance(kwargs.get('label'), str):
raise TypeError(f'<label> must be a string.')
if kwargs.get('color') != None:
self._validate_color(kwargs['color'])
if kwargs.get('alpha') != None:
self._validate_alpha(kwargs['alpha'])
if kwargs.get('linewidth') != None:
self._validate_linewidth(kwargs['linewidth'])
if kwargs.get('bins') is not None:
self._validate_bins(kwargs['bins'])
if kwargs.get('density') != None:
if kwargs.get('density') not in [True, False]:
raise ValueError(f'<density> must be either True or False, received <{kwargs.get("density")}>.')
if 'norm' in kwargs:
if kwargs['norm'] not in ['lin','log']:
raise ValueError(f'<norm> must be either "lin" or "log", received <{kwargs["norm"]}> of type {type(kwargs["norm"])}.')
#### Plotting methods ↓↓↓↓
"""
Plotting methods here do not have to "do the job", they just validate
things and define the interface. Each subclass has to do the job.
When implementing one of these plotting methods in a subclass, use
the same signature as here.
"""
def plot(self, x, y=None, **kwargs):
if 'plot' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<plot> not implemented for {type(self)}.')
implemented_kwargs = ['label', 'marker', 'color', 'alpha', 'linestyle', 'linewidth'] # This is specific for the "plot" method.
for kwarg in kwargs.keys():
if kwarg not in implemented_kwargs:
raise NotImplementedError(f'<{kwarg}> not implemented for <plot> by myplotlib.')
self._validate_xy_are_arrays_of_numbers(x)
if y is not None:
self._validate_xy_are_arrays_of_numbers(y)
if len(x) != len(y):
raise ValueError(f'Lengths of <x> and <y> are not the same, received len(x)={len(x)} and len(y)={len(y)}.')
else:
y = x
x = [i for i in range(len(x))]
if kwargs.get('color') is None:
kwargs['color'] = self.pick_default_color()
self._validate_kwargs(**kwargs)
validated_args = kwargs
validated_args['x'] = x
validated_args['y'] = y
return validated_args
def hist(self, samples, **kwargs):
if 'hist' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<hist> not implemented for {type(self)}.')
implemented_kwargs = ['label', 'color', 'alpha', 'bins', 'density', 'linewidth', 'linestyle'] # This is specific for the "hist" method.
for kwarg in kwargs.keys():
if kwarg not in implemented_kwargs:
raise NotImplementedError(f'<{kwarg}> not implemented for <hist> by myplotlib.')
self._validate_xy_are_arrays_of_numbers(samples)
if kwargs.get('color') is None:
kwargs['color'] = self.pick_default_color()
self._validate_kwargs(**kwargs)
samples = np.array(samples)
count, index = np.histogram(
samples[~np.isnan(samples)],
bins = kwargs.get('bins') if kwargs.get('bins') is not None else 'auto',
density = kwargs.get('density') if kwargs.get('density') != None else False,
)
count = list(count)
count.insert(0,0)
count.append(0)
index = list(index)
index.insert(0,index[0] - np.diff(index)[0])
index.append(index[-1] + np.diff(index)[-1])
index += np.diff(index)[0]/2 # This is because np.histogram returns the bins edges and I want to plot in the middle.
validated_args = kwargs
validated_args['samples'] = samples
validated_args['bins'] = index
validated_args['counts'] = count
return validated_args
def colormap(self, z, x=None, y=None, **kwargs):
if 'colormap' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<colormap> not implemented for {type(self)}.')
return self.validate_colormap_args(z=z, x=x, y=y, **kwargs)
def validate_colormap_args(self, z, x=None, y=None, **kwargs):
# I had to wrote this function because "contour" validates the same arguments as "colormap", but calling "self.colormap" inside contour created problems calling the contour method of the subclasses.
implemented_kwargs = ['alpha','norm', 'colorscalelabel'] # This is specific for the "colormap" method.
for kwarg in kwargs.keys():
if kwarg not in implemented_kwargs:
raise NotImplementedError(f'<{kwarg}> not implemented for <colormap> by myplotlib.')
self._validate_kwargs(**kwargs)
validated_args = kwargs
validated_args['x'] = x
validated_args['y'] = y
validated_args['z'] = z
return validated_args
def contour(self, z, x=None, y=None, **kwargs):
if 'contour' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<contour> not implemented for {type(self)}.')
if 'levels' in kwargs:
levels = kwargs['levels']
if not isinstance(levels, int):
raise TypeError(f'<levels> must be an integer number specifying the number of levels for the contour plot, received {levels} of type {type(levels)}.')
validated_args = self.validate_colormap_args(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
if 'levels' in locals():
validated_args['levels'] = levels
return validated_args
def fill_between(self, x, y1, y2=None, **kwargs):
if 'fill_between' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<fill_between> not implemented for {type(self)}.')
implemented_kwargs = ['label', 'color', 'alpha', 'linestyle', 'linewidth'] # This is specific for the "fill_between" method.
for kwarg in kwargs.keys():
if kwarg not in implemented_kwargs:
raise NotImplementedError(f'<{kwarg}> not implemented for <fill_between> by myplotlib.')
self._validate_xy_are_arrays_of_numbers(x)
self._validate_xy_are_arrays_of_numbers(y1)
if y2 is None:
y2 = np.zeros(len(x))
self._validate_xy_are_arrays_of_numbers(y2)
if kwargs.get('color') is None:
kwargs['color'] = self.pick_default_color()
self._validate_kwargs(**kwargs)
validated_args = kwargs
validated_args['x'] = x
validated_args['y1'] = y1
validated_args['y2'] = y2
validated_args['alpha'] = .5 # Default alpha value.
return validated_args
def error_band(self, x, y, ytop, ylow, **kwargs):
if 'error_band' not in self.__class__.__dict__.keys(): # Raise error if the method was not overriden
raise NotImplementedError(f'<error_band> not implemented for {type(self)}.')
self._validate_xy_are_arrays_of_numbers(x)
self._validate_xy_are_arrays_of_numbers(y)
self._validate_xy_are_arrays_of_numbers(ytop)
self._validate_xy_are_arrays_of_numbers(ylow)
if any(np.array(y)>np.array(ytop)) or any(np.array(y)<np.array(ylow)):
raise ValueError(f'Either y>ytop or y<ylow is true for at least one point, please check your arrays.')
if len(x) == len(y) == len(ytop) == len(ylow):
pass
else:
raise ValueError(f'len(x) == len(y) == len(ytop) == len(ylow) is not True, please check your arrays.')
if kwargs.get('color') is None:
kwargs['color'] = self.pick_default_color()
self._validate_kwargs(**kwargs)
validated_args = kwargs
validated_args['x'] = x
validated_args['y'] = y
validated_args['ytop'] = ytop
validated_args['ylow'] = ylow
return validated_args
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,038
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/wrapper_matplotlib.py
|
from .figure import MPLFigure
import numpy as np
class MPLMatplotlibWrapper(MPLFigure):
def __init__(self):
super().__init__()
import matplotlib.pyplot as plt # Import here so if the user does not plot with this package, it does not need to be installed.
import matplotlib.colors as colors # Import here so if the user does not plot with this package, it does not need to be installed.
self.matplotlib_plt = plt
self.matplotlib_colors = colors
fig, ax = plt.subplots()
ax.grid(b=True, which='minor', color='#000000', alpha=0.1, linestyle='-', linewidth=0.25)
self.matplotlib_fig = fig
self.matplotlib_ax = ax
def set(self, **kwargs):
super().set(**kwargs) # This does a validation of the arguments and stores them in the properties of the super() figure.
del(kwargs) # Remove it to avoid double access to the properties. Now you must access like "self.title" and so.
self.matplotlib_ax.set_xlabel(super().xlabel)
self.matplotlib_ax.set_ylabel(super().ylabel)
if self.xscale in [None, 'lin']:
self.matplotlib_ax.set_xscale('linear')
elif self.xscale == 'log':
self.matplotlib_ax.set_xscale('log')
if self.yscale in [None, 'lin']:
self.matplotlib_ax.set_yscale('linear')
elif self.yscale == 'log':
self.matplotlib_ax.set_yscale('log')
if self.title != None:
self.matplotlib_fig.canvas.set_window_title(self.title)
if self.show_title == True:
self.matplotlib_fig.suptitle(self.title)
if self.aspect == 'equal':
self.matplotlib_ax.set_aspect('equal')
if self.subtitle != None:
self.matplotlib_ax.set_title(self.subtitle)
def show(self):
self.matplotlib_plt.show()
def save(self, fname=None, *args, **kwargs):
if fname is None:
fname = self.title
if fname is None:
raise ValueError(f'Please provide a name for saving the figure to a file by the <fname> argument.')
if fname[-4] != '.': fname = f'{fname}.png'
self.matplotlib_fig.savefig(facecolor=(1,1,1,0), fname=fname, *args, **kwargs)
def close(self):
self.matplotlib_plt.close(self.matplotlib_fig)
def plot(self, x, y=None, **kwargs):
validated_args = super().plot(x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
x = validated_args.get('x')
y = validated_args.get('y')
validated_args.pop('x')
validated_args.pop('y')
self.matplotlib_ax.plot(x, y, **validated_args)
if validated_args.get('label') != None: # If you gave me a label it is obvious for me that you want to display it, no?
self.matplotlib_ax.legend()
def hist(self, samples, **kwargs):
validated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
validated_args['bins'] = np.array(validated_args['bins'][:-2]) + np.diff(validated_args['bins'])[:-1]/2 # This is to normalize the binning criteria with plotly.
samples = validated_args['samples']
validated_args.pop('samples')
validated_args.pop('counts') # Have no idea why I have to remove "counts", otherwise the next line raises a strange error.
self.matplotlib_ax.hist(x = samples, histtype='step', **validated_args)
if validated_args.get('label') != None: # If you provided a legend I assume you want to show it.
self.matplotlib_ax.legend()
def hist2d(self, _______, **kwargs):
# ~ validated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.
# ~ del(kwargs) # Remove it to avoid double access to the properties.
raise NotImplementedError(f'<hist2d> not yet implemented for {self.__class__.__name__}')
def colormap(self, z, x=None, y=None, **kwargs):
validated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
z = np.array(validated_args.get('z'))
validated_args.pop('z')
x = validated_args.get('x')
validated_args.pop('x')
y = validated_args.get('y')
validated_args.pop('y')
if validated_args.get('norm') in [None, 'lin']: # linear normalization
validated_args['norm'] = self.matplotlib_colors.Normalize(vmin=np.nanmin(z), vmax=np.nanmax(z))
elif validated_args.get('norm') == 'log':
temp = np.squeeze(np.asarray(z))
while temp.min() <= 0:
temp = temp[temp!=temp.min()]
if (z<=0).any():
z[z<=0] = float('Nan')
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float("inf") values for plotting (i.e. they will not appear in the plot).')
validated_args['norm'] = self.matplotlib_colors.LogNorm(vmin=np.nanmin(z), vmax=np.nanmax(z))
z[z!=z] = float('inf')
if 'colorscalelabel' in validated_args:
colorscalelabel = validated_args.get('colorscalelabel')
validated_args.pop('colorscalelabel')
if x is None and y is None:
cs = self.matplotlib_ax.pcolormesh(z, rasterized=True, shading='auto', cmap='Blues_r', **validated_args)
elif x is not None and y is not None:
cs = self.matplotlib_ax.pcolormesh(x, y, z, rasterized=True, shading='auto', cmap='Blues_r', **validated_args)
else:
raise ValueError('You must provide either "both x and y" or "neither x nor y"')
cbar = self.matplotlib_fig.colorbar(cs)
if 'colorscalelabel' in locals():
cbar.set_label(colorscalelabel, rotation = 90)
def contour(self, z, x=None, y=None, **kwargs):
validated_args = super().contour(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
z = np.array(validated_args.get('z'))
validated_args.pop('z')
x = validated_args.get('x')
validated_args.pop('x')
y = validated_args.get('y')
validated_args.pop('y')
if validated_args.get('norm') in [None, 'lin']: # linear normalization
validated_args['norm'] = self.matplotlib_colors.Normalize(vmin=np.nanmin(z), vmax=np.nanmax(z))
elif validated_args.get('norm') == 'log':
temp = np.squeeze(np.asarray(z))
while temp.min() <= 0:
temp = temp[temp!=temp.min()]
if (z<=0).any():
z[z<=0] = float('Nan')
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float("inf") values for plotting (i.e. they will not appear in the plot).')
validated_args['norm'] = self.matplotlib_colors.LogNorm(vmin=np.nanmin(z), vmax=np.nanmax(z))
z[z!=z] = float('inf')
if x is None and y is None:
cs = self.matplotlib_ax.contour(z, rasterized=True, shading='auto', cmap='Blues_r', **validated_args)
elif x is not None and y is not None:
cs = self.matplotlib_ax.contour(x, y, z, rasterized=True, shading='auto', cmap='Blues_r', **validated_args)
else:
raise ValueError('You must provide either "both x and y" or "neither x nor y"')
cbar = self.matplotlib_fig.colorbar(cs)
if 'colorscalelabel' in locals():
cbar.set_label(colorscalelabel, rotation = 90)
self.matplotlib_ax.clabel(cs, inline=True, fontsize=10)
def fill_between(self, x, y1, y2=None, **kwargs):
validated_args = super().fill_between(x, y1, y2, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
x = validated_args['x']
validated_args.pop('x')
y1 = validated_args['y1']
validated_args.pop('y1')
y2 = validated_args['y2']
validated_args.pop('y2')
self.matplotlib_ax.fill_between(x, y1, y2, **validated_args)
if validated_args.get('label') != None: # If you gave me a label it is obvious for me that you want to display it, no?
self.matplotlib_ax.legend()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,039
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_plot.py
|
import myplotlib as mpl
import numpy as np
x = np.linspace(1,3)
y = x**3
for package in ['matplotlib', 'plotly']:
fig = mpl.manager.new(
title = f'simple plot with {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
fig.plot(
x,
y,
label = 'Simple plot',
)
fig = mpl.manager.new(
title = f'Markers test {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
for marker in ['.', '+', 'x', 'o']:
fig.plot(
x,
y + np.random.randn(len(x)),
marker = marker,
label = f'Markers {marker}',
)
fig = mpl.manager.new(
title = f'Linestyle test {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
for linestyle in ['solid', 'none', 'dashed', 'dotted']:
fig.plot(
x,
y + np.random.randn(len(x)),
marker = '.',
linestyle = linestyle,
label = f'Linestyle {linestyle}',
)
mpl.manager.save_all()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,040
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_fill_between.py
|
import myplotlib as mpl
import numpy as np
x = np.linspace(-1,1)
y = x**3
for package in ['matplotlib', 'plotly']:
fig = mpl.manager.new(
title = f'Fill between with {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
fig.fill_between(
x,
y,
label = 'Fill between 0 and y',
)
fig.fill_between(
x,
y*1.1,
y*.9,
label = 'Fill between two curves',
color = (0,0,0),
)
mpl.manager.save_all()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,041
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/wrapper_saods9.py
|
from .figure import MPLFigure
class MPLSaoImageDS9Wrapper(MPLFigure):
"""
This is a very specific type of figure, intended to be used with
images.
"""
DIRECTORY_FOR_TEMPORARY_FILES = '.myplotlib_ds9_temp'
_norm = 'lin'
def __init__(self):
super().__init__()
import os
self.os = os
from astropy.io import fits
self.astropy_io_fits = fits
if not self.os.path.isdir(self.DIRECTORY_FOR_TEMPORARY_FILES):
self.os.makedirs(self.DIRECTORY_FOR_TEMPORARY_FILES)
@property
def title(self):
return self._title.replace(' ', '_')
def colormap(self, z, x=None, y=None, **kwargs):
validated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
z = np.array(validated_args.get('z'))
hdul_new = self.astropy_io_fits.PrimaryHDU(z)
if f'{self.title}.fits' in self.os.listdir(self.DIRECTORY_FOR_TEMPORARY_FILES):
self.os.remove(f'{self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits')
hdul_new.writeto(f'{self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits')
if 'norm' in validated_args and validated_args['norm'] == 'log':
self._norm = 'log'
def show(self):
self.os.system(f'ds9 {self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits' + (' -log' if self._norm == 'log' else ''))
def close(self):
if len(self.os.listdir(self.DIRECTORY_FOR_TEMPORARY_FILES)) == 0:
self.os.rmdir(self.DIRECTORY_FOR_TEMPORARY_FILES)
self.__del__()
def __del__(self):
if self.os.path.exists(f'{self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits'):
self.os.remove(f'{self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits')
def save(self, fname):
if fname[:-5] != '.fits':
fname = '.'.join(fname.split('.')[:-1] + ['fits'])
copyfile(f'{self.DIRECTORY_FOR_TEMPORARY_FILES}/{self.title}.fits', fname)
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,042
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_markers.py
|
import myplotlib as mpl
import numpy as np
x = np.linspace(0,1)
for package in ['plotly', 'matplotlib']:
fig = mpl.manager.new(
title = 'Markers test',
package = package,
)
fig.plot(
x,
x**3,
label = 'No markers',
)
for marker in ['.','x','+','o']:
fig.plot(
x,
x**np.random.rand(),
marker = marker,
label = f'Marker = {marker}',
linestyle = '',
)
mpl.manager.show()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,043
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/wrapper_plotly.py
|
from .figure import MPLFigure
import numpy as np
class MPLPlotlyWrapper(MPLFigure):
LINESTYLE_TRANSLATION = {
'solid': None,
'none': None,
'dashed': 'dash',
'dotted': 'dot',
}
def __init__(self):
super().__init__()
import plotly.graph_objects as go # Import here so if the user does not plot with this package, it does not need to be installed.
import plotly # Import here so if the user does not plot with this package, it does not need to be installed.
self.plotly_go = go
self.plotly = plotly
self.plotly_fig = go.Figure()
def set(self, **kwargs):
super().set(**kwargs) # This does a validation of the arguments and stores them in the properties of the super() figure.
del(kwargs) # Remove it to avoid double access to the properties. Now you must access like "self.title" and so.
if self.show_title == True and self.title != None:
self.plotly_fig.update_layout(title = self.title)
self.plotly_fig.update_layout(
xaxis_title = self.xlabel,
yaxis_title = self.ylabel,
)
# Axes scale:
if self.xscale in [None, 'lin']:
pass
elif self.xscale == 'log':
self.plotly_fig.update_layout(xaxis_type = 'log')
if self.yscale in [None, 'lin']:
pass
elif self.yscale == 'log':
self.plotly_fig.update_layout(yaxis_type = 'log')
if self.aspect == 'equal':
self.plotly_fig.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
)
if self.subtitle != None:
self.plotly_fig.add_annotation(
text = self.subtitle.replace('\n','<br>'),
xref = "paper",
yref = "paper",
x = .5,
y = 1,
align = 'left',
arrowcolor="#ffffff",
font=dict(
family="Courier New, monospace",
color="#999999"
),
)
def show(self):
self.plotly_fig.show()
def save(self, fname, include_plotlyjs='cdn', *args, **kwargs):
if fname is None:
fname = self.title
if fname is None:
raise ValueError(f'Please provide a name for saving the figure to a file by the <fname> argument.')
if fname[-5:] != '.html':
if len(fname.split('.')) > 1:
splitted = fname.split('.')
splitted[-1] = 'html'
fname = '.'.join(splitted)
else:
fname = f'{fname}.html'
self.plotly.offline.plot(
self.plotly_fig,
filename = fname,
auto_open = False,
include_plotlyjs = include_plotlyjs,
*args,
**kwargs
)
def close(self):
del(self.plotly_fig)
def plot(self, x, y=None, **kwargs):
validated_args = super().plot(x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
self.plotly_fig.add_trace(
self.plotly_go.Scatter(
x = validated_args['x'],
y = validated_args['y'],
name = validated_args.get('label'),
opacity = validated_args.get('alpha'),
mode = self.translate_marker_and_linestyle_to_mode(validated_args.get('marker'), validated_args.get('linestyle')),
marker_symbol = self._map_marker_to_plotly(validated_args.get('marker')),
showlegend = True if validated_args.get('label') != None else False,
line = dict(
dash = self.LINESTYLE_TRANSLATION[validated_args.get('linestyle')] if 'linestyle' in validated_args else None,
)
)
)
if validated_args.get('color') != None:
self.plotly_fig['data'][-1]['marker']['color'] = self._rgb2hexastr_color(validated_args.get('color'))
if validated_args.get('linewidth') != None:
self.plotly_fig['data'][-1]['line']['width'] = validated_args.get('linewidth')
def fill_between(self, x, y1, y2=None, **kwargs):
validated_args = super().fill_between(x, y1, y2, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
x = validated_args['x']
validated_args.pop('x')
y1 = validated_args['y1']
validated_args.pop('y1')
y2 = validated_args['y2']
validated_args.pop('y2')
self.plot(
x = list(x) + list(x)[::-1],
y = list(y1) + list(y2)[::-1],
**validated_args,
)
self.plotly_fig['data'][-1]['fill'] = 'toself'
self.plotly_fig['data'][-1]['hoveron'] = 'points'
self.plotly_fig['data'][-1]['line']['width'] = 0
def error_band(self, x, y, ytop, ylow, **kwargs):
validated_args = super().error_band(x, y, ytop, ylow, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
x = validated_args['x']
validated_args.pop('x')
y = validated_args['y']
validated_args.pop('y')
ytop = validated_args['ytop']
validated_args.pop('ytop')
ylow = validated_args['ylow']
validated_args.pop('ylow')
legendgroup = str(np.random.rand()) + str(np.random.rand())
self.plot(x, y, **validated_args)
self.plotly_fig['data'][-1]['legendgroup'] = legendgroup
self.fill_between(
x,
ylow,
ytop,
color = validated_args['color'],
)
self.plotly_fig['data'][-1]['showlegend'] = False
self.plotly_fig['data'][-1]['legendgroup'] = legendgroup
def hist(self, samples, **kwargs):
validated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
self.plotly_fig.add_traces(
self.plotly_go.Scatter(
x = validated_args['bins'],
y = validated_args['counts'],
mode = self.translate_marker_and_linestyle_to_mode(validated_args.get('marker'), validated_args.get('linestyle')),
opacity = validated_args.get('alpha'),
name = validated_args.get('label'),
showlegend = True if validated_args.get('label') != None else False,
line = dict(
shape='hvh',
dash = self.LINESTYLE_TRANSLATION[validated_args.get('linestyle')] if 'linestyle' in validated_args else None,
)
)
)
# ~ self.fig.update_layout(barmode='overlay')
if validated_args.get('color') != None:
self.plotly_fig['data'][-1]['marker']['color'] = self._rgb2hexastr_color(validated_args.get('color'))
if validated_args.get('linewidth') != None:
self.plotly_fig['data'][-1]['line']['width'] = validated_args.get('linewidth')
def hist2d(self, _______, **kwargs):
# ~ validated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.
# ~ del(kwargs) # Remove it to avoid double access to the properties.
raise NotImplementedError(f'<hist2d> not yet implemented for {self.__class__.__name__}')
def colormap(self, z, x=None, y=None, **kwargs):
validated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
z = np.array(validated_args.get('z'))
validated_args.pop('z')
x = validated_args.get('x')
validated_args.pop('x')
y = validated_args.get('y')
validated_args.pop('y')
if x is not None and y is not None:
if x.size == y.size == z.size:
x = x[0]
y = y.transpose()[0]
z2plot = z
if 'norm' in validated_args and validated_args['norm'] == 'log':
if (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float("NaN") values for plotting (i.e. they will not appear in the plot).')
z2plot[z2plot<=0] = float('NaN')
z2plot = np.log(z2plot)
self.plotly_fig.add_trace(
self.plotly_go.Heatmap(
z = z2plot,
x = x,
y = y,
colorbar = dict(
title = (('log ' if validated_args.get('norm') == 'log' else '') + validated_args.get('colorscalelabel')) if validated_args.get('colorscalelabel') is not None else None,
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else "x")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else "y")}: %{{y}}<br>{(validated_args.get("colorscalelabel") if "colorscalelabel" in validated_args is not None else "color scale")}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6
)
)
self.plotly_fig.update_layout(legend_orientation="h")
def contour(self, z, x=None, y=None, **kwargs):
validated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.
del(kwargs) # Remove it to avoid double access to the properties.
if 'levels' in validated_args:
# See in Matplotlib's documentation to see what this is supposed to do.
raise NotImplementedError(f'<levels> not yet implemented for <contour> for Plotly.')
z = np.array(validated_args.get('z'))
validated_args.pop('z')
x = validated_args.get('x')
validated_args.pop('x')
y = validated_args.get('y')
validated_args.pop('y')
if x is not None and y is not None:
if x.size == y.size == z.size:
x = x[0]
y = y.transpose()[0]
z2plot = z
if 'norm' in validated_args and validated_args['norm'] == 'log':
if (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float("NaN") values for plotting (i.e. they will not appear in the plot).')
z2plot[z2plot<=0] = float('NaN')
z2plot = np.log(z2plot)
self.plotly_fig.add_trace(
self.plotly_go.Contour(
z = z2plot,
x = x,
y = y,
colorbar = dict(
title = (('log ' if validated_args.get('norm') == 'log' else '') + validated_args.get('colorscalelabel')) if validated_args.get('colorscalelabel') is not None else None,
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else "x")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else "y")}: %{{y}}<br>{(validated_args.get("colorscalelabel") if "colorscalelabel" in validated_args is not None else "color scale")}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6
contours=dict(
coloring = 'heatmap',
showlabels = True, # show labels on contours
labelfont = dict( # label font properties
color = 'white',
)
)
)
)
self.plotly_fig.update_layout(legend_orientation="h")
def _rgb2hexastr_color(self, rgb_color: tuple):
# Assuming that <rgb_color> is a (r,g,b) tuple.
color_str = '#'
for rgb in rgb_color:
color_hex_code = hex(int(rgb*255))[2:]
if len(color_hex_code) < 2:
color_hex_code = f'0{color_hex_code}'
color_str += color_hex_code
return color_str
def _map_marker_to_plotly(self, marker):
if marker is None:
return None
markers_map = {
'.': 'circle',
'+': 'cross',
'x': 'x',
'o': 'circle-open',
}
return markers_map[marker]
def translate_marker_and_linestyle_to_mode(self, marker, linestyle):
if marker == None and linestyle != 'none':
mode = 'lines'
elif marker != None and linestyle != 'none':
mode = 'lines+markers'
elif marker != None and linestyle == 'none':
mode = 'markers'
else:
mode = 'lines'
return mode
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,044
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_hist.py
|
import myplotlib as mpl
import numpy as np
samples = [np.random.randn(999)*2*i for i in range(3)]
for package in ['matplotlib', 'plotly']:
fig = mpl.manager.new(
title = f'simple histogram with {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
for idx,s in enumerate(samples):
fig.hist(
s,
label = f'Plain histogram {idx}',
linestyle = ['solid','dashed','dotted'][idx],
)
fig = mpl.manager.new(
title = f'specifying bins with {package}',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
)
for idx,s in enumerate(samples):
fig.hist(
s,
bins = 5 if idx==0 else [0,2,3,3.5,4.4,4.5,4.6],
label = f'Plain histogram {idx}',
)
mpl.manager.save_all()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,045
|
SengerM/myplotlib
|
refs/heads/master
|
/myplotlib/__init__.py
|
from .wrapper_matplotlib import MPLMatplotlibWrapper
from .wrapper_plotly import MPLPlotlyWrapper
from .wrapper_saods9 import MPLSaoImageDS9Wrapper
from .utils import get_timestamp
import os
import __main__
from pathlib import Path
import warnings
warnings.warn(f'The package "myplotlib" is deprecated, not maintained anymore. Please use "grafica" instead https://github.com/SengerM/grafica')
class FigureManager:
def __init__(self):
self.set_plotting_package('plotly')
self.figures = []
def set_plotting_package(self, package):
IMPLEMENTED_PACKAGES = ['matplotlib', 'plotly', 'ds9']
if package not in IMPLEMENTED_PACKAGES:
raise ValueError('<package> must be one of ' + str(IMPLEMENTED_PACKAGES))
self.plotting_package = package
def new(self, **kwargs):
package_for_this_figure = kwargs.get('package') if 'package' in kwargs else self.plotting_package
if 'package' in kwargs: kwargs.pop('package')
if package_for_this_figure == 'plotly':
self.figures.append(MPLPlotlyWrapper())
elif package_for_this_figure == 'matplotlib':
self.figures.append(MPLMatplotlibWrapper())
elif package_for_this_figure == 'ds9':
self.figures.append(MPLSaoImageDS9Wrapper())
self.figures[-1].set(**kwargs)
if 'title' not in kwargs:
self.figures[-1].set(title = f'figure_{len(self.figures)}', show_title = False)
return self.figures[-1]
# ~ def set_style(self, style):
# ~ PLOTTING_STYLES = ['latex one column', 'latex two columns']
# ~ style = style.lower()
# ~ if style not in PLOTTING_STYLES:
# ~ raise ValueError('<style> must be one of ' + str(PLOTTING_STYLES))
# ~ elif style == 'latex one column' and self.plotting_package == 'matplotlib':
# ~ plt.style.use(os.path.dirname(os.path.abspath(__file__)) + '/rc_styles/latex_one_column_rc_style')
# ~ elif style == 'latex two columns' and self.plotting_package == 'matplotlib':
# ~ plt.style.use(os.path.dirname(os.path.abspath(__file__)) + '/rc_styles/latex_two_columns_rc_style')
def save_all(self, timestamp=False, mkdir=True, format='png', delete_all=True, *args, **kwargs):
"""
Use this function to save all plots made with the current manager at once.
Arguments
---------
timestamp : bool, optional
Default: False
If true then all file names will be identified with one (and the
same) timestamp. The timestamp is created at the moment this
function is called. If you call this function twice, you'll have
two different timestamps.
This is usefull when you want not to overwrite the plots each
time you run your code. Let's say you are doing a simulation and you
want to keep the plots of each different run, then you can use
"timestamp = True".
mkdir : str or True/False
Default: True
If a string is passed then a directory will be created (with the
specified name) and all figures will be saved in there. If True
the name for the directory is the same as the name of the top
level python script that called this function. If False, no directory
is created an figures are saved in the current working directory.
format : string, optional
Default: 'png'
Format of image files. Default is 'png'.
"""
current_timestamp = get_timestamp()
if mkdir != False:
if isinstance(mkdir, Path):
mkdir = str(mkdir)
if mkdir == True:
mkdir = __main__.__file__.replace('.py', '') + '_saved_plots'
directory = mkdir + '/'
if not os.path.exists(directory):
os.makedirs(directory)
else:
directory = './'
for k,_fig in enumerate(self.figures):
file_name = current_timestamp + ' ' if timestamp == True else ''
file_name += _fig.title if _fig.title != None else 'figure ' + str(k+1)
_fig.save(fname = str(Path(f'{directory}/{file_name}.{format}')), *args, **kwargs)
if delete_all == True:
self.delete_all()
def show(self):
for fig in self.figures:
fig.show()
def delete(self, fig):
self.figures.remove(fig)
fig.close()
def delete_all_figs(self):
for fig in self.figures:
fig.close()
self.figures = []
def delete_all(self):
self.delete_all_figs()
manager = FigureManager()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,046
|
SengerM/myplotlib
|
refs/heads/master
|
/tests/test_contour_colormap.py
|
import myplotlib as mpl
import numpy as np
x = np.linspace(-1,1)
y = x
xx, yy = np.meshgrid(x,y)
zz = xx**4 + yy**2 + np.random.rand(*xx.shape)*.1
for package in ['matplotlib', 'plotly']:
fig = mpl.manager.new(
title = f'colormap with {package} linear scale',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
aspect = 'equal',
)
fig.colormap(
x = xx,
y = yy,
z = zz,
colorscalelabel = 'Colormap value',
)
fig = mpl.manager.new(
title = f'contour with {package} linear scale',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
aspect = 'equal',
)
fig.contour(
x = xx,
y = yy,
z = zz,
colorscalelabel = 'Colormap value',
)
fig = mpl.manager.new(
title = f'colormap with {package} log scale',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
aspect = 'equal',
)
fig.colormap(
x = xx,
y = yy,
z = zz,
colorscalelabel = 'Colormap value',
norm = 'log',
)
fig = mpl.manager.new(
title = f'contour with {package} log scale',
subtitle = f'This is a test',
xlabel = 'x axis',
ylabel = 'y axis',
package = package,
aspect = 'equal',
)
fig.contour(
x = xx,
y = yy,
z = zz,
colorscalelabel = 'Colormap value',
norm = 'log',
)
mpl.manager.save_all()
|
{"/tests/test_error_band.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_matplotlib.py": ["/myplotlib/figure.py"], "/tests/test_plot.py": ["/myplotlib/__init__.py"], "/tests/test_fill_between.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_saods9.py": ["/myplotlib/figure.py"], "/tests/test_markers.py": ["/myplotlib/__init__.py"], "/myplotlib/wrapper_plotly.py": ["/myplotlib/figure.py"], "/tests/test_hist.py": ["/myplotlib/__init__.py"], "/myplotlib/__init__.py": ["/myplotlib/wrapper_matplotlib.py", "/myplotlib/wrapper_plotly.py", "/myplotlib/wrapper_saods9.py", "/myplotlib/utils.py"], "/tests/test_contour_colormap.py": ["/myplotlib/__init__.py"]}
|
20,049
|
woblob/UI-Select_text_to_print
|
refs/heads/main
|
/edittab.py
|
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from lxml import etree as et
import datetime
class NameItem(QStandardItem):
def __init__(self, txt):
super().__init__()
self.setEditable(True)
self.setText(txt)
self.setCheckState(Qt.Unchecked)
self.setCheckable(True)
# self.setAutoTristate(True)
class TextItem(QStandardItem):
def __init__(self, txt=''):
super().__init__()
self.setEditable(True)
self.setText(txt)
class EditTab(QWidget):
def __init__(self, link):
super().__init__()
self.helper_counter = 0
self.currently_selected_tree_item = None
self.add_subitem_button = None
self.remove_button = None
self.database = link.database
self.signal = link.send_signal
self.tree_model = link.tree_model
self.unsaved_changes = link.unsaved_changes
self.file_dialog = CustomFileDialog()
self.initialize_tab()
def initialize_tab(self):
edit_tab = QVBoxLayout()
buttons_groupbox = self.initialize_edit_button_boxes()
tree_groupbox = self.make_edit_tree()
IO_buttons_groupbox = self.initialize_IO_button_box()
edit_tab.addWidget(buttons_groupbox)
edit_tab.addWidget(tree_groupbox)
edit_tab.addWidget(IO_buttons_groupbox)
self.setLayout(edit_tab)
def initialize_edit_button_boxes(self):
hbox = QHBoxLayout()
add_item_button = QPushButton("Dodaj Element")
add_subitem_button = QPushButton("Dodaj podElement")
remove_button = QPushButton("Usuń")
add_subitem_button.setDisabled(True)
remove_button.setDisabled(True)
add_item_button.clicked.connect(self.add_tree_item)
add_subitem_button.clicked.connect(self.add_subitem_tree_item)
remove_button.clicked.connect(self.remove_tree_item)
self.add_subitem_button = add_subitem_button
self.remove_button = remove_button
hbox.addWidget(add_item_button)
hbox.addWidget(add_subitem_button)
hbox.addWidget(remove_button)
groupbox = QGroupBox()
groupbox.setLayout(hbox)
return groupbox
def make_edit_tree(self):
tree_view = QTreeView()
tree_view.setModel(self.tree_model)
tree_view.setAlternatingRowColors(True)
tree_view.header().setSectionResizeMode(QHeaderView.ResizeToContents)
# tree_view.clicked.connect(self.select_item)
tree_view.selectionModel().selectionChanged.connect(self.update_tree_item_selection)
self.tree_view = tree_view
return tree_view
def add_tree_item(self):
if self.currently_selected_tree_item is None:
parent = self.tree_model
else:
parent = self.currently_selected_tree_item.parent()
if parent is None:
parent = self.tree_model
self.make_dummy_tree_item(parent)
def make_dummy_tree_item(self, parent):
new_item = NameItem(f"Element {self.helper_counter}")
text_item = TextItem()
parent.appendRow([new_item, text_item])
self.helper_counter += 1
def add_subitem_tree_item(self):
parent = self.currently_selected_tree_item
parent_index = parent.index()
self.make_dummy_tree_item(parent)
self.tree_view.expand(parent_index)
def remove_tree_item(self):
item_index = self.tree_view.selectionModel().currentIndex()
p_index = item_index.parent()
parent = self.tree_model.itemFromIndex(p_index) or self.tree_model
parent.removeRow(item_index.row())
# def select_item(self, item):
# self.currently_selected_tree_item = item
def update_tree_item_selection(self, current, prev):
indexes = current.indexes()
disabled = True
if indexes == []:
self.currently_selected_tree_item = None
else:
nameindex, _ = indexes
nameitem = self.tree_model.itemFromIndex(nameindex)
self.currently_selected_tree_item = nameitem
disabled = False
self.add_subitem_button.setDisabled(disabled)
self.remove_button.setDisabled(disabled)
def initialize_IO_button_box(self):
hbox = QHBoxLayout()
save_button = QPushButton("Zapisz")
load_button = QPushButton("Ładuj")
save_button.clicked.connect(self.save_database)
load_button.clicked.connect(self.load_database)
hbox.addWidget(save_button)
hbox.addWidget(load_button)
groupbox = QGroupBox()
groupbox.setLayout(hbox)
return groupbox
def save_database(self):
filename = self.file_dialog.save()
if not filename:
return
xml_tree = self.lxml_get_all_items()
xml_tree.write(filename,
pretty_print=True,
xml_declaration=True,
encoding="utf-8")
message = f"Zapisano plik {filename}"
EditTab.display_message(message)
@staticmethod
def display_message(message):
msgBox = QMessageBox()
msgBox.setText(message)
# msgbox_format = QTextCharFormat()
# msgbox_format.setFontPointSize(20)
# msgBox.setTextFormat(msgbox_format)
msgBox.exec_()
def lxml_get_all_items(self):
def recursave(tree_node, root):
for i in range(tree_node.rowCount()):
name_node = tree_node.item(i, 0)
name = name_node.text()
text = tree_node.item(i, 1).text()
element = et.SubElement(root, "Element", Name=name, Text=text)
help_recursave(name_node, element)
def help_recursave(tree_node, root):
for i in range(tree_node.rowCount()):
name_node = tree_node.child(i, 0)
name = name_node.text()
text = tree_node.child(i, 1).text()
element = et.SubElement(root, "Element", Name=name, Text=text)
help_recursave(name_node, element)
timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
root = et.Element("root", timestamp=timestamp)
recursave(self.tree_model, root)
print(et.tostring(root))
tree = et.ElementTree(root)
return tree
# def lxml_get_all_items2(self):
# def recursave(tree_node, root):
# for i in range(tree_node.rowCount()):
# name_node = tree_node.item(i, 0)
# name = name_node.text()
# text = tree_node.item(i, 1).text()
# element = et.SubElement(root, "Element")
# name_elem = et.SubElement(element, "Name")
# name_elem.text = name
# text_elem = et.SubElement(element, "Text")
# text_elem.text = text
# help_recursave(name_node, element)
#
# def help_recursave(tree_node, root):
# for i in range(tree_node.rowCount()):
# name_node = tree_node.child(i)
# name = name_node.text()
# text = tree_node.child(i, 1).text()
# element = et.SubElement(root, "Element")
# name_elem = et.SubElement(element, "Name")
# name_elem.text = name
# text_elem = et.SubElement(element, "Text")
# text_elem.text = text
# help_recursave(name_node, element)
#
# timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
# root = et.Element("root", timestamp=timestamp)
# recursave(self.tree_model, root)
# print(et.tostring(root))
#
# tree = et.ElementTree(root)
# return tree
def load_database(self):
filename = self.file_dialog.open()
if not filename:
return
message = ''
try:
root = et.parse(filename).getroot()
except et.XMLSyntaxError as e:
message = f"Plik źle sformatowany.\n{e}"
except OSError as e:
message = f"Nie udało się otworzyć pliku.\n{e}"
except BaseException as e:
message = f"Nie obsługiwany błąd.\nError: {e}, {type(e)}"
finally:
if message:
EditTab.display_message(message)
return
self.database._setroot(root)
self.update_tree()
self.signal.emit()
def update_tree(self):
column_name0 = self.tree_model.headerData(0, Qt.Horizontal)
column_name1 = self.tree_model.headerData(1, Qt.Horizontal)
self.tree_model.clear()
def help_rec(xlm_tree, qroot):
for child in xlm_tree.getroot():
n, t = rec(child)
qroot.appendRow([n, t])
def rec(elem):
name = elem.get("Name")
text = elem.get("Text")
NAME, TEXT = NameItem(name), TextItem(text)
for child in elem:
n, t = rec(child)
NAME.appendRow([n, t])
return NAME, TEXT
help_rec(self.database, self.tree_model)
self.tree_view.expandAll()
self.tree_model.setHorizontalHeaderItem(0, QStandardItem(column_name0))
self.tree_model.setHorizontalHeaderItem(1, QStandardItem(column_name1))
self.currently_selected_tree_item = None
class CustomFileDialog(QFileDialog):
def __init__(self):
super().__init__()
self.filename = "database {}.xml"
# self.setParent(parent, Qt.Widget)
self.setViewMode(QFileDialog.List)
self.setNameFilter("XML Files (*.xml)")
self.setDirectory(QDir.currentPath())
self.setLabelText(QFileDialog.Reject, "Anuluj")
self.setLabelText(QFileDialog.LookIn, "Foldery")
self.setLabelText(QFileDialog.FileType, "Format pliku")
self.setLabelText(QFileDialog.FileName, "Nazwa pliku")
self.setWindowModality(Qt.ApplicationModal)
options = self.Options()
options |= self.DontUseNativeDialog
self.setOptions(options)
def save(self):
time_format = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
default_filename = self.filename.format(time_format)
self.setFileMode(QFileDialog.AnyFile)
self.setWindowTitle("Zapisz baze danych")
self.setLabelText(QFileDialog.Accept, "Zapisz")
self.selectFile(default_filename)
self.setAcceptMode(QFileDialog.AcceptSave)
filename = ""
if self.exec_():
filename = self.selectedFiles()[0]
return filename
def open(self):
self.setFileMode(QFileDialog.ExistingFile)
self.setWindowTitle("Załaduj baze danych")
self.setLabelText(QFileDialog.Accept, "Otwórz")
filename = ""
if self.exec_():
filename = self.selectedFiles()[0]
return filename
|
{"/main.py": ["/selecttab.py", "/edittab.py"]}
|
20,050
|
woblob/UI-Select_text_to_print
|
refs/heads/main
|
/main.py
|
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import lxml.etree as et
from selecttab import SelectTab
from edittab import EditTab
# Edycja elementu: zrobione jako klikanie
# zebranie info co drukowac: zrobione
# zapis do pliku: zrobione
# potwierdzenie zapisu: zrobione
# zaladowanie pliku do edit: zrobione
# zaladowanie pliku do select: zrobione
# wyswietlenie drzewa edit: zrobione
# wyswietlenie drzewa select, sygnal: zrobione
# zmienic database etree -> Qtree (połączone z następnym) treeview: zrobione
# update zmian drzewa edit -> select: zrobione
# zmiana aplikacji na bardziej elastyczną: zrobione
# drukowanie: zrobione
# jak drukowac, checkbox'y/ checkAll: zrobione
# TODO: które texty zaznaczyć aka profil domyślny
# TODO: jak drukowac, checkbox'y/ printAll
# TODO: Autoload database
# TODO: wyciagnac drzewo edit i zrobic nowa klase
# TODO: zapis zmian przed wyjściem
# TODO: ?zmienic zapis do XML'a
# TODO: ?ładne drukowanie
class ConnectionBetweenTabs(QObject):
unsaved_changes = 0
database = et.ElementTree()
send_signal = pyqtSignal()
tree_model = QStandardItemModel()
tree_model.setObjectName(u"treeModel")
tree_model.setColumnCount(2)
tree_model.setHorizontalHeaderItem(0, QStandardItem("Name"))
tree_model.setHorizontalHeaderItem(1, QStandardItem("Text"))
class MaybeSave(QMessageBox):
def __init__(self):
super().__init__()
self.setText("Dokonano zmian w bazie danych")
self.setInformativeText("Czy chcesz zapisać zmiany?")
self.setStandardButtons(QMessageBox.Save |
QMessageBox.Discard |
QMessageBox.Cancel)
self.setDefaultButton(QMessageBox.Save)
def run(self):
return self.exec()
class Window(QWidget):
def __init__(self):
super().__init__()
self.link = ConnectionBetweenTabs()
self.initializeWindow()
self.combine_tabs()
self.show()
def initializeWindow(self):
self.setWindowTitle(QCoreApplication.translate("Okienko", u"Okienko"))
self.setGeometry(QRect(100, 100, 520, 640))
def combine_tabs(self):
self.tab_bar = QTabWidget()
self.select_tab = SelectTab(self.link)
self.edit_tab = EditTab(self.link)
self.tab_bar.addTab(self.select_tab, "Wybór tekstów")
self.tab_bar.addTab(self.edit_tab, "Edycja tekstów")
main_h_box = QHBoxLayout()
main_h_box.addWidget(self.tab_bar)
self.setLayout(main_h_box)
def closeEvent(self, event):
self.link.unsaved_changes = 0
if self.unsaved_changes:
choice = MaybeSave().run()
if choice == QMessageBox.Save:
self.edit_tab.save_database()
elif choice == QMessageBox.Cancel:
event.ignore()
return
event.accept()
if __name__ == "__main__":
app = QApplication([])
screen = Window()
sys.exit(app.exec_())
|
{"/main.py": ["/selecttab.py", "/edittab.py"]}
|
20,051
|
woblob/UI-Select_text_to_print
|
refs/heads/main
|
/selecttab.py
|
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
from docx import Document
class SelectTab(QWidget):
def __init__(self, link):
super().__init__()
self.database = link.database
self.tree_model = link.tree_model
self.signal = link.send_signal
self.tree_view = None
self.signal.connect(self.update_tree)
self.initializeTab()
def initializeTab(self):
select_tab = QVBoxLayout()
print_groupbox = self.initialize_print_box()
tree_groupbox = self.make_select_tree_view()
# buttons_groupbox = self.initialize_select_button_box()
select_tab.addWidget(print_groupbox)
select_tab.addWidget(tree_groupbox)
# select_tab.addWidget(buttons_groupbox)
self.setLayout(select_tab)
def initialize_print_box(self):
hbox = QHBoxLayout()
checkboxes = self.initialize_check_boxes()
export_button = QPushButton("Eksportuj jako docx")
export_button.clicked.connect(self.export_tree_as_docx)
hbox.addWidget(checkboxes)
hbox.addWidget(export_button)
print_box = QGroupBox()
print_box.setLayout(hbox)
return print_box
def initialize_check_boxes(self):
vbox = QVBoxLayout()
checkbox1 = QCheckBox("zaznacz wszyskto")
checkbox1.toggled.connect(self.checkAll)
checkbox2 = QCheckBox("checkbox 2")
# checkbox2.setChecked(True)
vbox.addWidget(checkbox1)
vbox.addWidget(checkbox2)
groupbox = QGroupBox()
groupbox.setLayout(vbox)
return groupbox
def export_tree_as_docx(self):
root = self.tree_model.invisibleRootItem()
files = SelectTab.gather_files_from_tree(root)
Print_docx(files)
@staticmethod
def gather_files_from_tree(root):
def children_of_(item):
for index in range(item.rowCount()):
name_col = item.child(index, 0)
text_col = item.child(index, 1)
yield name_col, text_col
lst = []
for name_item, text_item in children_of_(root):
is_partially_checked = name_item.checkState() != Qt.Unchecked
if is_partially_checked:
if name_item.hasChildren():
files_to_print = SelectTab.gather_files_from_tree(name_item)
lst.extend(files_to_print)
else:
file_to_print = text_item.text()
lst.append(file_to_print)
return lst
def make_select_tree_view(self):
tree_view = QTreeView()
tree_view.setModel(self.tree_model)
tree_view.header().setSectionResizeMode(QHeaderView.ResizeToContents)
tree_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
tree_view.hideColumn(1)
tree_view.setHeaderHidden(True)
tree_view.clicked.connect(self.on_item_clicked)
self.tree_view = tree_view
return tree_view
def update_tree(self):
self.tree_view.hideColumn(1)
self.tree_view.expandAll()
self.tree_view.setHeaderHidden(True)
def checkAll(self, checkbox_state):
root = self.tree_model.invisibleRootItem()
if checkbox_state:
self.check_all_descendants(root)
else:
self.uncheck_all_descendants(root)
def on_item_clicked(self, index):
item = self.tree_model.itemFromIndex(index)
if item.checkState() == Qt.Checked:
self.check_all_descendants(item)
self.update_all_ancestors_Checked(item)
elif item.checkState() == Qt.Unchecked:
self.uncheck_all_descendants(item)
self.update_all_ancestors_Unhecked(item)
def update_all_ancestors_Checked(self, item):
parent = item.parent()
if parent is None:
return
tristate = 1
for child in SelectTab.children_of_(parent):
if not child.checkState() == Qt.Checked:
parent.setCheckState(tristate)
self.update_all_ancestors_Checked(parent)
break
else:
parent.setCheckState(Qt.Checked)
self.update_all_ancestors_Checked(parent)
def update_all_ancestors_Unhecked(self, item):
parent = item.parent()
if parent is None:
return
tristate = 1
for child in SelectTab.children_of_(parent):
if not child.checkState() == Qt.Unchecked:
parent.setCheckState(tristate)
self.update_all_ancestors_Unhecked(parent)
break
else:
parent.setCheckState(Qt.Unchecked)
self.update_all_ancestors_Unhecked(parent)
@staticmethod
def children_of_(item):
for index in range(item.rowCount()):
child = item.child(index, 0)
yield child
def check_all_descendants(self, item):
for child in SelectTab.children_of_(item):
if not child.checkState() == Qt.Checked:
child.setCheckState(Qt.Checked)
self.check_all_descendants(child)
def uncheck_all_descendants(self, item):
for child in SelectTab.children_of_(item):
if not child.checkState() == Qt.Unchecked:
child.setCheckState(Qt.Unchecked)
self.uncheck_all_descendants(child)
# def initialize_select_button_box(self):
# buttonBox = QDialogButtonBox()
# buttonBox.setObjectName(u"buttonBox")
# buttonBox.setOrientation(Qt.Horizontal)
# buttonBox.setStandardButtons(
# QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
# # buttonBox.accepted.connect(lambda: None)
# buttonBox.rejected.connect(sys.exit)
# return buttonBox
class Print_docx:
def __init__(self, list_of_files, filename = "Dokumenty do druku.docx"):
self.list_of_files = list_of_files
self.document = Document()
self.document.add_heading('Dokumenty do przyniesienia', 0)
self.table = self.make_table()
self.populate_table()
self.adjust_column_widths()
self.document.save(filename)
def make_table(self):
table = self.document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Nr.'
hdr_cells[1].text = 'tresc'
hdr_cells[2].text = 'Znak'
return table
def populate_table(self):
for index, text in enumerate(self.list_of_files, 1):
row_cells = self.table.add_row().cells
row_cells[0].text = str(index)
row_cells[1].text = text
row_cells[2].text = " "
def adjust_column_widths(self):
w_nr = 1 / 5
w_z = 1 / 3.6
w = self.table.columns[0].width
self.table.columns[0].width = int(w * w_nr)
w = self.table.columns[1].width
self.table.columns[1].width = int(w * 2.5)
w = self.table.columns[2].width
self.table.columns[2].width = int(w * w_z)
|
{"/main.py": ["/selecttab.py", "/edittab.py"]}
|
20,057
|
vvojvoda/django_iban_test
|
refs/heads/master
|
/nulliban/tests.py
|
from django.test import TestCase
# Create your tests here.
from nulliban.models import NullIban
class NullIbanTest(TestCase):
def test_null_iban_field(self):
iban = NullIban()
iban.save()
|
{"/nulliban/tests.py": ["/nulliban/models.py"]}
|
20,058
|
vvojvoda/django_iban_test
|
refs/heads/master
|
/nulliban/models.py
|
from django.db import models
from django_iban.fields import IBANField
class NullIban(models.Model):
iban = IBANField(null=True, blank=True)
|
{"/nulliban/tests.py": ["/nulliban/models.py"]}
|
20,060
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/mixins.py
|
from django.contrib.auth.mixins import UserPassesTestMixin
class UserApprovedMixin(UserPassesTestMixin):
"""
Deny access to unapproved users.
"""
def test_func(self):
return self.request.user.is_authenticated and self.request.user.is_approved
class AddClientMixin:
"""
Add the client to be saved on create views.
Override form_valid() of CreateView.
https://docs.djangoproject.com/en/stable/topics/class-based-views/generic-editing/#models-and-request-user
"""
def form_valid(self, form):
form.instance.client = self.request.user.client
return super().form_valid(form)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,061
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/tests/tests_views.py
|
from datetime import timedelta
from collections import namedtuple
from dataclasses import dataclass
from django.utils import timezone
from django.test import TestCase
from django.shortcuts import reverse
from ..models import Client, Place, Appliance, Manufacturer, CI, Contract
from accounts.models import User
@dataclass
class ListInfo:
"""
Wraps the details of each test.
Applied to Place, Appliance, and CI.
"""
message: str
context_object_name: str
template_name: str
lookup_text: str
letter: str = 'A'
@property
def contains(self):
return f'{self.lookup_text}{self.letter}'
@property
def not_contains(self):
return f"{self.lookup_text}{'B' if self.letter == 'A' else 'A'}"
class PlaceApplianceAndCIViewTest(TestCase):
"""
Test CI, Place and Appliance views.
"""
users = {}
places = {}
appliances = {}
@classmethod
def setUpTestData(cls):
"""
Set up the database to be used in all testes in this class.
Client A and Client B will have their respective User, CI, and Place.
cls.users = {'a': user_A, 'b': user_B}
"""
manufacturer = Manufacturer.objects.create(name='Cisco')
contract = create_contract()
for letter in {'A', 'B'}:
client = Client.objects.create(name=f'Client {letter}')
place = Place.objects.create(client=client, name=f'Place Client {letter}')
appliance = create_appliance(client, manufacturer, letter)
create_ci(client, place, letter, contract)
user = User.objects.create_user(f'user_{letter}', password='faith', client=client)
cls.users.update({letter: user})
cls.places.update({letter: place})
cls.appliances.update({letter: appliance})
cls.manufacturer = manufacturer
cls.contract = contract
# Maps the details of the tests applied to
# Place, Appliance, and, CI list views, respectively.
cls.list_details = {
reverse('cis:manage_client_places'): ListInfo(
'No place was found.',
'formset',
'cis/manage_client_places.html',
'Place Client ',
),
reverse('cis:appliance_list'): ListInfo(
'No appliance was found.',
'appliance_list',
'cis/appliance_list.html',
'SERIAL_CLIENT_',
),
reverse('cis:ci_list', args=(0,)): ListInfo(
'No configuration item was found.',
'ci_list',
'cis/ci_list.html',
'HOST_',
),
}
def test_show_correct_items_by_client(self):
# for client 'A' and client 'B'
for k, user in self.users.items():
self.client.force_login(user)
# test Place, Appliance, and CI
for url, test in self.list_details.items():
test.letter = k
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, test.template_name)
self.assertEqual(len(response.context[test.context_object_name]), 1)
self.assertContains(response, test.contains, count=1)
self.assertNotContains(response, test.not_contains)
self.client.logout()
def test_raise_exception_on_unapproved_user(self):
user = self.users['A']
user.client = None
user.save()
self.client.force_login(user)
# test Place, Appliance, and CI
for url in self.list_details.keys():
response = self.client.get(url)
self.assertIsNone(response.context)
self.assertEqual(response.status_code, 403)
def test_not_found(self):
client = Client.objects.create(name=f'Client C')
user = User.objects.create_user(f'user_c', password='faith', client=client)
self.client.force_login(user)
# test Place, Appliance, and CI
for url, test in self.list_details.items():
response = self.client.get(url)
self.assertContains(response, test.message, count=1)
self.assertEqual(len(response.context[test.context_object_name]), 0)
self.assertNotContains(response, test.not_contains)
def test_create(self):
self.client.force_login(self.users['A'])
# map urls to info that needs to be checked
CreateInfo = namedtuple('CreateInfo', ['data', 'template_name', 'contains'])
details = {
'cis:place_create': CreateInfo(
{'name': "New Place"},
'cis/place_form.html',
['The place New Place was created successfully.'],
),
'cis:appliance_create': CreateInfo(
{
'serial_number': 'NEW_SERIAL',
'manufacture': self.manufacturer,
'model': 'ABC123',
'virtual': True,
},
'cis/appliance_form.html',
['NEW_SERIAL', 'Cisco', 'ABC123'],
),
'cis:ci_create': CreateInfo(
{
'place': self.places['A'].id,
'appliances': (self.appliances['A'].id,),
'hostname': 'NEW_HOST',
'ip': '10.10.10.254',
'description': 'New Configuration Item',
'deployed': True,
'business_impact': 'high',
'contract': self.contract,
},
'cis/ci_form.html',
['NEW_HOST', self.appliances['A'].serial_number],
)
}
# test Place, Appliance, and CI
for url, info in details.items():
response = self.client.post(reverse(url), info.data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, info.template_name)
for text in info.contains:
self.assertContains(response, text, count=1)
class AdminViewTest(TestCase):
fixtures = ['all.json']
@classmethod
def setUpTestData(cls):
cls.user = User.objects.get(username='admin')
def setUp(self):
self.client.force_login(self.user)
def test_mark_selected_cis_as_approved_action(self):
data = {
'action': 'approve_selected_cis',
'_selected_action': [1, 2],
}
response = self.client.post(reverse('admin:cis_ci_changelist'), data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'The selected CIs were approved successfully.')
self.assertTemplateUsed(response, 'admin/change_list.html')
def test_user_display_approved(self):
response = self.client.get(reverse('admin:accounts_user_changelist'), follow=True)
self.assertEqual(response.status_code, 200)
self.assertTrue(self.user.is_approved)
def test_client_places_links(self):
response = self.client.get(reverse('admin:cis_client_changelist'), follow=True)
self.assertEqual(response.status_code, 200)
for place in Place.objects.all():
self.assertContains(response, place.name)
def test_appliance_manufacturer_links(self):
response = self.client.get(reverse('admin:cis_appliance_changelist'), follow=True)
self.assertEqual(response.status_code, 200)
for manufacturer in Manufacturer.objects.exclude(appliance=None):
self.assertContains(response, manufacturer.name)
def create_appliance(client, manufacturer, letter):
return Appliance.objects.create(
client=client,
serial_number=f'SERIAL_CLIENT_{letter}',
manufacturer=manufacturer,
model='ABC123',
virtual=True,
)
def create_contract():
return Contract.objects.create(
name='CONTRACT',
begin=timezone.now(),
end=timezone.now() + timedelta(days=356),
description='Contract Description',
)
def create_ci(client, place, letter, contract):
CI.objects.create(
client=client,
place=place,
hostname=f'HOST_{letter}',
ip='10.10.20.20',
description=f'Configuration Item {letter}',
deployed=True,
contract=contract,
)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,062
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/forms.py
|
from django import forms
from .models import CI, Place, Appliance, Client
class UploadCIsForm(forms.Form):
file = forms.FileField()
class CIForm(forms.ModelForm):
appliances = forms.ModelMultipleChoiceField(queryset=None)
place = forms.ModelChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
self.client = kwargs.pop('client')
super().__init__(*args, **kwargs)
self.fields['appliances'] = forms.ModelMultipleChoiceField(
queryset=Appliance.objects.filter(client=self.client)
)
self.fields['place'] = forms.ModelChoiceField(
queryset=Place.objects.filter(client=self.client)
)
class Meta:
model = CI
exclude = ('client', 'status', 'pack')
class ApplianceForm(forms.ModelForm):
class Meta:
model = Appliance
exclude = ('client',)
class PlaceForm(forms.ModelForm):
class Meta:
model = Place
fields = ('client',)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,063
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/tests/tests_functionals.py
|
"""
Functional tests.
Requires Selenium and geckodriver.
"""
from django.conf import settings
from django.test import tag
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from accounts.models import User
from ..models import Client, CI
from ..urls import app_name
LOGIN = 'client_a_user@example.com'
PASSWORD = 'UnQt5uGgjErbwkN'
SESSION_COOKIE = settings.SESSION_COOKIE_NAME
class CommonTestMixin:
"""
Add common fixtures and methods to TestCases.
A user is logged in before each test.
Place the mixin early in the MRO in order to isolate
setUpClass()/tearDownClass().
"""
fixtures = ['all.json']
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.driver = WebDriver()
def setUp(self):
# Login via Django
user = User.objects.get(pk=1)
self.client.force_login(user)
cookie = self.client.cookies[SESSION_COOKIE]
# Selenium will use the current domain to set the cookie
self.driver.get(f'{self.live_server_url}/any-404')
self.driver.add_cookie({
'name': SESSION_COOKIE,
'value': cookie.value,
'secure': False,
})
@classmethod
def tearDownClass(cls):
cls.driver.quit()
super().tearDownClass()
@staticmethod
def _get_alert_success_text(driver: WebDriver) -> str:
msg = WebDriverWait(driver, 2).until(
lambda d: d.find_element(By.CSS_SELECTOR, '.alert-success')
)
return msg.text
@tag('functional')
class LoginTest(CommonTestMixin, StaticLiveServerTestCase):
def setUp(self):
pass
def test_login_unapproved_user_shows_alert(self):
user = User.objects.get(pk=1)
user.client = None
user.save()
self._login_user(LOGIN)
message = self.driver.find_element(By.CSS_SELECTOR, '.alert-warning')
self.assertEqual(
'Your account needs to be approved. Please contact you Account Manager.',
message.text[2:]
)
self._logout()
def test_login_approved_user_does_not_show_alert(self):
self._login_user(LOGIN)
with self.assertRaises(NoSuchElementException):
self.driver.find_element(By.CSS_SELECTOR, '.alert-warning')
home = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(home.text, 'Homepage')
self._logout()
def _login_user(self, email):
self.driver.get(f'{self.live_server_url}/accounts/login/')
username_input = self.driver.find_element(By.ID, 'id_login')
username_input.send_keys(email)
password_input = self.driver.find_element(By.ID, 'id_password')
password_input.send_keys(PASSWORD)
self.driver.find_element(By.XPATH, '//input[@type="submit"]').click()
def _logout(self):
self.driver.find_element(By.LINK_TEXT, 'Logout').click()
self.driver.find_element(By.XPATH, '//button[@type="submit"]').click()
@tag('functional')
class SiteTest(CommonTestMixin, StaticLiveServerTestCase):
"""Test all features related to the Place model."""
def test_create_place(self):
self.driver.get(f'{self.live_server_url}/{app_name}/place/create/')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, 'Place')
new_place_name = 'Paulista'
name = self.driver.find_element(By.ID, 'id_name')
name.send_keys(new_place_name)
description = self.driver.find_element(By.ID, 'id_description')
description.send_keys('Place description' + Keys.ENTER)
msg = self._get_alert_success_text(self.driver)
self.assertTrue(f'The place {new_place_name} was created successfully.' in msg)
def test_viewing_place(self):
self.driver.get(f'{self.live_server_url}/{app_name}/place/1')
new_place = self.driver.find_element(By.ID, 'id_name')
self.assertEqual(new_place.get_attribute('value'), 'Main')
def test_listing_places(self):
self.driver.get(f'{self.live_server_url}/{app_name}/places/')
for i in range(2):
place = self.driver.find_element(By.ID, f'id_place_set-{i}-name')
self.assertTrue(place.get_attribute('value') in {'Main', 'Branch'})
def test_deleting_place(self):
self.driver.get(f'{self.live_server_url}/{app_name}/places/')
self.driver.find_element(By.ID, 'id_place_set-0-DELETE').click()
self.driver.find_element(By.XPATH, '//input[@value="Save"]').click()
msg = self._get_alert_success_text(self.driver)
self.assertTrue('The places were updated successfully.' in msg)
@tag('functional')
class ApplianceTest(CommonTestMixin, StaticLiveServerTestCase):
"""Test all features related to the Appliance model."""
def test_create_appliance(self):
self.driver.get(f'{self.live_server_url}/{app_name}/appliance/create/')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, 'Appliance')
the_serial_number = 'DEF456'
serial = self.driver.find_element(By.ID, 'id_serial_number')
serial.send_keys(the_serial_number)
manufacturer = self.driver.find_element(By.ID, 'id_manufacturer')
manufacturer_select = Select(manufacturer)
manufacturer_select.select_by_index(1)
model = self.driver.find_element(By.ID, 'id_model')
model.send_keys('C9000')
serial = self.driver.find_element(By.ID, 'id_serial_number')
self.assertEqual(serial.get_attribute('value'), the_serial_number)
def test_viewing_appliance(self):
_id = 3
self.driver.get(f'{self.live_server_url}/{app_name}/appliance/{_id}')
serial = self.driver.find_element(By.ID, 'id_serial_number')
self.assertEqual(serial.get_attribute('value'), f'SERIAL{_id}')
def test_listing_appliances(self):
self.driver.get(f'{self.live_server_url}/{app_name}/appliances/')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, 'Appliances')
serials = self.driver.find_elements(By.CSS_SELECTOR, 'td>a')
for i, serial in enumerate(serials):
self.assertEqual(serial.text, f'SERIAL{i + 1}')
def test_view_appliance_from_listing(self):
self.driver.get(f'{self.live_server_url}/{app_name}/appliances/')
serial_origin = self.driver.find_element(By.CSS_SELECTOR, 'td>a')
serial = serial_origin.text
serial_origin.click()
serial_target = self.driver.find_element(By.ID, 'id_serial_number')
self.assertEqual(serial, serial_target.get_attribute('value'))
@tag('functional')
class CITest(CommonTestMixin, StaticLiveServerTestCase):
"""Test all features related to the CI model."""
def test_create_ci(self):
self.driver.get(f'{self.live_server_url}/{app_name}/ci/create/')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, 'Configuration Item')
self.driver.find_element(By.ID, 'id_hostname').send_keys('NEW_HOST')
place_select = Select(self.driver.find_element(By.ID, 'id_place'))
place_select.select_by_value('1')
self.driver.find_element(By.ID, 'id_ip').send_keys('10.10.20.20')
contract_select = Select(self.driver.find_element(By.ID, 'id_contract'))
contract_select.select_by_index(1)
self.driver.find_element(By.ID, 'id_description').send_keys('Some text.')
appliances_select = Select(self.driver.find_element(By.ID, 'id_appliances'))
appliances_select.select_by_value('1')
appliances_select.select_by_value('2')
self.driver.find_element(By.ID, 'id_username').send_keys('admin')
self.driver.find_element(By.ID, 'id_password').send_keys('123')
self.driver.find_element(By.ID, 'id_enable_password').send_keys('enable123' + Keys.RETURN)
msg = self._get_alert_success_text(self.driver)
self.assertTrue('success' in msg)
def test_viewing_ci(self):
ci = CI.objects.get(pk=3)
self.driver.get(f'{self.live_server_url}/{app_name}/ci/3')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, str(ci))
def test_listing_cis(self):
self.driver.get(f'{self.live_server_url}/{app_name}/cis/0/')
h1 = self.driver.find_element(By.TAG_NAME, 'h1')
self.assertEqual(h1.text, 'Configuration Items Created')
cis = self.driver.find_elements(By.CSS_SELECTOR, 'td>a')
for hostname in cis:
hostnames = ('CORE', 'FLW2', 'FLW3')
self.assertTrue(hostname.text in hostnames)
def test_view_ci_from_listing(self):
self.driver.get(f'{self.live_server_url}/{app_name}/cis/0/')
ci_origin = self.driver.find_element(By.CSS_SELECTOR, 'td>a')
ci_hostname_origin = ci_origin.text
ci_origin.click()
ci_hostname_target = self.driver.find_element(By.ID, 'hostname')
self.assertEqual(ci_hostname_target.text, ci_hostname_origin)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,064
|
DiegoVilela/internalize
|
refs/heads/main
|
/accounts/models.py
|
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
class UserClientManager(UserManager):
def get_queryset(self):
return super().get_queryset().select_related('client')
class User(AbstractUser):
client = models.ForeignKey('cis.Client', on_delete=models.CASCADE, blank=True, null=True)
# modify the user manager's initial QuerySet to join the Client
# https://docs.djangoproject.com/en/3.1/topics/db/managers/#modifying-a-manager-s-initial-queryset
objects = UserClientManager()
def __str__(self):
return self.email
@property
def is_approved(self):
return bool(self.client) or self.is_superuser
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,065
|
DiegoVilela/internalize
|
refs/heads/main
|
/accounts/tests.py
|
from django.test import TestCase
from django.db.utils import IntegrityError
from .models import User
from cis.models import Client
class UserTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(username='new', email='new@example.com')
def test_is_approved_returns_true_when_user_has_client(self):
client = Client.objects.create(name='New Client')
self.user.client = client
self.assertTrue(self.user.is_approved)
def test_is_approved_returns_false_when_user_has_no_client(self):
self.user.client = None
self.assertFalse(self.user.is_approved)
def test_user_as_string_returns_email(self):
self.assertEqual(str(self.user), self.user.email)
def test_duplicate_name_raises_exception(self):
with self.assertRaises(IntegrityError):
self.user.pk = None
self.user.save()
self.user.pk = 1
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,066
|
DiegoVilela/internalize
|
refs/heads/main
|
/internalize/settings.py
|
"""
Django settings for internalize project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import django_heroku
import os
from pathlib import Path
from django.contrib.messages import constants as messages
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', '_zkf47_u&6yyr+b5wq_q0^_@+)%1nrl^vf=)+m4ut@%(^w_jco')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get('DEBUG', 1))
# 'ALLOWED_HOSTS' should be a single string of hosts with a space between each.
# For example: 'ALLOWED_HOSTS=127.0.0.1 [::1]'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '127.0.0.1 [::1]').split(' ')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# 3rd party
'allauth',
'allauth.account',
'allauth.socialaccount',
'crispy_forms',
'debug_toolbar',
'django_extensions',
# Local
'accounts',
'cis',
]
MIDDLEWARE = [
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'internalize.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'internalize.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_USER_MODEL = 'accounts.User'
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (BASE_DIR / 'static',)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# allauth
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
LOGIN_REDIRECT_URL = 'homepage'
ACCOUNT_LOGOUT_REDIRECT_URL = 'homepage'
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# Debug Toolbar
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#configuring-internal-ips
INTERNAL_IPS = ['127.0.0.1']
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# Sets a strict policy to disable many potentially privacy-invading and annoying features for all scripts.
# https://pypi.org/project/django-permissions-policy/
PERMISSIONS_POLICY = {
"accelerometer": [],
"ambient-light-sensor": [],
"autoplay": [],
"camera": [],
"document-domain": [],
"encrypted-media": [],
"fullscreen": [],
"geolocation": [],
"gyroscope": [],
"interest-cohort": [],
"magnetometer": [],
"microphone": [],
"midi": [],
"payment": [],
"usb": [],
}
# Activate Django-Heroku.
django_heroku.settings(locals())
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,067
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/tests/tests_models.py
|
from django.shortcuts import reverse
from django.test import TestCase
from django.db.utils import IntegrityError
from accounts.models import User
from ..models import Client, Place, Manufacturer, Contract, Appliance, CI, CIPack
CLIENT_NAME = 'Client A'
PLACE_NAME = 'Main'
MANUFACTURER = 'Cisco Systems'
CONTRACT_NAME = 'BR-001'
class FixtureMixin:
"""Add the same fixture to all TestCase"""
fixtures = ['all.json']
class ClientTest(FixtureMixin, TestCase):
def test_client_as_string_returns_name(self):
client = Client.objects.get(pk=1)
self.assertEqual(str(client), CLIENT_NAME)
def test_duplicate_name_raises_exception(self):
with self.assertRaises(IntegrityError):
Client.objects.create(name=CLIENT_NAME)
class PlaceTest(FixtureMixin, TestCase):
def test_as_string_returns_client_plus_place_name(self):
place = Place.objects.get(pk=1)
self.assertEqual(str(place), f'{CLIENT_NAME} | {PLACE_NAME}')
def test_duplicate_name_by_client_raises_exception(self):
client = Client.objects.get(pk=1)
with self.assertRaises(IntegrityError):
Place.objects.create(name=PLACE_NAME, client=client)
def test_duplicate_name_different_client_is_ok(self):
client = Client.objects.create(name='Different Client')
self.assertIsNotNone(Place.objects.create(name=PLACE_NAME, client=client))
def test_absolute_url_returns_correct_url(self):
place = Place.objects.get(pk=1)
self.assertEqual(
place.get_absolute_url(),
reverse('cis:place_update', args=[place.pk])
)
class ManufacturerTest(FixtureMixin, TestCase):
def test_as_string_returns_name(self):
manufacturer = Manufacturer.objects.get(pk=1)
self.assertEqual(str(manufacturer), MANUFACTURER)
def test_duplicate_name_raises_exception(self):
with self.assertRaises(IntegrityError):
Manufacturer.objects.create(name=MANUFACTURER)
class ContractTest(FixtureMixin, TestCase):
def test_as_string_returns_name(self):
contract = Contract.objects.get(pk=1)
self.assertEqual(str(contract), CONTRACT_NAME)
class ApplianceTest(FixtureMixin, TestCase):
def test_as_string_returns_full_name(self):
appliance = Appliance.objects.get(pk=1)
self.assertEqual(
str(appliance),
f'{MANUFACTURER} | {appliance.model} | {appliance.serial_number}'
)
def test_duplicate_serial_number_raises_exception(self):
appliance = Appliance.objects.get(pk=1)
appliance.pk = None
with self.assertRaises(IntegrityError):
appliance.save()
def test_absolute_url_returns_correct_url(self):
appliance = Appliance.objects.get(pk=1)
self.assertEqual(
appliance.get_absolute_url(),
reverse('cis:appliance_update', args=[appliance.pk])
)
class CITest(FixtureMixin, TestCase):
def test_as_string_returns_full_name(self):
ci = CI.objects.get(pk=1)
self.assertEqual(
str(ci),
f'{CLIENT_NAME} | {PLACE_NAME} | {ci.hostname} | {ci.ip}'
)
def test_unique_constraint_raises_exception(self):
ci = CI.objects.get(pk=1)
ci.pk = None
ci.credential_id = None
with self.assertRaises(IntegrityError):
ci.save()
def test_duplicate_hostname_with_different_client_is_ok(self):
new_client = Client.objects.create(name='Different Client')
ci = CI.objects.get(pk=1)
ci.pk = None
ci.credential_id = None
ci.client = new_client
ci.save()
self.assertIsNotNone(ci.pk)
def test_absolute_url_returns_correct_url(self):
ci = CI.objects.get(pk=1)
self.assertEqual(
ci.get_absolute_url(),
reverse('cis:ci_detail', args=[ci.pk])
)
class CIPackTest(FixtureMixin, TestCase):
@classmethod
def setUpTestData(cls):
cls.admin = User.objects.get(pk=2)
cls.user = User.objects.get(pk=1)
cls.pack = CIPack.objects.get(pk=1)
cls.cis = CI.objects.all()
def test_as_string_returns_responsible_plus_local_data(self):
self.assertEqual(
str(self.pack),
f"{self.user} 2021-04-20 09:25:38" # UTC-3
)
def test_percentage_of_cis_approved(self):
# Approve 0 of 3 CIs
self.assertEqual(self.pack.percentage_of_cis_approved, 0)
# Approve 1 of 3 CIs
self.pack.ci_set.filter(pk__in=(1,)).update(status=2)
self.assertEqual(self.pack.percentage_of_cis_approved, 33)
# Approve 2 of 3 CIs
self.pack.ci_set.filter(pk__in=(1, 2)).update(status=2)
self.assertEqual(self.pack.percentage_of_cis_approved, 67)
# Approve 3 of 3 CIs
self.pack.ci_set.filter(pk__in=(1, 2, 3)).update(status=2)
self.assertEqual(self.pack.percentage_of_cis_approved, 100)
def test_approved_by_returns_the_right_superuser(self):
self.pack.approved_by = self.admin
self.pack.save()
self.assertEqual(self.pack.approved_by, self.admin)
def test_send_cis_to_production(self):
ci_pks = (ci.pk for ci in self.cis)
self.pack.send_to_production(ci_pks)
for ci in self.pack.ci_set.all():
self.assertEqual(ci.status, 1)
def test_len_returns_count_of_ci_set(self):
self.assertEqual(len(self.pack), 3)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,068
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/tests/tests_loader.py
|
from pathlib import Path
from collections import namedtuple
from openpyxl import Workbook
from django.test import TestCase
from accounts.models import User
from ..models import Client, Place, Contract, Manufacturer
from ..loader import CILoader
from ..cis_mapping import CIS_SHEET, \
APPLIANCES_SHEET
SPREADSHEET_FILE = 'cis_test.xlsx'
CLIENT_NAME = 'New Client'
class CILoaderTest(TestCase):
@classmethod
def setUpTestData(cls):
create_workbook()
cls.company_client = Client.objects.create(name=CLIENT_NAME)
cls.loader = CILoader(SPREADSHEET_FILE, cls.company_client).save()
@classmethod
def tearDownClass(cls):
Path(SPREADSHEET_FILE).unlink()
super().tearDownClass()
def test_return_correct_client_object(self):
self.assertIsInstance(self.loader.client, Client)
self.assertEqual(self.loader.client.name, CLIENT_NAME)
def test_return_correct_site_objects(self):
sites = self.loader.places
keys = {'NY1', 'NY2', 'SP', 'BH'}
for k, site in sites.items():
self.assertIn(k, keys)
self.assertIsInstance(site, Place)
def test_return_correct_contract_objects(self):
contracts = self.loader.contracts
keys = {'SP-001', 'BH-001', 'NY-001', 'NY-002'}
for k, contract in contracts.items():
self.assertIn(k, keys)
self.assertIsInstance(contract, Contract)
def test_return_correct_manufacture_objects(self):
manufacturers = self.loader.manufacturers
keys = {'Cisco', 'F5'}
for k, manufacturer in manufacturers.items():
self.assertIn(k, keys)
self.assertIsInstance(manufacturer, Manufacturer)
def test_loader_contains_correct_number_of_cis(self):
self.assertEqual(len(self.loader.cis), 5)
def test_errors_contain_duplicated_items(self):
create_workbook()
loader = CILoader(SPREADSHEET_FILE, self.company_client).save()
self.assertEqual(len(loader.errors), 5)
self.assertEqual(len(loader.cis), 0)
self.assertTrue(
'unique constraint' in str(loader.errors[0].exc).lower()
)
def create_workbook():
wb = Workbook()
set_cis_sheet(wb)
set_appliances_sheet(wb)
wb.save(filename=SPREADSHEET_FILE)
def set_cis_sheet(workbook):
cis_sheet = workbook.create_sheet(CIS_SHEET)
Row = namedtuple('Row', (
'hostname',
'ip',
'description',
'deployed',
'business_impact',
'site',
'site_description',
'contract',
'contract_begin',
'contract_end',
'contract_description',
'username',
'password',
'enable_password',
'instructions',
))
base = Row('router_sp', '172.16.5.10', 'Main Router',
'x', 'high', 'SP', 'Center', 'SP-001',
'2021-01-01', '2022-01-01', 'Contract Details',
'admin', 'admin', 'enable', 'Instructions')
rows = (
Row._fields,
base,
base._replace(hostname='router_bh', ip='172.16.6.10',
site='BH', contract='BH-001'),
base._replace(hostname='wlc1', ip='172.16.10.10',
description='Controller Floor 1', site='NY1',
site_description='Main', contract='NY-001'),
base._replace(hostname='wlc2', ip='172.16.10.11',
description='Controller Floor 2', site='NY2',
site_description='Secondary', contract='NY-002'),
base._replace(hostname='fw', ip='10.10.20.20',
description='Firewall'),
)
for row in rows:
cis_sheet.append(row)
def set_appliances_sheet(workbook):
appliances_sheet = workbook.create_sheet(APPLIANCES_SHEET)
Row = namedtuple('ApplianceRow', (
'ci_hostname', 'serial_number', 'manufacture', 'model', 'virtual',
))
rows = (
Row._fields,
Row('wlc1', 'FOX123', 'Cisco', '3560', 'x'),
Row('wlc1', 'FOX124', 'Cisco', '3560', 'x'),
Row('wlc2', 'FOX125', 'Cisco', '3560', 'x'),
Row('router_sp', 'TYF987', 'Cisco', '2960', 'x'),
Row('router_bh', 'TYF654', 'Cisco', '2960', 'x'),
Row('fw', '687F', 'F5', 'BIG-IP', ''),
)
for row in rows:
appliances_sheet.append(row)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,069
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/migrations/0001_initial.py
|
# Generated by Django 3.2 on 2021-04-28 17:16
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import fernet_fields.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Client',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True)),
],
options={
'ordering': ['name'],
'abstract': False,
},
),
migrations.CreateModel(
name='Contract',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, unique=True)),
('begin', models.DateField()),
('end', models.DateField()),
('description', models.TextField()),
],
),
migrations.CreateModel(
name='Credential',
fields=[
('credential_id', models.AutoField(primary_key=True, serialize=False)),
('username', fernet_fields.fields.EncryptedCharField(max_length=50)),
('password', fernet_fields.fields.EncryptedCharField(max_length=50)),
('enable_password', fernet_fields.fields.EncryptedCharField(max_length=50)),
('instructions', fernet_fields.fields.EncryptedCharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='ISP',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True)),
],
options={
'ordering': ['name'],
'abstract': False,
},
),
migrations.CreateModel(
name='Manufacturer',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True)),
],
options={
'ordering': ['name'],
'abstract': False,
},
),
migrations.CreateModel(
name='CI',
fields=[
('credential_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='cis.credential')),
('hostname', models.CharField(max_length=50)),
('ip', models.GenericIPAddressField()),
('description', models.CharField(max_length=255)),
('deployed', models.BooleanField(default=False)),
('business_impact', models.PositiveSmallIntegerField(choices=[(0, 'low'), (1, 'medium'), (2, 'high')], default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(2)])),
('status', models.PositiveSmallIntegerField(choices=[(0, 'created'), (1, 'sent'), (2, 'approved')], default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(2)])),
],
options={
'ordering': ['hostname'],
},
bases=('cis.credential',),
),
migrations.CreateModel(
name='Place',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('description', models.CharField(blank=True, max_length=255, null=True)),
('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.client')),
],
),
migrations.CreateModel(
name='Circuit',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('identifier', models.CharField(max_length=50)),
('bandwidth', models.CharField(max_length=10)),
('type', models.CharField(max_length=50)),
('description', models.CharField(max_length=255)),
('isp', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.isp')),
('place', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.place')),
],
),
migrations.CreateModel(
name='CIPack',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sent_at', models.DateTimeField(auto_now_add=True, null=True)),
('approved_by', models.ForeignKey(limit_choices_to={'is_superuser': True}, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='cipacks_approved', to=settings.AUTH_USER_MODEL)),
('responsible', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Appliance',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('serial_number', models.CharField(max_length=255, unique=True)),
('model', models.CharField(max_length=100)),
('virtual', models.BooleanField(default=False)),
('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.client')),
('manufacturer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cis.manufacturer')),
],
options={
'ordering': ['serial_number'],
},
),
migrations.AddConstraint(
model_name='place',
constraint=models.UniqueConstraint(fields=('client', 'name'), name='unique_client_place_name'),
),
migrations.AddField(
model_name='ci',
name='appliances',
field=models.ManyToManyField(to='cis.Appliance'),
),
migrations.AddField(
model_name='ci',
name='client',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.client'),
),
migrations.AddField(
model_name='ci',
name='contract',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cis.contract'),
),
migrations.AddField(
model_name='ci',
name='pack',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cis.cipack'),
),
migrations.AddField(
model_name='ci',
name='place',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cis.place'),
),
migrations.AddConstraint(
model_name='ci',
constraint=models.UniqueConstraint(fields=('client', 'hostname', 'ip', 'description'), name='unique_client_hostname_ip_description'),
),
]
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,070
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/admin.py
|
from django.contrib import admin, messages
from django.contrib.admin import AdminSite
from django.db import DatabaseError, transaction
from django.db.models import QuerySet
from django.urls import reverse
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext
from .models import (
Client, Place, ISP, Circuit,
CI, Manufacturer, Appliance, Contract, CIPack
)
SITE = 'Internalize'
AdminSite.site_header = SITE
AdminSite.site_title = SITE
class ClientLinkMixin:
"""Add the Client name as a link"""
@admin.display(description='Client', ordering='client__name')
def client_link(self, obj):
url = f'{reverse("admin:cis_client_change", args={obj.client.pk})}'
return format_html('<a href="{}">{}</a>', url, obj.client.name)
class PlaceInline(admin.TabularInline):
model = Place
extra = 1
@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
list_display = ('name', 'view_places')
search_fields = ('name', 'place__name')
view_on_site = False
inlines = (PlaceInline,)
@admin.display(description='Places')
def view_places(self, obj):
places = obj.place_set.all()
places_link_list = ['<ul>']
for place in places:
url = f'{reverse("admin:cis_place_change", args={place.pk})}'
safe_link = format_html('<a href="{}">{}</a>', url, place.name)
places_link_list.append(f'<li>{safe_link}</li>')
places_link_list.append('</ul>')
return mark_safe('\n'.join(places_link_list))
class CIInline(admin.TabularInline):
model = CI
extra = 0
max_num = 0 # prevents the link `add another` from appearing
fields = ('description', 'deployed', 'business_impact', 'contract', 'status', 'pack')
readonly_fields = ('description', 'deployed', 'business_impact', 'contract', 'status', 'pack')
show_change_link = True
@admin.register(Place)
class PlaceAdmin(admin.ModelAdmin, ClientLinkMixin):
list_display = ('name', 'client_link', 'description')
list_filter = ('client',)
list_editable = ('description',)
search_fields = ('name', 'client__name', 'description')
inlines = (CIInline,)
@admin.register(Appliance)
class ApplianceAdmin(admin.ModelAdmin, ClientLinkMixin):
list_display = (
'serial_number',
'client_link',
'manufacturer_link',
'model',
'virtual',
)
list_filter = ('client', 'manufacturer', 'virtual')
list_editable = ('model', 'virtual')
search_fields = ('serial_number', 'model', 'client', 'manufacturer')
#autocomplete_fields = ('client', 'manufacturer')
@admin.display(description='Manufacturer', ordering='manufacturer__name')
def manufacturer_link(self, obj):
url = f'{reverse("admin:cis_manufacturer_change", args={obj.manufacturer.pk})}'
return format_html('<a href="{}">{}</a>', url, obj.manufacturer.name)
class ApplianceInline(admin.TabularInline):
model = Appliance
extra = 1
@admin.register(Manufacturer)
class ManufacturerAdmin(admin.ModelAdmin):
list_display = ('name', 'view_appliances')
search_fields = ('name',)
inlines = (ApplianceInline,)
@admin.display(description='Appliances')
def view_appliances(self, obj):
count = obj.appliance_set.count()
url = f'{reverse("admin:cis_appliance_changelist")}?manufacturer__id__exact={obj.pk}'
return format_html('<a href="{}">{} Appliances</a>', url, count)
@admin.register(Contract)
class ContractAdmin(admin.ModelAdmin):
FIELDS = ('name', 'begin', 'end', 'description')
date_hierarchy = 'begin'
list_display = FIELDS
list_filter = ('begin', 'end')
search_fields = FIELDS
inlines = (CIInline,)
@admin.register(CI)
class CIAdmin(admin.ModelAdmin, ClientLinkMixin):
list_display = (
'hostname',
'client_link',
'place_link',
'ip',
'description',
'deployed',
'business_impact',
'contract',
'status',
'view_appliances',
'pack',
)
list_filter = ('pack', 'status', 'client__name', 'place', 'deployed', 'contract')
actions = ['approve_selected_cis']
readonly_fields = ('status',)
fieldsets = (
('Client', {'fields': ((), ('client', 'place',))}),
('Configuration Item', {'fields': (
'appliances',
('hostname', 'ip', 'deployed'),
('description', 'business_impact'),
)}),
('Contract', {'fields': ('contract',)}),
('Credentials', {
'fields': (
(),
('username', 'password', 'enable_password', 'instructions')),
'classes': ('collapse',),
}),
('Management', {
'fields': ('status',),
})
)
filter_horizontal = ('appliances',)
list_editable = (
'ip',
'description',
'deployed',
'business_impact',
)
list_select_related = ('contract', 'client', 'place', 'pack')
@admin.display(description='Place', ordering='place__name')
def place_link(self, obj):
url = f'{reverse("admin:cis_place_change", args={obj.place.pk})}'
return format_html('<a href="{}">{}</a>', url, obj.place.name)
@admin.display(description='Appliances')
def view_appliances(self, obj):
count = obj.appliances.count()
url = f'{reverse("admin:cis_appliance_changelist")}?ci__exact={obj.pk}'
return format_html('<a href="{}">{} Appliances</a>', url, count)
@admin.action(description='Mark selected CIs as approved')
def approve_selected_cis(self, request, queryset: QuerySet):
# todo Write test
pack_ids = set(queryset.values_list('pack', flat=True))
try:
with transaction.atomic():
count = queryset.update(status=2)
CIPack.objects.filter(pk__in=pack_ids).update(approved_by=request.user)
self.message_user(
request,
ngettext(
'The selected CI was approved successfully.',
'The selected CIs were approved successfully.',
count
),
level=messages.SUCCESS,
)
except DatabaseError as e:
raise DatabaseError(f'An error occurred during the approval: {e}')
@admin.register(CIPack)
class CIPackAdmin(admin.ModelAdmin):
FIELDS = ('sent_at', 'responsible', 'percentage_of_cis_approved', 'approved_by')
list_display = FIELDS
actions = ['approve_all_cis']
list_filter = ('responsible', 'sent_at', 'approved_by')
readonly_fields = FIELDS
inlines = (CIInline,)
@admin.action(description="Approve all CIs of selected CIPacks")
def approve_all_cis(self, request, queryset: QuerySet):
try:
with transaction.atomic():
for pack in queryset:
pack.approve_all_cis()
self.message_user(
request,
ngettext(
'The selected CI pack was approved successfully.',
'The selected CI packs were approved successfully.',
len(queryset)
),
level=messages.SUCCESS,
)
except DatabaseError as e:
raise DatabaseError(f'An error occurred during the approval: {e}')
# admin.site.register(ISP)
# admin.site.register(Circuit)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,071
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/models.py
|
from typing import Tuple, NewType
from django.contrib import admin
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.urls import reverse
from django.utils import timezone
from fernet_fields import EncryptedCharField
from accounts.models import User
CIId = NewType('CIId', int)
class Company(models.Model):
"""Model representing an abstract Company.
Base for Client, ISP and Manufacturer
"""
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Meta:
abstract = True
ordering = ['name']
class Client(Company):
"""Model representing a Client company"""
search_fields = ('name',)
def get_absolute_url(self):
return reverse('cis:client_detail', args=(self.id,))
def __str__(self):
return self.name
class Place(models.Model):
"""Model representing a location of a Client"""
client = models.ForeignKey(Client, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
description = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return f"{self.client} | {self.name}"
def get_absolute_url(self):
return reverse('cis:place_update', args=(self.pk,))
class Meta:
constraints = [
models.UniqueConstraint(
fields=['client', 'name'],
name='unique_client_place_name'
)
]
class ISP(Company):
"""Model representing a Internet Service Provider company"""
class Manufacturer(Company):
"""Model representing a Manufacturer of a Configuration Item"""
class Circuit(models.Model):
"""Model representing a Circuit of a ISP installed in a Place"""
place = models.ForeignKey(Place, on_delete=models.CASCADE)
isp = models.ForeignKey(ISP, on_delete=models.CASCADE)
identifier = models.CharField(max_length=50)
bandwidth = models.CharField(max_length=10)
type = models.CharField(max_length=50)
description = models.CharField(max_length=255, help_text="")
def __str__(self):
return f"{self.isp.name} | {self.identifier} | {self.bandwidth}"
class Contract(models.Model):
"""Model representing a Contract applied to a CI"""
name = models.CharField(max_length=100, unique=True)
begin = models.DateField()
end = models.DateField()
description = models.TextField()
def __str__(self):
return self.name
class ApplianceManager(models.Manager):
def get_queryset(self):
return super().get_queryset().select_related('manufacturer')
class Appliance(models.Model):
"""Model representing a physical or virtual Appliance that compounds a Configuration Item"""
# modify the initial queryset to join the Manufacturer
objects = ApplianceManager()
client = models.ForeignKey(Client, on_delete=models.CASCADE)
serial_number = models.CharField(max_length=255, unique=True)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.SET_NULL, null=True)
model = models.CharField(max_length=100)
virtual = models.BooleanField(default=False)
def __str__(self):
return f"{self.manufacturer} | {self.model} | {self.serial_number}"
def get_absolute_url(self):
return reverse('cis:appliance_update', args=(self.pk,))
class Meta:
ordering = ['serial_number']
class Credential(models.Model):
"""Model representing access credentials of a Configuration Item"""
credential_id = models.AutoField(primary_key=True)
username = EncryptedCharField(max_length=50)
password = EncryptedCharField(max_length=50)
enable_password = EncryptedCharField(max_length=50)
instructions = EncryptedCharField(max_length=255, blank=True, null=True)
class CIPack(models.Model):
"""
Model representing a pack of CIs.
It is used to send CIs to production.
"""
responsible = models.ForeignKey('accounts.User', on_delete=models.SET_NULL, null=True)
sent_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
approved_by = models.ForeignKey(
'accounts.User',
on_delete=models.SET_NULL,
null=True,
related_name='cipacks_approved',
limit_choices_to={'is_superuser': True}
)
@property
@admin.display(description='Approved (%)')
def percentage_of_cis_approved(self) -> int:
num_cis_approved = self.ci_set.filter(status=2).count()
if not num_cis_approved:
return 0
return round((num_cis_approved / len(self)) * 100)
def send_to_production(self, ci_pks: Tuple[CIId, ...]):
cis = CI.objects.filter(pk__in=ci_pks)
self.ci_set.set(cis)
self.ci_set.update(status=1)
def approve_all_cis(self):
self.ci_set.update(status=2)
def __len__(self):
return self.ci_set.count()
def __str__(self):
local_date = timezone.localtime(self.sent_at)
return f"{self.responsible} {local_date.strftime('%Y-%m-%d %H:%M:%S')}"
class CI(Credential):
"""
Model representing a Configuration Item.
It is composed of a Setup and a Credential.
https://docs.djangoproject.com/en/stable/topics/db/models/#multiple-inheritance
"""
IMPACT_OPTIONS = (
(0, 'low'),
(1, 'medium'),
(2, 'high'),
)
STATUS_OPTIONS = (
(0, 'created'),
(1, 'sent'),
(2, 'approved'),
)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
place = models.ForeignKey(Place, on_delete=models.CASCADE)
appliances = models.ManyToManyField(Appliance)
hostname = models.CharField(max_length=50)
ip = models.GenericIPAddressField()
description = models.CharField(max_length=255)
deployed = models.BooleanField(default=False)
business_impact = models.PositiveSmallIntegerField(
choices=IMPACT_OPTIONS,
default=0,
validators=[MinValueValidator(0), MaxValueValidator(2)],
)
contract = models.ForeignKey(Contract, on_delete=models.SET_NULL, null=True)
status = models.PositiveSmallIntegerField(
choices=STATUS_OPTIONS,
default=0,
validators=[MinValueValidator(0), MaxValueValidator(2)],
)
pack = models.ForeignKey(CIPack, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f"{self.place} | {self.hostname} | {self.ip}"
def get_absolute_url(self):
return reverse('cis:ci_detail', args=(self.pk,))
class Meta:
ordering = ['hostname']
constraints = [
models.UniqueConstraint(
fields=['client', 'hostname', 'ip', 'description'],
name='unique_client_hostname_ip_description'
)
]
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,072
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/urls.py
|
from django.urls import path
from . import views
app_name = 'cis'
urlpatterns = [
path('cis/<status>/', views.CIListView.as_view(), name='ci_list'),
path('ci/create/', views.CICreateView.as_view(), name='ci_create'),
path('ci/upload/', views.ci_upload, name='ci_upload'),
path('ci/<int:pk>', views.CIDetailView.as_view(), name='ci_detail'),
path('ci/pack/send/', views.send_ci_pack, name='ci_pack_send'),
path('places/', views.manage_client_places, name='manage_client_places'),
path('place/create/', views.PlaceCreateView.as_view(), name='place_create'),
path('place/<int:pk>', views.PlaceUpdateView.as_view(), name='place_update'),
path('manufacturer/<int:pk>', views.ManufacturerDetailView.as_view(), name='manufacturer_detail'),
path('appliances/', views.ApplianceListView.as_view(), name='appliance_list'),
path('appliance/create/', views.ApplianceCreateView.as_view(), name='appliance_create'),
path('appliance/<int:pk>', views.ApplianceUpdateView.as_view(), name='appliance_update'),
]
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,073
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/views.py
|
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.utils.translation import ngettext
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import Http404
from django.forms import inlineformset_factory
from django.core.exceptions import PermissionDenied
from .models import CI, Client, Place, Manufacturer, Appliance, CIPack
from .forms import UploadCIsForm, CIForm, ApplianceForm, PlaceForm
from .loader import CILoader
from .mixins import UserApprovedMixin, AddClientMixin
def homepage(request):
user = request.user
if not user.is_anonymous and not user.is_approved:
messages.warning(request, 'Your account needs to be approved. '
'Please contact you Account Manager.')
return render(request, 'homepage.html')
class PlaceCreateView(UserApprovedMixin, SuccessMessageMixin, AddClientMixin, CreateView):
model = Place
fields = ('name', 'description')
success_message = "The place %(name)s was created successfully."
class PlaceUpdateView(UserApprovedMixin, SuccessMessageMixin, UpdateView):
model = Place
fields = ('name', 'description')
success_message = "The place %(name)s was updated successfully."
def get_queryset(self):
qs = Place.objects.select_related('client')
if not self.request.user.is_superuser:
qs.filter(client=self.request.user.client)
return qs
@login_required
def manage_client_places(request):
if not request.user.is_approved: raise PermissionDenied()
client = request.user.client
select_client_form = None
if request.user.is_superuser:
select_client_form = PlaceForm()
if request.method == 'GET':
if request.user.is_superuser:
if (client_id_selected := request.GET.get('client')):
# At this point, a client was selected by a superuser
select_client_form = PlaceForm(request.GET)
client = Client.objects.get(pk=client_id_selected)
PlaceInlineFormSet = inlineformset_factory(
Client, Place, fields=('name', 'description'), extra=0)
formset = PlaceInlineFormSet(instance=client)
if request.method == 'POST':
formset = PlaceInlineFormSet(request.POST, instance=client)
if formset.is_valid():
formset.save()
messages.success(request, "The places were updated successfully.")
return redirect('cis:manage_client_places')
return render(request, 'cis/manage_client_places.html', {
'formset': formset,
'select_client_form': select_client_form,
'client': client,
})
class CICreateView(UserApprovedMixin, SuccessMessageMixin, AddClientMixin, CreateView):
model = CI
form_class = CIForm
success_message = "The CI was created successfully."
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
# only places of the user.client will be shown in the form
kwargs.update({'client': self.request.user.client })
return kwargs
class CIListView(UserApprovedMixin, ListView):
model = CI
paginate_by = 10
def get_queryset(self):
qs = CI.objects.filter(
status=self.kwargs['status'],
place__client=self.request.user.client
)
if self.request.user.is_superuser:
qs = CI.objects.filter(status=self.kwargs['status'])
return qs
class CIDetailView(UserApprovedMixin, DetailView):
model = CI
queryset = CI.objects.select_related('place', 'contract')
def get_object(self, **kwargs):
object = super().get_object(**kwargs)
if not self.request.user.is_superuser:
if object.place.client != self.request.user.client:
# user authenticated but unauthorized
raise Http404
# user authenticated and authorized
return object
class ManufacturerDetailView(UserApprovedMixin, DetailView):
model = Manufacturer
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
qs = Appliance.objects.filter(
manufacturer=context['manufacturer'],
client=self.request.user.client,
)
if self.request.user.is_superuser:
qs = Appliance.objects.filter(manufacturer=context['manufacturer'])
context['num_appliances'] = qs.count()
return context
class ApplianceListView(UserApprovedMixin, ListView):
model = Appliance
paginate_by = 10
def get_queryset(self):
qs = Appliance.objects.filter(client=self.request.user.client)
if self.request.user.is_superuser:
qs = super().get_queryset()
return qs
class ApplianceCreateView(UserApprovedMixin, SuccessMessageMixin, AddClientMixin, CreateView):
model = Appliance
form_class = ApplianceForm
success_message = "The appliance %(serial_number)s was created successfully."
class ApplianceUpdateView(UserApprovedMixin, SuccessMessageMixin, UpdateView):
model = Appliance
form_class = ApplianceForm
success_message = "The appliance was updated successfully."
def get_queryset(self):
qs = Appliance.objects.select_related('client', 'manufacturer')
if not self.request.user.is_superuser:
qs.filter(client=self.request.user.client)
return qs
@login_required
def ci_upload(request):
if not request.user.is_approved: raise PermissionDenied()
result = None
form = UploadCIsForm()
if request.method == 'POST':
form = UploadCIsForm(request.POST, request.FILES)
if form.is_valid():
client = request.user.client
result = CILoader(request.FILES['file'], client).save()
return render(request, 'cis/ci_upload.html', {
'form': form,
'result': result
})
@login_required
def send_ci_pack(request):
if not request.user.is_approved: raise PermissionDenied()
if request.method == 'POST':
try:
pack = CIPack.objects.create(responsible=request.user)
ci_pks = request.POST.getlist('cis_selected')
if ci_pks:
pack.send_to_production(ci_pks)
messages.success(request, ngettext(
'The selected CI was sent to production successfully.',
'The selected CIs were sent to production successfully.',
len(ci_pks)
))
else:
messages.error(request, 'Please select at least one item to be sent to production.')
except DatabaseError:
raise DatabaseError('There was an error during the sending of the CIs to production.')
return redirect('cis:ci_list', status=0)
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,074
|
DiegoVilela/internalize
|
refs/heads/main
|
/accounts/admin.py
|
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext, gettext_lazy as _
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import User
@admin.register(User)
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
list_select_related = ('client',)
list_display = (
'username',
'email',
'client',
'is_superuser',
'is_staff',
'is_active',
'date_joined',
'last_login',
'is_approved',
)
list_filter = (
'last_login',
'is_superuser',
'is_staff',
'is_active',
'date_joined',
'client',
)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Client'), {'fields': ('client',)}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
@admin.display(boolean=True, description='Approved')
def is_approved(self, obj):
return obj.is_approved
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,075
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/cis_mapping.py
|
"""
Field names and their column location (zero-indexed) on the spreadsheet
"""
CIS_SHEET = 'cis'
# Fields in "cis" sheet
HOSTNAME = 0
IP = 1
DESCRIPTION = 2
DEPLOYED = 3
BUSINESS_IMPACT = 4
# Site fields in "cis" sheet
PLACE = 5
PLACE_DESCRIPTION = 6
# Contract fields in "cis" sheet
CONTRACT = 7
CONTRACT_BEGIN = 8
CONTRACT_END = 8
CONTRACT_DESCRIPTION = 10
# Credential fields in "cis" sheet
CREDENTIAL_USERNAME = 11
CREDENTIAL_PASSWORD = 12
CREDENTIAL_ENABLE_PASSWORD = 13
CREDENTIAL_INSTRUCTIONS = 14
# Appliances fields in "appliances" sheet
APPLIANCES_SHEET = 'appliances'
APPLIANCE_HOSTNAME = 0
APPLIANCE_SERIAL_NUMBER = 1
APPLIANCE_MANUFACTURER = 2
APPLIANCE_MODEL = 3
APPLIANCE_VIRTUAL = 4
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,076
|
DiegoVilela/internalize
|
refs/heads/main
|
/cis/loader.py
|
import logging
from collections import namedtuple
from openpyxl import load_workbook
from django.db import IntegrityError, transaction
from typing import Set
from .models import Client, Place, CI, Appliance, Contract, Manufacturer
from .cis_mapping import HOSTNAME, IP, DESCRIPTION, \
DEPLOYED, BUSINESS_IMPACT, PLACE, PLACE_DESCRIPTION, CONTRACT, \
CONTRACT_BEGIN, CONTRACT_END, CONTRACT_DESCRIPTION, CREDENTIAL_USERNAME, \
CREDENTIAL_PASSWORD, CREDENTIAL_ENABLE_PASSWORD, CREDENTIAL_INSTRUCTIONS, \
CIS_SHEET, APPLIANCES_SHEET, APPLIANCE_HOSTNAME, APPLIANCE_SERIAL_NUMBER, \
APPLIANCE_MANUFACTURER, APPLIANCE_MODEL, APPLIANCE_VIRTUAL
logger = logging.getLogger(__name__)
class CILoader:
def __init__(self, file, client: Client):
self._workbook = load_workbook(file, read_only=True, data_only=True)
self.client = client
self.places = {}
self.contracts = {}
self.manufacturers = {}
self.cis = []
self.errors = []
def save(self):
cis_sheet = self._workbook[CIS_SHEET]
logger.info(f'The method save() of the class {self.__class__.__name__} was called.')
Error = namedtuple('Error', ['exc', 'row'])
for row in cis_sheet.iter_rows(min_row=2, values_only=True):
try:
with transaction.atomic():
ci = self._create_ci(row)
ci.appliances.set(self._get_ci_appliances(row[HOSTNAME]))
self.cis.append(ci)
logger.info(f'{ci} was added to self.cis')
except IntegrityError as e:
self.errors.append(Error(e, row))
logger.error(f'{e} spreadsheet row: {row} was added to self.errors')
return self
def _create_ci(self, row: tuple) -> CI:
return CI.objects.create(
client=self.client,
hostname=row[HOSTNAME],
ip=row[IP],
description=row[DESCRIPTION],
deployed=bool(row[DEPLOYED]),
business_impact=self._get_business_impact(row[BUSINESS_IMPACT]),
place=self._get_place(row[PLACE], row[PLACE_DESCRIPTION]),
contract=self._get_contract(row),
username=row[CREDENTIAL_USERNAME],
password=row[CREDENTIAL_PASSWORD],
enable_password=row[CREDENTIAL_ENABLE_PASSWORD],
instructions=row[CREDENTIAL_INSTRUCTIONS],
)
def _get_ci_appliances(self, hostname: str) -> Set[Appliance]:
appliances = set()
appliances_sheet = self._workbook[APPLIANCES_SHEET]
for appl_row in appliances_sheet.iter_rows(min_row=2, values_only=True):
if appl_row[APPLIANCE_HOSTNAME] == hostname:
appliances.add(self._get_appliance(appl_row))
return appliances
def _get_place(self, name: str, description: str) -> Place:
if name in self.places:
return self.places[name]
else:
self.places[name] = Place.objects.get_or_create(
name=name,
description=description,
client=self.client
)[0]
return self.places[name]
def _get_contract(self, row: tuple) -> Contract:
contract_name = row[CONTRACT]
if contract_name in self.contracts:
return self.contracts[contract_name]
else:
self.contracts[contract_name] = Contract.objects.get_or_create(
description=row[CONTRACT_DESCRIPTION],
name=contract_name,
begin=row[CONTRACT_BEGIN],
end=row[CONTRACT_END],
)[0]
return self.contracts[contract_name]
def _get_appliance(self, row) -> Appliance:
appliance = Appliance.objects.get_or_create(
client=self.client,
serial_number=row[APPLIANCE_SERIAL_NUMBER],
manufacturer=self._get_manufacturer(row[APPLIANCE_MANUFACTURER]),
model=row[APPLIANCE_MODEL],
virtual=bool(str(row[APPLIANCE_VIRTUAL]).strip())
)[0]
return appliance
def _get_manufacturer(self, name: str) -> Manufacturer:
if name in self.manufacturers:
return self.manufacturers[name]
else:
self.manufacturers[name] = Manufacturer.objects.get_or_create(
name=name,
)[0]
return self.manufacturers[name]
@staticmethod
def _get_business_impact(business_impact: str) -> int:
model_choices = dict(CI.IMPACT_OPTIONS).items()
options = {value: key for key, value in model_choices}
return options.get(business_impact.lower())
|
{"/cis/tests/tests_views.py": ["/cis/models.py", "/accounts/models.py"], "/cis/forms.py": ["/cis/models.py"], "/cis/tests/tests_functionals.py": ["/accounts/models.py", "/cis/models.py", "/cis/urls.py"], "/accounts/tests.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_models.py": ["/accounts/models.py", "/cis/models.py"], "/cis/tests/tests_loader.py": ["/accounts/models.py", "/cis/models.py", "/cis/loader.py", "/cis/cis_mapping.py"], "/cis/admin.py": ["/cis/models.py"], "/cis/models.py": ["/accounts/models.py"], "/cis/views.py": ["/cis/models.py", "/cis/forms.py", "/cis/loader.py", "/cis/mixins.py"], "/accounts/admin.py": ["/accounts/models.py"], "/cis/loader.py": ["/cis/models.py", "/cis/cis_mapping.py"]}
|
20,078
|
brunocvs7/reputation_score
|
refs/heads/master
|
/src/data_acquisition.py
|
# Libs
import twint
# Functions
def get_tweets(query, since, until):
"""Function to get tweets using a query (string with terms) and
two dates, specifying a range to search .
Parameters:
query (string): query with terms to be used in the search.
since (string): string with the initial date.
until (string): string with the last date.
Returns:
tweet_df (dataframe): A pandas dataframe containing all information about
the tweets found with the query and within the range
of dates passed.
"""
c = twint.Config()
c.Search = query
c.Since = since
c.Until = until
c.Pandas = True
twint.run.Search(c)
tweet_df = twint.storage.panda.Tweets_df
return tweet_df
|
{"/main.py": ["/src/data_acquisition.py"]}
|
20,079
|
brunocvs7/reputation_score
|
refs/heads/master
|
/main.py
|
# Libs
import os
import datetime
import pandas as pd
from src.data_acquisition import get_tweets
# Constants
CURRENT_PATH = os.getcwd()
DATA_OUTPUT_NAME_RAW = ''
DATA_OUTPUT_PATH_RAW = os.path.join(CURRENT_PATH, 'data', 'raw', DATA_OUTPUT_NAME_RAW)
INITIAL_DATE = ''
FINAL_DATE = ''
QUERY = ''
# Data Structures
range_dates = pd.date_range(INITIAL_DATE, FINAL_DATE)
logs_fail = []
# Bring first day of the list
since_first_date = range_dates[0].strftime('%Y-%m-%d')
until_first_date = range_dates[1].strftime('%Y-%m-%d')
try:
df_tweets = get_tweets(query=QUERY,
since=since_first_date, until=until_first_date)
df_tweets.to_csv(DATA_OUTPUT_PATH, index=False)
except:
logs_fail.append(since_first_date)
# Loops from 2nd day til the last
for date in range_dates[1:]:
until = date + datetime.timedelta(days=1)
until = until.strftime('%Y-%m-%d')
since = date.strftime('%Y-%m-%d')
print("-----Start: ", since, "Until: ", until, "-----")
try:
df_tweets = get_tweets(query=QUERY, since=since, until=until)
except:
logs_fail.append(since)
else:
df_tweets.to_csv(DATA_OUTPUT_PATH_RAW, index=False, header=False, mode='a')
|
{"/main.py": ["/src/data_acquisition.py"]}
|
20,090
|
sykuningen/lil_amazons
|
refs/heads/master
|
/src/amazons_logic.py
|
# Tile meanings
BLANK = -1
BURNED = -2
class AmazonsLogic:
def validMove(self, board, piece, to):
# Trying to move to the same tile?
if piece == to:
return False
# Trying to move vertically?
elif piece['x'] == to['x']:
bgn = min(piece['y'], to['y'])
end = max(piece['y'], to['y'])
if (piece['y'] < to['y']):
bgn += 1
end += 1
for t in range(bgn, end):
if board.board[piece['x']][t] != BLANK:
return False
return True
# Trying to move horizontally?
elif piece['y'] == to['y']:
bgn = min(piece['x'], to['x'])
end = max(piece['x'], to['x'])
if (piece['x'] < to['x']):
bgn += 1
end += 1
for t in range(bgn, end):
if board.board[t][piece['y']] != BLANK:
return False
return True
# Trying to move diagonally?
elif abs(piece['x'] - to['x']) == abs(piece['y'] - to['y']):
change_x = 1 if piece['x'] < to['x'] else -1
change_y = 1 if piece['y'] < to['y'] else -1
x = piece['x']
y = piece['y']
while True:
x += change_x
y += change_y
if board.board[x][y] != BLANK:
return False
if x == to['x']:
return True
return False
def getPieces(self, board, player_n):
pieces = []
for x in range(0, board.width):
for y in range(0, board.height):
if board.board[x][y] == player_n:
pieces.append({'x': x, 'y': y})
return pieces
def getValidMoves(self, board, player_n):
pieces = self.getPieces(board, player_n)
valid = []
for x in range(0, board.width):
for y in range(0, board.height):
for p in pieces:
pos = {'x': x, 'y': y}
if pos not in valid and self.validMove(board, p, pos):
valid.append(pos)
return valid
def regions(self, board):
regions = {}
cregion = 0
tiles_uncheck = []
for x in range(0, board.width):
for y in range(0, board.height):
if board.board[x][y] != BURNED:
tiles_uncheck.append({'x': x, 'y': y})
regions[cregion] = {}
regions[cregion]['tiles'] = [tiles_uncheck[0]]
regions[cregion]['owner'] = []
while True:
if not tiles_uncheck:
break
f = []
for t1 in regions[cregion]['tiles']:
for t2 in tiles_uncheck:
if abs(t1['x'] - t2['x']) <= 1 and \
abs(t1['y'] - t2['y']) <= 1:
if t2 not in f:
f.append(t2)
if f:
for t in f:
if t not in regions[cregion]['tiles']:
regions[cregion]['tiles'].append(t)
tiles_uncheck.remove(t)
tile = board.board[t['x']][t['y']]
if tile >= 0:
regions[cregion]['owner'].append(tile)
else:
cregion += 1
regions[cregion] = {}
regions[cregion]['tiles'] = [tiles_uncheck[0]]
regions[cregion]['owner'] = []
for r in regions:
owner = regions[r]['owner']
if len(owner) > 1:
if all(x == owner[0] for x in owner):
regions[r]['owner'] = owner[0]
else:
regions[r]['owner'] = None
else:
regions[r]['owner'] = owner[0]
return regions
def calculateScores(self, region_info):
scores = {}
for r in region_info:
if region_info[r]['owner'] is not None:
o = region_info[r]['owner']
if o in scores:
scores[o] += len(region_info[r]['tiles'])
else:
scores[o] = len(region_info[r]['tiles'])
return scores
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,091
|
sykuningen/lil_amazons
|
refs/heads/master
|
/src/Lobby.py
|
from .Logger import logger
class Lobby:
def __init__(self, lobby_id, owner):
self.id = lobby_id
self.owner = owner
self.users = [] # All users currently in the lobby
self.players = [] # Users that are in the actual players list
self.started = False # Whether the game has started
self.active = True # Whether it should appear in lobby list
# Notify about lobby creation
self.logstr = f'Lobby#{self.id}'
logger.log(self.logstr, f'Lobby created (owner: {owner.username})')
def addUser(self, user):
if user not in self.users:
self.users.append(user)
logger.log(self.logstr, 'User joined: ' + user.username)
def removeUser(self, user, reason):
if user in self.users:
self.users.remove(user)
logger.log(self.logstr, f'User left: {user.username} ({reason})')
def addAsPlayer(self, user):
# Can't change players once the game has started
if self.started:
return
# Ensure that the user is in the lobby
if user in self.users and user not in self.players:
self.players.append(user)
def removeAsPlayer(self, user):
# Can't change players once the game has started
if self.started:
return
# Ensure that the user is in the players list
if user in self.players:
self.players.remove(user)
def shutdown(self, sio, reason):
logger.log(self.logstr, f'Host {reason}. Shutting down lobby')
for p in self.users:
p.lobby = None
sio.emit('leave_lobby', room=p.sid)
def setStarted(self):
self.started = True
def toJSON(self):
return {
'id': self.id,
'owner_sid': self.owner.sid,
'users': [u.sid for u in self.users],
'players': [p.sid for p in self.players],
'user_usernames': [u.username for u in self.users],
'player_usernames': [p.username for p in self.players],
'started': self.started,
'active': self.active
}
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,092
|
sykuningen/lil_amazons
|
refs/heads/master
|
/src/User.py
|
class User:
def __init__(self, sid, ai_player=False):
self.sid = sid
self.logged_in = False
self.username = None
self.lobby = None
# AI
self.ai_player = ai_player
if ai_player:
self.username = 'AI Player'
def setUsername(self, username):
self.username = username
self.logged_in = True
def joinLobby(self, lobby):
self.lobby = lobby
lobby.addUser(self)
def leaveLobby(self, reason):
lobby = self.lobby
self.lobby.removeUser(self, reason)
self.lobby = None
return lobby
def logOff(self):
self.logged_in = False
def toJSON(self):
return {
'sid': self.sid,
'username': self.username}
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,093
|
sykuningen/lil_amazons
|
refs/heads/master
|
/server.py
|
import eventlet
import os
import socketio
from src.Game import Game
from src.Lobby import Lobby
from src.Logger import logger
from src.User import User
# *============================================================= SERVER INIT
static_files = {
'/': 'pages/index.html',
'/css/default.css': 'public/css/default.css',
'/js/ui.js': 'public/js/ui.js',
'/js/client.js': 'public/js/client.js'}
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files=static_files)
port = 8000
if 'PORT' in os.environ.keys():
port = int(os.environ['PORT'])
# Logging
logger.setSIO(sio) # Give the logger object direct access to sockets
# Server runtime data
online_users = 0 # TODO: Use lock when accessing this?
users = {}
cur_lobby_id = 0 # TODO: Use lock when accessing this
lobbies = {}
games = {}
# *============================================================= HELPERS
def updateClientLobbyList():
sio.emit(
'lobby_list',
[lobbies[x].toJSON() for x in lobbies if lobbies[x].active])
# *============================================================= SOCKET.IO
@sio.on('connect')
def connect(sid, env):
# Create a new user object for this connection
users[sid] = User(sid)
# Update global user count
global online_users
online_users += 1
sio.emit('server_stats', {'online_users': online_users})
# Send client their sid and the lobby listing
sio.emit('sid', sid, room=sid)
updateClientLobbyList()
@sio.on('disconnect')
def disconnect(sid):
# Update global user count
global online_users
online_users -= 1
sio.emit('server_stats', {'online_users': online_users})
# Flag the user as being offline
users[sid].logOff()
# Leave the lobby the user was in, if any
if users[sid].lobby:
lobby = users[sid].lobby
# Shut down the lobby if this user owned it and the game hasn't started
if sid == lobby.owner.sid and not lobby.started:
lobby.shutdown(sio, 'disconnected')
del lobbies[lobby.id]
# Update lobby list for all users
updateClientLobbyList()
else:
users[sid].leaveLobby('disconnected')
# Update the lobby for the other users in it
for p in lobby.users:
sio.emit('update_lobby', lobby.toJSON(), room=p.sid)
logger.removeListener(sid)
@sio.on('login')
def login(sid, data):
# If the user was connected previously, re-use their old User object.
# This allows the player to easily resume games they were in.
for u in users:
# TODO: Use some kind of credentials
if users[u].username == data['username']:
# Ensure that the user is not still logged in
if users[u].logged_in:
return
users[sid] = users[users[u].sid]
users[sid].sid = sid # Change to user's new sid
users[sid].setUsername(data['username'])
sio.emit('logged_in', room=sid)
@sio.on('connect_log')
def connectLog(sid):
if not users[sid].logged_in:
return
logger.addListener(sid)
logger.log('server', f'{users[sid].username} connected to logging server')
# ============================================================== Lobby
@sio.on('create_lobby')
def createLobby(sid):
# Ensure that user is logged in
if not users[sid].logged_in:
return
# Allow users to create or be in only one lobby at a time
if users[sid].lobby:
return
# Create a new lobby
global cur_lobby_id
lobby = Lobby(cur_lobby_id, users[sid])
cur_lobby_id += 1
lobbies[lobby.id] = lobby
users[sid].joinLobby(lobby)
# Update lobby info for users
sio.emit('update_lobby', lobby.toJSON(), room=sid)
updateClientLobbyList()
@sio.on('join_lobby')
def joinLobby(sid, lobby_id):
# Ensure that user is logged in
if not users[sid].logged_in:
return
# Don't allow users to enter multiple lobbies at once
if users[sid].lobby:
return
lobby_id = int(lobby_id)
# Ensure that the lobby exists
if lobby_id not in lobbies:
return
lobby = lobbies[lobby_id]
users[sid].joinLobby(lobby)
# Update the lobby for the other users in it
for p in lobby.users:
sio.emit('update_lobby', lobby.toJSON(), room=p.sid)
@sio.on('leave_lobby')
def leaveLobby(sid):
# Leave the lobby the user was in, if any
if users[sid].lobby:
lobby = users[sid].lobby
# Shut down the lobby if this user owned it and the game hasn't started
if sid == lobby.owner.sid and not lobby.started:
lobby.shutdown(sio, 'left lobby')
del lobbies[lobby.id]
# Update lobby list for all users
updateClientLobbyList()
else:
lobby = users[sid].leaveLobby('left lobby')
sio.emit('leave_lobby', room=sid)
# Update the lobby for the other users in it
for p in lobby.users:
sio.emit('update_lobby', lobby.toJSON(), room=p.sid)
# Join the player list in a lobby (meaning you will be participating)
@sio.on('join_players')
def joinPlayers(sid):
# Ensure that the user is in a lobby
if not users[sid].lobby:
return
users[sid].lobby.addAsPlayer(users[sid])
# Update the lobby for the other users in it
for p in users[sid].lobby.users:
sio.emit('update_lobby', users[sid].lobby.toJSON(), room=p.sid)
# Update lobby list for all users
sio.emit('lobby_list', [lobbies[x].toJSON() for x in lobbies])
@sio.on('leave_players')
def leavePlayers(sid):
# Ensure that the user is in a lobby
if not users[sid].lobby:
return
users[sid].lobby.removeAsPlayer(users[sid])
# Update the lobby for the other users in it
for p in users[sid].lobby.users:
sio.emit('update_lobby', users[sid].lobby.toJSON(), room=p.sid)
# Update lobby list for all users
updateClientLobbyList()
@sio.on('add_ai_player')
def addAiPlayer(sid):
# Ensure that the user is in a lobby
if not users[sid].lobby:
return
if users[sid].lobby.owner.sid != sid:
return
if users[sid].lobby.started:
return
ai_player = User(None, ai_player=True)
users[sid].lobby.addUser(ai_player)
users[sid].lobby.addAsPlayer(ai_player)
# Update the lobby for the other users in it
for p in users[sid].lobby.users:
sio.emit('update_lobby', users[sid].lobby.toJSON(), room=p.sid)
# Update lobby list for all users
updateClientLobbyList()
# ============================================================== Game
@sio.on('start_game')
def startGame(sid, game_config):
# Ensure that the user has permission to start the game
if not users[sid].lobby:
return
if users[sid].lobby.owner.sid != sid:
return
if users[sid].lobby.started:
return
# Create a new game
game = Game(sio, users[sid].lobby, game_config)
games[users[sid].lobby.id] = game
# Update the lobby for the other users in it
for p in game.lobby.users:
sio.emit('update_lobby', game.lobby.toJSON(), room=p.sid)
# Update lobby list for all users
updateClientLobbyList()
@sio.on('watch_game')
def watchGame(sid):
# Ensure that the user is in a lobby
if not users[sid].lobby:
return
lobby_id = users[sid].lobby.id
if lobby_id in games:
games[lobby_id].emitBoard(sid)
@sio.on('attempt_move')
def attemptMove(sid, piece, to):
# Ensure that the user is in a lobby
if not users[sid].lobby:
return
# Ensure that the game has started
if not users[sid].lobby.started:
return
lobby_id = users[sid].lobby.id
if lobby_id in games:
games[lobby_id].attemptMove(users[sid], piece, to)
# TODO: Update lobby list for all users when a game ends
# *============================================================= MAIN
def main():
eventlet.wsgi.server(eventlet.listen(('', port)), app)
# *============================================================= ENTRYPOINT
if __name__ == '__main__':
main()
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,094
|
sykuningen/lil_amazons
|
refs/heads/master
|
/src/Logger.py
|
class Logger:
def __init__(self):
self.listeners = []
self.messages = []
def setSIO(self, sio):
self.sio = sio
def addListener(self, sid):
if sid not in self.listeners:
self.listeners.append(sid)
def removeListener(self, sid):
if sid in self.listeners:
self.listeners.remove(sid)
def log(self, sender, message):
new_msg = {
'sender': sender,
'message': message
}
self.messages.append(new_msg)
for l in self.listeners:
self.sio.emit('log_message', new_msg, room=l)
logger = Logger()
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,095
|
sykuningen/lil_amazons
|
refs/heads/master
|
/src/Game.py
|
import json
from .Logger import logger
from .amazons_logic import AmazonsLogic
# Tile meanings
BLANK = -1
BURNED = -2
class Board:
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[BLANK for y in range(height)] for x in range(width)]
def placePiece(self, player_n, pos):
try:
x, y = pos
self.board[x][y] = player_n
except IndexError:
pass # TODO: Dispatch an error
def toJSON(self):
return {
'width': self.width,
'height': self.height,
'board': self.board
}
class Game:
def __init__(self, sio, lobby, config):
self.sio = sio
self.lobby = lobby
self.id = lobby.id # Game IDs match their associated lobby ID
# Initialize the game board
self.board = Board(10, 10)
self.current_player = 0
self.lmp = None # Last moved piece
self.burning = False # Does current player have to burn a tile now?
# Initialize game pieces
self.config = json.loads(config.replace('\'', '"'))
for p in self.config['pieces']:
self.board.placePiece(p['owner'], (p['x'], p['y']))
# Game analysis stuff
self.regions = None
self.scores = None
self.ended = False
self.winner = None
# Finalize setup
self.lobby.setStarted()
self.emitBoard()
# Notify about game start
self.logstr = f'Game#{str(self.id)}'
player_list = str([p.username for p in lobby.players])
logger.log(self.logstr, f'Game started (players: {player_list})')
def attemptMove(self, player, piece, to):
if self.ended:
return
if self.burning:
self.attemptBurn(player, to)
return
try:
if player not in self.lobby.players:
return # This user isn't in this game
player_n = self.lobby.players.index(player)
piece_tile = self.board.board[piece['x']][piece['y']]
if self.current_player != player_n:
return # It isn't this player's turn
if piece['x'] < 0 or piece['y'] < 0:
return # Prevent weird list indexing
if piece_tile != player_n:
return # No piece here, or piece belongs to another player
if not AmazonsLogic().validMove(self.board, piece, to):
return # This isn't a valid move
# Move the piece
self.board.board[to['x']][to['y']] = piece_tile
self.board.board[piece['x']][piece['y']] = BLANK
self.lmp = {'x': to['x'], 'y': to['y']}
self.burning = True # Player must now burn a tile
self.emitBoard()
self.sio.emit('select_piece', self.lmp, player.sid)
except IndexError:
pass # TODO: Dispatch an error
def attemptBurn(self, player, to):
try:
player_n = self.lobby.players.index(player)
if player not in self.lobby.players:
return # This user isn't in this game
if self.current_player != player_n:
return # It isn't this player's turn
if not AmazonsLogic().validMove(self.board, self.lmp, to):
return # This isn't a valid burn
self.board.board[to['x']][to['y']] = BURNED
# Next player's turn
self.burning = False
self.current_player += 1
if self.current_player == len(self.lobby.players):
self.current_player = 0
self.analyzeGameState()
self.emitBoard()
self.sio.emit('select_piece', {'x': -1, 'y': -1}, player.sid)
except IndexError:
pass # TODO: Dispatch an error
def analyzeGameState(self):
self.regions = AmazonsLogic().regions(self.board)
self.scores = AmazonsLogic().calculateScores(self.regions)
total_tiles = 0
for r in self.regions:
total_tiles += len(self.regions[r]['tiles'])
total_score = 0
for s in self.scores:
total_score += self.scores[s]
if total_score == total_tiles:
self.ended = True
self.winner = max(self.scores, key=self.scores.get)
self.lobby.active = False
def toJSON(self):
return {
'id': self.id,
'lobby': self.lobby.toJSON(),
'board': self.board.toJSON(),
'current_player': self.current_player,
'lmp': self.lmp,
'burning': self.burning,
'regions': self.regions,
'scores': self.scores,
'ended': self.ended,
'winner': self.winner
}
def emitBoard(self, to=None):
if to:
self.sio.emit('game_data', self.toJSON(), room=to)
else:
for p in self.lobby.users:
self.sio.emit('game_data', self.toJSON(), room=p.sid)
|
{"/src/Lobby.py": ["/src/Logger.py"], "/server.py": ["/src/Game.py", "/src/Lobby.py", "/src/Logger.py", "/src/User.py"], "/src/Game.py": ["/src/Logger.py", "/src/amazons_logic.py"]}
|
20,103
|
huhailang9012/audio-extractor
|
refs/heads/main
|
/extractor.py
|
import os
import os.path
from database.repository import select_by_md5, storage
import hashlib
audio_dir = "/data/files/audios/"
def extract(video_id: str, local_video_path: str):
audio_name, audio_extension, local_audio_path = convert_one(local_video_path)
with open(local_audio_path, 'rb') as fp:
data = fp.read()
file_md5 = hashlib.md5(data).hexdigest()
audio = select_by_md5(file_md5)
if audio is None:
audio_id = storage(local_audio_path, audio_name, audio_extension, video_id)
return audio_id, local_audio_path
else:
return audio['id'], audio['local_audio_path']
def convert_one(video) :
""":param video
ffmpeg -i 3.mp4 -vn -y -acodec copy 3.aac
ffmpeg -i 2018.mp4 -codec copy -bsf: h264_mp4toannexb -f h264 tmp.264
ffmpeg -i killer.mp4 -an -vcodec copy out.h264
"""
print('*' * 15 + 'Start to run:')
ffmpeg_cmd = 'ffmpeg -i {} -vn -y -acodec copy {}'
video_name = os.path.basename(video)
audio_prefix = video_name.split('.')[0]
audio_extension = 'aac'
audio_name = audio_prefix + '.' + audio_extension
audio_path = os.path.join(audio_dir, audio_name)
cmd = ffmpeg_cmd.format(video, audio_path)
os.system(cmd)
return audio_name, audio_extension, audio_path
def convert_many(videos):
""":param videos: 所有视频的路径列表
ffmpeg -i 3.mp4 -vn -y -acodec copy 3.aac
ffmpeg -i 2018.mp4 -codec copy -bsf: h264_mp4toannexb -f h264 tmp.264
ffmpeg -i killer.mp4 -an -vcodec copy out.h264
"""
print('*' * 15 + 'Start to run:')
# 分离音频的执行命令,{}{}分别为原始视频与输出后保存的路径名
ffmpeg_cmd = 'ffmpeg -i {} -vn -y -acodec copy {}'
for path in videos:
video_name = os.path.basename(path)
audio_prefix = video_name.split('.')[0]
audio_extension = '.aac'
audio_name = audio_prefix + audio_extension
audio_path = os.path.join(audio_dir, audio_name)
# 最终执行提取音频的指令
cmd = ffmpeg_cmd.format(path, audio_path)
os.system(cmd)
print('End #################')
if __name__ == '__main__':
print(extract('8b14b14b2599a5ddf04a4cfecbf850dc', 'E:/docker_data/files/videos/7b14b14b2599a5ddf04a4cfecbf850dc.mp4'))
|
{"/extractor.py": ["/database/repository.py"], "/database/repository.py": ["/audio.py"], "/controller.py": ["/extractor.py", "/database/repository.py"]}
|
20,104
|
huhailang9012/audio-extractor
|
refs/heads/main
|
/audio.py
|
class Audio(object):
def __init__(self, id: str, name: str, md5: str, video_id: str, local_audio_path: str,
format: str, date_created: str):
self.id = id
self.name = name
self.md5 = md5
self.video_id = video_id
self.local_audio_path = local_audio_path
self.format = format
self.date_created = date_created
|
{"/extractor.py": ["/database/repository.py"], "/database/repository.py": ["/audio.py"], "/controller.py": ["/extractor.py", "/database/repository.py"]}
|
20,105
|
huhailang9012/audio-extractor
|
refs/heads/main
|
/database/repository.py
|
import json
from datetime import datetime
import uuid
import hashlib
from typing import Dict
from audio import Audio
from database.database_pool import PostgreSql
def insert(id: str, name: str, format: str, md5: str, local_audio_path: str,
video_id: str, date_created: str):
"""
insert into videos
:return:
"""
sql = """INSERT INTO audios (id, name, format, md5, local_audio_path, video_id, date_created)
VALUES
(%(id)s, %(name)s, %(format)s, %(md5)s, %(local_audio_path)s, %(video_id)s, %(date_created)s)"""
params = {'id': id, 'name': name, 'format': format, 'md5': md5, 'local_audio_path': local_audio_path,
'video_id': video_id, 'date_created': date_created}
db = PostgreSql()
db.execute(sql, params)
def select_by_md5(md5: str) -> Dict[str, any]:
"""
SELECT * FROM audios where md5 = %s;
:return: audio
"""
# sql语句 建表
sql = """SELECT * FROM audios where md5 = %s;"""
params = (md5,)
db = PostgreSql()
audio = db.select_one(sql, params)
return audio
def select_by_ids(audio_ids: list):
"""
select count(*) from audios
:return: record size
"""
tupVar = tuple(audio_ids)
# sql语句 建表
sql = """SELECT * FROM audios where id in %s;"""
db = PostgreSql()
results = db.select_by_ids(sql, (tupVar,))
audios = list()
for result in results:
audio_id = result['id']
audio_name = result['name']
audio_md5 = result['md5']
video_id = result['video_id']
local_audio_path = result['local_audio_path']
format = result['format']
date_created = result['date_created']
audio = Audio(audio_id,audio_name,audio_md5,video_id,local_audio_path,format,date_created)
audios.append(audio)
return audios
def storage(local_audio_path: str, name: str, format: str, video_id: str):
"""
storage videos
:return:
"""
id = uuid.uuid1().hex
with open(local_audio_path, 'rb') as fp:
data = fp.read()
file_md5 = hashlib.md5(data).hexdigest()
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
insert(id, name, format, file_md5, local_audio_path, video_id,
now)
return id
if __name__ == '__main__':
audios = list()
audios.append('12780ecc293511eb8bae005056c00008')
audios.append('7b0de605293511ebb5f5005056c00008')
data = select_by_ids(audios)
# print(data)
result = json.dumps(data, default=lambda obj: obj.__dict__, sort_keys=False, indent=4)
print(result)
|
{"/extractor.py": ["/database/repository.py"], "/database/repository.py": ["/audio.py"], "/controller.py": ["/extractor.py", "/database/repository.py"]}
|
20,106
|
huhailang9012/audio-extractor
|
refs/heads/main
|
/controller.py
|
from fastapi import FastAPI, Query
import extractor as ex
from database.repository import select_by_ids
from typing import List
import json
app = FastAPI()
@app.get("/audio/extract")
def audio_extract(video_id: str, local_video_path: str):
print('audio_extract')
audio_id, local_audio_path = ex.extract(video_id, local_video_path)
data = {'audio_id': audio_id, 'local_audio_path': local_audio_path}
return {"success": True, "code": 0, "msg": "ok", "data": data}
@app.get("/audio/batch/query")
def batch_query(audio_ids: List[str] = Query(None)):
data = select_by_ids(audio_ids)
result = json.dumps(data, default=lambda obj: obj.__dict__, sort_keys=False, indent=4)
return {"success": True, "code": 0, "msg": "ok", "data": result}
|
{"/extractor.py": ["/database/repository.py"], "/database/repository.py": ["/audio.py"], "/controller.py": ["/extractor.py", "/database/repository.py"]}
|
20,108
|
pawissanutt/MutatedSnake
|
refs/heads/master
|
/MutatedSnake.py
|
import arcade
from Models import World, Snake
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 600
class ModelSprite(arcade.Sprite):
def __init__(self, *args, **kwargs):
self.model = kwargs.pop('model', None)
super().__init__(*args, **kwargs)
def sync_with_model(self):
if self.model:
self.set_position(self.model.x, self.model.y)
self.angle = self.model.angle
def draw(self):
self.sync_with_model()
super().draw()
class WorldRenderer:
def __init__(self, world, width, height) :
self.world = world
self.width = width
self.height = height
self.snake_head_sprite = ModelSprite('Images/head.png', model=self.world.snake.head)
self.snake_body_sprite = [ModelSprite('Images/body.png', model=self.world.snake.body[0])]
self.snake_tail_sprite = ModelSprite('Images/tail.png', model=self.world.snake.tail)
self.red_boxes_sprite = []
self.green_box_sprite = ModelSprite('Images/box2.png', model=self.world.green_box)
def set_sprite_body(self):
while (len(self.snake_body_sprite) < len(self.world.snake.body)):
self.snake_body_sprite.append(ModelSprite('Images/body.png'
,model=self.world.snake.body[len(self.snake_body_sprite)]))
while (len(self.snake_body_sprite) > len(self.world.snake.body)):
del self.snake_body_sprite[-1]
def set_sprite_boxes(self):
while (len(self.red_boxes_sprite) > len(self.world.red_boxes)):
self.red_boxes_sprite = []
while (len(self.red_boxes_sprite) < len(self.world.red_boxes)):
self.red_boxes_sprite.append(ModelSprite('Images/box1.png',
model=self.world.red_boxes[len(self.red_boxes_sprite)]))
def draw(self):
self.snake_head_sprite.draw()
for body in self.snake_body_sprite:
body.draw()
self.snake_tail_sprite.draw()
for box in self.red_boxes_sprite:
box.draw()
self.green_box_sprite.draw()
arcade.draw_text(str(self.world.score),
self.width - 80, self.height - 30,
arcade.color.WHITE, 20)
if (self.world.god_mode):
arcade.draw_text("God Mode Activated!!!",
self.width/2 - 120, self.height - 50,
arcade.color.WHITE, 20)
if (self.world.gameover):
arcade.draw_text("Game Over",
self.width/2 - 120, self.height - 100,
arcade.color.WHITE, 40)
arcade.draw_text("Press any key to restart",
self.width/2 - 200, self.height - 200,
arcade.color.WHITE, 30)
def animate(self, delta):
self.set_sprite_body()
self.set_sprite_boxes()
class GameWindow(arcade.Window):
def __init__(self, width, height):
super().__init__(width, height)
arcade.set_background_color(arcade.color.BLACK)
self.world = World(width, height)
self.world_renderer = WorldRenderer(self.world, width, height)
def on_draw(self):
arcade.start_render()
self.world_renderer.draw()
def animate(self, delta):
self.world.animate(delta)
self.world_renderer.animate(delta)
def on_key_press(self, key, key_modifiers):
self.world.on_key_press(key, key_modifiers)
if (self.world.gameover):
self.world = World(SCREEN_WIDTH, SCREEN_HEIGHT)
self.world_renderer = WorldRenderer(self.world, SCREEN_WIDTH, SCREEN_HEIGHT)
if __name__ == '__main__':
window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run()
|
{"/MutatedSnake.py": ["/Models.py"]}
|
20,109
|
pawissanutt/MutatedSnake
|
refs/heads/master
|
/Models.py
|
import math
import arcade.key
import time
import random
class Model:
def __init__(self, world, x, y, angle):
self.world = world
self.x = x
self.y = y
self.angle = angle
self.lastx = [x,x,x,x,x]
self.lasty = [y,y,y,y,y]
self.last_angle = [angle,angle,angle,angle,angle]
def set_last_position(self):
count = 2
while (count > 0) :
self.lastx[count] = self.lastx[count-1]
self.lasty[count] = self.lasty[count-1]
self.last_angle[count] = self.last_angle[count-1]
count -= 1
self.lastx[0] = self.x
self.lasty[0] = self.y
self.last_angle[0] = self.angle
def get_nextx(self, speed):
return self.x - speed * math.sin(math.radians(self.angle))
def get_nexty(self, speed):
return self.y + speed * math.cos(math.radians(self.angle))
def set_position(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
def hit(self, other, hit_size):
return (abs(self.x - other.x) <= hit_size) and (abs(self.y - other.y) <= hit_size)
def is_at(self, x, y, size):
return (abs(self.x - x) <= size) and (abs(self.y - y) <= size)
class Snake:
def __init__(self, world, x, y, angle):
self.world = world
self.x = x
self.y = y
self.speed = 4
self.head = HeadSnake(self.world, x, y, angle, self.speed)
self.head.speed = self.speed
self.body = [BodySnake(self.world, x, y - 30 , angle)]
self.tail = TailSnake(self.world, x, y - 80, angle)
def changeAngle(self, angle) :
if (self.head.angle == self.head.next_angle ):
if (math.fabs(self.head.angle - angle) != 180):
self.head.next_angle = angle
def add_body(self):
self.body.append(BodySnake(self.world,
self.body[-1].lastx[5 - self.speed],
self.body[-1].lasty[5 - self.speed],
self.body[-1].last_angle[5 - self.speed]))
self.tail.set_position(self.body[-1].lastx[5 - self.speed],
self.body[-1].lasty[5 - self.speed],
self.body[-1].last_angle[5 - self.speed])
def remove_body(self):
if (self.body.__len__() > 1):
del self.body[-1]
def is_eat_itself(self):
x = self.head.get_nextx(10)
y = self.head.get_nexty(10)
return self.has_body_at(x, y)
def has_body_at(self, x, y):
for body in self.body:
if (body.is_at(x, y, 10)):
return True
return False
def has_snake_at(self, x, y):
if (has_body_at(x, y)):
return True
if (self.head.is_at(x, y, 30)):
return True
if (self.tail.is_at(x, y, 30)):
return True
return False
def animate(self, delta):
self.head.animate(delta)
for body in self.body:
body.animate(delta)
count = self.body.__len__() - 1
self.tail.set_position(self.body[count].lastx[6 - self.speed],
self.body[count].lasty[6 - self.speed],
self.body[count].last_angle[6 - self.speed])
while (count > 0):
self.body[count].set_position(self.body[count-1].lastx[6 - self.speed],
self.body[count-1].lasty[6 - self.speed],
self.body[count-1].last_angle[6 - self.speed])
count -= 1
self.body[0].set_position(self.head.lastx[6 - self.speed],
self.head.lasty[6 - self.speed],
self.head.last_angle[6 - self.speed])
class HeadSnake(Model):
def __init__(self, world, x, y, angle, speed):
super().__init__(world, x, y, angle)
self.next_angle = angle
self.speed = speed
def slow_rotate(self, delta):
self.angle %= 360
if (math.fabs(self.next_angle - self.angle) > 90):
if (self.next_angle < self.angle):
self.next_angle %= 360
self.next_angle += 360
else :
self.angle %= 360
self.angle += 360
if (self.next_angle - self.angle > 0):
self.angle += int(200 * delta) * 5
if (self.next_angle - self.angle < 0):
self.angle = self.next_angle
elif (self.next_angle - self.angle < 0):
self.angle -= int(200 * delta) * 5
if (self.next_angle - self.angle > 0):
self.angle = self.next_angle
def animate(self, delta):
self.slow_rotate(delta)
self.set_last_position()
self.x -= self.speed * 50 * delta * math.sin(math.radians(self.angle))
self.y += self.speed * 50 * delta * math.cos(math.radians(self.angle))
if (self.x > self.world.width):
self.x = 0
elif (self.x < 0):
self.x = self.world.width
if (self.y > self.world.height):
self.y = 0
elif (self.y < 0):
self.y = self.world.height
class BodySnake(Model):
def __init__(self, world, x, y, angle):
super().__init__(world, x, y, angle)
def animate(self, delta):
self.set_last_position()
class TailSnake(Model):
def __init__(self, world, x, y, angle):
super().__init__(world, x, y, angle)
class Box(Model):
def __init__(self, world, x, y):
super().__init__(world, x, y, 0)
class World:
def __init__(self, width, height):
self.width = width
self.height = height
self.score = 0
self.start_time = time.time()
self.gameover = False
self.god_mode = False
self.snake = Snake(self, 100, 100, 0)
self.number_body = 1
self.red_boxes = []
self.green_box = Box(self, 300, 300)
def animate(self, delta):
if (self.gameover == False) :
self.snake.animate(delta)
self.current_time = time.time()- self.start_time;
self.score = int(self.current_time)
self.increase_length()
self.should_create_boxes()
self.if_hit_green_box()
if (self.snake.is_eat_itself()):
self.gameover = True
if (self.is_hit_red_box()):
if (self.god_mode):
del self.red_boxes[self.get_hit_red_box()]
else :
self.gameover = True
def should_create_boxes(self):
if (len(self.red_boxes) * 5 < self.score):
self.random_create_red_box()
def is_hit_red_box(self):
x = self.snake.head.get_nextx(10)
y = self.snake.head.get_nexty(10)
return self.has_red_box_at(x, y)
def get_hit_red_box(self):
x = self.snake.head.get_nextx(10)
y = self.snake.head.get_nexty(10)
return self.get_red_box_at(x, y)
def has_red_box_at(self, x, y):
for box in self.red_boxes:
if (box.is_at(x, y, 15)):
return True
return False
def get_red_box_at(self, x, y):
count = 0
while (count < len(self.red_boxes)):
if (self.red_boxes[count].is_at(x, y, 15)):
return count
count += 1
return -1
def is_hit_green_box(self):
x = self.snake.head.get_nextx(10)
y = self.snake.head.get_nexty(10)
return self.has_green_box_at(x, y)
def has_green_box_at(self, x, y):
return self.green_box.is_at(x, y, 10)
def random_create_red_box(self):
x = random.randint(15, self.width - 15)
y = random.randint(50, self.height - 15)
while (self.snake.has_body_at(x,y)
or self.has_red_box_at(x, y)
or self.has_green_box_at(x, y)) :
x = random.randint(15, self.width - 15)
y = random.randint(50, self.height - 15)
self.red_boxes.append(Box(self, x , y))
def if_hit_green_box(self):
if (self.is_hit_green_box()):
x = random.randint(15, self.width - 15)
y = random.randint(50, self.height - 15)
while (self.snake.has_body_at(x,y)
or self.has_red_box_at(x, y)
or self.has_green_box_at(x, y)) :
x = random.randint(15, self.width - 15)
y = random.randint(50, self.height - 15)
self.green_box.x = x
self.green_box.y = y
self.random_decrease_length(10)
def increase_length(self):
if (self.number_body / 2 < self.current_time):
self.snake.add_body()
self.number_body += 1
def random_decrease_length(self, max_number):
num = random.randint(1, max_number)
while (num > 0):
self.snake.remove_body()
num -=1
def toggle_god_mode(self):
self.god_mode = not self.god_mode
def on_key_press(self, key, key_modifiers):
if key == arcade.key.LEFT:
self.snake.changeAngle(90)
if key == arcade.key.RIGHT:
self.snake.changeAngle(270)
if key == arcade.key.UP:
self.snake.changeAngle(0)
if key == arcade.key.DOWN:
self.snake.changeAngle(180)
if key == arcade.key.G:
self.toggle_god_mode()
|
{"/MutatedSnake.py": ["/Models.py"]}
|
20,111
|
RobertNFisher/KNN
|
refs/heads/master
|
/KNN2.py
|
"""
K-NN Model
"""
import math
k = 9
"""
Finds the Edistance by taking square root of the summation of the square differences of given features x
compared to given features yacross n iterations
"""
def eDistance(x, y, n):
ED = 0
for index in range(n):
ED += math.pow(float(x[index]) - float(y[index]), 2)
ED = math.sqrt(ED)
return ED
"""
Tally results from given votes and returns an array of arrays such that
[[n,v]sub1, ... [n,v]subi] where n = number of votes, v = the votes value and
i = the number of different vote values
"""
def tally(votes):
scores = []
for vote in votes:
for score in scores:
if vote[1][-1] == score[1]:
score[0] += 1
elif score == scores[-1]:
scores.append([1, vote[1][-1]])
break
if scores == []:
scores.append([1, vote[1][-1]])
return scores
"""
Main method of KNN that iterates through test samples comparing the euclidean distance from test feature to
train feature. Then taking the K closest Neighbors, tallys the 'votes' of each neighbor to predict the value
for the test data
"""
def evaluate (trainData, testData):
for test in testData:
KNN = []
for train in trainData:
ED = eDistance(test,train,len(test))
if len(KNN) < k:
KNN.append([ED, train])
else:
for index in range(len(KNN)):
if ED < KNN[index][0]:
KNN[index] = [ED, train]
KNN.sort(reverse=True)
KNN = tally(KNN)
KNN.sort(reverse=True)
test.append(KNN[-1][-1])
return testData
|
{"/Test.py": ["/PreProcessor.py", "/KNN2.py"]}
|
20,112
|
RobertNFisher/KNN
|
refs/heads/master
|
/Test.py
|
"""
Name: Robert Fisher
Date: 9/16/2019
Class: Machine Learning
Prof.: C. Hung
"""
"""
Main Class
"""
import PreProcessor as pP
import KNN2
featureRemovalIndex = -1
irisData = pP.preProcessor("iris.data")
studentData = pP.preProcessor("student-mat.csv")
data = irisData.getData()
data = studentData.getData()
train_data = data[0]
test_data = data[1]
sample_data =[[]]
# Remove a given feature to adjust accuracy
if featureRemovalIndex >= 0:
for i in range (0, len(test_data)):
test_data[i].pop(featureRemovalIndex)
for i in range (0, len(train_data)):
train_data[i].pop(featureRemovalIndex)
# Collect sample_data to check for accuracy
for set in range(0,len(test_data)):
for data in range(0, len(test_data[set])):
value = test_data[set][data]
sample_data[set].append(value)
sample_data.append([])
# Removes label from test_data
for i in range(0,len(test_data)-1):
if(len(test_data[i]) == 0):
test_data.pop(i)
try:
test_data[i].pop(len(test_data[i])-1)
except:
print("ERROR removing label")
# For simple visualization of the data given
print("Sample Test Data: {}".format(test_data[0]))
print("Sample Train Data: {}".format(train_data[0]))
results = KNN2.evaluate(train_data, test_data)
print("Sample comparison: {} ?= {}".format(train_data[0][-1], sample_data[0][-1]))
# Calculates loss by counting the correct guesses to the actual values
correct = 0
for i in range(len(results)):
given = results[i]
actual = sample_data[i]
if results[i] == sample_data[i]:
correct += 1
accuracy = (correct/len(results))*100
print("Accuracy:{}".format(accuracy))
|
{"/Test.py": ["/PreProcessor.py", "/KNN2.py"]}
|
20,113
|
RobertNFisher/KNN
|
refs/heads/master
|
/PreProcessor.py
|
"""
Pre-Processor
"""
import csv
import random as rndm
class preProcessor:
def __init__(self, filename):
data = []
self.test_data = []
self.train_data = []
# Opens CSV file and seperates rows
with open(filename) as iData:
file = csv.reader(iData, delimiter= ',')
# Randomly assigns data to test and train data groups
for row in file:
data.append(row)
if filename == "iris.data":
self.irisLabel(data)
elif filename == "student-mat.csv":
data = self.studentLabel(data)
rndm.shuffle(data)
for i in range(0, len(data)):
if i%4 == 0:
self.test_data.append(data[i])
else:
self.train_data.append(data[i])
self.cleanData(self.test_data)
self.cleanData(self.train_data)
# Call method for data
def getData(self):
return [self.test_data, self.train_data]
# Remove empty data
def cleanData(self, array):
for i in range(0, len(array)-1):
if len(array[i]) == 0:
array.pop(i)
# Organize data from iris set
def irisLabel(self, data):
for i in range(0, len(data)-1):
if data[i][4] == "Iris-setosa":
data[i][4] = 0
elif data[i][4] == "Iris-versicolor":
data[i][4] = 1
elif data[i][4] == "Iris-virginica":
data[i][4] = 2
def studentLabel(self, data):
keep = [4, 12, 13, 15, 24, 27, 29]
target = 14
newArray = []
for i in range(len(data)-1):
newArray.append([])
# Keep chosen features
for instance in range(0, len(data)-1):
for i in range(0, len(data[instance])-1):
for index in keep:
# Handle String Value
if i == 4 and index == i:
if data[instance][i] == "GT3":
newArray[instance].append(1)
elif data[instance][i] == "LE3":
newArray[instance].append(0)
# Handle String Value
elif i == 15 and index == i:
if data[instance][i] == "yes":
newArray[instance].append(1)
elif data[instance][i] == "no":
newArray[instance].append(0)
# Append info
elif i == index:
newArray[instance].append(data[instance][i])
if data[instance][target] == '0' or data[instance][target] == "failures":
newArray[instance].append(data[instance][target])
elif float(data[instance][target]) > 0:
newArray[instance].append(1)
# Remove the labels
print(newArray[0])
newArray.pop(0)
return newArray
|
{"/Test.py": ["/PreProcessor.py", "/KNN2.py"]}
|
20,137
|
zhucer2003/DAPPER
|
refs/heads/master
|
/mods/LorenzXY/defaults.py
|
# Inspired by berry2014linear, mitchell2014 and Hanna Arnold's thesis.
from common import *
from mods.LorenzXY.core import nX,m,dxdt,dfdx,plot_state
# Wilks2005 uses dt=1e-4 with RK4 for the full model,
# and dt=5e-3 with RK2 for the forecast/truncated model.
# Typically dt0bs = 0.01 and dt = dtObs/10 for truth.
# But for EnKF berry2014linear use dt = dtObs coz
# "numerical stiffness disappears when fast processes are removed".
#t = Chronology(dt=0.001,dtObs=0.05,T=4**3,BurnIn=6) # allows using rk2
t = Chronology(dt=0.005,dtObs=0.05,T=4**3,BurnIn=6) # requires rk4
f = {
'm' : m,
'model': with_rk4(dxdt,autonom=True,order=4),
'noise': 0,
'jacob': dfdx,
'plot' : plot_state
}
X0 = GaussRV(C=0.01*eye(m))
h = partial_direct_obs_setup(m,arange(nX))
h['noise'] = 0.1
other = {'name': os.path.relpath(__file__,'mods/')}
setup = TwinSetup(f,h,t,X0,**other)
####################
# Suggested tuning
####################
# # Expected RMSE_a:
#cfgs += Climatology() # 0.93
#cfgs += Var3D() # 0.38
#cfgs += EnKF_N(N=20) # 0.27
|
{"/mods/LorenzXY/defaults.py": ["/mods/LorenzXY/core.py"], "/mods/LorenzXY/truncated.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"], "/mods/LorenzXY/illust_parameterizations.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"]}
|
20,138
|
zhucer2003/DAPPER
|
refs/heads/master
|
/mods/LorenzXY/truncated.py
|
# Use truncated models and larger dt.
from common import *
from mods.LorenzXY.core import nX,dxdt_detp
from mods.LorenzXY.defaults import t
t = t.copy()
t.dt = 0.05
f = {
'm' : nX,
'model': with_rk4(dxdt_detp,autonom=True),
'noise': 0,
}
X0 = GaussRV(C=0.01*eye(nX))
h = partial_direct_obs_setup(nX,arange(nX))
h['noise'] = 0.1
other = {'name': os.path.relpath(__file__,'mods/')}
setup = TwinSetup(f,h,t,X0,**other)
|
{"/mods/LorenzXY/defaults.py": ["/mods/LorenzXY/core.py"], "/mods/LorenzXY/truncated.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"], "/mods/LorenzXY/illust_parameterizations.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"]}
|
20,139
|
zhucer2003/DAPPER
|
refs/heads/master
|
/mods/LorenzXY/core.py
|
####################################
# Lorenz95 two-scale/layer version
####################################
# See Wilks 2005 "Effects of stochastic parametrizations in the Lorenz '96 system"
# X: large amp, low frequency vars: convective events
# Y: small amp, high frequency vars: large-scale synoptic events
#
# Typically, the DA system will only use the truncated system
# (containing only the X variables),
# where the Y's are parameterized as model noise,
# while the truth is simulated by the full system.
#
# Stochastic parmateterization (Todo):
# Wilks: benefit of including stochastic noise negligible
# unless its temporal auto-corr is taken into account (as AR(1))
# (but spatial auto-corr can be neglected).
# But AR(1) noise is technically difficult because DAPPER
# is built around the Markov assumption. Possible work-around:
# - Don't use standard dxdt + rk4
# - Use persistent variables
import numpy as np
from numpy import arange
from tools.misc import rk4, is1d
# Parameters
nX= 8 # of X
J = 32 # of Y per X
m = (J+1)*nX # total state length
h = 1 # coupling constant
F = 20 # forcing
b = 10 # Spatial scale ratio
c = 10 # time scale ratio
#c = 4 more difficult to parameterize (less scale separation)
check_parameters = True
# Shift elements
s = lambda x,n: np.roll(x,-n,axis=-1)
# Indices of X and Y variables in state
iiX = (arange(J*nX)/J).astype(int)
iiY = arange(J*nX).reshape((nX,J))
def dxdt_trunc(x):
"""
Truncated dxdt: slow variables (X) only.
Same as "uncoupled" Lorenz-95.
"""
assert x.shape[-1] == nX
return -(s(x,-2)-s(x,1))*s(x,-1) - x + F
def dxdt(x):
"""Full (coupled) dxdt."""
# Split into X,Y
X = x[...,:nX]
Y = x[...,nX:]
assert Y.shape[-1] == J*X.shape[-1]
d = np.zeros_like(x)
# dX/dt
d[...,:nX] = dxdt_trunc(X)
# Couple Y-->X
for i in range(nX):
d[...,i] += -h*c/b * np.sum(Y[...,iiY[i]],-1)
# dY/dt
d[...,nX:] = -c*b*(s(Y,2)-s(Y,-1))*s(Y,1) - c*Y
# Couple X-->Y
d[...,nX:] += h*c/b * X[...,iiX]
return d
# Order of deterministic error parameterization.
# Note: In order to observe an improvement in DA performance when using
# higher orders, the EnKF must be reasonably tuned with inflation.
# There is very little improvement gained above order=1.
detp_order = 'UNSET' # set from outside
def dxdt_detp(x):
"""
Truncated dxdt with
polynomial (deterministic) parameterization of fast variables (Y)
"""
d = dxdt_trunc(x)
if check_parameters:
assert np.all([nX==8,J==32,F==20,c==10,b==10,h==1]), \
"""
The parameterizations have been tuned (by Wilks)
for specific param values. These are not currently in use.
"""
if detp_order==4:
# From Wilks
d -= 0.262 + 1.45*x - 0.0121*x**2 - 0.00713*x**3 + 0.000296*x**4
elif detp_order==3:
# From Arnold
d -= 0.341 + 1.30*x - 0.0136*x**2 - 0.00235*x**3
elif detp_order==1:
# From me -- see AdInf/illust_parameterizations.py
d -= 0.74 + 0.82*x
elif detp_order==0:
# From me -- see AdInf/illust_parameterizations.py
d -= 3.82
elif detp_order==-1:
# Leave as dxdt_trunc
pass
else:
raise NotImplementedError
return d
def dfdx(x,t,dt):
"""
Jacobian of x + dt*dxdt.
"""
assert is1d(x)
F = np.zeros((m,m))
# X
md = lambda i: np.mod(i,nX)
for i in range(nX):
# wrt. X
F[i,i] = - dt + 1
F[i,md(i-2)] = - dt * x[md(i-1)]
F[i,md(i+1)] = + dt * x[md(i-1)]
F[i,md(i-1)] = dt *(x[md(i+1)]-x[md(i-2)])
# wrt. Y
F[i,nX+iiY[i]] = dt * -h*c/b
# Y
md = lambda i: nX + np.mod(i-nX,nX*J)
for i in range(nX,(J+1)*nX):
# wrt. Y
F[i,i] = -dt*c + 1
F[i,md(i-1)] = +dt*c*b * x[md(i+1)]
F[i,md(i+1)] = -dt*c*b * (x[md(i+2)]-x[md(i-1)])
F[i,md(i+2)] = -dt*c*b * x[md(i+1)]
# wrt. X
F[i,iiX[i-nX]] = dt * h*c/b
return F
from matplotlib import pyplot as plt
def plot_state(x):
circX = np.mod(arange(nX+1) ,nX)
circY = np.mod(arange(nX*J+1),nX*J) + nX
lhX = plt.plot(arange(nX+1) ,x[circX],'b',lw=3)[0]
lhY = plt.plot(arange(nX*J+1)/J,x[circY],'g',lw=2)[0]
ax = plt.gca()
ax.set_xticks(arange(nX+1))
ax.set_xticklabels([(str(i) + '/\n' + str(i*J)) for i in circX])
ax.set_ylim(-5,15)
def setter(x):
lhX.set_ydata(x[circX])
lhY.set_ydata(x[circY])
return setter
|
{"/mods/LorenzXY/defaults.py": ["/mods/LorenzXY/core.py"], "/mods/LorenzXY/truncated.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"], "/mods/LorenzXY/illust_parameterizations.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"]}
|
20,140
|
zhucer2003/DAPPER
|
refs/heads/master
|
/mods/LorenzXY/illust_parameterizations.py
|
# Plot scattergram of "unresolved tendency"
# and the parameterization that emulate it.
# We plot the diff:
# model_step/dt - true_step/dt (1)
# Whereas Wilks plots
# model_dxdt - true_step/dt (2)
# Another option is:
# model_dxdt - true_dxdt (3)
# Thus, for us (eqn 1), the model integration scheme matters.
# Also, Wilks uses
# dt=0.001 for truth
# dt=0.005 for model.
from common import *
plt.style.use('AdInf/paper.mplstyle')
###########################
# Setup
###########################
from mods.LorenzXY.core import *
from mods.LorenzXY.defaults import plot_state
K = 4000
dt = 0.005
t0 = np.nan
seed(30) # 3 5 7 13 15 30
x0 = randn(m)
true_step = with_rk4(dxdt ,autonom=True)
model_step = with_rk4(dxdt_trunc,autonom=True)
###########################
# Compute truth trajectory
###########################
true_K = make_recursive(true_step,with_prog=1)
x0 = true_K(x0,int(2/dt),t0,dt)[-1] # BurnIn
xx = true_K(x0,K ,t0,dt)
# Plot truth evolution
# setter = plot_state(xx[0])
# ax = plt.gca()
# for k in progbar(range(K),'plot'):
# if not k%4:
# setter(xx[k])
# ax.set_title("t = {:<5.2f}".format(dt*k))
# plt.pause(0.01)
###########################
# Compute unresovled scales
###########################
gg = zeros((K,nX)) # "Unresolved tendency"
for k,x in enumerate(xx[:-1]):
X = x[:nX]
Z = model_step(X,t0,dt)
D = Z - xx[k+1,:nX]
gg[k] = 1/dt*D
###########################
# Scatter plot
###########################
xx = xx[:-1,:nX]
dk = int(8/dt/50) # step size
xx = xx[::dk].ravel()
gg = gg[::dk].ravel()
fig, ax = plt.subplots()
ax.scatter(xx,gg, facecolors='none', edgecolors=blend_rgb('k',0.5),s=40)
#ax.plot(xx,gg,'o',color=[0.7]*3)
ax.set_xlim(-10,17)
ax.set_ylim(-10,20)
ax.set_ylabel('Unresolved tendency ($q_{k,i}/\Delta t$)')
ax.set_xlabel('Resolved variable ($X_{k,i}$)')
###########################
# Parameterization plot
###########################
p0 = lambda x: 3.82+0.00*x
p1 = lambda x: 0.74+0.82*x # lin.reg(gg,xx)
p3 = lambda x: .341+1.30*x -.0136*x**2 -.00235*x**3 # Arnold'2013
p4 = lambda x: .262+1.45*x -.0121*x**2 -.00713*x**3 +.000296*x**4 # Wilks'2005
uu = linspace(-10,17,201)
plt.plot(uu,p0(uu),'g',lw=4.0)
plt.plot(uu,p1(uu),'r',lw=4.0)
plt.plot(uu,p4(uu),'b',lw=4.0)
#plt.plot(uu,p3(uu),'y',lw=3.0)
def an(T,xy,xyT,HA='left'):
ah = ax.annotate(T,
xy =xy , xycoords='data',
xytext=xyT, textcoords='data',
fontsize=16,
horizontalalignment=HA,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3",lw=2)
)
return ah
s4 = '$0.262$\n$+1.45X$\n$-0.0121X^2$\n$-0.00713X^3$\n$+0.000296X^4$'
an('$3.82$' ,(10 ,3.82),(10,-2) ,'center')
an('$0.74+0.82X$',(-7.4,-5.4),(1 ,-6))
an(s4 ,(7 ,8) ,(0 ,10) ,'right')
|
{"/mods/LorenzXY/defaults.py": ["/mods/LorenzXY/core.py"], "/mods/LorenzXY/truncated.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"], "/mods/LorenzXY/illust_parameterizations.py": ["/mods/LorenzXY/core.py", "/mods/LorenzXY/defaults.py"]}
|
20,144
|
rtvasu/ant-colony-tsp
|
refs/heads/main
|
/aco-a.py
|
from parameters import *
import numpy as np
def euclidean(c1, c2):
return pow(pow(c1[0] - c2[0], 2) + pow(c1[1] - c2[1], 2), 0.5)
def parse(filename):
with open(filename) as f:
content = f.readlines()
for line in content:
l = line.strip().split()
content[int(l[0]) - 1] = (int(l[1]), int(l[2]))
return content
def distance(list):
distance = [[0 for i in range(len(list))] for j in range(len(list))]
for i in range(len(list)):
for j in range(len(list)):
if (i == j):
distance[i][j] = 0
elif (i < j):
distance[i][j] = euclidean(list[i], list[j])
else:
distance[i][j] = distance[j][i]
return distance
def placeInitPheromone():
pheromone = [[0 for i in range(numCities)] for j in range(numCities)]
for i in range(len(pheromone)):
for j in range(len(pheromone)):
if (i == j):
pheromone[i][j] = 0
elif (i < j):
pheromone[i][j] = initPheromoneAmt
else:
pheromone[i][j] = pheromone[j][i]
return pheromone
def assignCities():
antLocations = [-1 for i in range(numAnts)]
cityPerGroup = np.random.permutation(numCities)
for i in range(numAnts):
antLocations[i] = cityPerGroup[i%numCities]
return antLocations
def pseudorandomProportionalRule(path):
probOfSelection = [0 for i in range(numCities)]
src = path[0]
for j in range(numCities):
if (j in path):
probOfSelection[j] = 0
else:
probOfSelection[j] = pheromoneAmounts[src][j]/pow(distances[src][j], beta)
return probOfSelection
def antSystemTransitionRule(path):
probOfSelection = [0 for i in range(numCities)]
# find denominator
src = path[-1]
den = 0
for dest in range(numCities):
if (src == dest):
continue
den += pow(pheromoneAmounts[src][dest], alpha)/pow(distances[src][dest], beta)
for j in range(numCities):
if (j in path):
probOfSelection[j] = 0
else:
probOfSelection[j] = pow(pheromoneAmounts[src][j], alpha)/pow(distances[src][j], beta)
if (den == 0):
probOfSelection[j] = pow(10, 100)
else:
probOfSelection[j] /= den
return probOfSelection
def evaporate():
for i in range(numCities):
for j in range(numCities):
pheromoneAmounts[i][j] = (1 - evapRate)*pheromoneAmounts[i][j]
def offlinePheromoneUpdate(length, path):
for i in range(numCities):
for j in range(numCities):
if (i < j):
for k in range(len(path) - 1):
if (path[k] == i and path[k + 1] == j) or (path[k] == j and path[k + 1] == i):
pheromoneAmounts[i][j] = ((1 - evapRate)*pheromoneAmounts[i][j]) + (evapRate/length)
else:
pheromoneAmounts[i][j] = ((1 - evapRate)*pheromoneAmounts[i][j])
elif (i > j):
pheromoneAmounts[i][j] = pheromoneAmounts[j][i]
def forage():
paths = [[antLocations[i]] for i in range(numAnts)]
pathLengths = [0 for i in range(numAnts)]
for i in range(maxIter):
q = np.random.rand()
for j in range(numAnts):
probOfSelection = []
if (q <= q0):
probOfSelection = pseudorandomProportionalRule(paths[j])
else:
probOfSelection = antSystemTransitionRule(paths[j])
evaporate()
maximum = max(probOfSelection)
if (maximum != 0):
paths[j].append(probOfSelection.index(max(probOfSelection)))
pathLengths[j] += distances[paths[j][-2]][paths[j][-1]]
pheromoneAmounts[paths[j][0]][paths[j][-1]] = ((1 - decayCoeff)*pheromoneAmounts[paths[j][0]][paths[j][-1]]) + (decayCoeff*initPheromoneAmt)
pheromoneAmounts[paths[j][-1]][paths[j][0]] = pheromoneAmounts[paths[j][0]][paths[j][-1]]
bestAnt = pathLengths.index(min(pathLengths))
offlinePheromoneUpdate(pathLengths[bestAnt], paths[bestAnt])
return min(pathLengths), paths[pathLengths.index(min(pathLengths))]
coordinates = parse(filename)
distances = distance(coordinates)
for i in range(3):
numAnts = numAntsList[0]
alpha = alphaList[0]
beta = betaList[0]
decayCoeff = decayCoeffList[i]
pheromoneAmounts = placeInitPheromone()
antLocations = assignCities()
bestPathLength, bestPath = forage()
print(round(bestPathLength), bestPath, len(bestPath))
|
{"/aco-a.py": ["/parameters.py"]}
|
20,145
|
rtvasu/ant-colony-tsp
|
refs/heads/main
|
/parameters.py
|
filename = 'bays29.tsp'
numAntsList = [30, 125]
initPheromoneAmt = 0.0001
numCities = 29
alphaList = [9, 5, 2]
betaList = [12, 2, 1]
maxIter = 500
evapRate = 0.2
q0 = 0.6
decayCoeffList = [0.2, 0.4, 0.6]
|
{"/aco-a.py": ["/parameters.py"]}
|
20,146
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fixutils/__init__.py
|
import sys
import os
fix_str_const = "{0}: {1}/{2} -> {3}"
fix_str_const2 = "{0}: attributes missing for MSD {1}"
def read_conllu_file(file: str) -> tuple:
"""Reads a CoNLL-U format file are returns it."""
print("{0}: reading corpus {1}".format(
read_conllu_file.__name__, file), file=sys.stderr, flush=True)
corpus = []
attributes = {}
with open(file, mode='r', encoding='utf-8') as f:
comments = []
sentence = []
linecounter = 0
for line in f:
linecounter += 1
line = line.strip()
if line:
if not line.startswith('#'):
parts = line.split()
if len(parts) == 10:
sentence.append(parts)
features = parts[5]
msd = parts[4]
if msd not in attributes:
attributes[msd] = features
else:
raise RuntimeError(
"CoNLL-U line not well formed at line {0!s} in file {1}".format(linecounter, file), file=sys.stderr)
else:
comments.append(line)
elif sentence:
corpus.append((comments, sentence))
sentence = []
comments = []
# end for line
# end with
return (corpus, attributes)
# This needs to sit alongside Romanin UD treebanks repositories, checked out in the same folder
# as the 'ro-ud-autocorrect' repository!
(_, morphosyntactic_features) = read_conllu_file(
os.path.join('..', 'UD_Romanian-RRT', 'ro_rrt-ud-train.conllu'))
(_, _attributes_dev) = read_conllu_file(
os.path.join('..', 'UD_Romanian-RRT', 'ro_rrt-ud-dev.conllu'))
(_, _attributes_test) = read_conllu_file(
os.path.join('..', 'UD_Romanian-RRT', 'ro_rrt-ud-test.conllu'))
msd_to_attributes = {}
for msd in _attributes_dev:
if msd not in morphosyntactic_features:
morphosyntactic_features[msd] = _attributes_dev[msd]
# end for
for msd in _attributes_test:
if msd not in morphosyntactic_features:
morphosyntactic_features[msd] = _attributes_test[msd]
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,147
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fixutils/syntax.py
|
import sys
import re
_todo_rx = re.compile('ToDo=([^|_]+)')
def fix_aux_pass(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that if an aux:pass is present the subject is also passive."""
auxpass_head = 0
for parts in sentence:
drel = parts[7]
head = int(parts[6])
if drel == 'aux:pass':
auxpass_head = head
break
# end if
# end for
if auxpass_head > 0:
for parts in sentence:
drel = parts[7]
head = int(parts[6])
if drel.startswith('nsubj') and drel != 'nsubj:pass' and head == auxpass_head:
parts[7] = 'nsubj:pass'
print("{0}: nsubj -> nsubj:pass".format(fix_aux_pass.__name__),
file=sys.stderr, flush=True)
elif drel.startswith('csubj') and drel != 'csubj:pass' and head == auxpass_head:
parts[7] = 'csubj:pass'
print("{0}: csubj -> csubj:pass".format(fix_aux_pass.__name__),
file=sys.stderr, flush=True)
# end if
# end for
# end if
def remove_todo(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that ToDo=... is removed if syntactic relation has been changed."""
for parts in sentence:
drel = parts[7]
misc = parts[9]
if 'ToDo' in misc:
m = _todo_rx.search(misc)
if m:
rel = m.group(1)
if drel == rel:
attr = 'ToDo=' + rel
misc = misc.replace(attr, '')
misc = misc.replace('||', '|')
if misc.startswith('|'):
misc = misc[1:]
if misc.endswith('|'):
misc = misc[:-1]
if not misc:
misc = '_'
print("{0}: {1} -> {2}".format(remove_todo.__name__, parts[9], misc),
file=sys.stderr, flush=True)
parts[9] = misc
# end replace condition
# end if m
# end if ToDo
# end parts
def fix_nmod2obl(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that nmod -> obl when nmod is headed by a verb."""
for parts in sentence:
drel = parts[7]
head = int(parts[6])
if drel == 'nmod' and head > 0 and sentence[head - 1][3] == 'VERB':
parts[7] = 'obl'
print("{0}: nmod -> obl".format(fix_nmod2obl.__name__),
file=sys.stderr, flush=True)
# end if
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,148
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fixutils/punctuation.py
|
import re
_paired_punct_left = '({[„'
_paired_punct_right = ')}]”'
_delete_prev_space_punct = ',:;.%'
# Patterns with UPOSes and punctuation in the middle.
# Empty string means any UPOS.
_delete_all_space_patterns_punct = [
['NUM', ',', 'NUM'],
['NUM', '-', 'NUM'],
['', '/', '']
]
_space_after_no_strconst = 'SpaceAfter=No'
_text_rx = re.compile('^#\\s*text\\s*=\\s*')
def _get_updated_misc(misc: str) -> str:
if _space_after_no_strconst in misc:
return misc
elif misc == '_':
return _space_after_no_strconst
else:
return misc + '|' + _space_after_no_strconst
def add_space_after_no(sentence: list, comments: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that all artificially inserted spaces around punctuation is removed."""
paired_stack = []
for i in range(len(sentence)):
prev_parts = None
prev_misc = None
next_parts = None
next_misc = None
if i > 0:
prev_parts = sentence[i - 1]
prev_misc = prev_parts[9]
if i < len(sentence) - 1:
next_parts = sentence[i + 1]
next_misc = next_parts[9]
parts = sentence[i]
word = parts[1]
misc = parts[9]
msd = parts[4]
upos = parts[3]
head = parts[6]
# 1. Deal with paired punctuation
if word in _paired_punct_left:
parts[9] = _get_updated_misc(misc)
elif word in _paired_punct_right and prev_parts:
prev_parts[9] = _get_updated_misc(prev_misc)
elif word == '"':
if paired_stack and paired_stack[-1] == '"':
prev_parts[9] = _get_updated_misc(prev_misc)
paired_stack.pop()
else:
parts[9] = _get_updated_misc(misc)
paired_stack.append(word)
elif word == "'":
if paired_stack and paired_stack[-1] == "'":
prev_parts[9] = _get_updated_misc(prev_misc)
paired_stack.pop()
else:
parts[9] = _get_updated_misc(misc)
paired_stack.append(word)
# end if
# 2. Deal with previous spaces
if word in _delete_prev_space_punct and prev_parts:
prev_parts[9] = _get_updated_misc(prev_misc)
# 3. Deal with Romanian clitics
if word.endswith('-') and \
(msd.endswith('y') or '-y-' in msd or \
(next_parts and next_parts[4].startswith('V'))):
parts[9] = _get_updated_misc(misc)
if word.startswith('-') and \
(upos == 'AUX' or upos == 'DET' or upos == 'ADP' or upos == 'PART' or upos == 'PRON') and prev_parts:
prev_parts[9] = _get_updated_misc(prev_misc)
# 3.1 Deal with noun compunds with '-'
if word.endswith('-') and 'BioNERLabel=' in misc and \
next_misc and 'BioNERLabel=' in next_misc:
parts[9] = _get_updated_misc(misc)
if word == '-' and head == prev_parts[0] and \
next_parts and next_parts[6] == head:
prev_parts[9] = _get_updated_misc(prev_misc)
parts[9] = _get_updated_misc(misc)
# end for
# 4. Deal with patterns
for patt in _delete_all_space_patterns_punct:
for i in range(len(sentence) - len(patt)):
ppi = -1
for j in range(i, i + len(patt)):
parts = sentence[j]
upos = parts[3]
word = parts[1]
if patt[j - i] and upos != patt[j - i] and word != patt[j - i]:
# Pattern match fail
ppi = -1
break
# end if
if word == patt[j - i]:
ppi = j
# end if
# end for slice in sentece, for current pattern
# Remove before and after spaces for this pattern
if ppi >= 1:
sentence[ppi][9] = _get_updated_misc(sentence[ppi][9])
sentence[ppi - 1][9] = _get_updated_misc(sentence[ppi - 1][9])
# end action if
# end all slices of length of pattern
# end all patterns
new_text = []
# 5. Redo the text = sentence
for i in range(len(sentence)):
parts = sentence[i]
word = parts[1]
misc = parts[9]
if _space_after_no_strconst in misc or i == len(sentence) - 1:
new_text.append(word)
else:
new_text.append(word + ' ')
# end if
# end for
for i in range(len(comments)):
if _text_rx.search(comments[i]):
comments[i] = '# text = ' + ''.join(new_text)
break
# end if
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,149
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/markutils/oblnmod.py
|
import sys
import re
_verbadjadv_rx = re.compile('^[VAR]')
_substpronnum_rx = re.compile('^([NPM]|Y[np])')
def mark_obl(sentence: list) -> None:
"""
- obl care nu au ca head verbe, adjective sau adverbe;
"""
for parts in sentence:
head = int(parts[6])
drel = parts[7]
if drel == 'obl' and head > 0:
hmsd = sentence[head - 1][4]
if not _verbadjadv_rx.match(hmsd):
parts[0] = '!' + parts[0]
print("obl -> {0}".format(hmsd), file=sys.stderr, flush=True)
# end if
# end if
# end for
def mark_nmod(sentence: list) -> None:
"""
- nmod care nu au ca head substantive, pronume sau numerale;
"""
for parts in sentence:
head = int(parts[6])
drel = parts[7]
if drel == 'nmod' and head > 0:
hmsd = sentence[head - 1][4]
if not _substpronnum_rx.match(hmsd):
parts[0] = '!' + parts[0]
print("nmod -> {0}".format(hmsd), file=sys.stderr, flush=True)
# end if
# end if
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,150
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/mark-all.py
|
import sys
from pathlib import Path
from fixutils import read_conllu_file
from markutils.oblnmod import mark_nmod, mark_obl
if __name__ == '__main__':
conllu_file = sys.argv[1]
if len(sys.argv) != 2:
print("Usage: python3 mark-all.py <.conllu file>", file=sys.stderr)
exit(1)
# end if
(corpus, _) = read_conllu_file(conllu_file)
for (comments, sentence) in corpus:
mark_nmod(sentence)
mark_obl(sentence)
# end all sentences
output_file = Path(conllu_file)
output_file = Path(output_file.parent) / Path(output_file.name + ".fixed")
with open(output_file, mode='w', encoding='utf-8') as f:
for (comments, sentence) in corpus:
f.write('\n'.join(comments))
f.write('\n')
f.write('\n'.join(['\t'.join(x) for x in sentence]))
f.write('\n')
f.write('\n')
# end for
# end with
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,151
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fixutils/numerals.py
|
import sys
import re
from . import fix_str_const, fix_str_const2, morphosyntactic_features
_num_rx = re.compile('^[0-9]+([.,][0-9]+)?$')
_int_rx = re.compile('^[0-9]+([.,][0-9]+)?(-|﹘|‐|‒|–|—)[0-9]+([.,][0-9]+)?$')
_romans = [
'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X',
'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII',
'XIX', 'XX', 'XXI', 'XXII', 'XXIII', 'XXIV', 'XXV', 'XXVI',
'XXVII', 'XXVIII', 'XXIX', 'XXX', 'XXXI', 'XXXII', 'XXXIII',
'XXXIV', 'XXXV', 'XXXVI', 'XXXVII', 'XXXVIII', 'XXXIX', 'XL',
'XLI', 'XLII', 'XLIII', 'XLIV', 'XLV', 'XLVI', 'XLVII', 'XLVIII',
'XLIX', 'L', 'LI', 'LII', 'LIII', 'LIV', 'LV', 'LVI', 'LVII',
'LVIII', 'LIX', 'LX', 'LXI', 'LXII', 'LXIII', 'LXIV', 'LXV',
'LXVI', 'LXVII', 'LXVIII', 'LXIX', 'LXX', 'LXXI', 'LXXII',
'LXXIII', 'LXXIV', 'LXXV', 'LXXVI', 'LXXVII', 'LXXVIII',
'LXXIX', 'LXXX', 'LXXXI', 'LXXXII', 'LXXXIII', 'LXXXIV',
'LXXXV', 'LXXXVI', 'LXXXVII', 'LXXXVIII', 'LXXXIX', 'XC',
'XCI', 'XCII', 'XCIII', 'XCIV', 'XCV', 'XCVI', 'XCVII',
'XCVIII', 'XCIX', 'C'
]
_literal_nums = [
'unu', 'doi', 'trei', 'patru', 'cinci', 'șase', 'șapte', 'opt',
'nouă', 'zece', 'unsprezece', 'doisprezece', 'treisprezece',
'paisprezece', 'cincisprezece', 'șaisprezece', 'șaptesprezece',
'optsprezece', 'nouăsprezece', 'douăzeci', 'treizeci', 'patruzeci',
'cincizeci', 'șaizeci', 'șaptezeci', 'optzeci', 'nouăzeci'
]
_literal_numbers_int_rx = re.compile(
'(' + '|'.join(_literal_nums) + ')(-|﹘|‐|‒|–|—)(' + '|'.join(_literal_nums) + ')', re.IGNORECASE)
_bullet_rx = re.compile('^[0-9]+[a-zA-Z0-9.]+$')
_telephone_rx = re.compile('^0[0-9]+([.-]?[0-9])+$')
def fix_numerals(sentence: list) -> None:
"""Takes a list of CoNLL-U sentences are produced by conllu.read_conllu_file() and applies
the numeral rules."""
for parts in sentence:
word = parts[1]
msd = parts[4]
performed = False
if parts[3] != 'NUM':
continue
if (_num_rx.match(word) or _telephone_rx.match(word)) and msd != 'Mc-s-d':
parts[4] = 'Mc-s-d'
performed = True
elif _int_rx.match(word) and msd != 'Mc-p-d':
parts[4] = 'Mc-p-d'
performed = True
elif (word in _romans or word.upper() in _romans) and msd != 'Mo-s-r':
parts[4] = 'Mo-s-r'
performed = True
elif (_bullet_rx.match(word) or '/CE' in word) and msd != 'Mc-s-b':
parts[4] = 'Mc-s-b'
if parts[5] != '_':
parts[5] = parts[5] + "|NumForm=Combi"
else:
parts[5] = "NumForm=Combi"
performed = True
elif _literal_numbers_int_rx.match(word) and msd != 'Mc-p-l':
parts[4] = 'Mc-p-l'
performed = True
# end if
if performed:
parts[2] = word
if parts[4] in morphosyntactic_features:
parts[5] = morphosyntactic_features[parts[4]]
else:
print(fix_str_const2.format(
fix_numerals.__name__, msd), file=sys.stderr, flush=True)
print(fix_str_const.format(
fix_numerals.__name__, word, msd, parts[4]), file=sys.stderr, flush=True)
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,152
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fixutils/words.py
|
import sys
import re
from . import fix_str_const, fix_str_const2, morphosyntactic_features
_letter_rx = re.compile('^[a-zA-ZșțăîâȘȚĂÎÂ]$')
_month_rx = re.compile('^(ianuarie|februarie|martie|aprilie|mai|iunie|iulie|august|septembrie|noiembrie|decembrie)$', re.IGNORECASE)
def fix_letters(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that all single-char letters are tagged with 'Ncms-n'."""
for parts in sentence:
word = parts[1]
lemma = parts[2]
msd = parts[4]
if parts[3] != 'NOUN':
continue
if _letter_rx.match(word) and msd != 'Ncms-n' and lemma == word:
# Do not change K -> Kelvin instances which are Yn!
parts[4] = 'Ncms-n'
if parts[4] in morphosyntactic_features:
parts[5] = morphosyntactic_features[parts[4]]
else:
print(fix_str_const2.format(
fix_letters.__name__, msd), file=sys.stderr, flush=True)
print(fix_str_const.format(
fix_letters.__name__, word, msd, parts[4]), file=sys.stderr, flush=True)
# end if
# end for
def fix_months(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that all month names are tagged with 'Ncm--n'."""
for parts in sentence:
word = parts[1]
msd = parts[4]
if parts[3] != 'NOUN':
continue
if _month_rx.match(word) and msd != 'Ncm--n':
parts[4] = 'Ncm--n'
parts[2] = word
if parts[4] in morphosyntactic_features:
parts[5] = morphosyntactic_features[parts[4]]
else:
print(fix_str_const2.format(
fix_months.__name__, msd), file=sys.stderr, flush=True)
print(fix_str_const.format(
fix_months.__name__, word, msd, parts[4]), file=sys.stderr, flush=True)
# end if
# end for
def fix_to_be(sentence: list) -> None:
"""Takes a sentence as returned by conll.read_conllu_file() and makes
sure that 'a fi' 'cop' or 'aux' is 'Va...'."""
for parts in sentence:
word = parts[1]
lemma = parts[2]
msd = parts[4]
drel = parts[7]
if lemma != 'fi':
continue
if (drel == 'aux' or drel == 'cop') and not msd.startswith('Va'):
parts[4] = 'Va' + msd[2:]
parts[3] = 'AUX'
if parts[4] in morphosyntactic_features:
parts[5] = morphosyntactic_features[parts[4]]
else:
print(fix_str_const2.format(
fix_to_be.__name__, msd), file=sys.stderr, flush=True)
print(fix_str_const.format(
fix_to_be.__name__, word, msd, parts[4]), file=sys.stderr, flush=True)
# end if
# end for
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,153
|
racai-ai/ro-ud-autocorrect
|
refs/heads/master
|
/fix-all.py
|
import sys
from pathlib import Path
from fixutils import read_conllu_file
from fixutils.numerals import fix_numerals
from fixutils.words import fix_letters, fix_months, fix_to_be
from fixutils.syntax import fix_aux_pass, remove_todo, fix_nmod2obl
from fixutils.punctuation import add_space_after_no
if __name__ == '__main__':
remove_spaces = False
conllu_file = sys.argv[1]
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python3 fix-all.py [-s] <.conllu file>", file=sys.stderr)
exit(1)
elif sys.argv[1] == '-s':
remove_spaces = True
conllu_file = sys.argv[2]
# end if
(corpus, _) = read_conllu_file(conllu_file)
for (comments, sentence) in corpus:
if remove_spaces:
add_space_after_no(sentence, comments)
fix_numerals(sentence)
fix_letters(sentence)
fix_months(sentence)
fix_to_be(sentence)
fix_aux_pass(sentence)
remove_todo(sentence)
fix_nmod2obl(sentence)
# end all sentences
output_file = Path(conllu_file)
output_file = Path(output_file.parent) / Path(output_file.name + ".fixed")
with open(output_file, mode='w', encoding='utf-8') as f:
for (comments, sentence) in corpus:
f.write('\n'.join(comments))
f.write('\n')
f.write('\n'.join(['\t'.join(x) for x in sentence]))
f.write('\n')
f.write('\n')
# end for
# end with
|
{"/mark-all.py": ["/fixutils/__init__.py", "/markutils/oblnmod.py"], "/fixutils/numerals.py": ["/fixutils/__init__.py"], "/fixutils/words.py": ["/fixutils/__init__.py"], "/fix-all.py": ["/fixutils/__init__.py", "/fixutils/numerals.py", "/fixutils/words.py", "/fixutils/syntax.py", "/fixutils/punctuation.py"]}
|
20,155
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/conftest.py
|
import os
import pytest
@pytest.fixture
def rootdir():
return os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def datadir(rootdir):
return os.path.join(rootdir, 'data')
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,156
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/music1030/fuzzy.py
|
from collections import Counter
from typing import List
import pandas as pd
def jaccard_similarity(a: str,
b: str) -> float:
"""Takes in two strings and computes their letter-wise
Jaccard similarity for bags.
Case should be ignored.
"""
# TODO: Task 3
# YOUR CODE HERE
pass
def fuzzy_merge(left: pd.DataFrame,
right: pd.DataFrame,
on: List[str]) -> pd.DataFrame:
"""Merge DataFrame objects by performing a fuzzy
database-style join operation by columns.
:param left: a DataFrame
:param right: a DataFrame
:param on: Column or index level names to join on. These must be
found in both DataFrames.
:return: the merged DataFrame
"""
# TODO: Task 3
# YOUR CODE HERE
pass
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,157
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/main.py
|
import flask
import pandas as pd
from music1030.billboard import clean_billboard
from music1030.spotify import clean_spotify_tracks
def handle_billboard(request: flask.Request):
"""
:param request: a flask Request containing the JSON data
:return: a
"""
data = request.get_json()
df = pd.DataFrame(data)
cleaned_df: pd.DataFrame = clean_billboard(df)
cleaned_json = cleaned_df.to_json(orient='records')
return flask.Response(response=cleaned_json,
status=200,
mimetype='application/json')
def handle_spotify(request: flask.Request):
# YOUR CODE HERE
pass
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,158
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Data Structure and Algorithms/Group Anagrams.py
|
# def groupAnagrams(strs):
# def is_anagram(a, b):
# count = {}
# for char in a:
# count[char] = count.get(char, 0) + 1
# for char in b:
# if not char in count.keys():
# return False
# else:
# count[char] -= 1
# if count[char] < 0:
# return False
# return sum(count.values()) == 0
#
# hashdic = {}
# used_index = []
# for s1 in strs:
# for s2 in strs:
# if is_anagram(s1, s2) and strs.index(s2) not in used_index:
# hashdic[s1] = hashdic.get(s1, [])
# hashdic[s1].append(s2)
# used_index.append(strs.index(s2))
# res = [hashdic[key] for key in hashdic.keys()]
# return res
def groupAnagrams(strs):
hashdic = {}
for s in strs:
if ''.join(sorted(s)) in hashdic.keys():
hashdic[''.join(sorted(s))].append(s)
else:
hashdic[''.join(sorted(s))] = [s]
return list(hashdic.values())
print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,159
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/main_test.py
|
import json
import requests
# TODO: You should put your cloud function URL here.
# The URL below links to the TA version
BILLBOARD_URL = 'https://us-central1-personal-198408.cloudfunctions.net' \
'/handle_billboard'
SPOTIFY_URL = 'https://us-central1-personal-198408.cloudfunctions.net' \
'/handle_spotify'
def test_handle_billboard():
response = requests.post(
BILLBOARD_URL,
headers={
'Content-type': 'application/json'
},
data=json.dumps([{
"artist_names": "Justin Bieber",
"rank": 1,
"song_name": "What Do You Mean?",
"week": "2015-09-19"
}])
)
assert response.json() == [
{"rank": 1,
"song_name": "What Do You Mean?",
"week": "2015-09-19",
"main_artist_name": "justin bieber"
}
]
def test_handle_spotify(datadir):
data = [{
"album": {
"album_type": "album",
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/"
"1E2AEtxaFaJtH0lO7kgNKw"
},
"href": "https://api.spotify.com/v1/artists/"
"1E2AEtxaFaJtH0lO7kgNKw",
"id": "1E2AEtxaFaJtH0lO7kgNKw",
"name": "Russell Dickerson",
"type": "artist",
"uri": "spotify:artist:1E2AEtxaFaJtH0lO7kgNKw"
}
],
"available_markets": [
"AD",
"AR",
"AT",
"AU",
"BE",
"BG",
"BO",
"BR",
"CA",
"CH",
"CL",
"CO",
"CR",
"CY",
"CZ",
"DE",
"DK",
"DO",
"EC",
"EE",
"ES",
"FI",
"FR",
"GB",
"GR",
"GT",
"HK",
"HN",
"HU",
"ID",
"IE",
"IS",
"IT",
"JP",
"LI",
"LT",
"LU",
"LV",
"MC",
"MT",
"MX",
"MY",
"NI",
"NL",
"NO",
"NZ",
"PA",
"PE",
"PH",
"PL",
"PT",
"PY",
"SE",
"SG",
"SK",
"SV",
"TH",
"TR",
"TW",
"US",
"UY"
],
"external_urls": {
"spotify": "https://open.spotify.com/album/"
"1B6iXA14exgSuBrdHoNqrB"
},
"href": "https://api.spotify.com/v1/albums/"
"1B6iXA14exgSuBrdHoNqrB",
"id": "1B6iXA14exgSuBrdHoNqrB",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/"
"736107f18625aec57f16a6d84ef51820b139a39d",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/"
"3c0f3d5fef38df51cc160f342275171bfe888822",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/"
"d65a7cbb93752e9442c3cb41c80493925bd70eb9",
"width": 64
}
],
"name": "Yours - EP",
"type": "album",
"uri": "spotify:album:1B6iXA14exgSuBrdHoNqrB"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/"
"1E2AEtxaFaJtH0lO7kgNKw"
},
"href": "https://api.spotify.com/v1/artists/"
"1E2AEtxaFaJtH0lO7kgNKw",
"id": "1E2AEtxaFaJtH0lO7kgNKw",
"name": "Russell Dickerson",
"type": "artist",
"uri": "spotify:artist:1E2AEtxaFaJtH0lO7kgNKw"
}
],
"available_markets": [
"AD",
"AR",
"AT",
"AU",
"BE",
"BG",
"BO",
"BR",
"CA",
"CH",
"CL",
"CO",
"CR",
"CY",
"CZ",
"DE",
"DK",
"DO",
"EC",
"EE",
"ES",
"FI",
"FR",
"GB",
"GR",
"GT",
"HK",
"HN",
"HU",
"ID",
"IE",
"IS",
"IT",
"JP",
"LI",
"LT",
"LU",
"LV",
"MC",
"MT",
"MX",
"MY",
"NI",
"NL",
"NO",
"NZ",
"PA",
"PE",
"PH",
"PL",
"PT",
"PY",
"SE",
"SG",
"SK",
"SV",
"TH",
"TR",
"TW",
"US",
"UY"
],
"disc_number": 1,
"duration_ms": 211240,
"explicit": False,
"external_ids": {
"isrc": "USQX91602319"
},
"external_urls": {
"spotify": "https://open.spotify.com/track/"
"6Axy0fL3FBtwx2rwl4soq9"
},
"href": "https://api.spotify.com/v1/tracks/6Axy0fL3FBtwx2rwl4soq9",
"id": "6Axy0fL3FBtwx2rwl4soq9",
"name": "Blue Tacoma",
"popularity": 78,
"preview_url": "https://p.scdn.co/mp3-preview/"
"4fd8dd4532f5c256745783bba52750e59af1238f?"
"cid=fd8abe6759d345499f8677c6c0adad96",
"track_number": 4,
"type": "track",
"uri": "spotify:track:6Axy0fL3FBtwx2rwl4soq9"
}]
response = requests.post(
SPOTIFY_URL,
headers={
'Content-type': 'application/json'
},
data=json.dumps(data)
)
assert response.json() == [{
"main_artist_id": "1E2AEtxaFaJtH0lO7kgNKw",
"main_artist_name": "russell dickerson",
"popularity": 78,
"song_id": "6Axy0fL3FBtwx2rwl4soq9",
"song_length": 211240,
"song_name": "blue tacoma"
}]
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,160
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Data Structure and Algorithms/Longest Palindromic Substring.py
|
#Given a string s, find the longest palindromic substring in s. You may assume
# that the maximum length of s is 1000.
def longestPalindrome(s: str) -> str:
left, right = 0, len(s) - 1
def is_palindrome(sub):
left, right = 0, len(sub) - 1
while left <= right:
if sub[left] != sub[right]:
return False
else:
left += 1
right -= 1
return True
if is_palindrome(s):
return s
else:
left_advance = longestPalindrome(s[left + 1:])
right_advance = longestPalindrome(s[:right])
if len(left_advance) >= len(right_advance):
return left_advance
else:
return right_advance
print(longestPalindrome("babaddtattarraaaaa"))
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,161
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/music1030/fuzzy_test.py
|
import os
import pandas as pd
import pytest
from .fuzzy import jaccard_similarity, fuzzy_merge
def test_jaccard():
assert jaccard_similarity('a', 'b') == 0
assert jaccard_similarity('c', 'c') == 1
assert jaccard_similarity('C', 'c') == 1
assert jaccard_similarity('ace', 'acd') == 2 / 4
def test_fuzzy_merge():
df1 = pd.DataFrame(['sipping on fire'], columns=['song'])
df2 = pd.DataFrame(['sippin’ on fire'], columns=['song'])
actual = fuzzy_merge(df1, df2, on=['song'])
expected = pd.DataFrame([('sipping on fire', 'sippin’ on fire')],
columns=['song_x', 'song_y'])
assert expected.equals(actual)
def test_fuzzy_merge_string_index():
df1 = pd.DataFrame(['sipping on fire'], columns=['song'], index=['a'])
df2 = pd.DataFrame(['sippin’ on fire'], columns=['song'], index=['b'])
actual = fuzzy_merge(df1, df2, on=['song'])
expected = pd.DataFrame([('sipping on fire', 'sippin’ on fire')],
columns=['song_x', 'song_y'])
assert expected.equals(actual)
def test_fuzzy_merge_spotify_lastfm_first100(datadir):
spotify_df = pd.read_csv(os.path.join(datadir, 'spotify.csv'))
spotify_df = spotify_df[1300:]
lastfm_df = pd.read_csv(os.path.join(datadir, 'lastfm.csv'))
actual = fuzzy_merge(spotify_df, lastfm_df,
on=['song_name', 'main_artist_name'])
mask = ((actual['song_name_x'] == 'trees get wheeled away') &
(actual['song_name_y'] == 'the trees get wheeled away'))
assert len(actual[mask]) == 1
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,162
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/music1030/billboard_test.py
|
import os
import pandas as pd
from .billboard import clean_artist_col, clean_billboard
def test_prune_dummy():
dummy1 = pd.Series(data=['Major Lazer & DJ Snake Featuring MO'])
pruned1 = clean_artist_col(dummy1)
assert pruned1[0] == 'major lazer'
dummy2 = pd.Series(data=['Selena Gomez Featuring A$AP Rocky',
# The following two lines represent a single row
('Macklemore & Ryan Lewis Featuring Eric Nally,' +
'Melle Mel, Kool Moe Dee & Grandmaster Caz'),
'Young Thug And Travis Scott Featuring Quavo'])
pruned2 = clean_artist_col(dummy2)
assert pruned2[0] == 'selena gomez'
assert pruned2[1] == 'macklemore'
assert pruned2[2] == 'young thug'
def test_prune_full(datadir):
hot100_path = os.path.join(datadir, 'hot100.csv')
df = pd.read_csv(hot100_path)
df_copy = df.copy()
pruned_col = clean_artist_col(df['artist_names'])
assert not pruned_col.str.contains(' and ').any()
assert not pruned_col.str.contains('&').any()
assert not pruned_col.str.contains(' featuring').any()
assert df.equals(df_copy)
def test_clean_partial(datadir):
hot100_path = os.path.join(datadir, 'hot100.csv')
df = pd.read_csv(hot100_path)
df_copy = df.copy()
cleaned = clean_billboard(df.iloc[0:10])
assert 'song_name' in cleaned.columns
assert 'rank' in cleaned.columns
assert 'week' in cleaned.columns
assert not df.isnull().values.any()
assert not df.duplicated().any()
assert df.equals(df_copy)
def test_clean_full(datadir):
hot100_path = os.path.join(datadir, 'hot100.csv')
df = pd.read_csv(hot100_path)
df_copy = df.copy()
cleaned = clean_billboard(df)
assert 'song_name' in cleaned.columns
assert 'rank' in cleaned.columns
assert 'week' in cleaned.columns
assert not df.isnull().values.any()
assert not df.duplicated().any()
assert df.equals(df_copy)
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,163
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Model Building From Scratch/logistic_regression.py
|
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
def preprocess():
"""Return the preprocessed data set"""
data = pd.read_csv('weatherAUS.csv')
# Drop certain features any any data with null values
data = data.drop(['Sunshine', 'Evaporation', 'Cloud3pm',
'Cloud9am', 'Location', 'RISK_MM', 'Date'], axis=1)
data = data.dropna(how='any')
# Change labels
data['RainToday'].replace({'No': 0, 'Yes': 1}, inplace=True)
data['RainTomorrow'].replace({'No': 0, 'Yes': 1}, inplace=True)
# Change categorical data to integers
categorical_columns = ['WindGustDir', 'WindDir3pm', 'WindDir9am']
data = pd.get_dummies(data, columns=categorical_columns)
# standardize data set
scaler = preprocessing.MinMaxScaler()
scaler.fit(data)
data = pd.DataFrame(scaler.transform(data),
index=data.index, columns=data.columns)
y = data.pop('RainTomorrow')
X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.2)
return X_train, X_test, y_train, y_test
class LogisticRegression(object):
def __init__(self):
self.X_train, X_test, self.y_train, y_test = preprocess()
# activation function
def sigmoid(self, x):
"""Return the output of sigmoid fuction"""
return 1 / (1 + np.exp(-x))
# fit part
def fit(self, X, y, learning_rate=0.01, epochs=32,
batch_size=1, num_iter=100000):
"""Train the model using SGD"""
# add intercept
intercept = np.ones((X.shape[0], 1))
X = np.concatenate((intercept, X), axis=1)
y = np.array(y)
# initialize weights
self.beta = np.zeros(X.shape[1])
# Utilizing SGD to do weight tuning
for i in range(epochs):
for j in range(num_iter):
index = np.random.randint(0, len(X) - 1)
z = np.dot(X[index], self.beta)
r = self.sigmoid(z)
gradient = (r - y[index]) * X[index]
self.beta -= learning_rate * gradient
# Prediction part
def predict(self, X):
"""Return the prediction list"""
# add intercept
intercept = np.ones((X.shape[0], 1))
X = np.concatenate((intercept, X), axis=1)
predict_value = self.sigmoid(np.dot(X, self.beta))
predict_value = np.array(list(map(lambda x: 1 if x > 0.5 else 0,
predict_value)))
return predict_value
# Evaluate part
def evaluate(self, X_test, y_test):
"""Returns a numpy array of prediction labels"""
self.fit(self.X_train, self.y_train)
predict_value = self.predict(X_test)
return predict_value
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,164
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/music1030/spotify.py
|
from typing import List, Dict
import pandas as pd
# YOUR CODE HERE
def clean_spotify_tracks(tracks: List[Dict]) -> pd.DataFrame:
# TODO: Task 5
# YOUR CODE HERE
pass
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,165
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Text Analysis and GCP Deployment/music1030/billboard.py
|
import re
import pandas as pd
def clean_artist_col(artist_names: pd.Series) -> pd.Series:
# TODO: Task 9
# YOUR CODE HERE
pass
def clean_billboard(df: pd.DataFrame) -> pd.DataFrame:
"""Returns a cleaned billboard DataFrame.
:param df: the billboard DataFrame
:return a new cleaned DataFrame
"""
pruned_col = clean_artist_col(df['artist_names'])
cleaned_df: pd.DataFrame = (df.assign(main_artist_name=pruned_col)
.drop_duplicates()
.dropna()
.drop('artist_names', axis=1))
return cleaned_df
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,166
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Data Structure and Algorithms/Tree and Traverse Methods.py
|
class Node(object):
"""Node"""
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree(object):
"""Tree"""
def _init_(self):
self.root = Node()
sefl.myQueue = []
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,167
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Model Building From Scratch/svm.py
|
import matplotlib.pyplot as plt
import numpy as np
import scipy
import cvxpy as cp
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import pandas as pd
def preprocess():
data = pd.read_csv('weatherAUS.csv')
# Drop certain features any any data with null values
data = data.drop(['Sunshine', 'Evaporation', 'Cloud3pm', 'Cloud9am',
'Location', 'RISK_MM','Date'], axis=1)
data = data.dropna(how='any')
# Change labels
data['RainToday'].replace({'No': 0, 'Yes': 1}, inplace = True)
data['RainTomorrow'].replace({'No': -1, 'Yes': 1}, inplace = True)
# Change categorical data to integers
categorical_columns = ['WindGustDir', 'WindDir3pm', 'WindDir9am']
data = pd.get_dummies(data, columns=categorical_columns)
# standardize data set
scaler = preprocessing.MinMaxScaler()
scaler.fit(data)
data = pd.DataFrame(scaler.transform(data),
index=data.index, columns=data.columns)
y = data.pop('RainTomorrow')
X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.2)
return X_train, X_test, y_train, y_test
class LinearSVM(object):
"""A support vector machine with linear kernel that trains using
the primal convex minimization problem"""
def __init__(self, C=1.0):
self.C = C
self.w = None
self.b = None
def train(self, X, y):
"""Use training arrays to set the values of self.w and self.b"""
if isinstance(X, pd.DataFrame):
X = X.values
if isinstance(y, pd.DataFrame):
y = y.values
y = np.array([-1 if x == 0 else 1 for x in y])
nrows, ncols = np.shape(X)
ζ = cp.Variable(nrows)
# insert the correct length for w
w = cp.Variable(ncols)
b = cp.Variable()
# use cp.sum_squares and cp.sum to form the objective function
objective = cp.Minimize(0.5 * cp.sum_squares(w) + self.C * cp.sum(ζ))
# apply the optimization constraints (hint: cp.multiply)
constraints = [cp.multiply(y, X * w + b) >= 1 - ζ,
ζ >= 0]
prob = cp.Problem(objective, constraints)
prob.solve()
self.w = w.value
self.b = b.value
def predict(self, X_test):
"""Return a numpy array of prediction labels"""
if isinstance(X_test, pd.DataFrame):
X_test = X_test.values
predict = np.dot(X_test, self.w) + self.b
predict = [1 if x >= 0 else 0 for x in predict]
return np.array(predict)
def linear_kernel(a, b):
"""Return the data converted by linear kernel"""
return np.dot(a, b.T)
def polynomial_kernel(a, b):
"""Return the data converted by polynomial kernel"""
return (np.dot(a, b.T) + 1) ** 2
def rbf_kernel(a, b):
"""Return the data converted by RBF kernel"""
return np.exp(-(np.dot(a, a.T) + np.dot(b, b.T) - 2 * np.dot(a, b.T)))
class SVM(object):
def __init__(self, kernel=rbf_kernel, C=1.0):
self.kernel = kernel
self.C = C
self.X = None
self.y = None
self.α = None
self.b = None
def train(self, X, y):
"""Use training arrays X and y to set the values of
self.α and self.b"""
if isinstance(X, pd.DataFrame):
X = X.values
if isinstance(y, pd.DataFrame):
y = y.values
y = np.array([-1 if x == 0 else 1 for x in y])
nrows, ncols = np.shape(X)
α = cp.Variable(nrows)
w = cp.Variable(ncols)
# form a kernel matrix (as a numpy array)
K = self.kernel(X, X)
objective = cp.Minimize(1/2 * cp.quad_form(cp.multiply(α, y), K)
- cp.sum(α))
# list the constraints for the optimization problem
constraints = [α >= 0,
α <= self.C,
α * y == 0]
prob = cp.Problem(objective, constraints)
prob.solve()
self.X = X
self.y = y
# fill in the value of α
self.α = α.value
# fill in the value of b
self.b = np.mean(y - np.dot(X, np.dot(X.T, self.α * self.y)))
def predict(self, X_test):
"""Return a numpy array of prediction labels"""
if isinstance(X_test, pd.DataFrame):
X_test = X_test.values
predict = np.dot(rbf_kernel(X_test, X_test), self.α * self.y) + self.b
predict = [1 if x >= 0 else 0 for x in predict]
return np.array(predict)
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,168
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Model Building From Scratch/CNN.py
|
import numpy as np
from functools import reduce
class Conv2D(object):
def __init__(self, shape, output_channels, ksize=3, stride=1, method='VALID'):
self.input_shape = shape
self.output_channels = output_channels
self.input_channels = shape[-1]
self.batchsize = shape[0]
self.stride = stride
self.ksize = ksize
self.method = method
self.weights = np.random.standard_normal(
(ksize, ksize, self.input_channels, self.output_channels))
if method == 'VALID':
self.eta = np.zeros((shape[0], (shape[1] - ksize + 1) //
self.stride, (shape[1] - ksize + 1) // self.stride,
self.output_channels))
if method == 'SAME':
self.eta = np.zeros((shape[0], shape[1]//self.stride,
shape[2]//self.stride,self.output_channels))
self.output_shape = self.eta.shape
def forward(self, x):
col_weights = self.weights.reshape([-1, self.output_channels])
if self.method == 'SAME':
x = np.pad(x, (
(0, 0), (self.ksize // 2, self.ksize // 2),
(self.ksize // 2, self.ksize // 2), (0, 0)),
'constant', constant_values=0)
self.col_image = []
conv_out = np.zeros(self.eta.shape)
for i in range(self.batchsize):
img_i = x[i][np.newaxis, :]
self.col_image_i = im2col(img_i, self.ksize, self.stride)
conv_out[i] = np.reshape(np.dot(self.col_image_i,
col_weights),
self.eta[0].shape)
self.col_image.append(self.col_image_i)
self.col_image = np.array(self.col_image)
return conv_out
def im2col(image, ksize, stride):
# image is a 4d tensor([batchsize, width ,height, channel])
image_col = []
for i in range(0, image.shape[1] - ksize + 1, stride):
for j in range(0, image.shape[2] - ksize + 1, stride):
col = image[:, i:i + ksize, j:j + ksize, :].reshape([-1])
image_col.append(col)
image_col = np.array(image_col)
return image_col
class Relu(object):
def __init__(self, shape):
self.eta = np.zeros(shape)
self.x = np.zeros(shape)
self.output_shape = shape
def forward(self, x):
self.x = x
return np.maximum(x, 0)
class MaxPooling(object):
def __init__(self, shape, ksize=2, stride=2):
self.input_shape = shape
self.ksize = ksize
self.stride = stride
self.output_channels = shape[-1]
self.index = np.zeros(shape)
self.output_shape = [shape[0], shape[1] // self.stride,
shape[2] // self.stride, self.output_channels]
def forward(self, x):
out = np.zeros([x.shape[0], x.shape[1] // self.stride, x.shape[2] //
self.stride, self.output_channels])
for b in range(x.shape[0]):
for c in range(self.output_channels):
for i in range(0, x.shape[1], self.stride):
for j in range(0, x.shape[2], self.stride):
out[b, i // self.stride, j // self.stride, c] = np.max(
x[b, i:(i + self.ksize), j:(j + self.ksize), c])
index = np.argmax(x[b, i:i + self.ksize, j:j + self.ksize, c])
self.index[b, i+index//self.stride, j + index % self.stride, c] = 1
return out
class DenselyConnect(object):
def __init__(self, shape, output_num=2):
self.input_shape = shape
self.batchsize = shape[0]
input_len = reduce(lambda x, y: x * y, shape[1:])
self.weights = np.random.standard_normal((input_len, output_num))
self.output_shape = [self.batchsize, output_num]
def forward(self, x):
self.x = x.reshape([self.batchsize, -1])
output = np.dot(self.x, self.weights)
return output
class Softmax(object):
def __init__(self, shape):
self.softmax = np.zeros(shape)
self.eta = np.zeros(shape)
self.batchsize = shape[0]
def predict(self, prediction):
exp_prediction = np.zeros(prediction.shape)
self.softmax = np.zeros(prediction.shape)
for i in range(self.batchsize):
prediction[i, :] -= np.max(prediction[i, :])
exp_prediction[i] = np.exp(prediction[i])
self.softmax[i] = exp_prediction[i]/np.sum(exp_prediction[i])
return self.softmax
if __name__ == "__main__":
img = np.ones((1, 28, 28, 1))
conv1 = Conv2D(img.shape, 3, 3, 1)
layer1 = conv1.forward(img)
assert layer1.shape == (1, 26, 26, 3)
print('The shape of conv1 layer is:', layer1.shape)
relu1 = Relu(layer1.shape)
layer2 = relu1.forward(layer1)
assert layer2.shape == (1, 26, 26, 3)
print('The shape of relu1 layer is:', layer2.shape)
maxpooling1 = MaxPooling(layer2.shape, 2, 2)
layer3 = maxpooling1.forward(layer2)
assert layer3.shape == (1, 13, 13, 3)
print('The shape of maxpooling1 layer is:', layer3.shape)
conv2 = Conv2D(layer3.shape, 5, 4, 1)
layer4 = conv2.forward(layer3)
assert layer4.shape == (1, 10, 10, 5)
print('The shape of conv2 layer is:', layer4.shape)
relu2 = Relu(layer4.shape)
layer5 = relu1.forward(layer4)
assert layer5.shape == (1, 10, 10, 5)
print('The shape of relu2 layer is:', layer5.shape)
maxpooling2 = MaxPooling(layer5.shape, 2, 2)
layer6 = maxpooling2.forward(layer5)
assert layer6.shape == (1, 5, 5, 5)
print('The shape of maxpooling2 layer is:', layer6.shape)
dense1 = DenselyConnect(layer6.shape, 125)
layer7 = dense1.forward(layer6)
assert layer7.shape == (1, 125)
print('The shape of flaten layer is:', layer7.shape)
dense2 = DenselyConnect(layer7.shape, 10)
layer8 = dense2.forward(layer7)
assert layer8.shape == (1, 10)
print('The shape of output layer is:', layer8.shape)
softmax = Softmax(layer8.shape)
layer9 = softmax.predict(layer8)
assert layer9.shape == (1, 10)
print('The shape of softmax layer is:', layer9.shape)
img = np.array([[-11, 4, 1, -1, 12, 9],
[1, -4, 3, 0, 1, 10],
[9, 2, -5, -7, -10, -8],
[8, -2, 1, -11, -5, 7],
[-5, 0, -5, -1, -5, 3],
[-8, 2, 6, 5, -3, -4]])
img = np.pad(img, (1,1), 'reflect')
print(img)
img = img.reshape(1, 8, 8, 1)
conv = Conv2D(img.shape, 1, 3, 1)
conv.weights = np.array([[2,8,11],
[-7,-6,-6],
[1,-9,-11]])
conv.weights = conv.weights.reshape(3,3,1,1)
print(conv.weights.shape)
output = conv.forward(img)
print(output)
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,169
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Data Structure and Algorithms/K Closest Points to Origin.py
|
# We have a list of points on the plane.
# Find the K closest points to the origin (0, 0).
def kClosest(points, K):
def cal_square_dis(point):
return point[0] ** 2 + point[1] ** 2
square_dis = [cal_square_dis(point) for point in points]
max_heap = [i for i in range(K)]
curr_max = max([square_dis[i] for i in max_heap])
curr_max_idx = square_dis.index(curr_max)
for i in range(K, len(points)):
if square_dis[i] < curr_max:
max_heap = [i for i in max_heap if i != curr_max_idx]
max_heap.append(i)
curr_max = max([square_dis[j] for j in max_heap])
curr_max_idx = square_dis.index(curr_max)
return [points[i] for i in max_heap]
# faster version:
def kClosest(points, K):
def cal_square_dis(point):
return point[0] ** 2 + point[1] ** 2
square_dis = [cal_square_dis(point) for point in points]
max_heap = [i for i in range(K)]
curr_max = max([square_dis[i] for i in max_heap])
curr_max_idx = square_dis.index(curr_max)
curr_max_idx_heap = max_heap.index(curr_max_idx)
for i in range(K, len(points)):
if square_dis[i] < curr_max:
max_heap[curr_max_idx_heap] = i
curr_max = max([square_dis[i] for i in max_heap])
curr_max_idx = square_dis.index(curr_max)
curr_max_idx_heap = max_heap.index(curr_max_idx)
return [points[i] for i in max_heap]
# sort version(much faster):
def kClosest(points, K):
def cal_square_dis(point):
return point[0] ** 2 + point[1] ** 2
square_dis = [cal_square_dis(point) for point in points]
hash_dic = dict((key, value) for key, value in
zip(list(range(len(points))), square_dis))
sorted_dic = sorted(hash_dic.items(), key=lambda x: x[1])
index_k = [sorted_dic[k][0] for k in range(K)]
return [points[k] for k in index_k]
kClosest([[-95,76],[17,7],[-55,-58],[53,20],[-69,-8],[-57,87],[-2,-42],
[-10,-87],[-36,-57],[97,-39],[97,49]],5)
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,170
|
Cedric-Liu/Coding-Journal
|
refs/heads/master
|
/Data Structure and Algorithms/First Unique Character in a String.py
|
#Given a string, find the first non-repeating character in
# it and return it's index. If it doesn't exist, return -1.
def firstUniqChar(s: str) -> int:
if not s:
return -1
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
distinct = list(filter(lambda x: count[x] == 1, [key for key, value in
zip(count.keys(),
count.values())]))
if not distinct:
return -1
return min([s.find(item) for item in distinct])
firstUniqChar("leetcode")
|
{"/Text Analysis and GCP Deployment/music1030/fuzzy_test.py": ["/Text Analysis and GCP Deployment/music1030/fuzzy.py"], "/Text Analysis and GCP Deployment/music1030/billboard_test.py": ["/Text Analysis and GCP Deployment/music1030/billboard.py"]}
|
20,183
|
annabjorgo/keypad
|
refs/heads/master
|
/kpc_agent.py
|
import keypad
import led_board
from led_board import Led_board
import rule
import GPIOSimulator_v5
class Agent:
"""Random doc:)"""
def __init__(self):
self.keypad = keypad.KeyPad()
self.led_board = Led_board()
self.pathname = 'password.txt'
self.override_signal = None
self.cump = ''
self.led_num = ''
self.led_dur = ''
def append_digit(self, digit):
self.cump += digit
print('Cumulative password: {}'.format(self.cump))
def read_password(self, *_):
""" Reads and returns password from file """
with open(self.pathname, 'r') as password_file:
return password_file.readline().rstrip('\n')
def reset_passcode_entry(self, *_):
"""Clear the passcode-buffer and initiate a “power up” lighting sequence on the LED Board."""
# Method is called when user tries to log in and when user tries to change password
self.cump = ''
self.led_board.powering_up()
print('Enter password')
def reset_passcode_entry2(self, *_):
"""Clear the passcode-buffer and initiate a “power up” lighting sequence on the LED Board."""
# Method is called when user tries to log in and when user tries to change password
self.cump = ''
self.led_board.powering_up()
print('Enter new password')
def get_next_signal(self, *_):
if self.override_signal is not None:
sig = self.override_signal
self.override_signal = None
return sig
else:
# query the keypad for the next pressed key
return self.keypad.get_next_signal()
def verify_login(self, *_):
"""Check that the password just entered via the keypad matches that in the
password file. Store the result (Y or N) in the override signal. Also, this should call the
LED Board to initiate the appropriate lighting pattern for login success or failure."""
# Not implemented yet
current_password = self.read_password()
if self.cump == current_password:
self.twinkle_leds()
print('Correct password')
self.override_signal = 'Y'
else:
self.flash_leds()
print('Wrong password')
self.override_signal = 'N'
self.cump = ''
def validate_passcode_change(self, *_):
""" Check that the new password is legal. If so, write the new
password in the password file. A legal password should be at least 4 digits long and should
contain no symbols other than the digits 0-9. As in verify login, this should use the LED
Board to signal success or failure in changing the password."""
if self.cump.isdigit() and len(self.cump) >= 4:
with open(self.pathname, 'w') as password_file:
password_file.write(self.cump)
self.twinkle_leds()
print('New password saved')
else:
self.flash_leds()
print('Password must be at least 4 digits and only digits 0-9')
def select_led(self, led_digit):
print('Led {} is selected'.format(led_digit))
self.led_num = led_digit
def reset_duration(self, *_):
print('Enter duration')
self.led_dur = ''
def add_duration_digit(self, digit):
self.led_dur += digit
print('Current duration: {}'.format(self.led_dur))
def logout1(self, *_):
print('Press # again to log out')
def light_one_led(self, *_):
""" Using values stored in the Lid and Ldur slots, call the LED Board and
request that LED # Lid be turned on for Ldur seconds"""
self.led_board.light_led(self.led_num, self.led_dur)
def flash_leds(self):
"""Call the LED Board and request the flashing of all LEDs."""
self.led_board.flash_all_leds(1)
def twinkle_leds(self):
"""Call the LED Board and request the twinkling of all LEDs."""
self.led_board.twinkle_all_leds(1)
def exit_action(self, *_):
"""Call the LED Board to initiate the “power down” lighting sequence."""
self.led_board.powering_down()
print('Logging out.')
def d_function(self, *_):
"""Dummy function"""
pass
|
{"/kpc_agent.py": ["/keypad.py", "/led_board.py", "/rule.py"], "/fsm.py": ["/kpc_agent.py", "/rule.py"]}
|
20,184
|
annabjorgo/keypad
|
refs/heads/master
|
/fsm.py
|
from kpc_agent import Agent
from rule import Rule
class FSM():
"""The Finite State Machine"""
def __init__(self):
"""The FSM begins in state S-Init"""
self.state = "S-init"
self.agent = Agent()
self.fsm_rule_list = [
Rule('S-init', 'S-read', signal_is_any_symbol, self.agent.reset_passcode_entry), # Initializing
Rule('S-read', 'S-read', signal_is_digit, self.agent.append_digit), # Reads digit
Rule('S-read', 'S-verify', '*', self.agent.verify_login), # Request for verification
Rule('S-verify', 'S-active', 'Y', self.agent.d_function), # Password accepted
Rule('S-verify', 'S-init', 'N', self.agent.d_function), # Password not accecpted
Rule('S-active', 'S-read-2', '*', self.agent.reset_passcode_entry2), # Attempt to change password
Rule('S-read-2', 'S-read-2', signal_is_digit, self.agent.append_digit), # Reads digit
Rule('S-read-2', 'S-active', '*', self.agent.validate_passcode_change), # Validates new password
Rule('S-active', 'S-led', signal_is_valid_led, self.agent.select_led), # Selects a led
Rule('S-led', 'S-time', '*', self.agent.reset_duration), # Resets duration
Rule('S-time', 'S-time', signal_is_digit, self.agent.add_duration_digit), # Adds digit to duration
Rule('S-time', 'S-active', '*', self.agent.light_one_led), # Light chosen led for "duration" time
Rule('S-active', 'S-logout', '#', self.agent.logout1), # Start logout process
Rule('S-logout', 'S-final', '#', self.agent.exit_action) # Finish logout process
]
def add_rule(self, rule):
"""Add a new rule to the end of the FSM’s rule list"""
self.fsm_rule_list.append(rule)
def get_next_signal(self):
"""Query the agent for the next signal"""
return self.agent.get_next_signal()
def run(self):
"""Begin in the FSM’s default initial state and then repeatedly call get next signal and
run the rules one by one until reaching the final state"""
self.set_state('S-init')
while self.state != 'S-final':
print(self.state)
next_signal = self.get_next_signal()
for rule in self.fsm_rule_list:
if rule.match(self.state, next_signal):
rule.fire(self, next_signal)
break
def set_state(self, state):
self.state = state
def get_agent(self):
return self.agent
def signal_is_digit(signal): return 48 <= ord(signal) <= 57
def signal_is_any_symbol(*_): return True
def signal_is_valid_led(signal): return 48 <= ord(signal) <= 54
def main():
"""The main function for keypad for testing purposes"""
fsm = FSM()
fsm.run()
if __name__ == "__main__":
main()
|
{"/kpc_agent.py": ["/keypad.py", "/led_board.py", "/rule.py"], "/fsm.py": ["/kpc_agent.py", "/rule.py"]}
|
20,185
|
annabjorgo/keypad
|
refs/heads/master
|
/led_board.py
|
from GPIOSimulator_v5 import *
import time
GPIO = GPIOSimulator()
class Led_board:
""" A charliplexed circuit with 6 leds and 3 pins"""
def setup(self):
GPIO.cleanup()
GPIO.setup(PIN_CHARLIEPLEXING_0, GPIO.IN, state=GPIO.LOW)
GPIO.setup(PIN_CHARLIEPLEXING_1, GPIO.IN, state=GPIO.LOW)
GPIO.setup(PIN_CHARLIEPLEXING_2, GPIO.IN, state=GPIO.LOW)
def light_led(self, led_num, duration_wait=0):
"""Turn on one of the 6 LEDs by making the appropriate combination of input
and output declarations, and then making the appropriate HIGH / LOW settings on the
output pins."""
led_num = int(led_num)
self.setup()
if led_num == 0:
GPIO.setup(PIN_CHARLIEPLEXING_0, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_1, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_0, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 0 on')
elif led_num == 1:
GPIO.setup(PIN_CHARLIEPLEXING_0, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_1, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_1, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 1 on')
elif led_num == 2:
GPIO.setup(PIN_CHARLIEPLEXING_1, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_2, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_1, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 2 on')
elif led_num == 3:
GPIO.setup(PIN_CHARLIEPLEXING_1, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_2, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_2, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 4 on')
elif led_num == 4:
GPIO.setup(PIN_CHARLIEPLEXING_0, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_2, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_0, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 5 on')
elif led_num == 5:
GPIO.setup(PIN_CHARLIEPLEXING_0, GPIO.OUT)
GPIO.setup(PIN_CHARLIEPLEXING_2, GPIO.OUT)
GPIO.output(PIN_CHARLIEPLEXING_2, GPIO.HIGH)
GPIO.show_leds_states()
print('Led 5 on')
time.sleep(int(duration_wait))
print('Led off')
def flash_all_leds(self, k):
"""Flash all 6 LEDs on and off for k seconds, where k is an argument of the
method."""
print("Flashing")
for i in range(6):
self.light_led(i, k / 6)
time.sleep(k / 6)
print("------------------------")
def twinkle_all_leds(self, k):
"""Turn all LEDs on and off in sequence for k seconds, where k is an
argument of the method."""
start_t = time.time()
print("Twinkling")
while time.time() - start_t < k:
for i in range(6):
self.light_led(i, 0.5)
GPIO.show_leds_states()
print("--------")
def powering_up(self):
""" Light show for startup """
print("Powering up")
self.light_led(3, 0.1)
self.light_led(4, 0.1)
self.light_led(5, 0.1)
print("--------")
def powering_down(self):
""" Light show for shutdown """
self.light_led(0, 0.1)
self.light_led(1, 0.1)
self.light_led(2, 0.1)
print("--------")
def main():
led_board = Led_board()
led_board.twinkle_all_leds(4)
if __name__ == '__main__':
main()
|
{"/kpc_agent.py": ["/keypad.py", "/led_board.py", "/rule.py"], "/fsm.py": ["/kpc_agent.py", "/rule.py"]}
|
20,186
|
annabjorgo/keypad
|
refs/heads/master
|
/keypad.py
|
import sys
from GPIOSimulator_v5 import *
import time
GPIO = GPIOSimulator()
class KeyPad:
key_coord = {(3, 7): '1', (3, 8): '2', (3, 9): '3',
(4, 7): '4', (4, 8): '5', (4, 9): '6',
(5, 7): '7', (5, 8): '8', (5, 9): '9',
(6, 7): '*', (6, 8): '0', (6, 9): '#'}
def setup(self):
"""initialize the row pins as outputs and the column pins as inputs."""
GPIO.setup(PIN_KEYPAD_ROW_0, GPIO.OUT)
GPIO.setup(PIN_KEYPAD_ROW_1, GPIO.OUT)
GPIO.setup(PIN_KEYPAD_ROW_2, GPIO.OUT)
GPIO.setup(PIN_KEYPAD_ROW_3, GPIO.OUT)
GPIO.setup(PIN_KEYPAD_COL_0, GPIO.IN, state=GPIO.LOW)
GPIO.setup(PIN_KEYPAD_COL_1, GPIO.IN, state=GPIO.LOW)
GPIO.setup(PIN_KEYPAD_COL_2, GPIO.IN, state=GPIO.LOW)
def do_polling(self):
"""Use nested loops (discussed above) to determine the key currently being
pressed on the keypad."""
time.sleep(0.3) # kan endre på antall sekunder
for row_pin in keypad_row_pins:
GPIO.output(row_pin, GPIO.HIGH)
for col_pin in keypad_col_pins:
high = GPIO.input(col_pin)
if high == GPIO.HIGH:
# Hvis den kommer inn i denne if-en, så betyr det at denne knappen (rad, kolonne) er trykket ned
return (row_pin, col_pin)
GPIO.output(row_pin, GPIO.LOW)
return None
def get_next_signal(self):
"""This is the main interface between the agent and the keypad. It should
initiate repeated calls to do polling until a key press is detected."""
self.setup()
while True:
poll = self.do_polling()
if poll is not None:
GPIO.cleanup()
break
return self.key_coord.get(poll)
def main():
"""The main function for keypad for testing purposes"""
keypad = KeyPad()
keypad.setup()
signal = keypad.get_next_signal()
print(f"sigalet er {signal}")
GPIO.cleanup()
if __name__ == "__main__":
main()
|
{"/kpc_agent.py": ["/keypad.py", "/led_board.py", "/rule.py"], "/fsm.py": ["/kpc_agent.py", "/rule.py"]}
|
20,187
|
annabjorgo/keypad
|
refs/heads/master
|
/rule.py
|
import inspect
from inspect import isfunction
class Rule():
def __init__(self, state1, state2, signal, action):
"""State1 og state2 are strings. Action is a function that tells the agent what to do.
Signal can be a symbol or a function that takes in a symbol and returns true if the symbol is valid for the rule"""
self.state1 = state1
self.state2 = state2
self.signal = signal
self.action = action
def match(self, state, sig):
"""Check whether the rule condition is fulfilled"""
if (inspect.isfunction(self.signal) and self.signal(sig)) or (sig == self.signal):
if state == self.state1:
return True
def fire(self, fsm, sig):
"""Use the consequent of a rule to a) set the next state of the FSM, and b)
call the appropriate agent action method."""
fsm.set_state(self.state2)
self.action(sig)
def __str__(self):
return "state1: {}, signal: {}, state2: {}".format(self.state1, self.signal, self.state2)
|
{"/kpc_agent.py": ["/keypad.py", "/led_board.py", "/rule.py"], "/fsm.py": ["/kpc_agent.py", "/rule.py"]}
|
20,192
|
DevinDeSilva/BookLibrary
|
refs/heads/main
|
/Library/models.py
|
import os
import re
from django.conf import settings
# Create your models here.
def getBooks(search_str, search_by):
books = readTxt(search_str, search_by)
print("get books")
return books
def addBook(title, author, genre, height, publication, file_name='books_list.txt',
data_dir=os.path.join(settings.BASE_DIR, 'Library\\data')):
data_file = open(os.path.join(data_dir, file_name), "a+")
data_file.write(f"\n{','.join([title, author, genre, height, publication])}")
data_file.close()
print("addBook")
def deleteBook(title, file_name='books_list.txt',
data_dir=os.path.join(settings.BASE_DIR, 'Library\\data')):
data_file = open(os.path.join(data_dir, file_name), "r+")
lines = []
while data_file:
line = data_file.readline()
if line == "":
break
data = text_to_dic(line)
if data['title'] == title:
continue
lines.append(line)
data_file.truncate(0)
total_text = "".join(lines)
total_text = total_text[:-1] if total_text[-1] == '\n' else total_text
print(total_text)
data_file.write(total_text)
data_file.close()
print("deleteBook")
def text_to_dic(line):
list_data = line.split(",")
if len(list_data) == 5:
dic_data = {
"title": list_data[0],
"author": list_data[1],
"genre": list_data[2],
"height": list_data[3],
"publisher": list_data[4][:-1] if list_data[4][-1] == '\n' else list_data[4],
}
return dic_data
if len(list_data) == 6:
dic_data = {
"title": list_data[0],
"author": ','.join([list_data[1], list_data[2]]),
"genre": list_data[3],
"height": list_data[4],
"publisher":list_data[5][:-1] if list_data[5][-1] == '\n' else list_data[5],
}
return dic_data
if len(list_data) == 7:
dic_data = {
"title": ','.join([list_data[0], list_data[1]]),
"author": ','.join([list_data[2], list_data[3]]),
"genre": list_data[4],
"height": list_data[5],
"publisher": list_data[6][:-1] if list_data[6][-1] == '\n' else list_data[6],
}
return dic_data
def readTxt(search_str, search_by, file_name='books_list.txt',
data_dir=os.path.join(settings.BASE_DIR, 'Library\\data')):
data_file = open(os.path.join(data_dir, file_name), "r")
books = []
while data_file:
line = data_file.readline()
print(line)
if line == "":
break
data = text_to_dic(line)
if data['title'] == 'Title':
continue
if search_str is not None and search_by is not None:
if search_by == "name":
search_key = 'title'
else:
search_key = 'genre'
reg_result = re.match(f'({search_str[:-1]})\w+', data[search_key], re.IGNORECASE)
if not reg_result:
data = None
if data is not None:
books.append(data)
data_file.close()
return books
|
{"/Library/views.py": ["/Library/forms/RegisterBookForm.py", "/Library/forms/DeleteBookForm.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.