code
stringlengths 20
13.2k
| label
stringlengths 21
6.26k
|
---|---|
1 def removeChars(str, n):
2 return str[n:]
3
4 print("pynative")
5 n = int(input("Enter the removing number: "))
6 print(removeChars("pynative", n))
| 2 - warning: bad-indentation
1 - warning: redefined-builtin
1 - warning: redefined-outer-name
|
1 import pyautogui
2 import time
3 message = 100
4 while message > 0:
5 time.sleep(0)
6 pyautogui.typewrite('Hi BC!!!')
7 pyautogui.press('enter')
8 message = message - 1 | Clean Code: No Issues Detected
|
1 def divisible(numl):
2 print("Given List is ",numl)
3 print("Divisible of 5 in a list ")
4 for num in numl :
5 if (num % 5 == 0):
6 print(num)
7
8 numl = [10, 15, 12, 17, 20]
9 divisible(numl) | 1 - warning: redefined-outer-name
|
1
2
3 n = int(input("Enter the last number: "))
4 sum = 0
5 for x in range(2,n+2,2):
6 sum = sum+x*x
7 print(sum) | 4 - warning: redefined-builtin
|
1 roll = [101,102,103,104,105,106]
2 name = ["Alex Biswas", "Sabuj Chandra Das", "Ahad Islam Moeen", "Sonia Akter", "Mariam Akter", "Sajib Das"]
3
4 print(list(zip(roll,name)))
5 print(list(zip(roll,name,"ABCDEF"))) | Clean Code: No Issues Detected
|
1 import torch
2 from torchvision import transforms
3 from ops import relu_x_1_style_decorator_transform, relu_x_1_transform
4 from PIL import Image
5 import os
6
7
8 def eval_transform(size):
9 return transforms.Compose([
10 transforms.Resize(size),
11 transforms.ToTensor()
12 ])
13
14
15 def load_image(path):
16 return Image.open(path).convert('RGB')
17
18
19 def preprocess(img, size):
20 transform = eval_transform(size)
21 return transform(img).unsqueeze(0)
22
23
24 def deprocess(tensor):
25 tensor = tensor.cpu()
26 tensor = tensor.squeeze(0)
27 tensor = torch.clamp(tensor, 0, 1)
28 return transforms.ToPILImage()(tensor)
29
30
31 def extract_image_names(path):
32 r_ = []
33 valid_ext = ['.jpg', '.png']
34
35 items = os.listdir(path)
36
37 for item in items:
38 item_path = os.path.join(path, item)
39
40 _, ext = os.path.splitext(item_path)
41 if ext not in valid_ext:
42 continue
43
44 r_.append(item_path)
45
46 return r_
| 3 - warning: unused-import
3 - warning: unused-import
|
1 import torch
2 import torch.nn.functional as F
3
4
5 def extract_image_patches_(image, kernel_size, strides):
6 kh, kw = kernel_size
7 sh, sw = strides
8 patches = image.unfold(2, kh, sh).unfold(3, kw, sw)
9 patches = patches.permute(0, 2, 3, 1, 4, 5)
10 patches = patches.reshape(-1, *patches.shape[-3:]) # (patch_numbers, C, kh, kw)
11 return patches
12
13
14 def style_swap(c_features, s_features, kernel_size, stride=1):
15
16 s_patches = extract_image_patches_(s_features, [kernel_size, kernel_size], [stride, stride])
17 s_patches_matrix = s_patches.reshape(s_patches.shape[0], -1)
18 s_patch_wise_norm = torch.norm(s_patches_matrix, dim=1)
19 s_patch_wise_norm = s_patch_wise_norm.reshape(-1, 1, 1, 1)
20 s_patches_normalized = s_patches / (s_patch_wise_norm + 1e-8)
21 # Computes the normalized cross-correlations.
22 # At each spatial location, "K" is a vector of cross-correlations
23 # between a content activation patch and all style activation patches.
24 K = F.conv2d(c_features, s_patches_normalized, stride=stride)
25 # Replace each vector "K" by a one-hot vector corresponding
26 # to the best matching style activation patch.
27 best_matching_idx = K.argmax(1, keepdim=True)
28 one_hot = torch.zeros_like(K)
29 one_hot.scatter_(1, best_matching_idx, 1)
30 # At each spatial location, only the best matching style
31 # activation patch is in the output, as the other patches
32 # are multiplied by zero.
33 F_ss = F.conv_transpose2d(one_hot, s_patches, stride=stride)
34 overlap = F.conv_transpose2d(one_hot, torch.ones_like(s_patches), stride=stride)
35 F_ss = F_ss / overlap
36 return F_ss
37
38
39 def relu_x_1_transform(c, s, encoder, decoder, relu_target, alpha=1):
40 c_latent = encoder(c, relu_target)
41 s_latent = encoder(s, relu_target)
42 t_features = wct(c_latent, s_latent, alpha)
43 return decoder(t_features)
44
45
46 def relu_x_1_style_decorator_transform(c, s, encoder, decoder, relu_target, kernel_size, stride=1, alpha=1):
47 c_latent = encoder(c, relu_target)
48 s_latent = encoder(s, relu_target)
49 t_features = style_decorator(c_latent, s_latent, kernel_size, stride, alpha)
50 return decoder(t_features)
51
52
53 def style_decorator(cf, sf, kernel_size, stride=1, alpha=1):
54 cf_shape = cf.shape
55 sf_shape = sf.shape
56
57 b, c, h, w = cf_shape
58 cf_vectorized = cf.reshape(c, h * w)
59
60 b, c, h, w = sf.shape
61 sf_vectorized = sf.reshape(c, h * w)
62
63 # map features to normalized domain
64 cf_whiten = whitening(cf_vectorized)
65 sf_whiten = whitening(sf_vectorized)
66
67 # in this normalized domain, we want to align
68 # any element in cf with the nearest element in sf
69 reassembling_f = style_swap(
70 cf_whiten.reshape(cf_shape),
71 sf_whiten.reshape(sf_shape),
72 kernel_size, stride
73 )
74
75 b, c, h, w = reassembling_f.shape
76 reassembling_vectorized = reassembling_f.reshape(c, h*w)
77 # reconstruct reassembling features into the
78 # domain of the style features
79 result = coloring(reassembling_vectorized, sf_vectorized)
80 result = result.reshape(cf_shape)
81
82 bland = alpha * result + (1 - alpha) * cf
83 return bland
84
85
86 def wct(cf, sf, alpha=1):
87 cf_shape = cf.shape
88
89 b, c, h, w = cf_shape
90 cf_vectorized = cf.reshape(c, h*w)
91
92 b, c, h, w = sf.shape
93 sf_vectorized = sf.reshape(c, h*w)
94
95 cf_transformed = whitening(cf_vectorized)
96 cf_transformed = coloring(cf_transformed, sf_vectorized)
97
98 cf_transformed = cf_transformed.reshape(cf_shape)
99
100 bland = alpha * cf_transformed + (1 - alpha) * cf
101 return bland
102
103
104 def feature_decomposition(x):
105 x_mean = x.mean(1, keepdims=True)
106 x_center = x - x_mean
107 x_cov = x_center.mm(x_center.t()) / (x_center.size(1) - 1)
108
109 e, d, _ = torch.svd(x_cov)
110 d = d[d > 0]
111 e = e[:, :d.size(0)]
112
113 return e, d, x_center, x_mean
114
115
116 def whitening(x):
117 e, d, x_center, _ = feature_decomposition(x)
118
119 transform_matrix = e.mm(torch.diag(d ** -0.5)).mm(e.t())
120 return transform_matrix.mm(x_center)
121
122
123 def coloring(x, y):
124 e, d, _, y_mean = feature_decomposition(y)
125
126 transform_matrix = e.mm(torch.diag(d ** 0.5)).mm(e.t())
127 return transform_matrix.mm(x) + y_mean
| 24 - error: not-callable
33 - error: not-callable
34 - error: not-callable
39 - refactor: too-many-arguments
39 - refactor: too-many-positional-arguments
46 - refactor: too-many-arguments
46 - refactor: too-many-positional-arguments
53 - refactor: too-many-locals
57 - warning: unused-variable
89 - warning: unused-variable
|
1 import torch
2 from models import NormalisedVGG, Decoder
3 from utils import load_image, preprocess, deprocess, extract_image_names
4 from ops import style_decorator, wct
5 import argparse
6 import os
7
8
9 parser = argparse.ArgumentParser(description='WCT')
10
11 parser.add_argument('--content-path', type=str, help='path to the content image')
12 parser.add_argument('--style-path', type=str, help='path to the style image')
13 parser.add_argument('--content-dir', type=str, help='path to the content image folder')
14 parser.add_argument('--style-dir', type=str, help='path to the style image folder')
15
16 parser.add_argument('--style-decorator', type=int, default=1)
17 parser.add_argument('--kernel-size', type=int, default=12)
18 parser.add_argument('--stride', type=int, default=1)
19 parser.add_argument('--alpha', type=float, default=0.8)
20 parser.add_argument('--ss-alpha', type=float, default=0.6)
21 parser.add_argument('--synthesis', type=int, default=0, help='0-transfer, 1-synthesis')
22
23 parser.add_argument('--encoder-path', type=str, default='encoder/vgg_normalised_conv5_1.pth')
24 parser.add_argument('--decoders-dir', type=str, default='decoders')
25
26 parser.add_argument('--save-dir', type=str, default='./results')
27 parser.add_argument('--save-name', type=str, default='result', help='save name for single output image')
28 parser.add_argument('--save-ext', type=str, default='jpg', help='The extension name of the output image')
29
30 parser.add_argument('--content-size', type=int, default=768, help='New (minimum) size for the content image')
31 parser.add_argument('--style-size', type=int, default=768, help='New (minimum) size for the style image')
32 parser.add_argument('--gpu', type=int, default=0, help='ID of the GPU to use; for CPU mode set --gpu = -1')
33
34 args = parser.parse_args()
35
36 assert args.content_path is not None or args.content_dir is not None, \
37 'Either --content-path or --content-dir should be given.'
38 assert args.style_path is not None or args.style_dir is not None, \
39 'Either --style-path or --style-dir should be given.'
40
41 device = torch.device('cuda:%s' % args.gpu if torch.cuda.is_available() and args.gpu != -1 else 'cpu')
42
43 encoder = NormalisedVGG(pretrained_path=args.encoder_path).to(device)
44 d5 = Decoder('relu5_1', pretrained_path=os.path.join(args.decoders_dir, 'd5.pth')).to(device)
45 d4 = Decoder('relu4_1', pretrained_path=os.path.join(args.decoders_dir, 'd4.pth')).to(device)
46 d3 = Decoder('relu3_1', pretrained_path=os.path.join(args.decoders_dir, 'd3.pth')).to(device)
47 d2 = Decoder('relu2_1', pretrained_path=os.path.join(args.decoders_dir, 'd2.pth')).to(device)
48 d1 = Decoder('relu1_1', pretrained_path=os.path.join(args.decoders_dir, 'd1.pth')).to(device)
49
50
51 def style_transfer(content, style):
52
53 if args.style_decorator:
54 relu5_1_cf = encoder(content, 'relu5_1')
55 relu5_1_sf = encoder(style, 'relu5_1')
56 relu5_1_scf = style_decorator(relu5_1_cf, relu5_1_sf, args.kernel_size, args.stride, args.ss_alpha)
57 relu5_1_recons = d5(relu5_1_scf)
58 else:
59 relu5_1_cf = encoder(content, 'relu5_1')
60 relu5_1_sf = encoder(style, 'relu5_1')
61 relu5_1_scf = wct(relu5_1_cf, relu5_1_sf, args.alpha)
62 relu5_1_recons = d5(relu5_1_scf)
63
64 relu4_1_cf = encoder(relu5_1_recons, 'relu4_1')
65 relu4_1_sf = encoder(style, 'relu4_1')
66 relu4_1_scf = wct(relu4_1_cf, relu4_1_sf, args.alpha)
67 relu4_1_recons = d4(relu4_1_scf)
68
69 relu3_1_cf = encoder(relu4_1_recons, 'relu3_1')
70 relu3_1_sf = encoder(style, 'relu3_1')
71 relu3_1_scf = wct(relu3_1_cf, relu3_1_sf, args.alpha)
72 relu3_1_recons = d3(relu3_1_scf)
73
74 relu2_1_cf = encoder(relu3_1_recons, 'relu2_1')
75 relu2_1_sf = encoder(style, 'relu2_1')
76 relu2_1_scf = wct(relu2_1_cf, relu2_1_sf, args.alpha)
77 relu2_1_recons = d2(relu2_1_scf)
78
79 relu1_1_cf = encoder(relu2_1_recons, 'relu1_1')
80 relu1_1_sf = encoder(style, 'relu1_1')
81 relu1_1_scf = wct(relu1_1_cf, relu1_1_sf, args.alpha)
82 relu1_1_recons = d1(relu1_1_scf)
83
84 return relu1_1_recons
85
86
87 if not os.path.exists(args.save_dir):
88 print('Creating save folder at', args.save_dir)
89 os.mkdir(args.save_dir)
90
91 content_paths = []
92 style_paths = []
93
94 if args.content_dir:
95 # use a batch of content images
96 content_paths = extract_image_names(args.content_dir)
97 else:
98 # use a single content image
99 content_paths.append(args.content_path)
100
101 if args.style_dir:
102 # use a batch of style images
103 style_paths = extract_image_names(args.style_dir)
104 else:
105 # use a single style image
106 style_paths.append(args.style_path)
107
108 print('Number content images:', len(content_paths))
109 print('Number style images:', len(style_paths))
110
111 with torch.no_grad():
112
113 for i in range(len(content_paths)):
114 content = load_image(content_paths[i])
115 content = preprocess(content, args.content_size)
116 content = content.to(device)
117
118 for j in range(len(style_paths)):
119 style = load_image(style_paths[j])
120 style = preprocess(style, args.style_size)
121 style = style.to(device)
122
123 if args.synthesis == 0:
124 output = style_transfer(content, style)
125 output = deprocess(output)
126
127 if len(content_paths) == 1 and len(style_paths) == 1:
128 # used a single content and style image
129 save_path = '%s/%s.%s' % (args.save_dir, args.save_name, args.save_ext)
130 else:
131 # used a batch of content and style images
132 save_path = '%s/%s_%s.%s' % (args.save_dir, i, j, args.save_ext)
133
134 print('Output image saved at:', save_path)
135 output.save(save_path)
136 else:
137 content = torch.rand(*content.shape).uniform_(0, 1).to(device)
138 for iteration in range(3):
139 output = style_transfer(content, style)
140 content = output
141 output = deprocess(output)
142
143 if len(content_paths) == 1 and len(style_paths) == 1:
144 # used a single content and style image
145 save_path = '%s/%s_%s.%s' % (args.save_dir, args.save_name, iteration, args.save_ext)
146 else:
147 # used a batch of content and style images
148 save_path = '%s/%s_%s_%s.%s' % (args.save_dir, i, j, iteration, args.save_ext)
149
150 print('Output image saved at:', save_path)
151 output.save(save_path)
| 51 - refactor: too-many-locals
51 - warning: redefined-outer-name
51 - warning: redefined-outer-name
|
1 import torch
2 import torch.nn as nn
3 import copy
4
5
6 normalised_vgg_relu5_1 = nn.Sequential(
7 nn.Conv2d(3, 3, 1),
8 nn.ReflectionPad2d((1, 1, 1, 1)),
9 nn.Conv2d(3, 64, 3),
10 nn.ReLU(),
11 nn.ReflectionPad2d((1, 1, 1, 1)),
12 nn.Conv2d(64, 64, 3),
13 nn.ReLU(),
14 nn.MaxPool2d(2, ceil_mode=True),
15 nn.ReflectionPad2d((1, 1, 1, 1)),
16 nn.Conv2d(64, 128, 3),
17 nn.ReLU(),
18 nn.ReflectionPad2d((1, 1, 1, 1)),
19 nn.Conv2d(128, 128, 3),
20 nn.ReLU(),
21 nn.MaxPool2d(2, ceil_mode=True),
22 nn.ReflectionPad2d((1, 1, 1, 1)),
23 nn.Conv2d(128, 256, 3),
24 nn.ReLU(),
25 nn.ReflectionPad2d((1, 1, 1, 1)),
26 nn.Conv2d(256, 256, 3),
27 nn.ReLU(),
28 nn.ReflectionPad2d((1, 1, 1, 1)),
29 nn.Conv2d(256, 256, 3),
30 nn.ReLU(),
31 nn.ReflectionPad2d((1, 1, 1, 1)),
32 nn.Conv2d(256, 256, 3),
33 nn.ReLU(),
34 nn.MaxPool2d(2, ceil_mode=True),
35 nn.ReflectionPad2d((1, 1, 1, 1)),
36 nn.Conv2d(256, 512, 3),
37 nn.ReLU(),
38 nn.ReflectionPad2d((1, 1, 1, 1)),
39 nn.Conv2d(512, 512, 3),
40 nn.ReLU(),
41 nn.ReflectionPad2d((1, 1, 1, 1)),
42 nn.Conv2d(512, 512, 3),
43 nn.ReLU(),
44 nn.ReflectionPad2d((1, 1, 1, 1)),
45 nn.Conv2d(512, 512, 3),
46 nn.ReLU(),
47 nn.MaxPool2d(2, ceil_mode=True),
48 nn.ReflectionPad2d((1, 1, 1, 1)),
49 nn.Conv2d(512, 512, 3),
50 nn.ReLU()
51 )
52
53
54 class NormalisedVGG(nn.Module):
55
56 def __init__(self, pretrained_path=None):
57 super().__init__()
58 self.net = normalised_vgg_relu5_1
59 if pretrained_path is not None:
60 self.net.load_state_dict(torch.load(pretrained_path, map_location=lambda storage, loc: storage))
61
62 def forward(self, x, target):
63 if target == 'relu1_1':
64 return self.net[:4](x)
65 elif target == 'relu2_1':
66 return self.net[:11](x)
67 elif target == 'relu3_1':
68 return self.net[:18](x)
69 elif target == 'relu4_1':
70 return self.net[:31](x)
71 elif target == 'relu5_1':
72 return self.net(x)
73
74
75 vgg_decoder_relu5_1 = nn.Sequential(
76 nn.ReflectionPad2d((1, 1, 1, 1)),
77 nn.Conv2d(512, 512, 3),
78 nn.ReLU(),
79 nn.Upsample(scale_factor=2),
80 nn.ReflectionPad2d((1, 1, 1, 1)),
81 nn.Conv2d(512, 512, 3),
82 nn.ReLU(),
83 nn.ReflectionPad2d((1, 1, 1, 1)),
84 nn.Conv2d(512, 512, 3),
85 nn.ReLU(),
86 nn.ReflectionPad2d((1, 1, 1, 1)),
87 nn.Conv2d(512, 512, 3),
88 nn.ReLU(),
89 nn.ReflectionPad2d((1, 1, 1, 1)),
90 nn.Conv2d(512, 256, 3),
91 nn.ReLU(),
92 nn.Upsample(scale_factor=2),
93 nn.ReflectionPad2d((1, 1, 1, 1)),
94 nn.Conv2d(256, 256, 3),
95 nn.ReLU(),
96 nn.ReflectionPad2d((1, 1, 1, 1)),
97 nn.Conv2d(256, 256, 3),
98 nn.ReLU(),
99 nn.ReflectionPad2d((1, 1, 1, 1)),
100 nn.Conv2d(256, 256, 3),
101 nn.ReLU(),
102 nn.ReflectionPad2d((1, 1, 1, 1)),
103 nn.Conv2d(256, 128, 3),
104 nn.ReLU(),
105 nn.Upsample(scale_factor=2),
106 nn.ReflectionPad2d((1, 1, 1, 1)),
107 nn.Conv2d(128, 128, 3),
108 nn.ReLU(),
109 nn.ReflectionPad2d((1, 1, 1, 1)),
110 nn.Conv2d(128, 64, 3),
111 nn.ReLU(),
112 nn.Upsample(scale_factor=2),
113 nn.ReflectionPad2d((1, 1, 1, 1)),
114 nn.Conv2d(64, 64, 3),
115 nn.ReLU(),
116 nn.ReflectionPad2d((1, 1, 1, 1)),
117 nn.Conv2d(64, 3, 3)
118 )
119
120
121 class Decoder(nn.Module):
122 def __init__(self, target, pretrained_path=None):
123 super().__init__()
124 if target == 'relu1_1':
125 self.net = nn.Sequential(*copy.deepcopy(list(vgg_decoder_relu5_1.children())[-5:])) # current -2
126 elif target == 'relu2_1':
127 self.net = nn.Sequential(*copy.deepcopy(list(vgg_decoder_relu5_1.children())[-9:]))
128 elif target == 'relu3_1':
129 self.net = nn.Sequential(*copy.deepcopy(list(vgg_decoder_relu5_1.children())[-16:]))
130 elif target == 'relu4_1':
131 self.net = nn.Sequential(*copy.deepcopy(list(vgg_decoder_relu5_1.children())[-29:]))
132 elif target == 'relu5_1':
133 self.net = nn.Sequential(*copy.deepcopy(list(vgg_decoder_relu5_1.children())))
134
135 if pretrained_path is not None:
136 self.net.load_state_dict(torch.load(pretrained_path, map_location=lambda storage, loc: storage))
137
138 def forward(self, x):
139 return self.net(x)
| 2 - refactor: consider-using-from-import
63 - refactor: no-else-return
62 - refactor: inconsistent-return-statements
|
1 import zmq
2
3 PUB_ADDR = 'ipc:///tmp/pub';
4 SUB_ADDR = 'ipc:///tmp/sub';
5
6 class zcomm:
7
8 def __init__(self):
9 self.ctx = zmq.Context()
10 self.pub = self.ctx.socket(zmq.PUB)
11 self.pub.connect(PUB_ADDR)
12 self.sub = self.ctx.socket(zmq.SUB)
13 self.sub.connect(SUB_ADDR)
14 self.callbacks = {} # maps channels -> callbacks
15
16 def subscribe(self, channel, callback):
17 self.sub.setsockopt(zmq.SUBSCRIBE, channel)
18 self.callbacks[channel] = callback
19
20 def publish(self, channel, data):
21 self.pub.send_multipart([channel, data])
22
23 def handle(self):
24 channel, msg = self.sub.recv_multipart()
25 if channel in self.callbacks:
26 self.callbacks[channel](channel, msg)
27 elif '' in self.callbacks:
28 self.callbacks[''](channel, msg)
29
30 def run(self):
31 while True:
32 self.handle()
| 3 - warning: unnecessary-semicolon
4 - warning: unnecessary-semicolon
|
1 #!/usr/bin/env python
2 import itertools
3 import sys
4 import time
5 from zcomm import zcomm
6
7 HZ = 1
8
9 def main(argv):
10 z = zcomm()
11
12 msg_counter = itertools.count()
13 while True:
14 msg = str(msg_counter.next())
15 z.publish('FROB_DATA', msg);
16 time.sleep(1/float(HZ))
17
18 if __name__ == "__main__":
19 try:
20 main(sys.argv)
21 except KeyboardInterrupt:
22 pass
| 15 - warning: unnecessary-semicolon
14 - error: no-member
9 - warning: unused-argument
|
1 #!/usr/bin/env python
2 import sys
3 import time
4 from zcomm import zcomm
5
6 def handle_msg(channel, data):
7 print ' channel:%s, data:%s' % (channel, data)
8
9 def main(argv):
10 z = zcomm()
11 z.subscribe('', handle_msg)
12 z.run()
13
14 if __name__ == "__main__":
15 try:
16 main(sys.argv)
17 except KeyboardInterrupt:
18 pass
| 7 - error: syntax-error
|
1 #!/usr/bin/env python
2 import zmq
3
4 SUB_ADDR = 'ipc:///tmp/sub'
5 PUB_ADDR = 'ipc:///tmp/pub'
6
7 def main():
8
9 try:
10 context = zmq.Context(1)
11
12 userpub = context.socket(zmq.SUB)
13 userpub.bind(PUB_ADDR)
14 userpub.setsockopt(zmq.SUBSCRIBE, "")
15
16 usersub = context.socket(zmq.PUB)
17 usersub.bind(SUB_ADDR)
18
19 zmq.device(zmq.FORWARDER, userpub, usersub)
20 except Exception, e:
21 print e
22 print "bringing down zmq device"
23 except KeyboardInterrupt:
24 pass
25 finally:
26 pass
27 userpub.close()
28 usersub.close()
29 context.term()
30
31 if __name__ == "__main__":
32 main()
| 20 - error: syntax-error
|
1 # AC:
2 # from others' solution
3 #
4 class Solution(object):
5 def distinctEchoSubstrings(self, S):
6 N = len(S)
7 P, MOD = 37, 344555666677777 # MOD is prime
8 Pinv = pow(P, MOD - 2, MOD)
9
10 prefix = [0]
11 pwr = 1
12 ha = 0
13
14 for x in map(ord, S):
15 ha = (ha + pwr * x) % MOD
16 pwr = pwr * P % MOD
17 prefix.append(ha)
18
19 seen = set()
20 pwr = 1
21 for length in range(1, N // 2 + 1):
22 pwr = pwr * P % MOD # pwr = P^length
23 for i in range(N - 2 * length + 1):
24 left = (prefix[i + length] - prefix[i]) * pwr % MOD # hash of s[i:i+length] * P^length
25 right = (prefix[i + 2 * length] - prefix[i + length]) % MOD # hash of s[i+length:i+2*length]
26 if left == right:
27 seen.add(left * pow(Pinv, i, MOD) % MOD) # left * P^-i is the canonical representation
28 return len(seen) | 4 - refactor: useless-object-inheritance
4 - refactor: too-few-public-methods
|
1 # -*- coding: utf-8 -*-
2 """
3 Created on Wed Oct 24 09:50:29 2018
4
5 @author: fd
6 """
7
8 import json
9
10 dic = {
11 "真实流量测试":
12 {
13 "dspflow": ["flow.pcap"],
14
15 "flow": ["flow2.pcap", "3.pcap"],
16 },
17
18 "恶意流量测试":
19 {
20 "情况1": ["6.pcap"],
21
22 "情况2": ["7.pcap", "8.pcap"],
23 "情况3": ["9.pcap", "10.pcap"],
24 },
25 "具体流量测试":
26 {
27 "ARP": ["arp.pcap"],
28 "DB2": ["db2.pcap"],
29 "DNS": ["dns.pcap"],
30 "FTP": ["dns.pcap"],
31 "HTTP": ["http.pcap"],
32 "HTTPS": ["https.pcap"],
33 "MEMCACHE": ["memcached.pcap"],
34 "MONGO": ["mongo.pcap"],
35 "MYSQL": ["mysql.pcap"],
36 "ORACLE": ["oracle.pcap"],
37 "REDIS": ["redis.pcap"],
38 "SMTP": ["smtp.pcap"],
39 "SNMPv1": ["snmp1.pcap"],
40 "SNMPv2": ["snmp2.pcap"],
41 "SNMPv3": ["snmp3.pcap"],
42 "SSH": ["ssh.pcap"],
43 "SSL": ["ssl.pcap"],
44 "SYBASE": ["sybase.pcap"],
45 "TELNET": ["telnet.pcap"],
46 "UDP": ["udp.pcap"],
47 "VLAN": ["vlan.pcap"],
48 }
49
50 }
51 with open("config.json","w") as dump_f:
52 json.dump(dic,dump_f,ensure_ascii=False)
53
54 with open('config.json', 'r') as json_file:
55 """
56 读取该json文件时,先按照gbk的方式对其解码再编码为utf-8的格式
57 """
58 data = json_file.read()
59 print(type(data)) # type(data) = 'str'
60 result = json.loads(data)
61 print(result)
| 51 - warning: unspecified-encoding
54 - warning: unspecified-encoding
55 - warning: pointless-string-statement
|
1 # -*- coding: utf-8 -*-
2 """
3 Created on Tue Nov 27 20:07:59 2018
4
5 @author: Imen
6 """
7
8 import numpy as np
9 import pandas as pd
10 from sklearn.cluster import KMeans
11 import matplotlib.pyplot as plt
12 from sklearn.datasets.samples_generator import make_blobs
13
14 #Create a database of random values of 4 features and a fixed number of clusters
15 n_clusters=6
16 dataset,y=make_blobs(n_samples=200,n_features=4,centers=n_clusters)
17 #plt.scatter(dataset[:,2],dataset[:,3])
18
19 #Firstly,i will calculate Vsc for this number of clusters
20 #Create the k-means
21 kmeans=KMeans(init="k-means++",n_clusters=n_clusters,random_state=0)
22 kmeans.fit(dataset)
23 mu_i=kmeans.cluster_centers_
24 k_means_labels=kmeans.labels_
25 mu=dataset.mean(axis=0)
26 SB=np.zeros((4,4))
27 for line in mu_i:
28 diff1=line.reshape(1,4)-mu.reshape(1,4)
29 diff2=np.transpose(line.reshape(1,4)-mu.reshape(1,4))
30 SB+=diff1*diff2
31 Sw=np.zeros((4,4))
32 sum_in_cluster=np.zeros((4,4))
33 comp_c=0
34 for k in range(n_clusters):
35 mes_points=(k_means_labels==k)
36 cluster_center=mu_i[k]
37 for i in dataset[mes_points]:
38 diff11=i.reshape(1,4)-cluster_center.reshape(1,4)
39 diff22=np.transpose(i.reshape(1,4)-cluster_center.reshape(1,4))
40 sum_in_cluster+=diff11*diff22
41 Sw+=sum_in_cluster
42 comp_c+=np.trace(Sw)
43
44 sep_c=np.trace(SB)
45 Vsc=sep_c/comp_c
46 print("For n_clusters=",n_clusters," => Vsc=",Vsc)
47
48 #Secondly,i will determine Vsc for each number of cluster from 2 to 10
49 #Define a function validity_index
50 def validity_index(c):
51 kmeans=KMeans(init="k-means++",n_clusters=c,random_state=0)
52 kmeans.fit(dataset)
53 #mu_i is the centers of clusters
54 mu_i=kmeans.cluster_centers_
55 k_means_labels=kmeans.labels_
56 #mu is the center of the whole dataset
57 mu=dataset.mean(axis=0)
58 #initialize the between clusters matrix
59 SB=np.zeros((4,4))
60 for line in mu_i:
61 diff1=line.reshape(1,4)-mu.reshape(1,4)
62 diff2=np.transpose(line.reshape(1,4)-mu.reshape(1,4))
63 SB+=diff1*diff2
64 comp_c=0
65 #initialize the within matrix
66 Sw=np.zeros((4,4))
67 sum_in_cluster=np.zeros((4,4))
68 for k in range(c):
69 mes_points=(k_means_labels==k)
70 cluster_center=mu_i[k]
71 for i in dataset[mes_points]:
72 diff11=i.reshape(1,4)-cluster_center.reshape(1,4)
73 diff22=np.transpose(i.reshape(1,4)-cluster_center.reshape(1,4))
74 sum_in_cluster+=diff11*diff22
75 Sw+=sum_in_cluster
76 #calculate the compactness in each cluster
77 comp_c+=np.trace(Sw)
78 #define the separation between clusters
79 sep_c=np.trace(SB)
80 #determin the Vsc
81 Vsc=sep_c/comp_c
82 return Vsc
83 #We have to find that the max Vsc is for the n_cluster defined initially
84 Vsc_vector=[]
85 cc=[2,3,4,5,6,7,8,9,10]
86 for i in cc:
87 Vsc_vector.append(validity_index(i))
88 print("Number of clusters which has max of Vsc:",Vsc_vector.index(max(Vsc_vector))+2 ,"=> Vsc=",max(Vsc_vector))
| 50 - refactor: too-many-locals
51 - warning: redefined-outer-name
54 - warning: redefined-outer-name
55 - warning: redefined-outer-name
57 - warning: redefined-outer-name
59 - warning: redefined-outer-name
60 - warning: redefined-outer-name
61 - warning: redefined-outer-name
62 - warning: redefined-outer-name
64 - warning: redefined-outer-name
66 - warning: redefined-outer-name
67 - warning: redefined-outer-name
68 - warning: redefined-outer-name
69 - warning: redefined-outer-name
70 - warning: redefined-outer-name
71 - warning: redefined-outer-name
72 - warning: redefined-outer-name
73 - warning: redefined-outer-name
79 - warning: redefined-outer-name
81 - warning: redefined-outer-name
9 - warning: unused-import
11 - warning: unused-import
|
1 AWS_SCIPY_ARN = 'arn:aws:lambda:region:account_id:layer:AWSLambda-Python37-SciPy1x:2' | Clean Code: No Issues Detected
|
1 def lambda_handler(event, context):
2 if event['parallel_no'] % 2 == 0:
3 raise Exception('偶数です')
4
5 return {
6 'message': event['message'],
7 'const_value': event['const_value']
8 }
| 3 - warning: broad-exception-raised
1 - warning: unused-argument
|
1 def lambda_handler(event, context):
2 if event['parallel_no'] == 1:
3 raise Exception('強制的にエラーとします')
4
5 return 'only 3rd message.'
| 3 - warning: broad-exception-raised
1 - warning: unused-argument
|
1 #!/usr/bin/env python3
2
3 from aws_cdk import core
4
5 from step_functions.step_functions_stack import StepFunctionsStack
6
7
8 app = core.App()
9
10 # CFnのStack名を第2引数で渡す
11 StepFunctionsStack(app, 'step-functions')
12
13 app.synth()
| Clean Code: No Issues Detected
|
1 import json
2
3
4 def lambda_handler(event, context):
5 # {
6 # "resource": "arn:aws:lambda:region:id:function:sfn_error_lambda",
7 # "input": {
8 # "Error": "Exception",
9 # "Cause": "{\"errorMessage\": \"\\u5076\\u6570\\u3067\\u3059\",
10 # \"errorType\": \"Exception\",
11 # \"stackTrace\": [\" File \\\"/var/task/lambda_function.py\\\", line 5,
12 # in lambda_handler\\n raise Exception('\\u5076\\u6570\\u3067\\u3059')
13 # \\n\"]}"
14 # },
15 # "timeoutInSeconds": null
16 # }
17
18 return {
19 # JSONをPythonオブジェクト化することで、文字化けを直す
20 'error_message': json.loads(event['Cause']),
21 }
| 4 - warning: unused-argument
|
1 import os
2 import boto3
3 from numpy.random import rand
4
5
6 def lambda_handler(event, context):
7 body = f'{event["message"]} \n value: {rand()}'
8 client = boto3.client('s3')
9 client.put_object(
10 Bucket=os.environ['BUCKET_NAME'],
11 Key='sfn_first.txt',
12 Body=body,
13 )
14
15 return {
16 'body': body,
17 'message': event['message'],
18 }
| 6 - warning: unused-argument
|
1 import time
2 import cPickle
3 import numpy as np
4 import torch
5
6 class InstanceBag(object):
7 def __init__(self, entities, rel, num, sentences, positions, entitiesPos):
8 self.entities = entities
9 self.rel = rel
10 self.num = num
11 self.sentences = sentences
12 self.positions = positions
13 self.entitiesPos = entitiesPos
14
15 def bags_decompose(data_bags):
16 bag_sent = [data_bag.sentences for data_bag in data_bags]
17 bag_pos = [data_bag.positions for data_bag in data_bags]
18 bag_num = [data_bag.num for data_bag in data_bags]
19 bag_rel = [data_bag.rel for data_bag in data_bags]
20 bag_epos = [data_bag.entitiesPos for data_bag in data_bags]
21 return [bag_rel, bag_num, bag_sent, bag_pos, bag_epos]
22
23 def select_instance(rels, nums, sents, poss, eposs, model):
24 batch_x = []
25 batch_len = []
26 batch_epos = []
27 batch_y = []
28 for bagIndex, insNum in enumerate(nums):
29 maxIns = 0
30 maxP = -1
31 if insNum > 1:
32 for m in range(insNum):
33 insX = sents[bagIndex][m]
34 epos = eposs[bagIndex][m]
35 sel_x, sel_len, sel_epos = prepare_data([insX], [epos])
36 results = model(sel_x, sel_len, sel_epos)
37 tmpMax = results.max()
38 if tmpMax > maxP:
39 maxIns = m
40 maxP=tmpMax
41
42 batch_x.append(sents[bagIndex][maxIns])
43 batch_epos.append(eposs[bagIndex][maxIns])
44 batch_y.append(rels[bagIndex])
45
46 batch_x, batch_len, batch_epos = prepare_data(batch_x, batch_epos)
47 batch_y = torch.LongTensor(np.array(batch_y).astype("int32")).cuda()
48
49 return [batch_x, batch_len, batch_epos, batch_y]
50
51 def prepare_data(sents, epos):
52 lens = [len(sent) for sent in sents]
53
54 n_samples = len(lens)
55 max_len = max(lens)
56
57 batch_x = np.zeros((n_samples, max_len)).astype("int32")
58 for idx, s in enumerate(sents):
59 batch_x[idx, :lens[idx]] = s
60
61 batch_len = np.array(lens).astype("int32")
62 batch_epos = np.array(epos).astype("int32")
63
64 return torch.LongTensor(batch_x).cuda(), torch.LongTensor(batch_len).cuda(), torch.LongTensor(batch_epos).cuda()
| 34 - error: syntax-error
|
1 import sys
2 import re
3 import numpy as np
4 import cPickle as pkl
5 import codecs
6
7 import logging
8
9 from data_iterator import *
10
11 logger = logging.getLogger()
12 extra_token = ["<PAD>", "<UNK>"]
13
14 def display(msg):
15 print(msg)
16 logger.info(msg)
17
18 def datafold(filename):
19 f = open(filename, 'r')
20 data = []
21 while 1:
22 line = f.readline()
23 if not line:
24 break
25 entities = map(int, line.split(' '))
26 line = f.readline()
27 bagLabel = line.split(' ')
28
29 rel = map(int, bagLabel[0:-1])
30 num = int(bagLabel[-1])
31 positions = []
32 sentences = []
33 entitiesPos = []
34 for i in range(0, num):
35 sent = f.readline().split(' ')
36 positions.append(map(int, sent[0:2]))
37 epos = map(int, sent[0:2])
38 epos.sort()
39 entitiesPos.append(epos)
40 sentences.append(map(int, sent[2:-1]))
41 ins = InstanceBag(entities, rel, num, sentences, positions, entitiesPos)
42 data += [ins]
43 f.close()
44 return data
45
46 def dicfold(textfile):
47 vocab = []
48 with codecs.open(textfile, "r", encoding = "utf8") as f:
49 for line in f:
50 line = line.strip()
51 if line:
52 vocab.append(line)
53 return vocab
54
55 def build_word2idx(vocab, textFile):
56 msg = "Building word2idx..."
57 display(msg)
58
59 pre_train_emb = []
60 part_point = len(vocab)
61
62 if textFile:
63 word2emb = load_emb(vocab, textFile)
64
65 pre_train_vocab = []
66 un_pre_train_vocab = []
67
68 for word in vocab:
69 if word in word2emb:
70 pre_train_vocab.append(word)
71 pre_train_emb.append(word2emb[word])
72 else:
73 un_pre_train_vocab.append(word)
74
75 part_point = len(un_pre_train_vocab)
76 un_pre_train_vocab.extend(pre_train_vocab)
77 vocab = un_pre_train_vocab
78
79 word2idx = {}
80 for v, k in enumerate(extra_token):
81 word2idx[k] = v
82
83 for v, k in enumerate(vocab):
84 word2idx[k] = v + 2
85
86 part_point += 2
87
88 return word2idx, pre_train_emb, part_point
89
90 def load_emb(vocab, textFile):
91 msg = 'load emb from ' + textFile
92 display(msg)
93
94 vocab_set = set(vocab)
95 word2emb = {}
96
97 emb_p = re.compile(r" |\t")
98 count = 0
99 with codecs.open(textFile, "r", "utf8") as filein:
100 for line in filein:
101 count += 1
102 array = emb_p.split(line.strip())
103 word = array[0]
104 if word in vocab_set:
105 vector = [float(array[i]) for i in range(1, len(array))]
106 word2emb[word] = vector
107
108 del vocab_set
109
110 msg = "find %d words in %s" %(count, textFile)
111 display(msg)
112
113 msg = "Summary: %d words in the vocabulary and %d of them appear in the %s" %(len(vocab), len(word2emb), textFile)
114 display(msg)
115
116 return word2emb
117
118 def positive_evaluation(predict_results):
119 predict_y = predict_results[0]
120 predict_y_prob = predict_results[1]
121 y_given = predict_results[2]
122
123 positive_num = 0
124 #find the number of positive examples
125 for yi in range(y_given.shape[0]):
126 if y_given[yi, 0] > 0:
127 positive_num += 1
128 # if positive_num == 0:
129 # positive_num = 1
130 # sort prob
131 index = np.argsort(predict_y_prob)[::-1]
132
133 all_pre = [0]
134 all_rec = [0]
135 p_n = 0
136 p_p = 0
137 n_p = 0
138 # print y_given.shape[0]
139 for i in range(y_given.shape[0]):
140 labels = y_given[index[i],:] # key given labels
141 py = predict_y[index[i]] # answer
142
143 if labels[0] == 0:
144 # NA bag
145 if py > 0:
146 n_p += 1
147 else:
148 # positive bag
149 if py == 0:
150 p_n += 1
151 else:
152 flag = False
153 for j in range(y_given.shape[1]):
154 if j == -1:
155 break
156 if py == labels[j]:
157 flag = True # true positive
158 break
159 if flag:
160 p_p += 1
161 if (p_p+n_p) == 0:
162 precision = 1
163 else:
164 precision = float(p_p)/(p_p+n_p)
165 recall = float(p_p)/positive_num
166 if precision != all_pre[-1] or recall != all_rec[-1]:
167 all_pre.append(precision)
168 all_rec.append(recall)
169 return [all_pre[1:], all_rec[1:]] | 15 - warning: bad-indentation
16 - warning: bad-indentation
19 - warning: bad-indentation
20 - warning: bad-indentation
21 - warning: bad-indentation
22 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
31 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
34 - warning: bad-indentation
35 - warning: bad-indentation
36 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
40 - warning: bad-indentation
41 - warning: bad-indentation
42 - warning: bad-indentation
43 - warning: bad-indentation
44 - warning: bad-indentation
47 - warning: bad-indentation
48 - warning: bad-indentation
49 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
52 - warning: bad-indentation
53 - warning: bad-indentation
56 - warning: bad-indentation
57 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
62 - warning: bad-indentation
63 - warning: bad-indentation
65 - warning: bad-indentation
66 - warning: bad-indentation
68 - warning: bad-indentation
69 - warning: bad-indentation
70 - warning: bad-indentation
71 - warning: bad-indentation
72 - warning: bad-indentation
73 - warning: bad-indentation
75 - warning: bad-indentation
76 - warning: bad-indentation
77 - warning: bad-indentation
79 - warning: bad-indentation
80 - warning: bad-indentation
81 - warning: bad-indentation
83 - warning: bad-indentation
84 - warning: bad-indentation
86 - warning: bad-indentation
88 - warning: bad-indentation
91 - warning: bad-indentation
92 - warning: bad-indentation
94 - warning: bad-indentation
95 - warning: bad-indentation
97 - warning: bad-indentation
98 - warning: bad-indentation
99 - warning: bad-indentation
100 - warning: bad-indentation
101 - warning: bad-indentation
102 - warning: bad-indentation
103 - warning: bad-indentation
104 - warning: bad-indentation
105 - warning: bad-indentation
106 - warning: bad-indentation
108 - warning: bad-indentation
110 - warning: bad-indentation
111 - warning: bad-indentation
113 - warning: bad-indentation
114 - warning: bad-indentation
116 - warning: bad-indentation
119 - warning: bad-indentation
120 - warning: bad-indentation
121 - warning: bad-indentation
123 - warning: bad-indentation
125 - warning: bad-indentation
126 - warning: bad-indentation
127 - warning: bad-indentation
131 - warning: bad-indentation
133 - warning: bad-indentation
134 - warning: bad-indentation
135 - warning: bad-indentation
136 - warning: bad-indentation
137 - warning: bad-indentation
139 - warning: bad-indentation
140 - warning: bad-indentation
141 - warning: bad-indentation
143 - warning: bad-indentation
145 - warning: bad-indentation
146 - warning: bad-indentation
147 - warning: bad-indentation
149 - warning: bad-indentation
150 - warning: bad-indentation
151 - warning: bad-indentation
152 - warning: bad-indentation
153 - warning: bad-indentation
154 - warning: bad-indentation
155 - warning: bad-indentation
156 - warning: bad-indentation
157 - warning: bad-indentation
158 - warning: bad-indentation
159 - warning: bad-indentation
160 - warning: bad-indentation
161 - warning: bad-indentation
162 - warning: bad-indentation
163 - warning: bad-indentation
164 - warning: bad-indentation
165 - warning: bad-indentation
166 - warning: bad-indentation
167 - warning: bad-indentation
168 - warning: bad-indentation
169 - warning: bad-indentation
9 - warning: wildcard-import
19 - warning: unspecified-encoding
38 - error: no-member
41 - error: undefined-variable
19 - refactor: consider-using-with
34 - warning: unused-variable
118 - refactor: too-many-locals
118 - refactor: too-many-branches
1 - warning: unused-import
4 - warning: unused-import
|
1 from module import *
2 from util import *
3 from data_iterator import *
| 1 - warning: wildcard-import
2 - warning: wildcard-import
3 - warning: wildcard-import
|
1 import sys
2 import codecs
3
4 class InstanceBag(object):
5 def __init__(self, entities, rel, num, sentences, positions, entitiesPos):
6 self.entities = entities
7 self.rel = rel
8 self.num = num
9 self.sentences = sentences
10 self.positions = positions
11 self.entitiesPos = entitiesPos
12
13 def bags_decompose(data_bags):
14 bag_sent = [data_bag.sentences for data_bag in data_bags]
15 bag_pos = [data_bag.positions for data_bag in data_bags]
16 bag_num = [data_bag.num for data_bag in data_bags]
17 bag_rel = [data_bag.rel for data_bag in data_bags]
18 bag_epos = [data_bag.entitiesPos for data_bag in data_bags]
19 return [bag_rel, bag_num, bag_sent, bag_pos, bag_epos]
20
21 def datafold(filename):
22 f = open(filename, 'r')
23 data = []
24 while 1:
25 line = f.readline()
26 if not line:
27 break
28 entities = map(int, line.split(' '))
29 line = f.readline()
30 bagLabel = line.split(' ')
31
32 rel = map(int, bagLabel[0:-1])
33 num = int(bagLabel[-1])
34 positions = []
35 sentences = []
36 entitiesPos = []
37 for i in range(0, num):
38 sent = f.readline().split(' ')
39 positions.append(map(int, sent[0:2]))
40 epos = map(int, sent[0:2])
41 epos.sort()
42 entitiesPos.append(epos)
43 sentences.append(map(int, sent[2:-1]))
44 ins = InstanceBag(entities, rel, num, sentences, positions, entitiesPos)
45 data += [ins]
46 f.close()
47 return data
48
49 def change_word_idx(data):
50 new_data = []
51 for inst in data:
52 entities = inst.entities
53 rel = inst.rel
54 num = inst.num
55 sentences = inst.sentences
56 positions = inst.positions
57 entitiesPos = inst.entitiesPos
58 new_sentences = []
59 for sent in sentences:
60 new_sent = []
61 for word in sent:
62 if word == 160696:
63 new_sent.append(1)
64 elif word == 0:
65 new_sent.append(0)
66 else:
67 new_sent.append(word + 1)
68 new_sentences.append(new_sent)
69 new_inst = InstanceBag(entities, rel, num, new_sentences, positions, entitiesPos)
70 new_data.append(new_inst)
71 return new_data
72
73 def save_data(data, textfile):
74 with codecs.open(textfile, "w", encoding = "utf8") as f:
75 for inst in data:
76 f.write("%s\n" %(" ".join(map(str, inst.entities))))
77 f.write("%s %s\n" %(" ".join(map(str, inst.rel)), str(inst.num)))
78 for pos, sent in zip(inst.positions, inst.sentences):
79 f.write("%s %s\n" %(" ".join(map(str, pos)), " ".join(map(str, sent))))
80
81 def main(argv):
82 data = datafold(argv[0])
83 new_data = change_word_idx(data)
84 save_data(new_data, argv[1])
85
86 if "__main__" == __name__:
87 main(sys.argv[1:]) | 5 - warning: bad-indentation
6 - warning: bad-indentation
7 - warning: bad-indentation
8 - warning: bad-indentation
9 - warning: bad-indentation
10 - warning: bad-indentation
11 - warning: bad-indentation
22 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
34 - warning: bad-indentation
35 - warning: bad-indentation
36 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
40 - warning: bad-indentation
41 - warning: bad-indentation
42 - warning: bad-indentation
43 - warning: bad-indentation
44 - warning: bad-indentation
45 - warning: bad-indentation
46 - warning: bad-indentation
47 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
52 - warning: bad-indentation
53 - warning: bad-indentation
54 - warning: bad-indentation
55 - warning: bad-indentation
56 - warning: bad-indentation
57 - warning: bad-indentation
58 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
61 - warning: bad-indentation
62 - warning: bad-indentation
63 - warning: bad-indentation
64 - warning: bad-indentation
65 - warning: bad-indentation
66 - warning: bad-indentation
67 - warning: bad-indentation
68 - warning: bad-indentation
69 - warning: bad-indentation
70 - warning: bad-indentation
71 - warning: bad-indentation
74 - warning: bad-indentation
75 - warning: bad-indentation
76 - warning: bad-indentation
77 - warning: bad-indentation
78 - warning: bad-indentation
79 - warning: bad-indentation
82 - warning: bad-indentation
83 - warning: bad-indentation
84 - warning: bad-indentation
87 - warning: bad-indentation
4 - refactor: useless-object-inheritance
5 - refactor: too-many-arguments
5 - refactor: too-many-positional-arguments
4 - refactor: too-few-public-methods
22 - warning: unspecified-encoding
41 - error: no-member
22 - refactor: consider-using-with
37 - warning: unused-variable
|
1 import torch
2 import torch.nn as nn
3
4 from lib import *
5
6 class Model(nn.Module):
7 def __init__(self,
8 fine_tune,
9 pre_train_emb,
10 part_point,
11 size_vocab,
12 dim_emb,
13 dim_proj,
14 head_count,
15 dim_FNN,
16 act_str,
17 num_layer,
18 num_class,
19 dropout_rate):
20 super(Model, self).__init__()
21
22 self.fine_tune = fine_tune
23 self.pre_train_emb = pre_train_emb
24 self.part_point = part_point
25 self.size_vocab = size_vocab
26 self.dim_emb = dim_emb
27 self.dim_proj = dim_proj
28 self.head_count = head_count
29 self.dim_FNN = dim_FNN
30 self.act_str = act_str
31 self.num_layer = num_layer
32 self.num_class = num_class
33 self.dropout_rate = dropout_rate
34
35 self._init_params()
36
37 def _init_params(self):
38 self.wemb = Word_Emb(self.fine_tune,
39 self.pre_train_emb,
40 self.part_point,
41 self.size_vocab,
42 self.dim_emb)
43
44 self.encoder = TransformerEncoder(self.dim_proj,
45 self.head_count,
46 self.dim_FNN,
47 self.act_str,
48 self.num_layer,
49 self.dropout_rate)
50
51 self.dense = MLP(self.dim_proj * 3, self.dim_proj)
52 self.relu = torch.nn.ReLU()
53 self.classifier = MLP(self.dim_proj, self.num_class)
54 self.dropout = nn.Dropout(self.dropout_rate)
55
56 def forward(self, inp, lengths, epos):
57 mask, mask_l, mask_m, mask_r = self.pos2mask(epos, lengths)
58
59 emb_inp = self.wemb(inp)
60 emb_inp = self.dropout(emb_inp)
61
62 proj_inp, _ = self.encoder(emb_inp, self.create_attention_mask(mask, mask))
63 proj_inp = proj_inp * mask[:, :, None]
64
65 pool_inp_l = torch.sum(proj_inp * mask_l[:, :, None], dim = 1) / torch.sum(mask_l, dim = 1)[:, None]
66 pool_inp_m = torch.sum(proj_inp * mask_m[:, :, None], dim = 1) / torch.sum(mask_m, dim = 1)[:, None]
67 pool_inp_r = torch.sum(proj_inp * mask_r[:, :, None], dim = 1) / torch.sum(mask_r, dim = 1)[:, None]
68
69 pool_inp = torch.cat([pool_inp_l, pool_inp_m, pool_inp_r], dim = 1)
70
71 pool_inp = self.dropout(pool_inp)
72
73 logit = self.relu(self.dense(pool_inp))
74
75 logit = self.dropout(logit)
76
77 logit = self.classifier(logit)
78
79 return logit
80
81 def pos2mask(self, epos, lengths):
82 mask = self.len2mask(lengths)
83
84 nsample = lengths.size()[0]
85 max_len = torch.max(lengths)
86 idxes = torch.arange(0, max_len).cuda()
87 mask_l = (idxes < epos[:, 0].unsqueeze(1)).float()
88 mask_r = mask - (idxes < epos[:, 1].unsqueeze(1)).float()
89 mask_m = torch.ones([nsample, max_len]).float().cuda() - mask_l - mask_r
90 return mask, mask_l, mask_m, mask_r
91
92 def len2mask(self, lengths):
93 max_len = torch.max(lengths)
94 idxes = torch.arange(0, max_len).cuda()
95 mask = (idxes < lengths.unsqueeze(1)).float()
96 return mask
97
98 def create_attention_mask(self, query_mask, key_mask):
99 return torch.matmul(query_mask[:, :, None], key_mask[:, None, :]).byte() | 7 - warning: bad-indentation
20 - warning: bad-indentation
22 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
31 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
35 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
44 - warning: bad-indentation
51 - warning: bad-indentation
52 - warning: bad-indentation
53 - warning: bad-indentation
54 - warning: bad-indentation
56 - warning: bad-indentation
57 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
62 - warning: bad-indentation
63 - warning: bad-indentation
65 - warning: bad-indentation
66 - warning: bad-indentation
67 - warning: bad-indentation
69 - warning: bad-indentation
71 - warning: bad-indentation
73 - warning: bad-indentation
75 - warning: bad-indentation
77 - warning: bad-indentation
79 - warning: bad-indentation
81 - warning: bad-indentation
82 - warning: bad-indentation
84 - warning: bad-indentation
85 - warning: bad-indentation
86 - warning: bad-indentation
87 - warning: bad-indentation
88 - warning: bad-indentation
89 - warning: bad-indentation
90 - warning: bad-indentation
92 - warning: bad-indentation
93 - warning: bad-indentation
94 - warning: bad-indentation
95 - warning: bad-indentation
96 - warning: bad-indentation
98 - warning: bad-indentation
99 - warning: bad-indentation
2 - refactor: consider-using-from-import
4 - warning: wildcard-import
6 - refactor: too-many-instance-attributes
7 - refactor: too-many-arguments
7 - refactor: too-many-positional-arguments
20 - refactor: super-with-arguments
38 - error: undefined-variable
44 - error: undefined-variable
51 - error: undefined-variable
53 - error: undefined-variable
|
1 from os import path
2
3 from bcbio.pipeline import config_utils
4 from bcbio.utils import safe_makedir, file_exists, get_in
5 from bcbio.provenance import do
6
7 CLEANUP_FILES = ["Aligned.out.sam", "Log.out", "Log.progress.out"]
8
9 def align(fastq_file, pair_file, ref_file, names, align_dir, data):
10 config = data["config"]
11 out_prefix = path.join(align_dir, names["lane"])
12 out_file = out_prefix + "Aligned.out.sam"
13 if file_exists(out_file):
14 return out_file
15 star_path = config_utils.get_program("STAR", config)
16 fastq = " ".join([fastq_file, pair_file]) if pair_file else fastq_file
17 num_cores = config["algorithm"].get("num_cores", 1)
18
19 safe_makedir(align_dir)
20 cmd = ("{star_path} --genomeDir {ref_file} --readFilesIn {fastq} "
21 "--runThreadN {num_cores} --outFileNamePrefix {out_prefix} "
22 "--outReadsUnmapped Fastx --outFilterMultimapNmax 10")
23 fusion_mode = get_in(data, ("config", "algorithm", "fusion_mode"), False)
24 if fusion_mode:
25 cmd += " --chimSegmentMin 15 --chimJunctionOverhangMin 15"
26 strandedness = get_in(data, ("config", "algorithm", "strandedness"),
27 "unstranded").lower()
28 if strandedness == "unstranded":
29 cmd += " --outSAMstrandField intronMotif"
30 run_message = "Running STAR aligner on %s and %s." % (pair_file, ref_file)
31 do.run(cmd.format(**locals()), run_message, None)
32 return out_file
33
34 def _get_quality_format(config):
35 qual_format = config["algorithm"].get("quality_format", None)
36 if qual_format.lower() == "illumina":
37 return "fastq-illumina"
38 elif qual_format.lower() == "solexa":
39 return "fastq-solexa"
40 else:
41 return "fastq-sanger"
42
43 def remap_index_fn(ref_file):
44 """Map sequence references to equivalent star indexes
45 """
46 return path.join(path.dirname(path.dirname(ref_file)), "star")
47
48 def job_requirements(cores, memory):
49 MIN_STAR_MEMORY = 30.0
50 if not memory or cores * memory < MIN_STAR_MEMORY:
51 memory = MIN_STAR_MEMORY / cores
52 return cores, memory
53
54 align.job_requirements = job_requirements
| 9 - refactor: too-many-arguments
9 - refactor: too-many-positional-arguments
9 - refactor: too-many-locals
15 - warning: possibly-unused-variable
16 - warning: possibly-unused-variable
17 - warning: possibly-unused-variable
36 - refactor: no-else-return
|
1 """Calculate potential effects of variations using external programs.
2
3 Supported:
4 snpEff: http://sourceforge.net/projects/snpeff/
5 """
6 import os
7 import csv
8 import glob
9
10 from bcbio import utils
11 from bcbio.distributed.transaction import file_transaction
12 from bcbio.pipeline import config_utils, tools
13 from bcbio.provenance import do
14 from bcbio.variation import vcfutils
15
16 # ## snpEff variant effects
17
18 def snpeff_effects(data):
19 """Annotate input VCF file with effects calculated by snpEff.
20 """
21 vcf_in = data["vrn_file"]
22 interval_file = data["config"]["algorithm"].get("variant_regions", None)
23 if vcfutils.vcf_has_variants(vcf_in):
24 se_interval = (_convert_to_snpeff_interval(interval_file, vcf_in)
25 if interval_file else None)
26 try:
27 vcf_file = _run_snpeff(vcf_in, se_interval, "vcf", data)
28 finally:
29 for fname in [se_interval]:
30 if fname and os.path.exists(fname):
31 os.remove(fname)
32 return vcf_file
33
34 def _snpeff_args_from_config(data):
35 """Retrieve snpEff arguments supplied through input configuration.
36 """
37 config = data["config"]
38 args = []
39 # General supplied arguments
40 resources = config_utils.get_resources("snpeff", config)
41 if resources.get("options"):
42 args += [str(x) for x in resources.get("options", [])]
43 # cancer specific calling arguments
44 if data.get("metadata", {}).get("phenotype") in ["tumor", "normal"]:
45 args += ["-cancer"]
46 # Provide options tuned to reporting variants in clinical environments
47 if config["algorithm"].get("clinical_reporting"):
48 args += ["-canon", "-hgvs"]
49 return args
50
51 def get_db(ref_file, resources, config=None):
52 """Retrieve a snpEff database name and location relative to reference file.
53 """
54 snpeff_db = resources.get("aliases", {}).get("snpeff")
55 if snpeff_db:
56 snpeff_base_dir = utils.safe_makedir(os.path.normpath(os.path.join(
57 os.path.dirname(os.path.dirname(ref_file)), "snpeff")))
58 # back compatible retrieval of genome from installation directory
59 if config and not os.path.exists(os.path.join(snpeff_base_dir, snpeff_db)):
60 snpeff_base_dir, snpeff_db = _installed_snpeff_genome(snpeff_db, config)
61 else:
62 snpeff_base_dir = None
63 return snpeff_db, snpeff_base_dir
64
65 def get_cmd(cmd_name, datadir, config):
66 """Retrieve snpEff base command line, handling command line and jar based installs.
67 """
68 resources = config_utils.get_resources("snpeff", config)
69 memory = " ".join(resources.get("jvm_opts", ["-Xms750m", "-Xmx5g"]))
70 try:
71 snpeff = config_utils.get_program("snpeff", config)
72 cmd = "{snpeff} {memory} {cmd_name} -dataDir {datadir}"
73 except config_utils.CmdNotFound:
74 snpeff_jar = config_utils.get_jar("snpEff",
75 config_utils.get_program("snpeff", config, "dir"))
76 config_file = "%s.config" % os.path.splitext(snpeff_jar)[0]
77 cmd = "java {memory} -jar {snpeff_jar} {cmd_name} -c {config_file} -dataDir {datadir}"
78 return cmd.format(**locals())
79
80 def _run_snpeff(snp_in, se_interval, out_format, data):
81 snpeff_db, datadir = get_db(data["sam_ref"], data["genome_resources"], data["config"])
82 assert datadir is not None, \
83 "Did not find snpEff resources in genome configuration: %s" % data["genome_resources"]
84 assert os.path.exists(os.path.join(datadir, snpeff_db)), \
85 "Did not find %s snpEff genome data in %s" % (snpeff_db, datadir)
86 snpeff_cmd = get_cmd("eff", datadir, data["config"])
87 ext = utils.splitext_plus(snp_in)[1] if out_format == "vcf" else ".tsv"
88 out_file = "%s-effects%s" % (utils.splitext_plus(snp_in)[0], ext)
89 if not utils.file_exists(out_file):
90 interval = "-filterinterval %s" % (se_interval) if se_interval else ""
91 config_args = " ".join(_snpeff_args_from_config(data))
92 if ext.endswith(".gz"):
93 bgzip_cmd = "| %s -c" % tools.get_bgzip_cmd(data["config"])
94 else:
95 bgzip_cmd = ""
96 with file_transaction(out_file) as tx_out_file:
97 cmd = ("{snpeff_cmd} {interval} {config_args} -noLog -1 -i vcf -o {out_format} "
98 "{snpeff_db} {snp_in} {bgzip_cmd} > {tx_out_file}")
99 do.run(cmd.format(**locals()), "snpEff effects", data)
100 if ext.endswith(".gz"):
101 out_file = vcfutils.bgzip_and_index(out_file, data["config"])
102 return out_file
103
104 def _convert_to_snpeff_interval(in_file, base_file):
105 """Handle wide variety of BED-like inputs, converting to BED-3.
106 """
107 out_file = "%s-snpeff-intervals.bed" % utils.splitext_plus(base_file)[0]
108 if not os.path.exists(out_file):
109 with open(out_file, "w") as out_handle:
110 writer = csv.writer(out_handle, dialect="excel-tab")
111 with open(in_file) as in_handle:
112 for line in (l for l in in_handle if not l.startswith(("@", "#"))):
113 parts = line.split()
114 writer.writerow(parts[:3])
115 return out_file
116
117 # ## back-compatibility
118
119 def _find_snpeff_datadir(config_file):
120 with open(config_file) as in_handle:
121 for line in in_handle:
122 if line.startswith("data_dir"):
123 data_dir = config_utils.expand_path(line.split("=")[-1].strip())
124 if not data_dir.startswith("/"):
125 data_dir = os.path.join(os.path.dirname(config_file), data_dir)
126 return data_dir
127 raise ValueError("Did not find data directory in snpEff config file: %s" % config_file)
128
129 def _installed_snpeff_genome(base_name, config):
130 """Find the most recent installed genome for snpEff with the given name.
131 """
132 snpeff_config_file = os.path.join(config_utils.get_program("snpEff", config, "dir"),
133 "snpEff.config")
134 data_dir = _find_snpeff_datadir(snpeff_config_file)
135 dbs = [d for d in sorted(glob.glob(os.path.join(data_dir, "%s*" % base_name)), reverse=True)
136 if os.path.isdir(d)]
137 if len(dbs) == 0:
138 raise ValueError("No database found in %s for %s" % (data_dir, base_name))
139 else:
140 return data_dir, os.path.split(dbs[0])[-1]
| 18 - refactor: inconsistent-return-statements
65 - warning: unused-argument
65 - warning: unused-argument
69 - warning: possibly-unused-variable
71 - warning: possibly-unused-variable
76 - warning: possibly-unused-variable
86 - warning: possibly-unused-variable
90 - warning: possibly-unused-variable
91 - warning: possibly-unused-variable
93 - warning: possibly-unused-variable
96 - warning: possibly-unused-variable
109 - warning: unspecified-encoding
111 - warning: unspecified-encoding
120 - warning: unspecified-encoding
137 - refactor: no-else-raise
|
1 """Run distributed functions provided a name and json/YAML file with arguments.
2
3 Enables command line access and alternative interfaces to run specific
4 functionality within bcbio-nextgen.
5 """
6 import yaml
7
8 from bcbio.distributed import multitasks
9
10 def process(args):
11 """Run the function in args.name given arguments in args.argfile.
12 """
13 try:
14 fn = getattr(multitasks, args.name)
15 except AttributeError:
16 raise AttributeError("Did not find exposed function in bcbio.distributed.multitasks named '%s'" % args.name)
17 with open(args.argfile) as in_handle:
18 fnargs = yaml.safe_load(in_handle)
19 fn(fnargs)
20
21 def add_subparser(subparsers):
22 parser = subparsers.add_parser("runfn", help=("Run a specific bcbio-nextgen function."
23 "Intended for distributed use."))
24 parser.add_argument("name", help="Name of the function to run")
25 parser.add_argument("argfile", help="JSON file with arguments to the function")
| 16 - warning: raise-missing-from
17 - warning: unspecified-encoding
|
1 """Run distributed tasks in parallel using IPython or joblib on multiple cores.
2 """
3 import functools
4
5 try:
6 import joblib
7 except ImportError:
8 joblib = False
9
10 from bcbio.distributed import ipython
11 from bcbio.log import logger, setup_local_logging
12 from bcbio.provenance import diagnostics, system
13
14 def parallel_runner(parallel, dirs, config):
15 """Process a supplied function: single, multi-processor or distributed.
16 """
17 def run_parallel(fn_name, items, metadata=None):
18 items = [x for x in items if x is not None]
19 if len(items) == 0:
20 return []
21 items = diagnostics.track_parallel(items, fn_name)
22 sysinfo = system.get_info(dirs, parallel)
23 if parallel["type"] == "ipython":
24 return ipython.runner(parallel, fn_name, items, dirs["work"], sysinfo, config)
25 else:
26 imodule = parallel.get("module", "bcbio.distributed")
27 logger.info("multiprocessing: %s" % fn_name)
28 fn = getattr(__import__("{base}.multitasks".format(base=imodule),
29 fromlist=["multitasks"]),
30 fn_name)
31 return run_multicore(fn, items, config, parallel["cores"])
32 return run_parallel
33
34 def zeromq_aware_logging(f):
35 """Ensure multiprocessing logging uses ZeroMQ queues.
36
37 ZeroMQ and local stdout/stderr do not behave nicely when intertwined. This
38 ensures the local logging uses existing ZeroMQ logging queues.
39 """
40 @functools.wraps(f)
41 def wrapper(*args, **kwargs):
42 config = None
43 for arg in args:
44 if ipython.is_std_config_arg(arg):
45 config = arg
46 break
47 elif ipython.is_nested_config_arg(arg):
48 config = arg["config"]
49 break
50 assert config, "Could not find config dictionary in function arguments."
51 if config.get("parallel", {}).get("log_queue"):
52 handler = setup_local_logging(config, config["parallel"])
53 else:
54 handler = None
55 try:
56 out = f(*args, **kwargs)
57 finally:
58 if handler and hasattr(handler, "close"):
59 handler.close()
60 return out
61 return wrapper
62
63 def run_multicore(fn, items, config, cores=None):
64 """Run the function using multiple cores on the given items to process.
65 """
66 if cores is None:
67 cores = config["algorithm"].get("num_cores", 1)
68 parallel = {"type": "local", "cores": cores}
69 sysinfo = system.get_info({}, parallel)
70 jobr = ipython.find_job_resources([fn], parallel, items, sysinfo, config,
71 parallel.get("multiplier", 1),
72 max_multicore=int(sysinfo["cores"]))
73 items = [ipython.add_cores_to_config(x, jobr.cores_per_job) for x in items]
74 if joblib is None:
75 raise ImportError("Need joblib for multiprocessing parallelization")
76 out = []
77 for data in joblib.Parallel(jobr.num_jobs)(joblib.delayed(fn)(x) for x in items):
78 if data:
79 out.extend(data)
80 return out
| 23 - refactor: no-else-return
17 - warning: unused-argument
44 - refactor: no-else-break
|
1 import copy
2
3 # Setup:
4 s = "s"
5 states = ["s", "!s"]
6 actions = ["N", "M"]
7 Xt = {"A1": 1.0, "A2": 1.0}
8 R = {"s": 2.0, "!s": 3.0}
9 y = 0.5
10
11 def E(c, R):
12 E = c * max(R.values())
13 return E
14
15 def max_key(dictionary):
16 return list(Xt.keys())[list(Xt.values()).index(max(Xt.values()))]
17
18 def value_iteration(states, Xt, y):
19 iterations = 0
20 best = 0
21 U = [0] * len(states)
22 U_ = [0] * len(states)
23 A = [""] * len(states)
24
25 while (best < E((1 - y), R) / y and iterations < 1000):
26 U = copy.deepcopy(U_)
27 best = 0
28 for i, state in enumerate(states):
29
30 # VELGER UANSETT DEN MEST SANNSYNLIGE TRANSITION... DET ER JO IKKE NOE BRA POLICY...
31
32 best_action = max_key(Xt)
33 U_[i] = R[state] + y * max([a * U[i] for a in Xt.values()])
34
35 if abs(U_[i] - U[i]) > best:
36 best = abs(U_[i] - U[i])
37
38 iterations += 1
39 # y = y * 0.99
40
41 print("Found optimal policy after %d iteration(s)" % iterations)
42 print("Best policy: ", str(A))
43
44
45 value_iteration(states, Xt, y)
| 11 - warning: redefined-outer-name
12 - warning: redefined-outer-name
15 - warning: unused-argument
18 - warning: redefined-outer-name
18 - warning: redefined-outer-name
18 - warning: redefined-outer-name
33 - refactor: consider-using-generator
35 - refactor: consider-using-max-builtin
32 - warning: unused-variable
|
1 import random
2 import sys
3 actions = ["LEFT", "RIGHT", "UP", "DOWN"]
4
5 def perform_action(x, y, action):
6 if action == "LEFT" and x != 0: return x-1, y
7 if action == "RIGHT" and x != 3: return x+1, y
8 if action == "UP" and y != 0: return x, y-1
9 if action == "DOWN" and y != 2: return x, y+1
10 return x, y
11
12 def transition_model(x, y, action):
13 preferred = [
14 ["RIGHT", "RIGHT", "RIGHT", "LEFT"],
15 ["UP", "DOWN", "UP", "UP" ],
16 ["UP", "LEFT", "UP", "LEFT"],
17 ][y][x]
18 return 1 if action == preferred else 0.0
19
20 def policy_evaluation(policy, utilities, states, discount):
21 for x, y in states:
22 transitions = [transition_model(x, y, policy[y][x]) * utilities[yy][xx] for xx, yy in all_possibles(x, y)]
23 utilities[y][x] = reward[y][x] + discount * sum(transitions)
24 return utilities
25
26
27 def best_action(state, u):
28 best_action = (None, -sys.maxsize)
29 for a in actions:
30 score = aciton_score(state, a, u)
31 if score > best_action[1]:
32 best_action = (a, score)
33 return best_action
34
35 all_possibles = lambda x, y: [perform_action(x, y, action) for action in actions]
36 aciton_score = lambda s, a, u: sum([transition_model(x, y, a) * u[y][x] for x, y in all_possibles(*s)])
37
38
39 reward = [
40 [-0.04, -0.04, -0.04, +1],
41 [-0.04, -100, -0.04, -1],
42 [-0.04, -0.04, -0.04, -0.04],
43 ]
44 states = [(x, y) for x in range(4) for y in range(3)]
45 random_initial_policy = [random.sample(actions, 4)]*3
46
47 def policy_iteration(mdp, policy, discount):
48
49 unchanged = False
50 u = [[0]*4]*3
51 i = 0
52 while not unchanged:
53 # Evaluate policy using bellman equation
54 u = policy_evaluation(policy, u, states, discount)
55 unchanged = True
56
57 for state in mdp:
58 x, y = state
59 # Compare with action in policy with all others to see if best:
60 if best_action(state, u)[1] > aciton_score(state, policy[y][x], u):
61 policy[y][x] = best_action(state, u)[0]
62
63 # Mark as changed to loop one more time.
64 unchanged = False
65 if i == 100: break
66 i += 1
67 return policy
68
69 print(policy_iteration(states, random_initial_policy, 0.9)) | 20 - warning: redefined-outer-name
28 - warning: redefined-outer-name
36 - refactor: consider-using-generator
|
1 # %%
2 import numpy as np
3
4 # Transition model for state_t (Answer to to PART A, 1)
5 Xt = np.array([[0.7, 0.3], [0.3, 0.7]])
6
7 # Sensor model for state_t (Answer to PART A, 2)
8 O1 = np.array([[0.9, .0], [.0, 0.2]])
9 O3 = np.array([[0.1, .0], [.0, 0.8]])
10
11
12 init = np.array([0.5, 0.5])
13
14
15 def forward(f, Xt, OT, OF, E, k):
16 t = Xt.transpose().dot(f) # Transition
17 u = (OT if E[k] else OF).dot(t) # Update
18 delta = u / np.sum(u) # Normalize
19
20 # Day 0 (base case)?
21 if not k:
22 return delta
23 return forward(delta, Xt, OT, OF, E, k-1)
24
25 def backward(Xt, OT, OF, E, k):
26 e = (OT if E[k] else OF)
27 if k < len(E)-1:
28 res = Xt.dot(e).dot(backward(Xt, OT, OF, E, k+1))
29 else:
30 res = Xt.dot(e).dot(np.array([1, 1]))
31
32 return res / np.sum(res)
33
34 E = [True, True]
35 rain_day_2 = forward(init, Xt, O1, O3, E, len(E)-1)
36 print("Probability of rain on day 2 using forward: ", rain_day_2)
37
38 E = np.array([True, True, False, True, True])
39 print("Probability of rain on day 5 using forward: ", forward(init, Xt, O1, O3, E, len(E)-1))
40 print("Probability of rain on day 2 using backward: ", backward(Xt, O1, O3, E, 0))
41
| 15 - refactor: too-many-arguments
15 - refactor: too-many-positional-arguments
15 - warning: redefined-outer-name
15 - warning: redefined-outer-name
25 - warning: redefined-outer-name
25 - warning: redefined-outer-name
|
1 import pandas as pd
2 from math import log2
3
4 _TRAINING_FILE = "/Users/magnus/Downloads/data/training.csv"
5 _TESTING_FILE = "/Users/magnus/Downloads/data/test.csv"
6
7 def entropy(V):
8 """ ENTROPY SHOWS HOW MUCH OF THE TOTAL DECSISION SPACE AN ATTRIBUTE TAKES UP """
9 return - sum(vk * log2(vk) for vk in V if vk > 0)
10
11 def remainder(attribute, examples):
12 """ REMAINDER EXPLAINS HOW MUCH IS UNDECIDED AFTER AN ATTRIBUTE IS SET """
13 remain = 0
14 p, n = len(examples[examples['CLASS'] == 1]), len(examples[examples['CLASS'] == 2])
15 for k in examples[attribute].unique():
16 ex = examples[[attribute, 'CLASS']][examples[attribute] == k]
17 pk, nk = len(ex[ex['CLASS'] == 1]), len(ex[ex['CLASS'] == 2])
18 remain += ((pk + nk) / (p + n)) * entropy([pk / (pk + nk), nk / (pk + nk)])
19 return remain
20
21 def importance(attribute, examples):
22 """ INFORMATION GAIN FORMULA """
23 p = len(examples[attribute][examples['CLASS'] == 1])
24 n = len(examples[attribute][examples['CLASS'] == 2])
25 return entropy([p/(p+n), n/(p+n)]) - remainder(attribute, examples)
26
27 def plurality(examples):
28 return 1 if len(examples['CLASS'][examples['CLASS'] == 1]) > len(examples['CLASS']) / 2 else 2
29
30 def decision_tree(examples, attributes, parent_examples):
31 """ CREATES A DECISION TREE BASED ON A SET OF EXAMPLES AND ATTRIBUTES. """
32 if examples.empty: return plurality(parent_examples)
33 elif (examples['CLASS'] == 1).all(): return 1
34 elif (examples['CLASS'] == 2).all(): return 2
35 elif attributes.empty: return plurality(examples)
36
37 rating = [importance(a, examples) for a in attributes]
38 A = attributes[rating.index(max(rating))]
39 node = {A: {}}
40 for k in examples[A].unique():
41 node[A][k] = decision_tree(examples[examples[A] == k], attributes.drop(A), examples)
42 return node
43
44 def classify(tree, example):
45 attr = list(tree.keys())[0]
46 res = tree[attr][example[attr]]
47 if isinstance(res, dict):
48 return classify(res, example)
49 else:
50 return res
51
52
53 if __name__ == "__main__":
54 # Load datasets:
55 training = pd.read_csv(_TRAINING_FILE, header=0)
56 testing = pd.read_csv(_TESTING_FILE, header=0)
57
58 # Build tree:
59 tree = decision_tree(training, training.columns[:-1], None)
60
61 # Test by classifying each dataset:
62 for name, data in {"train":training, "test": testing}.items():
63 correct = 0
64 for _, example in data.iterrows():
65 classification = example['CLASS']
66 result = classify(tree, example.drop('CLASS'))
67 correct += 1 if result == classification else 0
68 print("Accuracy on", name, "set:\t", correct / len(data)) | 32 - refactor: no-else-return
44 - warning: redefined-outer-name
44 - warning: redefined-outer-name
47 - refactor: no-else-return
|
1 from django.urls import path
2 from django.conf import settings
3 from django.conf.urls.static import static
4
5 from map.views import MapView
6 from map.api import SpotsApi, SpotApi, RatingsApi, VotesApi
7
8 app_name = 'map'
9 urlpatterns = [
10 path('', MapView.as_view(), name='index'),
11
12 path('spots/', SpotsApi.as_view()),
13 path('spots/<int:spot_id>/', SpotApi.as_view()),
14 path('spots/<int:spot_id>/ratings/', RatingsApi.as_view()),
15 path('spots/<int:spot_id>/votes/', VotesApi.as_view()),
16 ]
17
18 if settings.DEBUG is True:
19 urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| Clean Code: No Issues Detected
|
1 # Generated by Django 2.0.1 on 2018-03-06 21:19
2
3 from django.db import migrations
4
5
6 class Migration(migrations.Migration):
7
8 dependencies = [
9 ('map', '0009_auto_20180305_2215'),
10 ]
11
12 operations = [
13 migrations.RenameField(
14 model_name='rating',
15 old_name='rating',
16 new_name='rating_type',
17 ),
18 ]
| 6 - refactor: too-few-public-methods
|
1 # Generated by Django 2.0.1 on 2018-03-05 22:11
2
3 from django.db import migrations, models
4
5
6 class Migration(migrations.Migration):
7
8 dependencies = [
9 ('map', '0007_auto_20180305_2139'),
10 ]
11
12 operations = [
13 migrations.RenameField(
14 model_name='rating',
15 old_name='rating_type',
16 new_name='rating',
17 ),
18 migrations.AddField(
19 model_name='rating',
20 name='score',
21 field=models.IntegerField(default=0),
22 ),
23 ]
| 6 - refactor: too-few-public-methods
|
1 from django.db import models
2 from django.core.validators import MaxValueValidator, MinValueValidator
3
4
5 class Spot(models.Model):
6
7 name = models.CharField(max_length=50)
8 description = models.CharField(max_length=500)
9 latitude = models.DecimalField(max_digits=10, decimal_places=7)
10 longitude = models.DecimalField(max_digits=10, decimal_places=7)
11 created = models.DateTimeField(auto_now_add=True)
12 updated = models.DateTimeField(auto_now=True)
13
14 def __str__(self):
15 spot = "Spot %s - %s: %s" % (self.id, self.name, self.description)
16 return spot
17
18 def get_score(self):
19 votes = Vote.objects.filter(spot=self.id)
20
21 score = 0
22 for vote in votes:
23 score += 1 if vote.positive else -1
24
25 return score
26
27 def get_ratings_dict(self):
28 ratings = Rating.objects.filter(spot=self.id)
29
30 ratings_dict = {}
31 for rating in ratings:
32 if rating.rating_type.name in ratings_dict:
33 ratings_dict[rating.rating_type.name] += rating.score
34 else:
35 ratings_dict[rating.rating_type.name] = rating.score
36
37 for rating_type, score in ratings_dict.items():
38 ratings_dict[rating_type] = round((score / ratings.count()), 2)
39
40 return ratings_dict
41
42 class RatingType(models.Model):
43
44 name = models.CharField(max_length=50)
45
46 def __str__(self):
47 rating_type = self.name
48 return rating_type
49
50 class Rating(models.Model):
51
52 spot = models.ForeignKey(Spot, on_delete=models.CASCADE)
53 rating_type = models.ForeignKey(RatingType, on_delete=models.CASCADE)
54 score = models.IntegerField(
55 validators=[
56 MaxValueValidator(10),
57 MinValueValidator(1)
58 ]
59 )
60
61 class Vote(models.Model):
62
63 spot = models.ForeignKey(Spot, on_delete=models.CASCADE)
64 positive = models.BooleanField()
| 42 - refactor: too-few-public-methods
50 - refactor: too-few-public-methods
61 - refactor: too-few-public-methods
|
1 # Generated by Django 2.0.1 on 2018-03-05 22:15
2
3 from django.db import migrations, models
4 import django.db.models.deletion
5
6
7 class Migration(migrations.Migration):
8
9 dependencies = [
10 ('map', '0008_auto_20180305_2211'),
11 ]
12
13 operations = [
14 migrations.CreateModel(
15 name='Vote',
16 fields=[
17 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18 ('positive', models.BooleanField()),
19 ('spot', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='map.Spot')),
20 ],
21 ),
22 migrations.AlterField(
23 model_name='rating',
24 name='score',
25 field=models.IntegerField(),
26 ),
27 ]
| 7 - refactor: too-few-public-methods
|
1 from django.shortcuts import render
2 from django.views import View
3
4 class MapView(View):
5 def get(self, request):
6 return render(request, 'map/index.html')
| 4 - refactor: too-few-public-methods
|
1 from django import forms
2 from django.forms import ModelForm, Textarea
3
4 from map.models import Spot, Rating, Vote
5
6 class SpotForm(ModelForm):
7 class Meta:
8 model = Spot
9 fields = ['name', 'description', 'latitude', 'longitude']
10 widgets = {
11 'latitude': forms.HiddenInput(),
12 'longitude': forms.HiddenInput(),
13 }
14
15 class RatingForm(ModelForm):
16 class Meta:
17 model = Rating
18 fields = ['spot', 'rating_type', 'score']
19 widgets = {
20 'spot': forms.HiddenInput(),
21 'rating_type': forms.HiddenInput(),
22 }
23
24 class VoteForm(ModelForm):
25 class Meta:
26 model = Vote
27 fields = ['positive']
28 widgets = {
29 'positive': forms.HiddenInput(),
30 }
| 7 - refactor: too-few-public-methods
6 - refactor: too-few-public-methods
16 - refactor: too-few-public-methods
15 - refactor: too-few-public-methods
25 - refactor: too-few-public-methods
24 - refactor: too-few-public-methods
2 - warning: unused-import
|
1 from abc import ABC, ABCMeta, abstractmethod
2 from django.forms.models import model_to_dict
3 from django.http import HttpResponse, JsonResponse
4 from django.shortcuts import get_object_or_404
5 from django.views import View
6 from django.views.decorators.csrf import csrf_exempt
7 from django.utils.decorators import method_decorator
8 from map.models import Spot
9 from map.models import Vote
10 from map.forms import SpotForm, VoteForm
11
12 class BaseApi(View):
13 __metaclass__ = ABCMeta
14
15 def _response(self, body):
16 response = {'data': body}
17 return JsonResponse(response)
18
19 def _error_response(self, status, error):
20 response = {'error': error}
21 return JsonResponse(response, status=status)
22
23
24 class BaseSpotsApi(BaseApi):
25 __metaclass__ = ABCMeta
26
27 def _spot_to_dict(self, spot):
28 spot_dict = model_to_dict(spot)
29 spot_dict['score'] = spot.get_score()
30
31 return spot_dict
32
33 # @method_decorator(csrf_exempt, name='dispatch')
34 class SpotsApi(BaseSpotsApi):
35 def get(self, request):
36 # TODO: only retrieve nearest spots and make them dynamically load as the map moves
37 nearby_spots = Spot.objects.all()
38 nearby_spots = list(map(self._spot_to_dict, nearby_spots))
39
40 return self._response(nearby_spots)
41
42 def post(self, request):
43 form = SpotForm(request.POST)
44
45 if form.is_valid():
46 new_spot = Spot(
47 name=request.POST['name'],
48 description=request.POST['description'],
49 latitude=request.POST['latitude'],
50 longitude=request.POST['longitude']
51 )
52 new_spot.save()
53
54 return self._response(self._spot_to_dict(new_spot))
55
56 return self._error_response(422, 'Invalid input.')
57
58 class SpotApi(BaseSpotsApi):
59 def get(self, request, spot_id):
60 spot = get_object_or_404(Spot, pk=spot_id)
61
62 return self._response(self._spot_to_dict(spot))
63
64 # @method_decorator(csrf_exempt, name='dispatch')
65 class RatingsApi(BaseApi):
66 def get(self, request, spot_id):
67 spot = get_object_or_404(Spot, pk=spot_id)
68
69 ratings = Rating.objects.filter(spot=spot_id, rating_type=rating_type.id)
70
71 pass
72
73 def post(self, request, spot_id):
74 spot = get_object_or_404(Spot, pk=spot_id)
75
76 pass
77
78 # @method_decorator(csrf_exempt, name='dispatch')
79 class VotesApi(BaseApi):
80 def get(self, request, spot_id):
81 spot = get_object_or_404(Spot, pk=spot_id)
82
83 return self._response(spot.get_score())
84
85 def post(self, request, spot_id):
86 spot = get_object_or_404(Spot, pk=spot_id)
87 form = VoteForm(request.POST)
88
89 if form.is_valid():
90 new_vote = Vote(spot=spot, positive=request.POST['positive'])
91 new_vote.save()
92
93 return self._response(model_to_dict(new_vote))
94
95 return self._error_response(422, 'Invalid input.')
| 36 - warning: fixme
12 - refactor: too-few-public-methods
24 - refactor: too-few-public-methods
35 - warning: unused-argument
59 - warning: unused-argument
58 - refactor: too-few-public-methods
69 - error: undefined-variable
69 - error: undefined-variable
71 - warning: unnecessary-pass
66 - warning: unused-argument
67 - warning: unused-variable
69 - warning: unused-variable
76 - warning: unnecessary-pass
73 - warning: unused-argument
74 - warning: unused-variable
80 - warning: unused-argument
1 - warning: unused-import
1 - warning: unused-import
3 - warning: unused-import
6 - warning: unused-import
7 - warning: unused-import
|
1 # Generated by Django 2.0.1 on 2018-03-05 21:39
2
3 from django.db import migrations
4
5
6 class Migration(migrations.Migration):
7
8 dependencies = [
9 ('map', '0006_rating'),
10 ]
11
12 operations = [
13 migrations.RenameField(
14 model_name='rating',
15 old_name='rating_type_id',
16 new_name='rating_type',
17 ),
18 migrations.RenameField(
19 model_name='rating',
20 old_name='spot_id',
21 new_name='spot',
22 ),
23 ]
| 6 - refactor: too-few-public-methods
|
1 # Generated by Django 2.0.1 on 2018-03-05 21:31
2
3 from django.db import migrations, models
4
5
6 class Migration(migrations.Migration):
7
8 dependencies = [
9 ('map', '0004_ratingtype'),
10 ]
11
12 operations = [
13 migrations.AlterField(
14 model_name='spot',
15 name='latitude',
16 field=models.DecimalField(decimal_places=7, max_digits=10),
17 ),
18 migrations.AlterField(
19 model_name='spot',
20 name='longitude',
21 field=models.DecimalField(decimal_places=7, max_digits=10),
22 ),
23 ]
| 6 - refactor: too-few-public-methods
|
1 # Generated by Django 2.0 on 2017-12-17 18:04
2
3 from django.db import migrations, models
4
5
6 class Migration(migrations.Migration):
7
8 initial = True
9
10 dependencies = [
11 ]
12
13 operations = [
14 migrations.CreateModel(
15 name='Spot',
16 fields=[
17 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18 ('name', models.CharField(max_length=50)),
19 ('description', models.CharField(max_length=500)),
20 ('latitude', models.DecimalField(decimal_places=6, max_digits=9)),
21 ('longitude', models.DecimalField(decimal_places=6, max_digits=9)),
22 ],
23 ),
24 ]
| 6 - refactor: too-few-public-methods
|
1 """
2 Heart attack detection in colour images using convolutional neural networks
3
4 This code make a neural network to detect infarcts
5 Written by Gabriel Rojas - 2019
6 Copyright (c) 2019 G0 S.A.S.
7 Licensed under the MIT License (see LICENSE for details)
8 """
9
10
11 from os import scandir
12 import numpy as np
13 from keras.models import load_model
14 from keras.preprocessing.image import load_img, img_to_array
15 from keras.preprocessing.image import ImageDataGenerator
16
17 # === Configuration vars ===
18 # Path of image folder
19 INPUT_PATH_TEST = "./dataset/test/"
20 MODEL_PATH = "./model/" + "model.h5" # Full path of model
21
22 # Test configurations
23 WIDTH, HEIGHT = 256, 256 # Size images to train
24 CLASS_COUNTING = True # Test class per class and show details each
25 BATCH_SIZE = 32 # How many images at the same time, change depending on your GPU
26 CLASSES = ['00None', '01Infarct'] # Classes to detect. they most be in same position with output vector
27 # === ===== ===== ===== ===
28
29 print("Loading model from:", MODEL_PATH)
30 NET = load_model(MODEL_PATH)
31 NET.summary()
32
33 def predict(file):
34 """
35 Returns values predicted
36 """
37 x = load_img(file, target_size=(WIDTH, HEIGHT))
38 x = img_to_array(x)
39 x = np.expand_dims(x, axis=0)
40 array = NET.predict(x)
41 result = array[0]
42 answer = np.argmax(result)
43 return CLASSES[answer], result
44
45 print("\n======= ======== ========")
46
47 if CLASS_COUNTING:
48 folders = [arch.name for arch in scandir(INPUT_PATH_TEST) if arch.is_file() == False]
49
50 generalSuccess = 0
51 generalCases = 0
52 for f in folders:
53 files = [arch.name for arch in scandir(INPUT_PATH_TEST + f) if arch.is_file()]
54 clase = f.replace(INPUT_PATH_TEST, '')
55 print("Class: ", clase)
56 indivSuccess = 0
57 indivCases = 0
58 for a in files:
59 p, r = predict(INPUT_PATH_TEST + f + "/" + a)
60 if p == clase:
61 indivSuccess = indivSuccess + 1
62 #elif p == '00None':
63 # print(f + "/" + a)
64 indivCases = indivCases + 1
65
66 print("\tCases", indivCases, "Success", indivSuccess, "Rate", indivSuccess/indivCases)
67
68 generalSuccess = generalSuccess + indivSuccess
69 generalCases = generalCases + indivCases
70
71 print("Totals: ")
72 print("\tCases", generalCases, "Success", generalSuccess, "Rate", generalSuccess/generalCases)
73 else:
74 test_datagen = ImageDataGenerator()
75 test_gen = test_datagen.flow_from_directory(
76 INPUT_PATH_TEST,
77 target_size=(HEIGHT, WIDTH),
78 batch_size=BATCH_SIZE,
79 class_mode='categorical')
80 scoreSeg = NET.evaluate_generator(test_gen, 100)
81 progress = 'loss: {}, acc: {}, mse: {}'.format(
82 round(float(scoreSeg[0]), 4),
83 round(float(scoreSeg[1]), 4),
84 round(float(scoreSeg[2]), 4)
85 )
86 print(progress)
87
88 print("======= ======== ========")
| Clean Code: No Issues Detected
|
1 """
2 Heart attack detection in colour images using convolutional neural networks
3
4 This code make a neural network to detect infarcts
5 Written by Gabriel Rojas - 2019
6 Copyright (c) 2019 G0 S.A.S.
7 Licensed under the MIT License (see LICENSE for details)
8 """
9
10 import os
11 import sys
12 from time import time
13 import tensorflow
14 import keras
15 from keras import backend as K
16 from keras.models import Sequential
17 from keras.optimizers import SGD
18 from keras.preprocessing.image import ImageDataGenerator
19 from keras.layers import Dropout, Flatten, Dense, Activation
20 from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
21
22 # === Configuration vars ===
23 # Path of image folder (use slash at the end)
24 INPUT_PATH_TRAIN = "./dataset/train/"
25 INPUT_PATH_VAL = "./dataset/val/"
26 INPUT_PATH_TEST = "./dataset/test/"
27 OUTPUT_DIR = "./model/"
28
29 # Checkpoints
30 EPOCH_CHECK_POINT = 2 # How many epoch til save next checkpoint
31 NUM_CHECK_POINT = 10 # How many epoch will be saved
32 KEEP_ONLY_LATEST = False# Keeping only the last checkpoint
33
34 # Train configurations
35 WIDTH, HEIGHT = 256, 256# Size images to train
36 STEPS = 500 # How many steps per epoch
37 VALIDATION_STEPS = 100 # How many steps per next validation
38 BATCH_SIZE = 48 # How many images at the same time, change depending on your GPU
39 LR = 0.003 # Learning rate
40 CLASSES = 2 # Don't chage, 0=Infarct, 1=Normal
41 # === ===== ===== ===== ===
42
43 if not os.path.exists(OUTPUT_DIR):
44 os.mkdir(OUTPUT_DIR)
45
46 K.clear_session()
47
48 train_datagen = ImageDataGenerator()
49 val_datagen = ImageDataGenerator()
50 test_datagen = ImageDataGenerator()
51
52 train_gen = train_datagen.flow_from_directory(
53 INPUT_PATH_TRAIN,
54 target_size=(HEIGHT, WIDTH),
55 batch_size=BATCH_SIZE,
56 class_mode='categorical')
57 val_gen = val_datagen.flow_from_directory(
58 INPUT_PATH_VAL,
59 target_size=(HEIGHT, WIDTH),
60 batch_size=BATCH_SIZE,
61 class_mode='categorical')
62 test_gen = test_datagen.flow_from_directory(
63 INPUT_PATH_TEST,
64 target_size=(HEIGHT, WIDTH),
65 batch_size=BATCH_SIZE,
66 class_mode='categorical')
67
68 NET = Sequential()
69 NET.add(Convolution2D(64, kernel_size=(3 ,3), padding ="same", input_shape=(256, 256, 3), activation='relu'))
70 NET.add(MaxPooling2D((3,3), strides=(3,3)))
71 NET.add(Convolution2D(128, kernel_size=(3, 3), activation='relu'))
72 NET.add(MaxPooling2D((3,3), strides=(3,3)))
73 NET.add(Convolution2D(256, kernel_size=(3, 3), activation='relu'))
74 NET.add(MaxPooling2D((2,2), strides=(2,2)))
75 NET.add(Convolution2D(512, kernel_size=(3, 3), activation='relu'))
76 NET.add(MaxPooling2D((2,2), strides=(2,2)))
77 NET.add(Convolution2D(1024, kernel_size=(3, 3), activation='relu'))
78 NET.add(MaxPooling2D((2,2), strides=(2,2)))
79 NET.add(Dropout(0.3))
80 NET.add(Flatten())
81
82 for _ in range(5):
83 NET.add(Dense(128, activation='relu'))
84 NET.add(Dropout(0.5))
85
86 for _ in range(5):
87 NET.add(Dense(128, activation='relu'))
88 NET.add(Dropout(0.5))
89
90 for _ in range(5):
91 NET.add(Dense(128, activation='relu'))
92 NET.add(Dropout(0.5))
93
94 NET.add(Dense(CLASSES, activation='softmax'))
95
96 sgd = SGD(lr=LR, decay=1e-4, momentum=0.9, nesterov=True)
97
98 NET.compile(optimizer=sgd,
99 loss='binary_crossentropy',
100 metrics=['acc', 'mse'])
101
102 NET.summary()
103
104 for i in range(NUM_CHECK_POINT):
105 NET.fit_generator(
106 train_gen,
107 steps_per_epoch=STEPS,
108 epochs=EPOCH_CHECK_POINT,
109 validation_data=val_gen,
110 validation_steps=VALIDATION_STEPS,
111 verbose=1
112 )
113
114 print('Saving model: {:02}.'.format(i))
115 NET.save(OUTPUT_DIR + "{:02}_model.h5".format(i))
| 11 - warning: unused-import
12 - warning: unused-import
13 - warning: unused-import
14 - warning: unused-import
19 - warning: unused-import
20 - warning: unused-import
|
1 from flask import Flask, render_template, request
2 from flask_sqlalchemy import SQLAlchemy
3
4 import pymysql
5 pymysql.install_as_MySQLdb()
6
7 app = Flask(__name__)
8 app.config['SQLALCHEMY_DATABASE_URI']="mysql://root:horsin@123@localhost:3306/flask"
9 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
10
11 db = SQLAlchemy(app)
12
13 class loginUser(db.Model):
14 __tablename__ = "loginUser"
15 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
16 username = db.Column(db.String(30), unique=True)
17 passwd = db.Column(db.String(120))
18
19 def __init__(self, username, passwd):
20 self.username = username
21 self.passwd = passwd
22
23 def __repr__(self):
24 return "<loginUser: %r>" % self.username
25
26 db.create_all()
27
28 @app.route('/login')
29 def login_views():
30 return render_template('06-login.html')
31
32 @app.route('/server', methods=['POST'])
33 def server_views():
34 username = request.form['username']
35 user = loginUser.query.filter_by(username=username).first()
36 if user:
37 return "找到用户名为 %s 的账户" % user.username
38 else:
39 return "找不到该用户!"
40
41 if __name__ == '__main__':
42 app.run(debug=True) | 13 - refactor: too-few-public-methods
36 - refactor: no-else-return
|
1 from flask import Flask, render_template
2 from flask_sqlalchemy import SQLAlchemy
3 import json
4
5 import pymysql
6 pymysql.install_as_MySQLdb()
7
8 app = Flask(__name__)
9 app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:horsin@123@localhost:3306/flask"
10 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
11
12 db = SQLAlchemy(app)
13
14 class Users(db.Model):
15 __tablename__ = "users"
16 id = db.Column(db.Integer,primary_key=True)
17 uname = db.Column(db.String(50))
18 upwd = db.Column(db.String(50))
19 realname = db.Column(db.String(30))
20
21 # 将当前对象中的所有属性封装到一个字典中
22 def to_dict(self):
23 dic = {
24 "id" : self.id,
25 "uname" : self.uname,
26 "upwd" : self.upwd,
27 "realname" : self.realname
28 }
29 return dic
30
31 def __init__(self,uname,upwd,realname):
32 self.uname = uname
33 self.upwd = upwd
34 self.realname = realname
35
36 def __repr__(self):
37 return "<Users : %r>" % self.uname
38
39 @app.route('/json')
40 def json_views():
41 # list = ["Fan Bingbing","Li Chen","Cui Yongyuan"]
42 dic = {
43 'name' : 'Bingbing Fan',
44 'age' : 40,
45 'gender' : "female"
46 }
47 uList = [
48 {
49 'name' : 'Bingbing Fan',
50 'age' : 40,
51 'gender' : "female"
52 },
53 {
54 'name' : 'Li Chen',
55 "age" : 40,
56 "gender" : 'male'
57 }
58 ]
59 # jsonStr = json.dumps(list)
60 jsonStr = json.dumps(dic)
61 return jsonStr
62
63 @app.route('/page')
64 def page_views():
65 return render_template('01-page.html')
66
67 @app.route('/json_users')
68 def json_users():
69 # user = Users.query.filter_by(id=1).first()
70 # print(user)
71 # return json.dumps(user.to_dict())
72 users = Users.query.filter_by(id=1).all()
73 print(users)
74 list = []
75 for user in users:
76 list.append(user.to_dict())
77 return json.dumps(list)
78
79 @app.route('/show_info')
80 def show_views():
81 return render_template('02-user.html')
82
83 @app.route('/server')
84 def server_views():
85 users = Users.query.filter().all()
86 list = []
87 for user in users:
88 list.append(user.to_dict())
89 return json.dumps(list)
90
91 @app.route('/load')
92 def load_views():
93 return render_template('04-load.html')
94
95 @app.route('/load_server')
96 def load_server():
97 return "这是使用jquery的load方法发送的请求"
98
99 if __name__ == "__main__":
100 app.run(debug=True) | 47 - warning: unused-variable
74 - warning: redefined-builtin
86 - warning: redefined-builtin
|
1 from flask import Flask, render_template, request
2 from flask_sqlalchemy import SQLAlchemy
3 import json
4
5 import pymysql
6 pymysql.install_as_MySQLdb()
7
8 app = Flask(__name__)
9 app.config['SQLALCHEMY_DATABASE_URI']="mysql://root:horsin@123@localhost:3306/flask"
10 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
11
12 db = SQLAlchemy(app)
13
14 class Users(db.Model):
15 __tablename__ = "loginUser"
16 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
17 username = db.Column(db.String(30), unique=True)
18 passwd = db.Column(db.String(120))
19
20 def __init__(self, username):
21 self.username = username
22
23 def to_dict(self):
24 dic = {
25 "username" : self.username,
26 "passwd" : self.passwd
27 }
28 return dic
29
30 def __repr__(self):
31 return "<Users : %r>" % self.username
32
33 class Province(db.Model):
34 __tablename__="province"
35 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
36 proname = db.Column(db.String(30))
37 cities = db.relationship("City", backref="province", lazy="dynamic")
38
39 def __init__(self, proname):
40 self.proname = proname
41
42 def __repr__(self):
43 return "<Province : %r>" % self.proname
44
45 def to_dict(self):
46 dic = {
47 "id" : self.id,
48 "proname" : self.proname
49 }
50 return dic
51
52 class City(db.Model):
53 __tablename__="city"
54 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
55 cityname = db.Column(db.String(30))
56 pro_id = db.Column(db.Integer, db.ForeignKey("province.id"))
57
58 def __init__(self, cityname, pro_id):
59 self.cityname = cityname
60 self.pro_id = pro_id
61
62 def __repr__(self):
63 return "<City : %r>" % self.cityname
64
65 def to_dict(self):
66 dic = {
67 "id" : self.id,
68 "cityname" : self.cityname,
69 "pro_id" : self.pro_id
70 }
71 return dic
72
73 @app.route('/01-ajax')
74 def ajax_views():
75 return render_template('01-ajax.html')
76
77 @app.route('/01-server')
78 def server_01():
79 uname = request.args.get("username")
80 print(uname)
81 user = Users.query.filter_by(username=uname).first()
82 if user:
83 return json.dumps(user.to_dict())
84 else:
85 dic = {
86 'status' : '0',
87 'msg' : '没有查到任何信息!'
88 }
89 return dic
90
91 @app.route('/02-province')
92 def province_views():
93 return render_template('03-province.html')
94
95 @app.route('/loadPro')
96 def loadPro_views():
97 provinces = Province.query.all()
98 list = []
99 for province in provinces:
100 list.append(province.to_dict())
101 return json.dumps(list)
102
103 @app.route('/loadCity')
104 def loadCity_views():
105 pid = request.args.get("pid")
106 cities = City.query.filter_by(pro_id=pid).all()
107 list = []
108 for city in cities:
109 list.append(city.to_dict())
110 return json.dumps(list)
111
112 @app.route('/crossdomain')
113 def crossdomain_views():
114 return render_template('04-crossdomain.html')
115
116 @app.route('/02-server')
117 def server_02():
118 return "show('这是server_02响应回来的数据')"
119
120 if __name__ == '__main__':
121 app.run(debug=True)
122
123
124
125
126
| 82 - refactor: no-else-return
98 - warning: redefined-builtin
107 - warning: redefined-builtin
|
1 from flask import Flask, render_template, request
2 from flask_sqlalchemy import SQLAlchemy
3 import json
4
5 import pymysql
6 pymysql.install_as_MySQLdb()
7
8 app = Flask(__name__)
9 app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:horsin@123@localhost:3306/flask"
10 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
11
12 db = SQLAlchemy(app)
13
14 class Province(db.Model):
15 __tablename__ = "province"
16 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
17 proname = db.Column(db.String(30), nullable=False)
18 cities = db.relationship("City", backref="province", lazy="dynamic")
19
20 def __init__(self, proname):
21 self.proname = proname
22
23 def to_dict(self):
24 dic = {
25 'id' : self.id,
26 'proname' : self.proname
27 }
28 return dic
29
30 def __repr__(self):
31 return "<Province : %r>" % self.proname
32
33 class City(db.Model):
34 __tablename__ = "city"
35 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
36 cityname = db.Column(db.String(30), nullable=False)
37 pro_id = db.Column(db.Integer, db.ForeignKey("province.id"))
38
39 def __init__(self, cityname, pro_id):
40 self.cityname = cityname
41 self.pro_id = pro_id
42
43 def to_dict(self):
44 dic = {
45 'id' : self.id,
46 'cityname' : self.cityname,
47 'pro_id' : self.pro_id
48 }
49 return dic
50
51 def __repr__(self):
52 return "<City : %r>" % self.cityname
53
54 db.create_all()
55
56 @app.route('/province')
57 def province_views():
58 return render_template('03-province.html')
59
60 @app.route('/loadPro')
61 def loadPro_views():
62 provinces = Province.query.all()
63 list = []
64 for pro in provinces:
65 list.append(pro.to_dict())
66 return json.dumps(list)
67
68 @app.route('/loadCity')
69 def loadCity_view():
70 pid = request.args.get('pid')
71 cities = City.query.filter_by(pro_id=pid).all()
72 list = []
73 for city in cities:
74 list.append(city.to_dict())
75 return list
76
77 if __name__ == "__main__":
78 app.run(debug=True)
| 63 - warning: redefined-builtin
72 - warning: redefined-builtin
|
1 from flask import Flask, render_template, request
2
3 app = Flask(__name__)
4
5 @app.route('/01-getxhr')
6 def getxhr():
7 return render_template('01-getxhr.html')
8
9 @app.route('/02-get')
10 def get_views():
11 return render_template('02-get.html')
12
13 @app.route('/03-get')
14 def get03_view():
15 return render_template('03-get.html')
16
17 @app.route('/02-server')
18 def server02_views():
19 return "这是AJAX的请求"
20
21 @app.route('/03-server')
22 def server03_views():
23 uname = request.args.get('uname')
24 return "欢迎: "+uname
25
26 @app.route('/04-post')
27 def post_views():
28 return render_template('04-post.html')
29
30 @app.route('/04-server', methods=['POST'])
31 def server04_views():
32 uname = request.form['uname']
33 return uname
34
35 @app.route('/05-post')
36 def post05_views():
37 return render_template('05-post.html')
38
39 if __name__ == '__main__':
40 app.run(debug=True) | Clean Code: No Issues Detected
|
1 import cv2
2 import numpy as np
3
4 # minDist = 120
5 # param1 = 50
6 # param2 = 30
7 # minRadius = 5
8 # maxRadius = 0
9
10 def circleScan(frame, camX, camY):
11 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
12 blurred = cv2.GaussianBlur(gray,(11,11),0)
13 circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1,120, param1=220, param2=30, minRadius=50, maxRadius=300)
14
15 # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius)
16 if circles is not None:
17 circles = np.round(circles[0, :]).astype("int")
18 for (x, y, r) in circles:
19 cv2.circle(frame, (x, y), r, (0, 255, 0), 4)
20 cv2.rectangle(frame, (x - 5, y - 5),
21 (x + 5, y + 5), (0, 128, 255), -1)
22 x = x - camX/2
23 y = (y - camY/2) * -1
24 return [x,y]
25
26
27
28 # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100)
| 10 - refactor: inconsistent-return-statements
|
1 import RPi.GPIO as GPIO
2 import time
3 import os
4
5 GPIO.setmode(GPIO.BCM)
6 GPIO.setup("1",GPIO.IN)
7 GPIO.setup("2",GPIO.IN)
8
9 input = GPIO.input("1")
10 input = GPIO.input("2")
11
12
13 while True:
14 inputValue = GPIO.input("1")
15 if (inputValue == False):
16 print("1. Görev")
17 os.system('..\\daire\\main.py') # Daha verimli
18 # if keyboard.is_pressed("2"):
19 # os.system('..\\dikdörtgen\\main.py') # Daha verimli
20 # if keyboard.is_pressed("3"):
21 # print("3. Görev")
22 # # os.startfile('..\\daire\\main.py') | 14 - warning: bad-indentation
15 - warning: bad-indentation
16 - warning: bad-indentation
17 - warning: bad-indentation
9 - warning: redefined-builtin
1 - refactor: consider-using-from-import
2 - warning: unused-import
|
1 import keyboard
2 import os
3
4 while True:
5 if keyboard.is_pressed("1"):
6 print("1. Görev")
7 os.system('..\\daire\\main.py')
8 if keyboard.is_pressed("2"):
9 os.system('..\\dikdörtgen\\main.py')
10 if keyboard.is_pressed("3"):
11 print("3. Görev") | Clean Code: No Issues Detected
|
1 import cv2
2 from daire import circleScan
3 import keyboard
4 import os
5
6 cameraX = 800
7 cameraY = 600
8
9 cap = cv2.VideoCapture(0)
10 # Cemberin merkezinin ekranın orta noktaya uzaklıgını x ve y cinsinden uzaklıgı
11 while True:
12 if keyboard.is_pressed("2"):
13 print("2. Görev")
14 cap.release()
15 cv2.destroyAllWindows()
16 os.system('..\\dikdörtgen\\main.py') # Daha verimli
17 break
18 if keyboard.is_pressed("3"):
19 cap.release()
20 cv2.destroyAllWindows()
21 print("3. Görev")
22 break
23
24 ret, frame = cap.read()
25 frame = cv2.resize(frame, (cameraX, cameraY))
26 data = circleScan(frame, cameraX, cameraY)
27 if data is not None:
28 print("X : " ,data[0] , " Y : " , data[1])
29
30 cv2.imshow("output", frame)
31
32 if cv2.waitKey(1) & 0xFF == ord('q'):
33 break
34 cap.release()
35 cv2.destroyAllWindows() | Clean Code: No Issues Detected
|
1 import cv2
2 # import numpy as np
3 import keyboard
4 import os
5
6 cameraX = 800
7 cameraY = 600
8
9 cap = cv2.VideoCapture(0)
10
11 while(True):
12 if keyboard.is_pressed("1"):
13 print("1. Görev Dikdortgende")
14 cap.release()
15 cv2.destroyAllWindows()
16 os.system('..\\daire\\main.py') # Daha verimli
17 break
18 if keyboard.is_pressed("3"):
19 print("3. Görev Dikdortgende")
20 break
21
22 ret, image = cap.read()
23 image = cv2.resize(image, (cameraX, cameraY))
24 original = image.copy()
25 cv2.rectangle(original, (395, 295),
26 (405, 305), (0, 128, 50), -1)
27 blurred = cv2.medianBlur(image, 3)
28 # blurred = cv2.GaussianBlur(hsv,(3,3),0)
29
30 hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
31 mask = cv2.inRange(hsv,(15,0,0), (29, 255, 255))
32 cnts,_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
33
34 minArea = []
35 minC = []
36 for c in cnts:
37 area = cv2.contourArea(c)
38 if area > 400:
39 approx = cv2.approxPolyDP(c, 0.125 * cv2.arcLength(c, True), True)
40 if(len(approx) == 4):
41 minArea.append(area)
42 minC.append([area, c])
43 if minArea:
44 minArea.sort()
45 print(minArea)
46 mArea = minArea[0]
47 mC = []
48 for x in minC:
49 if x[0] == mArea:
50 mC = x[1]
51
52 M = cv2.moments(mC)
53 cx = int(M['m10']/M['m00'])
54 cy = int(M['m01']/M['m00'])
55
56 x = cx - cameraX/2
57 y = (cy - cameraY/2) * -1
58 print(cx, cy , x , y)
59 cv2.rectangle(original, (cx - 5, cy - 5),
60 (cx + 5, cy + 5), (0, 128, 255), -1)
61 cv2.drawContours(original, [approx], 0, (0, 0, 255), 5)
62
63 cv2.imshow('mask', mask)
64 cv2.imshow('original', original)
65
66 if cv2.waitKey(1) & 0xFF == ord('q'):
67 cap.release()
68 break
69
70 cv2.destroyAllWindows() | Clean Code: No Issues Detected
|
1 import cv2 as cv
2 import numpy as np
3 import sys
4 from matplotlib import pyplot as plt
5
6 def main():
7 square = cv.imread('./img/square.png')
8 ball = cv.imread('./img/ball.png')
9 mask = cv.imread('./img/mask2.png')
10
11 square_gray = cv.cvtColor(square, cv.COLOR_BGR2GRAY)
12 ball_gray = cv.cvtColor(ball, cv.COLOR_BGR2GRAY)
13
14 args = sys.argv
15 if (len(args) > 1):
16 if (args[1] == 'add'):
17 title = 'Sum'
18 image = add(square, ball)
19 elif (args[1] == 'sub'):
20 title = 'Subtraction'
21 image = sub(square, ball)
22 elif (args[1] == 'mult'):
23 title = 'Multiplication'
24 image = mult(square, ball)
25 elif (args[1] == 'div'):
26 title = 'Division'
27 image = div(square, ball)
28 elif (args[1] == 'and'):
29 title = 'And operation'
30 image = andF(square, ball)
31 elif (args[1] == 'or'):
32 title = 'Or operation'
33 image = orF(square, ball)
34 elif (args[1] == 'xor'):
35 title = 'Xor operation'
36 image = xorF(square, ball)
37 elif (args[1] == 'not'):
38 title = 'Not operation'
39 image = notF(square, ball)
40 elif (args[1] == 'blur'):
41 title = 'Blur'
42 image = blur(mask)
43 elif (args[1] == 'box'):
44 title = 'Box filter'
45 image = box(mask)
46 elif (args[1] == 'median'):
47 title = 'Median filter'
48 image = median(mask)
49 elif (args[1] == 'dd'):
50 title = '2D filter'
51 image = dd(mask)
52 elif (args[1] == 'gaussian'):
53 title = 'Gaussian filter'
54 image = gaussian(mask)
55 elif (args[1] == 'bilateral'):
56 title = 'Bilateral filter'
57 image = bilateral(mask)
58 else:
59 print('(!) -- Error - no operation called')
60 exit(0)
61
62 if (len(args) > 2 and args[2] == 'special'):
63 original = mask if args[1] == 'blur' or args[1] == 'box' or args[1] == 'median' or args[1] == 'dd' or args[1] == 'gaussian' or args[1] == 'bilateral' else square
64 plt.subplot(121),plt.imshow(original),plt.title('Original')
65 plt.xticks([]), plt.yticks([])
66 plt.subplot(122),plt.imshow(image),plt.title(title)
67 plt.xticks([]), plt.yticks([])
68 plt.show()
69 else:
70 cv.imshow(title, image)
71 cv.waitKey(15000)
72 cv.destroyAllWindows()
73 else:
74 print('(!) -- Error - no operation called')
75 exit(0)
76
77 def add(image1, image2):
78 # return cv.add(image1, image2, 0)
79 return cv.addWeighted(image1, 0.7, image2, 0.3, 0)
80
81 def sub(image1, image2):
82 return cv.subtract(image1, image2, 0)
83
84 def mult(image1, image2):
85 return cv.multiply(image1, image2)
86
87 def div(image1, image2):
88 return cv.divide(image1, image2)
89
90 def andF(image1, image2):
91 return cv.bitwise_and(image1, image2)
92
93 def orF(image1, image2):
94 return cv.bitwise_or(image1, image2)
95
96 def xorF(image1, image2):
97 return cv.bitwise_xor(image1, image2)
98
99 def notF(image1, image2):
100 return cv.bitwise_not(image1)
101
102 def blur(image1):
103 return cv.blur(image1, (5, 5))
104
105 def box(image1):
106 return cv.boxFilter(image1, 50, (5, 5), False)
107
108 def median(image1):
109 return cv.medianBlur(image1, 5)
110
111 def dd(image1):
112 kernel = np.ones((5,5),np.float32)/25
113 return cv.filter2D(image1, -1, kernel)
114
115 def gaussian(image1):
116 return cv.GaussianBlur(image1, (5, 5), 0)
117
118 def bilateral(image1):
119 return cv.bilateralFilter(image1, 9, 75, 75)
120
121 if __name__ == '__main__':
122 main()
| 60 - refactor: consider-using-sys-exit
64 - warning: expression-not-assigned
65 - warning: expression-not-assigned
66 - warning: expression-not-assigned
67 - warning: expression-not-assigned
75 - refactor: consider-using-sys-exit
6 - refactor: too-many-branches
6 - refactor: too-many-statements
11 - warning: unused-variable
12 - warning: unused-variable
99 - warning: unused-argument
|
1 """
2 Sudoku Solution Validator
3 http://www.codewars.com/kata/529bf0e9bdf7657179000008/train/python
4 """
5
6 def validSolution(board):
7 test = range(1,10,1)
8 def tester(alist):
9 return set(test)==set(alist)
10
11 for i in range(len(board)):
12 tem = board[i]
13 if not tester(tem):
14 return False
15
16
17 for i in range(len(board[0])):
18 if not tester([alist[i] for alist in board]):
19 return False
20
21
22 for i in range(3):
23 for j in range(3):
24 if not tester(sum([alist[j*3:j*3+3] for alist in board[i*3:i*3+3]] , [])):
25 return False
26
27 return True
28
29
30 boardOne = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
31 [6, 7, 2, 1, 9, 0, 3, 4, 8],
32 [1, 0, 0, 3, 4, 2, 5, 6, 0],
33 [8, 5, 9, 7, 6, 1, 0, 2, 0],
34 [4, 2, 6, 8, 5, 3, 7, 9, 1],
35 [7, 1, 3, 9, 2, 4, 8, 5, 6],
36 [9, 0, 1, 5, 3, 7, 2, 1, 4],
37 [2, 8, 7, 4, 1, 9, 6, 3, 5],
38 [3, 0, 0, 4, 8, 1, 1, 7, 9]]
39
40
41 boardTwo =[[5, 3, 4, 6, 7, 8, 9, 1, 2],
42 [6, 7, 2, 1, 9, 5, 3, 4, 8],
43 [1, 9, 8, 3, 4, 2, 5, 6, 7],
44 [8, 5, 9, 7, 6, 1, 4, 2, 3],
45 [4, 2, 6, 8, 5, 3, 7, 9, 1],
46 [7, 1, 3, 9, 2, 4, 8, 5, 6],
47 [9, 6, 1, 5, 3, 7, 2, 8, 4],
48 [2, 8, 7, 4, 1, 9, 6, 3, 5],
49 [3, 4, 5, 2, 8, 6, 1, 7, 9]]
50
51
52 print validSolution(boardOne)
53 print validSolution(boardTwo) | 52 - error: syntax-error
|
1 """
2 Validate Sudoku with size `NxN`
3 http://www.codewars.com/kata/540afbe2dc9f615d5e000425/train/python
4 """
5
| Clean Code: No Issues Detected
|
1 """
2 Vigenere Autokey Cipher Helper
3 http://www.codewars.com/kata/vigenere-autokey-cipher-helper
4 """
5
6 class VigenereAutokeyCipher:
7 def __init__(self, key, alphabet):
8 self.key = key
9 self.alphabet = alphabet
10
11 def code(self, text, direction):
12
13 toText = list(text)
14 result = []
15 newKey = filter(lambda x: (x in self.alphabet) == True, list(self.key)) #+ filter(lambda x: (x in self.alphabet) == True, toEncode)
16
17 #print 'new' ,newKey
18 j = 0
19 for i in range(len(toText)):
20 #print i ,self.key[i%(len(self.key))]
21 if toText[i] in self.alphabet:
22 if direction:
23 newKey.append(toText[i])
24 result.append(self.alphabet[(self.alphabet.index(toText[i]) + self.alphabet.index(newKey[j]))%len(self.alphabet)])
25 else:
26 result.append(self.alphabet[(self.alphabet.index(toText[i]) - self.alphabet.index(newKey[j]))%len(self.alphabet)])
27 newKey.append(result[-1])
28 j += 1
29 else:
30 result.append(toText[i])
31 return ''.join(result)
32
33
34 def encode(self, toEncode):
35 return self.code(toEncode,1)
36
37
38
39 def decode(self, toDecode):
40 return self.code(toDecode, 0)
41
42
43 def main():
44 alphabet = 'abcdefghijklmnopqrstuvwxyz'
45 #alphabet = 'abcdefgh'
46 key = 'password'
47 tester = VigenereAutokeyCipher(key,alphabet)
48
49 print tester.encode('codewars')
50 print tester.encode('amazingly few discotheques provide jukeboxes')
51 print 'pmsrebxoy rev lvynmylatcwu dkvzyxi bjbswwaib'
52
53 print tester.decode('pmsrebxoy rev lvynmylatcwu dkvzyxi bjbswwaib')
54 print 'amazingly few discotheques provide jukeboxes'
55
56 if __name__ == '__main__':
57 main() | 49 - error: syntax-error
|
1 '''
2
3 http://www.codewars.com/kata/53d3173cf4eb7605c10001a8/train/python
4
5 Write a function that returns all of the sublists of a list or Array.
6 Your function should be pure; it cannot modify its input.
7
8 Example:
9 power([1,2,3])
10 # => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
11 '''
12
13 def power(s):
14 """Computes all of the sublists of s"""
15 length = len(s)
16 count = 2**length
17 result = []
18 for i in range(count):
19 st = str(bin(i)[2:]).zfill(length)
20 temp = []
21 for j in range(length):
22 if st[length - 1 - j] == str(1):
23 temp.append(s[j])
24 result.append(temp)
25 return result
26
27 def powersetlist(s):
28 r = [[]]
29 for e in s:
30 # print "r: %-55r e: %r" % (r,e)
31 r += [x+[e] for x in r]
32 return r
33
34
35 #print "\npowersetlist(%r) =\n %r" % (s, powersetlist(s))
36
37
38 #print power([0,1,2,3])
39 if __name__ == '__main__':
40 print power([0,1,2,3])
41 | 40 - error: syntax-error
|
1 """
2 Create the function prefill that returns an array of n elements that all have the same value v. See if you can do this without using a loop.
3
4 You have to validate input:
5
6 v can be anything (primitive or otherwise)
7 if v is ommited, fill the array with undefined
8 if n is 0, return an empty array
9 if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError
10 When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.
11
12 see: http://www.codewars.com/kata/54129112fb7c188740000162/train/python
13
14 """
15
16 def prefill(n,v=None):
17 #your code here
18 try:
19 if isNumber(n):
20 if v is None:
21 return ['undefined'] * int(n)
22 return [v]*int(n)
23 raise TypeError
24 except TypeError:
25 return str(n) + " is invalid."
26
27
28 def isNumber(n):
29 if isinstance( n, int ):
30 return True
31 elif isinstance( n , str) and n.isdigit():
32 if int(n):
33 return True
34 return False
35
36
37
38
39 print prefill(5,)
40 print prefill(5,prefill(3,'abc'))
41 print prefill(3,5)
42
43 print isNumber(5.3)
44
| 39 - error: syntax-error
|
1 '''
2 Where my anagrams at?
3 http://www.codewars.com/kata/523a86aa4230ebb5420001e1/train/python
4 Also could construct prime list, assign each character from word to a prime number. multiply them
5 then divid prime number from word in words.
6 '''
7
8 def anagrams(word, words):
9 #your code here
10
11 return filter(lambda x: sorted(x) == sorted(word) , words)
12
13
14
15 print anagrams("thisis" , ["thisis", "isthis", "thisisis"])
16 print anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer'])
17 print anagrams('laser', ['lazing', 'lazy', 'lacer']) | 15 - error: syntax-error
|
1 def sierpinski(n):
2 result = []
3 for i in range(0,n+1):
4 if i == 0:
5 result.append('"')
6 else:
7 for j in range(2**(i-1),2**i):
8 result.append(addSpace(j,i,result))
9 r = result[0]
10 for line in result[1:]:
11 r= r+'\n'+line
12 return r
13
14 def addSpace(l,n,string_list):
15 result = string_list[l-2**(n-1)]
16 space = len(range(0,2*2**(n-1)-l)) * 2 - 1
17 for i in range(0,space):
18 result = ' ' +result
19 return string_list[l-2**(n-1)]+result
20
21
22
23 #print sierpinski(1)
24 print sierpinski(6) | 24 - error: syntax-error
|
1 """
2 The Millionth Fibonacci Kata
3 http://www.codewars.com/kata/53d40c1e2f13e331fc000c26/train/python
4 """
5 import math
6 import sys
7 import time
8 from collections import defaultdict
9
10 # following not working , took too much time to compute.
11
12 def fib(n , i):
13
14
15 dic = defaultdict(list)
16
17 def find_dim(k):
18 if k == 0:
19 return []
20 if k == 1:
21 return [0]
22 else:
23 return [int(math.log(k,2))] + find_dim(k - 2**(int(math.log(k,2))))
24
25 def matrix_multi(a, b):
26 return [a[0]*b[0]+a[1]*b[2],
27 a[0]*b[1]+a[1]*b[3],
28 a[2]*b[0]+a[3]*b[2],
29 a[2]*b[1]+a[3]*b[3]]
30
31
32 def matrix_power(pow):
33 a = [1,1,1,0]
34 if pow in dic:
35 return dic[pow]
36 else:
37 if pow == 0:
38 return a
39 else:
40 for i in range(1,pow+1):
41 if i not in dic:
42 a = matrix_multi(a , a)
43 dic[i] = a
44
45 else:
46 a = dic[i]
47 return a
48 #print matrix_power([1,1,1,0])
49
50 def matrix_fib(t):
51 if t == 0 or t == 1:
52 return t
53 else:
54 result = [1,0,0,1]
55 alist = find_dim(t-1)
56 for i in alist:
57 result = matrix_multi(result,matrix_power(i))
58 return result
59
60 def dynamic_fib(n):
61 a = 0
62 b = 1
63 if n == 0:
64 return (a , b)
65
66 for i in range(n):
67 temp = a + b
68 a = b
69 b = temp
70 return (a , b )
71
72
73
74 def double_fast(n):
75 #really fast
76 if n == 0:
77 return (0 , 1)
78 else:
79 a, b = double_fast(n/2)
80 c = a * (2* b -a )
81 d = b **2 + a**2
82 if n%2 == 0:
83 return (c , d)
84 else:
85 return (d , d+c)
86
87 def compute_fib(n ,i ):
88 func = {0: matrix_fib,
89 1: double_fast,
90 2: dynamic_fib }
91
92
93 return func[i](n)[0] if n >= 0 else (-1)**(n%2+1) * func[i](-n)[0]
94
95
96
97
98
99 return compute_fib(n , i)
100
101 def size_base10(n):
102 size = 0
103 while n /10 != 0:
104 size += 1
105 n = n/10
106
107 return size
108
109
110 def main():
111 '''
112 func = {0: matrix_fib,
113 1: double_fast,
114 2: dynamic_fib }
115 '''
116 try:
117 #var = int(raw_input("Please enter the n-th Fib number you want:"))
118 var = 200000
119 start = time.time()
120 i = 1
121 result = fib(var , i)
122
123 end = time.time()
124
125 #print "Lenght of %dth fib number is %d" %(var , size_base10(result))
126 print "Time is %s seconds." % (end - start)
127 #print result
128 #print "The %dth fib number is %d"%(var , result)
129 except:
130 pass
131
132
133 if __name__ == '__main__':
134 main()
135
136
137
| 20 - error: syntax-error
|
1 """
2 Square into Squares. Protect trees!
3 http://www.codewars.com/kata/square-into-squares-protect-trees
4 """
5 import math
6
7 def decompose(n):
8 # your code
9 def sub_decompose(s,i):
10 if s < 0 :
11 return None
12 if s == 0:
13 return []
14 for j in xrange(i-1, 0 ,-1):
15 #print s,s - j**2 ,j
16 sub = sub_decompose(s - j**2, j)
17 #print j,sub
18 if sub != None:
19 # print s,j,sub
20 return sub + [j]
21 return sub_decompose(n**2,n)
22
23 if __name__ == "__main__":
24 print decompose(11)
| 24 - error: syntax-error
|
1 """
2 Going to zero or to infinity?
3 http://www.codewars.com/kata/55a29405bc7d2efaff00007c/train/python
4 """
5
6 import math
7 def going(n):
8 result = 0
9 for i in range(n):
10 result = 1.0*result/(i+1) + 1
11 return math.floor(result * (10**6))/(10**6)
12
13
14
15
16 if __name__ == "__main__":
17 for i in range(10):
18 print i, going(i) | 18 - error: syntax-error
|
1 def solution(n):
2 # TODO convert int to roman string
3 result = ""
4
5
6 remainder = n
7 if n == 0:
8 return ""
9 for i in range(0,len(roman_number)):
10 time = 1.0*remainder/roman_number[i][0]
11 if str(roman_number[i][0])[0] == '1':
12 if time < 4 and time >=1:
13 temp = remainder % roman_number[i][0]
14 div = remainder / roman_number[i][0]
15 remainder = temp
16 result += div * roman_number[i][1]
17 if time < 1 and time >= 0.9:
18 result += (roman_number[i+2][1]+roman_number[i][1])
19 remainder = remainder % roman_number[i+2][0]
20 else:
21 if time < 1 and time >= 0.8:
22 result += (roman_number[i+1][1]+roman_number[i][1])
23 remainder = remainder % roman_number[i+1][0]
24 if time >= 1 and time < 1.8:
25 div = (remainder - roman_number[i][0]) / roman_number[i+1][0]
26 result += roman_number[i][1] + div * roman_number[i+1][1]
27 remainder = remainder % roman_number[i+1][0]
28 if time >= 1.8:
29 result += roman_number[i+1][1]+roman_number[i-1][1]
30 remainder = remainder % roman_number[i+1][0]
31 return result
32
33 roman_number = [(1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I')]
34
35 #print solution(4)
36 #print solution(6)
37 print solution(3991) | 23 - error: syntax-error
|
1 '''
2 A poor miner is trapped in a mine and you have to help him to get out !
3
4 Only, the mine is all dark so you have to tell him where to go.
5
6 In this kata, you will have to implement a method solve(map, miner, exit) that has to return the path the miner must take to reach the exit as an array of moves, such as : ['up', 'down', 'right', 'left']. There are 4 possible moves, up, down, left and right, no diagonal.
7
8 map is a 2-dimensional array of boolean values, representing squares. false for walls, true for open squares (where the miner can walk). It will never be larger than 5 x 5. It is laid out as an array of columns. All columns will always be the same size, though not necessarily the same size as rows (in other words, maps can be rectangular). The map will never contain any loop, so there will always be only one possible path. The map may contain dead-ends though.
9
10 miner is the position of the miner at the start, as an object made of two zero-based integer properties, x and y. For example {x:0, y:0} would be the top-left corner.
11
12 exit is the position of the exit, in the same format as miner.
13
14 Note that the miner can't go outside the map, as it is a tunnel.
15
16 Let's take a pretty basic example :
17
18 map = [[True, False],
19 [True, True]];
20
21 solve(map, {'x':0,'y':0}, {'x':1,'y':1})
22 // Should return ['right', 'down']
23
24 http://www.codewars.com/kata/5326ef17b7320ee2e00001df/train/python
25
26 '''
27
28 def solve(map, miner, exit):
29 #your code here
30 dirc = { 'right': [1,0],
31 'left': [-1,0],
32 'down': [0,1],
33 'up': [0,-1] }
34
35
36 matrix = [[ int(map[i][j]) for i in range(len(map)) ] for j in range(len(map[0]))]
37
38 start = [ value for key , value in miner.itemiters() ]
39 end = [ value for key , value in exit.itemiters() ]
40
41 print start
| 41 - error: syntax-error
|
1 #!/usr/bin/python
2 from collections import defaultdict
3
4 def sum_for_list(lst):
5
6
7 aDict = defaultdict(lambda : 0)
8
9
10 def primes(n):
11
12 d = 2
13 aN = n
14 n = abs(n)
15 while d*d <= n:
16 aBool = True
17 while (n % d) == 0:
18 #primfac.add(d) # supposing you want multiple factors repeated
19 if aBool:
20 aDict[d] += aN
21 aBool = False
22 n /= d
23 d += 1
24 if n > 1:
25 aDict[n] += aN
26 return aDict
27 for i in lst:
28 primes(i)
29 #primes(i)
30
31
32 result = [ [k,v] for k,v in aDict.iteritems()]
33 result.sort(key = lambda x:x[0])
34 return result
35
36 a = [12,15]
37 b = [15, 30, -45]
38 c = [15, 21, 24, 30, 45]
39 test = sum_for_list(b)
40
41
42 #print test
43 #print sum_for_list(a)
44 d = sum_for_list(c)
45 print d
46 d.sort(key = lambda x: x[0] ,reverse =True)
47 print d
48 | 45 - error: syntax-error
|
1 #!/usr/bin/python
2 '''
3 An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: Exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term.
4
5 You have to write the function findMissing (list) , list will always be atleast 3 numbers.
6
7 http://www.codewars.com/kata/52de553ebb55d1fca3000371/train/python
8
9 '''
10
11
12 def find_missing(sequence):
13 should = 1.0 * (sequence[0] + sequence[-1])* (len(sequence)+1) / 2
14 actual = reduce(lambda x, y: x+y, sequence)
15 #print actual
16 return int(should - actual)
17
18
19 if __name__ == "__main__":
20
21
22 a = [1, 2, 3, 4, 6, 7, 8, 9]
23 print find_missing(a) | 23 - error: syntax-error
|
1 """
2 You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:
3
4
5 http://www.codewars.com/kata/55983863da40caa2c900004e/train/python
6
7 """
8
9 def next_bigger(n):
10 #your code here
11 | 11 - error: syntax-error
|
1 """
2 Decimal to any Rational or Irrational Base Converter
3 http://www.codewars.com/kata/5509609d1dbf20a324000714/train/python
4
5 wiki_page : https://en.wikipedia.org/wiki/Non-integer_representation
6
7 """
8 import math
9 from math import pi , log
10 '''
11 def converter(n, decimals=0, base=pi):
12 """takes n in base 10 and returns it in any base (default is pi
13 with optional x decimals"""
14 #your code here
15 alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
16 m = 1
17 if n < 0:
18 n = -n
19 m = -m
20
21 times = 0 if n == 0 else int(math.floor(math.log(n, base)))
22
23 result = ''
24
25 while times >= -decimals :
26 if times == -1:
27 result += '.'
28 val = int(n / base**times)
29
30 result+=alpha[val]
31 #print "base time " ,n/(base**times)
32 n -= int(n / base**times) * base**times
33
34 #print result,n , times
35
36 times-=1
37 if m == -1:
38 result = '-'+result
39 result = str(result)
40 if decimals != 0:
41 loc = result.index('.')
42 last = len(result)-1
43 if decimals > last - loc:
44 result+='0'* (decimals-(last - loc))
45 return result
46
47 '''
48
49
50 def converter(n , decimals = 0 , base = pi):
51 alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
52 if n == 0 : return '0' if not decimals else '0.' + '0'*decimals
53
54 result = '' if n > 0 else '-'
55
56 n = abs(n)
57
58 for i in range(int(log(n, base)) , -decimals -1, -1 ):
59 if i == -1:
60 result += '.'
61 result += alpha[int(n / base**i)]
62 n %= base**i
63 return result
64
65 def main():
66 print converter(0,4,26)
67 print converter(-15.5,2,23)
68 print converter(13,0,10)
69 print converter(5.5, 1,10)
70 if __name__ == '__main__':
71 main()
72
| 66 - error: syntax-error
|
1 l = [1, 5, 12, 2, 15, 6]
2 i = 0
3 s = 0
4 for i in l:
5 s += i
6 print(s)
7
8 i = 0
9 s = 0
10 while i<len(l):
11 s += l[i]
12 i += 1
13 print(s) | Clean Code: No Issues Detected
|
1 import datetime as dt
2 today = dt.datetime.today()
3 yesterday = today - dt.timedelta(days=1)
4 tomorrow = today + dt.timedelta(days=1)
5
6 print("Yesterday", yesterday)
7 print("Today", today)
8 print("Tomorrow", tomorrow) | Clean Code: No Issues Detected
|
1 #Write a python program to find the longest word in a file.
2 f = open("demo.txt", "r")
3 line = f.readline()
4 longestWord = ""
5 while line:
6 words = line.split(" ")
7 lineLongestWord = max(words, key=len)
8 if len(lineLongestWord) > len(longestWord):
9 longestWord = lineLongestWord
10
11 line = f.readline()
12
13 print("Longest word")
14 print(longestWord) | 2 - warning: unspecified-encoding
2 - refactor: consider-using-with
|
1 # 0 1 1 2 3 5 8
2 def fib(n):
3 a = 0
4 b = 1
5 print(a, end=" ")
6 print(b, end=" ")
7 for i in range(2, n):
8 c = a + b
9 print(c, end=" ")
10 a = b
11 b = c
12
13 n = int(input("Enter the number\n"))
14 fib(n) | 2 - warning: redefined-outer-name
7 - warning: unused-variable
|
1 import datetime as dt
2 today = dt.datetime.today()
3 print("Current date and time", dt.datetime.now())
4 print("Current Time in 12 Hours Format", today.strftime("%I:%M:%S %p"))
5 print("Current year", today.year)
6 print("Month of the year", today.strftime("%B"))
7 print("Week number of the year", today.strftime("%W"))
8 print("Week day of the week", today.strftime("%A"))
9 print("Day of the year", today.strftime("%j"))
10 print("Day of the month", today.strftime("%d"))
11 print("Day of the week", today.strftime("%w")) | Clean Code: No Issues Detected
|
1 x = input("Enter a string \n")
2 d = l = 0
3
4 for c in x:
5 if c.isalpha():
6 l += 1
7
8 if c.isdigit():
9 d += 1;
10
11 print("Letters %d" % (l))
12 print("Digits %d" % (d)) | 9 - warning: unnecessary-semicolon
|
1 x = 65
2 for i in range(5):
3 for j in range(i+1):
4 print(chr(x+j), end=" ")
5
6 print() | Clean Code: No Issues Detected
|
1 import datetime as dt
2 today = dt.datetime.today()
3 for i in range(1, 6):
4 nextday = today + dt.timedelta(days=i)
5 print(nextday) | Clean Code: No Issues Detected
|
1 class Student:
2 def __init__(self, name, roll_no):
3 self.name = name
4 self.roll_no = roll_no
5 self.age = 0
6 self.marks = 0
7
8 def display(self):
9 print("Name", self.name)
10 print("Roll No", self.roll_no)
11 print("Age", self.age)
12 print("Marks", self.marks)
13
14 def setAge(self, age):
15 self.age = age
16
17 def setMarks(self, marks):
18 self.marks = marks
19
20 s1 = Student("Sahil", 12)
21 s1.setAge(20)
22 s1.setMarks(90)
23 s1.display()
24
25 s2 = Student("Rohit", 20)
26 s2.display() | Clean Code: No Issues Detected
|
1 x = int(input("Enter a number\n"))
2 for i in range(x):
3 print(i ** 2)
| Clean Code: No Issues Detected
|
1 p = 3
2 n = 1
3 for i in range(4):
4 for j in range(7):
5 if j >= p and j <= p+n-1:
6 print("X", end=" ")
7 else:
8 print(" ", end=" ")
9
10 print()
11 p -= 1
12 n += 2
13
14 print("The python string multiplication way")
15 p = 3
16 n = 1
17 for i in range(4):
18 print(" " * p, end="")
19 print("X " * n, end="")
20 print()
21 p -= 1
22 n += 2 | 5 - refactor: chained-comparison
|
1 # Given the participants' score sheet for your University Sports Day,
2 # you are required to find the runner-up score. You are given n scores.
3 # Store them in a list and find the score of the runner-up.
4
5 score_str = input("Enter scores\n")
6 score_list = score_str.split(" ")
7 highestScore = 0;
8 rupnnerUp = 0
9 for score in score_list:
10 score = int(score)
11 if score > highestScore:
12 highestScore = score
13
14 for score in score_list:
15 score = int(score)
16 if score > rupnnerUp and score < highestScore:
17 rupnnerUp = score
18
19 print(rupnnerUp) | 7 - warning: unnecessary-semicolon
11 - refactor: consider-using-max-builtin
16 - refactor: chained-comparison
|
1 samples = (1, 2, 3, 4, 12, 5, 20, 11, 21)
2 e = o = 0
3 for s in samples:
4 if s % 2 == 0:
5 e += 1
6 else:
7 o += 1
8
9 print("Number of even numbers : %d" % (e))
10 print("Number of odd numbers : %d" % (o)) | Clean Code: No Issues Detected
|
1 # Consider that vowels in the alphabet are a, e, i, o, u and y.
2 # Function score_words takes a list of lowercase words as an
3 # argument and returns a score as follows:
4 # The score of a single word is 2 if the word contains an even number
5 # of vowels. Otherwise, the score of this word is 1 . The score for the
6 # whole list of words is the sum of scores of all words in the list.
7 # Debug the given function score_words such that it returns a correct
8 # score.
9
10 # Rules:
11 # even number of vowels then score is 2
12 # odd number of vowels then score is 1
13
14 vowels = ["a", "e", "i", "o", "u"]
15
16 def score_word(word):
17 v = 0
18 for c in word:
19 if c in vowels:
20 v += 1
21
22 if v % 2 == 0:
23 return 2
24 else:
25 return 1
26
27 def score_words(words):
28 score = 0;
29 for word in words:
30 score += score_word(word)
31 return score
32
33 sentance = input("Enter a sentance\n")
34 words = sentance.split(" ")
35 print(score_words(words)) | 28 - warning: unnecessary-semicolon
22 - refactor: no-else-return
27 - warning: redefined-outer-name
|
1 # GUI Programing
2 # Tkinter
3
4 import tkinter as tk
5 from tkinter import messagebox
6
7 # 1. Intialize Root Window
8 root = tk.Tk()
9 root.title("Login Application")
10 root.geometry("200x200")
11
12 # 2. Application Logic
13
14 # 3. Intialize widgets
15
16 # 4. Placement of widgets (pack, grid, place)
17
18
19 # 5. Running the main looper
20 root.mainloop() | 5 - warning: unused-import
|
1 x = int(input("Enter the value of X\n"))
2 if x%2 != 0:
3 print("Weird")
4 elif x >= 2 and x <= 5:
5 print("Not Weird")
6 elif x >= 6 and x<= 20:
7 print("Weird")
8 elif x > 20:
9 print("Not Weird") | 4 - refactor: chained-comparison
6 - refactor: chained-comparison
|
1 # Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player
2 # plays (using input), compare them, print out a message of
3 # congratulations to the winner, and ask if the players want to start a
4 # new game)
5
6 def is_play_valid(play):
7 if play != 'rock' and play != 'paper' and play != 'scissors':
8 return False
9 else:
10 return True
11
12 def play_game():
13 p1 = input("Player 1, what are you playing?\n")
14 while not is_play_valid(p1):
15 p1 = input("Wrong play, please play again.\n")
16
17 p2 = input("Player 2, what are you playing?\n")
18 while not is_play_valid(p2):
19 p2 = input("Wrong play, please play again.\n")
20
21 # Game Logic
22 if p1 == p2:
23 print("Its a tie!")
24 elif p1 == "rock":
25 if p2 == 'scissors':
26 print("Player 1 wins")
27 else:
28 print("Player 2 wins")
29 elif p1 == "paper":
30 if p2 == "rock":
31 print("Player 1 wins")
32 else:
33 print("Player 2 wins")
34 else:
35 if p2 == 'paper':
36 print("Player 1 wins")
37 else:
38 print("Player 2 wins")
39
40 ans = input("Do you want to start a new game?\n")
41 if ans == 'yes':
42 print("Starting a new game")
43 play_game()
44
45 play_game() | 7 - refactor: no-else-return
7 - refactor: consider-using-in
|
1 def add(a, b):
2 return a + b
3
4 def sub(a, b):
5 return a - b
6
7 def pow(a,b):
8 return a ** b
9
10 if __name__ != "__main__":
11 print("Basic Module Imported") | 7 - warning: redefined-builtin
|
1 w = input("Enter a word")
2 r = "";
3 for a in w:
4 r = a + r
5
6 print(r) | 2 - warning: unnecessary-semicolon
|
1 def checkPrime(x):
2 for i in range(2, x):
3 if x % i == 0:
4 print("Not a prime number")
5 break;
6 else:
7 print("Print number")
8
9 x = int(input("Enter any number\n"))
10 checkPrime(x) | 5 - warning: unnecessary-semicolon
1 - warning: redefined-outer-name
|
1 # Generate a random number between 1 and 9 (including 1 and 9).
2 # Ask the user to guess the number, then tell them whether they
3 # guessed too low, too high, or exactly right.
4
5 import random as r
6 a = r.randint(1, 9)
7
8 def ask_user():
9 u = int(input("Guess the number?\n"))
10
11 if a == u:
12 print("Exactly")
13 elif a > u:
14 print("Too low")
15 ask_user()
16 else:
17 print("Too high")
18 ask_user()
19
20 ask_user()
| Clean Code: No Issues Detected
|
1 for i in range(5):
2 for j in range(i+1):
3 print(i+1, end=" ")
4
5 print()
6
7 print("The python way...")
8 for i in range(5):
9 print(str(str(i+1) + " ") * int(i+1)) | Clean Code: No Issues Detected
|
1 # GUI Programing
2 # Tkinter
3
4 import tkinter as tk
5 from tkinter import messagebox
6
7 ## Welcome Window
8 def show_welcome():
9 welcome = tk.Tk()
10 welcome.title("Welcome ADMIN")
11 welcome.geometry("200x200")
12 welcome.mainloop()
13
14
15 ## Login Window
16 # 1. Intialize Root Window
17 root = tk.Tk()
18 root.title("Login Application")
19 root.geometry("200x200")
20
21 # 2. Application Logic
22 def button1Click():
23 username = entry1.get()
24 password = entry2.get()
25 if username == 'admin' and password == 'admin':
26 messagebox.showinfo("Login Application", "Login Successfull!")
27 root.destroy()
28 show_welcome()
29 else:
30 messagebox.showerror("Login Application", "Login Failed!")
31
32 def button2Click():
33 if messagebox.askokcancel("Login Application", "Do you want to quit?"):
34 root.destroy()
35
36 # 3. Intialize widgets
37 label1 = tk.Label(root, text="Username")
38 label2 = tk.Label(root, text="Password")
39 entry1 = tk.Entry(root)
40 entry2 = tk.Entry(root)
41 button1 = tk.Button(root, text="Login", command=button1Click)
42 button2 = tk.Button(root, text="Quit", command=button2Click)
43
44 # 4. Placement of widgets (pack, grid, place)
45 label1.grid(row=1, column=1, pady=10)
46 label2.grid(row=2, column=1, pady=10)
47 entry1.grid(row=1, column=2)
48 entry2.grid(row=2, column=2)
49 button1.grid(row=3, column=2)
50 button2.grid(row=3, column=1)
51
52 # 5. Running the main looper
53 root.mainloop()
54 print("END") | Clean Code: No Issues Detected
|
1 # Password generator
2 import random as r
3 lenth = int(input("Enter the length of password\n"))
4 password = ""
5 for i in range(lenth):
6 password += chr(r.randint(33, 123))
7
8 print(password) | Clean Code: No Issues Detected
|
1 # GUI Calculator Program
2 import tkinter as tk
3
4 # Intialize window
5 window = tk.Tk()
6 window.title("Calculator")
7
8 # Application Logic
9 result = tk.StringVar()
10 def add(value):
11 result.set(result.get() + value)
12 def peform():
13 result.set(eval(result.get()))
14 def clear():
15 result.set("")
16
17 # Initialize Widgets
18 label1 = tk.Label(window, textvariable=result)
19 button1 = tk.Button(window, text="1", padx=10, pady=10, bg="white", fg="black", command=lambda : add("1"))
20 button2 = tk.Button(window, text="2", padx=10, pady=10, bg="white", fg="black",command=lambda : add("2"))
21 button3 = tk.Button(window, text="3", padx=10, pady=10, bg="white", fg="black",command=lambda : add("3"))
22
23 button4 = tk.Button(window, text="4", padx=10, pady=10, bg="white", fg="black",command=lambda : add("4"))
24 button5 = tk.Button(window, text="5", padx=10, pady=10, bg="white", fg="black",command=lambda : add("5"))
25 button6 = tk.Button(window, text="6", padx=10, pady=10, bg="white", fg="black",command=lambda : add("6"))
26
27 button7 = tk.Button(window, text="7", padx=10, pady=10, bg="white", fg="black",command=lambda : add("7"))
28 button8 = tk.Button(window, text="8", padx=10, pady=10, bg="white", fg="black",command=lambda : add("8"))
29 button9 = tk.Button(window, text="9", padx=10, pady=10, bg="white", fg="black",command=lambda : add("9"))
30
31 button0 = tk.Button(window, text="0", padx=10, pady=10, bg="white", fg="black",command=lambda : add("0"))
32 button_dot = tk.Button(window, text=".", padx=10, pady=10, bg="#eee", fg="black",command=lambda : add("."))
33 button_equal = tk.Button(window, text="=", padx=10, pady=10, bg="green", fg="white",command=peform)
34 button_clear = tk.Button(window, text="C", padx=10, pady=10, bg="white", fg="black",command=clear)
35
36 button_multiply = tk.Button(window, text="*", padx=10, pady=10, bg="#eee", fg="black",command=lambda : add("*"))
37 button_minus = tk.Button(window, text="-", padx=10, pady=10, bg="#eee", fg="black",command=lambda : add("-"))
38 button_add = tk.Button(window, text="+", padx=10, pady=10, bg="#eee", fg="black",command=lambda : add("+"))
39 # Placement of Widgets
40 # Row0
41 label1.grid(row=0, column=0, columnspan=3, sticky="W")
42 # Row1
43 button7.grid(row=1, column=0)
44 button8.grid(row=1, column=1)
45 button9.grid(row=1, column=2)
46 button_multiply.grid(row=1, column=3)
47 # Row2
48 button4.grid(row=2, column=0)
49 button5.grid(row=2, column=1)
50 button6.grid(row=2, column=2)
51 button_minus.grid(row=2, column=3)
52 # Row3
53 button1.grid(row=3, column=0)
54 button2.grid(row=3, column=1)
55 button3.grid(row=3, column=2)
56 button_add.grid(row=3, column=3)
57 # Row4
58 button_clear.grid(row=4, column=0)
59 button0.grid(row= 4, column=1)
60 button_dot.grid(row= 4, column=2)
61 button_equal.grid(row= 4, column=3)
62 # Main Loop
63 window.mainloop() | 13 - warning: eval-used
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.