ngram
listlengths 0
67.8k
|
|---|
[
"-*- from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name = 'allink_core.core_apps.allink_legacy_redirect' verbose_name = \"Legacy",
"-*- coding: utf-8 -*- from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name = 'allink_core.core_apps.allink_legacy_redirect'",
"coding: utf-8 -*- from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name = 'allink_core.core_apps.allink_legacy_redirect' verbose_name",
"utf-8 -*- from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name = 'allink_core.core_apps.allink_legacy_redirect' verbose_name =",
"from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name = 'allink_core.core_apps.allink_legacy_redirect' verbose_name = \"Legacy Redirect\"",
"# -*- coding: utf-8 -*- from django.apps import AppConfig class AllinkLegacyConfig(AppConfig): name ="
] |
[
"y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake):",
"optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch",
"x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def",
"leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class",
"test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy()",
"0 while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1,",
"x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b batch_nr += 1 def",
"real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1))",
"= real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val",
"batches_generator(): batch_nr = 0 while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size))",
"self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2",
"tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake",
"output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d =",
"self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4",
"= train_generator(optim_g, data_fake).item() # generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images",
"= np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return real_labels def",
"def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32)",
"from abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2)",
"in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests,",
"size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b batch_nr",
"loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad()",
"= Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self,",
"Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item()",
"= generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images after each epoch fake_images",
"self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def",
"import make_grid, save_image import torch from abc import abstractmethod import os def leakyrelu(x,",
"n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b",
"fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f:",
"np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise NotImplementedError @property def",
"f: return f.read() dat = requests.get(url).content with open(fp + '.tmp', 'wb') as f:",
"+= 1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels",
"return dat def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse = lambda",
"import torch from abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu())",
"NotImplementedError @property def params(self): return tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor))",
"batch_size = 512 n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise =",
"generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images after each epoch fake_images =",
"n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g =",
"data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step()",
"= requests.get(url).content with open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return",
"Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x):",
"return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad()",
"= x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b batch_nr += 1",
"isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512))",
"forward(self, x): raise NotImplementedError @property def params(self): return tuple(v for k,v in self.__dict__.items()",
"= LinearGen() discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train =",
"loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake):",
"1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2))",
"return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output =",
"real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return",
"import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1.,",
"128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images after each",
"data_fake).item() # generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1,",
"leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile, os fp =",
"= os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f: return",
"torch from abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val),",
"28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs):",
"def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class",
"generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images = make_grid(torch.tensor(fake_images))",
"-2.0 real_labels = Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs),",
"discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim,",
"https://github.com/geohot/tinygrad/blob/master/examples/mnist_gan.py from simplegrad import Tensor, Device, Adam import numpy as np import itertools",
"data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise =",
"fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels =",
"Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return",
"real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels =",
"= Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 =",
"= np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def",
"class nn: @abstractmethod def forward(self, x): raise NotImplementedError @property def params(self): return tuple(v",
"= parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size = 512",
"Tensor, Device, Adam import numpy as np import itertools as it from torchvision.utils",
"class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 =",
"- 0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs): y = np.zeros((bs,2), np.float32)",
"def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import",
"self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 =",
"Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784))",
"LinearGen() discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url",
"return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod",
"y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return real_labels def fake_label(bs): y =",
"each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) /",
"Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size)",
"generator = LinearGen() discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train",
"discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in range(epochs): batches",
"= generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size,",
"self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024))",
"fp) return dat def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse =",
"x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512))",
"= Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images",
"= \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size = 512 n_batches =",
"discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url =",
"= -2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels =",
"self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile, os fp",
"= real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake",
"np import itertools as it from torchvision.utils import make_grid, save_image import torch from",
"= train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g =",
"np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim,",
"= discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward()",
"loss.val for epoch in range(epochs): batches = tuple(batches_generator()) for data_real in batches: data_real",
"# rough copy of https://github.com/geohot/tinygrad/blob/master/examples/mnist_gan.py from simplegrad import Tensor, Device, Adam import numpy",
"512 n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g",
"data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val)",
"abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def",
"= 10 batch_size = 512 n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\"",
"output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in",
"= (image_b - 0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs): y =",
"0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs),",
"as f: return f.read() dat = requests.get(url).content with open(fp + '.tmp', 'wb') as",
"save_image import torch from abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return",
"dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs =",
"learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr < n_batches: idx =",
"epoch in range(epochs): batches = tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real)",
"Adam import numpy as np import itertools as it from torchvision.utils import make_grid,",
"batch_nr += 1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0",
"as np import itertools as it from torchvision.utils import make_grid, save_image import torch",
"Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr < n_batches: idx",
"return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(),",
"self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 =",
"int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002,",
"def batches_generator(): batch_nr = 0 while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0],",
"import gzip def fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if",
"for epoch in range(epochs): batches = tuple(batches_generator()) for data_real in batches: data_real =",
"noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate",
"as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator = LinearGen() discriminator",
"x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex())",
"128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise",
"< n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b =",
"data_real in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise)",
"= fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels",
"size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise NotImplementedError @property def params(self): return",
"__init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256))",
"class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3",
"for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self):",
"for k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 =",
"os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as",
"epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2",
"x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def",
"abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return",
"Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256,",
"in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2",
"'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator = LinearGen()",
"np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator():",
"data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real",
"loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake)",
"data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real =",
"self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def",
"batch_nr = 0 while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b",
"simplegrad import Tensor, Device, Adam import numpy as np import itertools as it",
"f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator = LinearGen() discriminator =",
"\"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size = 512 n_batches = int(len(x_train)",
"import abstractmethod import os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape):",
"self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]:",
"np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real,",
"= \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params,",
"= generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images =",
"= tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128))",
"= -2.0 real_labels = Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32)",
"as it from torchvision.utils import make_grid, save_image import torch from abc import abstractmethod",
"Tensor(random_uniform(256, 2)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return",
"image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b batch_nr +=",
"import numpy as np import itertools as it from torchvision.utils import make_grid, save_image",
"def params(self): return tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn):",
"LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512,",
"range(epochs): batches = tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real) noise =",
"np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10",
"2)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax()",
"= Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d",
"ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5)",
"'rb') as f: return f.read() dat = requests.get(url).content with open(fp + '.tmp', 'wb')",
"os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read() dat = requests.get(url).content",
"os def leakyrelu(x, neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1.,",
"after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1)",
"and os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read() dat = requests.get(url).content with",
"from simplegrad import Tensor, Device, Adam import numpy as np import itertools as",
"def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y)",
"= Tensor(random_uniform(256, 2)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer))",
"return f.read() dat = requests.get(url).content with open(fp + '.tmp', 'wb') as f: f.write(dat)",
"os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse",
"output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward()",
"generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28,",
"optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1))",
"f.read() dat = requests.get(url).content with open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp',",
"os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read() dat = requests.get(url).content with open(fp",
"Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images after",
"\"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002,",
"real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return",
"= (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images = make_grid(torch.tensor(fake_images)) save_image(fake_images, os.path.join(output_folder,",
"/ batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5)",
"Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0",
"def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real =",
"for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url):",
"epochs = 10 batch_size = 512 n_batches = int(len(x_train) / batch_size) output_folder =",
"= 512 n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32)",
"return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels",
"= np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5",
"dat def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse = lambda dat:",
"512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for",
"= np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels def",
"1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels =",
"itertools as it from torchvision.utils import make_grid, save_image import torch from abc import",
"loss_g = train_generator(optim_g, data_fake).item() # generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val",
"fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake =",
"data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item()",
"loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g",
"batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d",
"if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256,",
"= discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def",
"np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return real_labels def fake_label(bs): y",
"def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 = Tensor(random_uniform(512,",
"Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x):",
"y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return real_labels",
"Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0",
"parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) #",
"return loss.val for epoch in range(epochs): batches = tuple(batches_generator()) for data_real in batches:",
"self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for layer",
"Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d =",
"in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake",
"random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise NotImplementedError",
"x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def",
"neg_slope=0.2): return x.relu().sub(x.fork().mul(Tensor(neg_slope).mul(Tensor(-1.0))).relu()) torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn:",
"k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256))",
"dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size",
"__init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4",
"= int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise = np.random.randn(64,128).astype(np.float32) optim_g = Adam(generator.params,",
"open(fp, 'rb') as f: return f.read() dat = requests.get(url).content with open(fp + '.tmp',",
"Tensor)) class LinearGen(nn): def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3",
"forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip",
"requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp,",
"def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y)",
"= lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters",
"loss.backward() optim.step() return loss.val for epoch in range(epochs): batches = tuple(batches_generator()) for data_real",
"optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output",
"image_b = (image_b - 0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs): y",
"f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc()",
"train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g,",
"512)) self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for",
"np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] = -2.0 real_labels = Tensor(y) return real_labels def fake_label(bs):",
"self.l3 = Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for layer",
"= LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1,",
"fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size:",
"numpy as np import itertools as it from torchvision.utils import make_grid, save_image import",
"os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read()",
"batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b",
"-2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size)",
"requests.get(url).content with open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat",
"real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val +",
"self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile, os",
"10 batch_size = 512 n_batches = int(len(x_train) / batch_size) output_folder = \"outputs\" ds_noise",
"gzip def fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp)",
"optim.step() return loss.val for epoch in range(epochs): batches = tuple(batches_generator()) for data_real in",
"x): raise NotImplementedError @property def params(self): return tuple(v for k,v in self.__dict__.items() if",
"yield image_b batch_nr += 1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs]",
"noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d,",
"torchvision.utils import make_grid, save_image import torch from abc import abstractmethod import os def",
"= fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake",
"in range(epochs): batches = tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real) noise",
"tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self): self.l1",
"= Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024,",
"return tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def __init__(self):",
"Hyperparameters epochs = 10 batch_size = 512 n_batches = int(len(x_train) / batch_size) output_folder",
"= discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in range(epochs):",
"copy of https://github.com/geohot/tinygrad/blob/master/examples/mnist_gan.py from simplegrad import Tensor, Device, Adam import numpy as np",
"(image_b - 0.5)/0.5 yield image_b batch_nr += 1 def real_label(bs): y = np.zeros((bs,2),",
"tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb')",
"batches = tuple(batches_generator()) for data_real in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size,",
"@property def params(self): return tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor)) class",
"'.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator =",
"image_b batch_nr += 1 def real_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [1]*bs] =",
"images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+",
"= Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real,",
"real_labels = Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs]",
"it from torchvision.utils import make_grid, save_image import torch from abc import abstractmethod import",
"784)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh()",
"= Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels =",
"nn: @abstractmethod def forward(self, x): raise NotImplementedError @property def params(self): return tuple(v for",
"data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake",
"forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn):",
"Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for layer in [self.l1,",
"import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with",
"learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while",
"train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real)",
"Device, Adam import numpy as np import itertools as it from torchvision.utils import",
"for data_real in batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake =",
"[self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import requests, tempfile,",
"optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr <",
"real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake =",
"fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return",
"def forward(self, x): raise NotImplementedError @property def params(self): return tuple(v for k,v in",
"real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for",
"rough copy of https://github.com/geohot/tinygrad/blob/master/examples/mnist_gan.py from simplegrad import Tensor, Device, Adam import numpy as",
"loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size)",
"with open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def",
"raise NotImplementedError @property def params(self): return tuple(v for k,v in self.__dict__.items() if isinstance(v,",
"def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1))",
"fake_labels = fake_label(batch_size) optim.zero_grad() output_real = discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake)",
"= 0 while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b =",
"(fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images = make_grid(torch.tensor(fake_images)) save_image(fake_images, os.path.join(output_folder, f'image_{epoch}.jpg'))",
"= Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr =",
"return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024,",
"lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs",
"data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() # generate images after each epoch",
"# generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1,",
"+ '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan(): generator",
"layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1",
"torch.functional.F.leaky_relu(torch.tensor(x.val), negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self,",
"open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp) return dat def test_minst_gan():",
"optim_g = Adam(generator.params, learning_rate=0.0002, beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr",
"return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise NotImplementedError @property",
"with open(fp, 'rb') as f: return f.read() dat = requests.get(url).content with open(fp +",
"fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels",
"import itertools as it from torchvision.utils import make_grid, save_image import torch from abc",
"@abstractmethod def forward(self, x): raise NotImplementedError @property def params(self): return tuple(v for k,v",
"loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return",
"negative_slope=0.2) def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x):",
"28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size = 512 n_batches = int(len(x_train) /",
"discriminator.forward(data_real) loss_real = real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step()",
"output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val + loss_real.val",
"= Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] =",
"import Tensor, Device, Adam import numpy as np import itertools as it from",
"url.encode()[-10:].hex()) if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read() dat",
"= Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer))",
"batches: data_real = Tensor(data_real) noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) data_fake =",
"in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 =",
"# Hyperparameters epochs = 10 batch_size = 512 n_batches = int(len(x_train) / batch_size)",
"def test_minst_gan(): generator = LinearGen() discriminator = LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat),",
"= Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in",
"= Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake =",
"self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in [self.l1, self.l2, self.l3]:",
"y = np.zeros((bs,2), np.float32) y[range(bs), [0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels",
"1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise NotImplementedError @property def params(self):",
"def fetch(url): import requests, tempfile, os fp = os.path.join(tempfile.gettempdir(), url.encode()[-10:].hex()) if os.path.isfile(fp) and",
"= Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr < n_batches:",
"fake_images = generator.forward(Tensor(ds_noise)).val fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images",
"idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b -",
"loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in range(epochs): batches =",
"LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 = Tensor(random_uniform(1024, 512)) self.l3 =",
"while batch_nr < n_batches: idx = np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255.",
"train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss = real_labels.mul(output).mean(axis=(0,1)) loss.backward()",
"[0]*bs] = -2.0 fake_labels = Tensor(y) return fake_labels def train_discriminator(optim, data_real, data_fake): real_labels",
"256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for layer in [self.l1, self.l2,",
"x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield image_b",
"generator.forward(noise) data_fake = Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128))",
"= real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in range(epochs): batches = tuple(batches_generator())",
"Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in [self.l1,",
"dat = requests.get(url).content with open(fp + '.tmp', 'wb') as f: f.write(dat) os.rename(fp+'.tmp', fp)",
"params(self): return tuple(v for k,v in self.__dict__.items() if isinstance(v, Tensor)) class LinearGen(nn): def",
"real_labels.mul(output).mean(axis=(0,1)) loss.backward() optim.step() return loss.val for epoch in range(epochs): batches = tuple(batches_generator()) for",
"1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self, x): for layer in [self.l1, self.l2,",
"= Tensor(random_uniform(512, 256)) self.l4 = Tensor(random_uniform(256, 2)) def forward(self, x): for layer in",
"+ loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss",
"LinearDisc() parse = lambda dat: np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy() x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32)",
"parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size = 512 n_batches",
"x_train = parse(fetch(url = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\"))[0x10:].reshape((-1, 28*28)).astype(np.float32) # Hyperparameters epochs = 10 batch_size =",
"beta1=0.5) optim_d = Adam(discriminator.params, learning_rate=0.0002, beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr",
"fake_labels def train_discriminator(optim, data_real, data_fake): real_labels = real_label(batch_size) fake_labels = fake_label(batch_size) optim.zero_grad() output_real",
"fake_images = (fake_images.reshape(-1, 1, 28, 28)+ 1) / 2 fake_images = make_grid(torch.tensor(fake_images)) save_image(fake_images,",
"[1]*bs] = -2.0 real_labels = Tensor(y) return real_labels def fake_label(bs): y = np.zeros((bs,2),",
"make_grid, save_image import torch from abc import abstractmethod import os def leakyrelu(x, neg_slope=0.2):",
"leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784, 1024)) self.l2 =",
"if os.path.isfile(fp) and os.stat(fp).st_size: with open(fp, 'rb') as f: return f.read() dat =",
"Tensor(data_fake.val) loss_d = train_discriminator(optim_d, data_real, data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise)",
"np.random.randint(0, x_train.shape[0], size=(batch_size)) image_b = x_train[idx].reshape(-1, 28*28).astype(np.float32)/255. image_b = (image_b - 0.5)/0.5 yield",
"data_fake).item() noise = Tensor(np.random.randn(batch_size, 128)) data_fake = generator.forward(noise) loss_g = train_generator(optim_g, data_fake).item() #",
"from torchvision.utils import make_grid, save_image import torch from abc import abstractmethod import os",
"beta1=0.5) def batches_generator(): batch_nr = 0 while batch_nr < n_batches: idx = np.random.randint(0,",
"def random_uniform(*shape): return np.random.uniform(-1., 1., size=shape)/np.sqrt(np.prod(shape)).astype(np.float32) class nn: @abstractmethod def forward(self, x): raise",
"def __init__(self): self.l1 = Tensor(random_uniform(128,256)) self.l2 = Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024))",
"= Tensor(random_uniform(256, 512)) self.l3 = Tensor(random_uniform(512, 1024)) self.l4 = Tensor(random_uniform(1024, 784)) def forward(self,",
"loss_real.val def train_generator(optim, data_fake): real_labels = real_label(batch_size) optim.zero_grad() output = discriminator.forward(data_fake) loss =",
"layer in [self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).logsoftmax() import gzip def fetch(url): import",
"train_generator(optim_g, data_fake).item() # generate images after each epoch fake_images = generator.forward(Tensor(ds_noise)).val fake_images =",
"= real_labels.mul(output_real).mean(axis=(0,1)) output_fake = discriminator.forward(data_fake) loss_fake = fake_labels.mul(output_fake).mean(axis=(0,1)) loss_real.backward() loss_fake.backward() optim.step() return loss_fake.val",
"of https://github.com/geohot/tinygrad/blob/master/examples/mnist_gan.py from simplegrad import Tensor, Device, Adam import numpy as np import",
"[self.l1, self.l2, self.l3]: leakyrelu(x.dot(layer)) return x.dot(self.l4).tanh() class LinearDisc(nn): def __init__(self): self.l1 = Tensor(random_uniform(784,"
] |
[
"# | 01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- # | # |",
"traceback from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator",
"MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary file name cannot",
"import re import sys import time import traceback from CommonEnvironment import CommandLine from",
"dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as f:",
"YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears",
"= year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates = [ 0,",
"a binary file name cannot be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines):",
"<NAME> 2011.' ] # The following expressions must have a 'begin' capture; 'end'",
"[0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict()",
"for common copyright signatures. When one is encountered, it will be updated to",
"CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else",
"import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\"",
"copyright, but it isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if",
"sys import time import traceback from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem",
"binary file name cannot be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for",
"isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end",
"in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles(",
"= os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright",
"] MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 Mb # ---------------------------------------------------------------------------",
"from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower()",
"# Matches single year ] MAX_FILE_SIZE = 100 * 1024 * 1024 #",
"io import inflect import os import re import sys import time import traceback",
"= str(((int(year) // 100) * 100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING:",
"= os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) #",
"GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing",
"looking for common copyright signatures. When one is encountered, it will be updated",
"end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line",
"year=None, output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year = str(int(year) %",
"expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if",
"def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # ---------------------------------------------------------------------------",
"f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError,",
"True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines))",
"FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in",
"too large to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] # --------------------------------------------------------------------------- def",
"def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year",
"copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] =",
"break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it",
"('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()],",
"* 100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have",
"updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with",
"100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1,",
"have a copyright, but it isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip()))",
"try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large to",
"line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0]",
"name: name[0] == '.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose:",
"name cannot be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for copyright_expr in",
"updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # ---------------------------------------------------------------------------",
"'Copyright <NAME> 2011.' ] # The following expressions must have a 'begin' capture;",
"int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but",
"UpdateCopyright.py # | # | <NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15",
"copyright_updated[0]: return \"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager(",
"100) * 100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to",
"of files looking for common copyright signatures. When one is encountered, it will",
"include the current year. \"\"\" import io import inflect import os import re",
"exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] ==",
"# | # --------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18. # |",
"= None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if",
"\"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, )",
"have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches",
"cannot be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS:",
"== year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line =",
"if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath))",
"[ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE",
"CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if",
"have a copyright, but it isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip()))",
"[2].\\n\".format(fullpath, line.strip())) continue if end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin,",
"io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines,",
"{}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\":",
"lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n'",
"len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't",
"len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\": try:",
"display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\",",
"<NAME> 2016-18. # | # | Distributed under the Boost Software License, Version",
"file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1",
"import traceback from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import",
"--------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18. # | # | Distributed",
"# | # | UpdateCopyright.py # | # | <NAME> (<EMAIL>) # |",
"if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary file name cannot be",
"in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda",
"output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath",
"DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath))",
"was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm:",
"0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\",",
"copyright, but it isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if",
"io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc()",
"output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ ==",
"] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]),",
"process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]:",
"import inflect import os import re import sys import time import traceback from",
"it will be updated to include the current year. \"\"\" import io import",
"[ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]),",
"if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't",
") as file_dm: with io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n') newline_char",
"code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0]",
"_script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches",
"# | Copyright <NAME> 2016-18. # | # | Distributed under the Boost",
"with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[",
"optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single",
"100) updates = [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {}",
"# --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'),",
") as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\",",
"have a copyright, but it isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip()))",
"else begin if len(end) == 2: end = str(((int(year) // 100) * 100)",
"year_match = year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to",
"# | # | <NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15 PM",
"'Copyright (c) 2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches",
"# The following expressions must have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS",
"'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), #",
"two_digit_year = str(int(year) % 100) updates = [ 0, ] # --------------------------------------------------------------------------- def",
"str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates = [ 0, ] # ---------------------------------------------------------------------------",
"CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # ---------------------------------------------------------------------------",
"it isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\")",
"inflect import os import re import sys import time import traceback from CommonEnvironment",
"'{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles( code_dir,",
"\"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], )",
"os import re import sys import time import traceback from CommonEnvironment import CommandLine",
"if \"end\" in year_match.groupdict() else begin if len(end) == 2: end = str(((int(year)",
"@CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout,",
"(?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] # The following expressions must have",
"encountered, it will be updated to include the current year. \"\"\" import io",
"# | UpdateCopyright.py # | # | <NAME> (<EMAIL>) # | # |",
"100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a",
"expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears",
"2: end = str(((int(year) // 100) * 100) + int(end)) if len(begin) !=",
"+ int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright,",
"re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE =",
"verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated = [ False,",
"year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a",
"len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't",
"PM # | # --------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18. #",
"or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a",
"a copyright, but it isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue",
"to have a copyright, but it isn't in an expected format ('{}') [2].\\n\".format(fullpath,",
"an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year: continue copyright",
"if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None for year_expr in",
"line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else",
"import io import inflect import os import re import sys import time import",
"year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING:",
"'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR:",
"max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year =",
"from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator #",
"copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() +",
"format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year: continue copyright = \"{}{}{}\".format(",
"MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 Mb # --------------------------------------------------------------------------- plural",
"copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match:",
"in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue",
"'\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary",
"= [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\",",
"copyright_updated = [ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"*****",
"\"\"\"\\ Iterates through a directory of files looking for common copyright signatures. When",
"= copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if",
"not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS:",
"year ] MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 Mb #",
"updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, )",
"# --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\": try: sys.exit(CommandLine.Main()) except KeyboardInterrupt: pass",
"is too large to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] # ---------------------------------------------------------------------------",
"--------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name =",
"files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in",
"StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\",",
"* 1024 * 1024 # 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() #",
"| # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files looking for common",
"enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright",
"format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to",
"--------------------------------------------------------------------------- # | # | UpdateCopyright.py # | # | <NAME> (<EMAIL>) #",
"with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except:",
"to include the current year. \"\"\" import io import inflect import os import",
"in year_match.groupdict() else begin if len(end) == 2: end = str(((int(year) // 100)",
"+ copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True if copyright_updated[0]:",
"accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates",
"following expressions must have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [",
"as file_dm: with io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n') newline_char =",
"appears to have a copyright, but it isn't in an expected format ('{}')",
"= [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ]",
"== 2: end = str(((int(year) // 100) * 100) + int(end)) if len(begin)",
"Matches single year ] MAX_FILE_SIZE = 100 * 1024 * 1024 # 100",
"copyright = copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright)",
"else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\)",
"year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if len(end) == 2: end =",
"updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False,",
"| # | Copyright <NAME> 2016-18. # | # | Distributed under the",
"# | # | 01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- # |",
"copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] # The following",
"year_match.groupdict() else begin if len(end) == 2: end = str(((int(year) // 100) *",
"): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large",
"\".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ], ): try:",
"an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\")",
"done_suffix_functor=GlobalDoneSuffix, ) as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\",",
"* 1024 # 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint",
"Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #",
"> MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated",
"line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match:",
"current year. \"\"\" import io import inflect import os import re import sys",
"plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix,",
"if copyright_updated[0]: return \"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with",
"= inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def",
"as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR:",
"f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be",
"f: f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \"))))",
"Distributed under the Boost Software License, Version 1.0. # | (See accompanying file",
"os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c)",
"line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright,",
"f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines)",
"'{}' appears to be a binary file name cannot be processed.\\n\".format(fullpath)) continue for",
"copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):],",
"fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\",",
"# | <NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15 PM # |",
"1.0. # | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # |",
"year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't in an",
"str(int(year) % 100) updates = [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return",
"in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [",
"\")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\": try: sys.exit(CommandLine.Main())",
"= traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if",
"copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\")",
"year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if len(end) ==",
"# --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), )",
"*****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath,",
"line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True if",
"name[0] == '.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO:",
"re import sys import time import traceback from CommonEnvironment import CommandLine from CommonEnvironment",
"# Matches 'Copyright <NAME> 2011.' ] # The following expressions must have a",
"= \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] =",
"return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files",
"continue copyright_updated = [ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return",
"as dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\",",
"def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing",
"False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated",
"], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too",
"except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary file",
") # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as",
"lambda name: name[0] == '.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if",
"Matches 'Copyright (c) 2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), #",
"else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to",
"year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but",
"FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name:",
"import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath",
"line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char)",
"arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year",
"with io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if",
"year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format(",
"continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin",
"for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[",
"copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as",
"updates = [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format(",
"('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in",
"<NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15 PM # | # ---------------------------------------------------------------------------",
"format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\"",
"year = year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates = [",
"Boost Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy",
"re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE = 100 * 1024 * 1024",
"# Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE = 100",
"\"\"\" import io import inflect import os import re import sys import time",
"# --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir,",
"= f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except",
"(<EMAIL>) # | # | 01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- #",
"(f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose:",
"| Distributed under the Boost Software License, Version 1.0. # | (See accompanying",
"sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"),",
"end = str(((int(year) // 100) * 100) + int(end)) if len(begin) != 4:",
"= (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if",
"| # | Distributed under the Boost Software License, Version 1.0. # |",
"continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start()",
"file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content",
"] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated *****\"",
"The following expressions must have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS =",
"with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content =",
"\"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True",
"# | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files looking for",
"updated to include the current year. \"\"\" import io import inflect import os",
"When one is encountered, it will be updated to include the current year.",
"= year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have",
"to have a copyright, but it isn't in an expected format ('{}') [1].\\n\".format(fullpath,",
"[ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission to use,",
"but it isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin =",
"or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates = [ 0, ] #",
"in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin = year_match.group(\"begin\") end =",
"line.strip())) continue if end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year),",
"# | Distributed under the Boost Software License, Version 1.0. # | (See",
"(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\",
"# --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\": try: sys.exit(CommandLine.Main()) except",
"to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] #",
"| (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # ---------------------------------------------------------------------------",
"import os import re import sys import time import traceback from CommonEnvironment import",
"--------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__ == \"__main__\": try: sys.exit(CommandLine.Main()) except KeyboardInterrupt:",
"Copyright <NAME> 2016-18. # | # | Distributed under the Boost Software License,",
"[1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a",
") def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0])",
"<filename>Scripts/UpdateCopyright.py # --------------------------------------------------------------------------- # | # | UpdateCopyright.py # | # | <NAME>",
"--------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>.",
"if len(end) == 2: end = str(((int(year) // 100) * 100) + int(end))",
"be updated to include the current year. \"\"\" import io import inflect import",
"expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year: continue copyright =",
"dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as f: try: lines =",
"2016-18. # | # | Distributed under the Boost Software License, Version 1.0.",
"two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index]",
"files looking for common copyright signatures. When one is encountered, it will be",
"'{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as f: try:",
"for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright =",
"\"end\" in year_match.groupdict() else begin if len(end) == 2: end = str(((int(year) //",
"# --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files looking for common copyright",
"traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ], ): try: if os.path.getsize(fullpath) >",
"year_match = None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break",
"continue if end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():],",
"# | # | Distributed under the Boost Software License, Version 1.0. #",
"to be a binary file name cannot be processed.\\n\".format(fullpath)) continue for index, line",
"inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint(",
"tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears",
"appears to be a binary file name cannot be processed.\\n\".format(fullpath)) continue for index,",
"with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as f: try: lines",
"| # | UpdateCopyright.py # | # | <NAME> (<EMAIL>) # | #",
"Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as",
"# --------------------------------------------------------------------------- # | # | UpdateCopyright.py # | # | <NAME> (<EMAIL>)",
"| <NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15 PM # | #",
"Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ]",
"'.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is",
"# | # | Copyright <NAME> 2016-18. # | # | Distributed under",
"as f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else",
"from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__)",
"copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of",
"] # The following expressions must have a 'begin' capture; 'end' is optional.",
"os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue",
"\".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ],",
"| # | 01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- # | #",
"1024 # 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints(",
"): year = year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates =",
"in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match",
"--------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None,",
"# --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18",
"sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright",
"the Boost Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or",
"Matches 'Copyright <NAME> 2011.' ] # The following expressions must have a 'begin'",
"\"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS =",
"isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}'",
"a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year",
"# 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(),",
"= str(int(year) % 100) updates = [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix():",
"'{}' appears to have a copyright, but it isn't in an expected format",
"06:12:15 PM # | # --------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18.",
"capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"),",
"end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if len(end) == 2:",
"common copyright signatures. When one is encountered, it will be updated to include",
"isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year:",
"copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] +=",
"100 * 1024 * 1024 # 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine()",
"not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't in",
"file name cannot be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for copyright_expr",
"--------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as",
"copyright, but it isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue begin",
"Mb # --------------------------------------------------------------------------- plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000,",
"1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # ---------------------------------------------------------------------------",
"processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match =",
"(UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary file name",
"if end == year: continue copyright = \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], )",
"newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError):",
"--------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files looking for common copyright signatures.",
"if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS",
"must have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), #",
"large to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] # --------------------------------------------------------------------------- def DoneSuffix():",
"copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with",
"for index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if",
"_script_dir, _script_name = os.path.split(_script_fullpath) # --------------------------------------------------------------------------- COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), #",
"StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir,",
"a directory of files looking for common copyright signatures. When one is encountered,",
"import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable",
"\\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission to use, copy, '",
"len(end) == 2: end = str(((int(year) // 100) * 100) + int(end)) if",
"file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't in an expected",
"--------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm: for",
"dm: for fullpath in FileSystem.WalkFiles( code_dir, exclude_file_extensions=[ \".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ],",
"a copyright, but it isn't in an expected format ('{}') [0].\\n\".format(fullpath, line.strip())) continue",
"index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not",
"+= 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- #",
"be processed.\\n\".format(fullpath)) continue for index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match",
"newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content,",
"(c) 2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright",
"or copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory",
"' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] # The following expressions",
"| # | <NAME> (<EMAIL>) # | # | 01/01/2016 06:12:15 PM #",
"output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100)",
"4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't in an",
"through a directory of files looking for common copyright signatures. When one is",
"// 100) * 100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears",
"except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- #",
"code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year = str(int(year)",
"if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f: f.write('\\n'.join(lines)) updates[0]",
"a copyright, but it isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue",
") lines[index] = line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with",
"copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\")",
"# --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated *****\" #",
"= [ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright",
"expressions must have a 'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"),",
"be a binary file name cannot be processed.\\n\".format(fullpath)) continue for index, line in",
"\"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in",
"begin = year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if",
"return \"***** Copyright was updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix,",
"= line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w',",
"single year ] MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 Mb",
"copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None for year_expr",
"copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS: year_match",
"if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright,",
"2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME>",
"!= 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it isn't in",
"if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it",
"but it isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end",
"lines[index] = line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath,",
"multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE = 100 * 1024",
"{} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir))",
"Iterates through a directory of files looking for common copyright signatures. When one",
"begin if len(end) == 2: end = str(((int(year) // 100) * 100) +",
"import sys import time import traceback from CommonEnvironment import CommandLine from CommonEnvironment import",
"_script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath)",
"content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # ---------------------------------------------------------------------------",
"# --------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18. # | # |",
"\".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ], ): try: if",
"at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files",
"traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- if __name__",
"continue copyright = copyright_match.group(\"copyright\") year_match = None for year_expr in YEAR_EXPRESSIONS: year_match =",
"f.write('\\n'.join(lines)) updates[0] += 1 except: content = traceback.format_exc() output_stream.write(\"ERROR: {}\".format(StreamDecorator.LeftJustify(content, len(\"ERROR: \")))) #",
"(?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright",
"% 100) updates = [ 0, ] # --------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{}",
"year. \"\"\" import io import inflect import os import re import sys import",
"updated *****\" # --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with",
"verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates",
"os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name = os.path.split(_script_fullpath) # ---------------------------------------------------------------------------",
"MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated =",
"2011.' ] # The following expressions must have a 'begin' capture; 'end' is",
"| 01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- # | # | Copyright",
"| # --------------------------------------------------------------------------- # | # | Copyright <NAME> 2016-18. # | #",
"== '.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE: if verbose: dm.stream.write(\"INFO: '{}'",
"the current year. \"\"\" import io import inflect import os import re import",
"one is encountered, it will be updated to include the current year. \"\"\"",
"| UpdateCopyright.py # | # | <NAME> (<EMAIL>) # | # | 01/01/2016",
"--------------------------------------------------------------------------- def GlobalDoneSuffix(): return \"{} {} updated\".format( plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) #",
"if isinstance(f.newlines, tuple) else f.newlines) or '\\r\\n' except (UnicodeDecodeError, MemoryError): if verbose: file_dm.stream.write(\"INFO:",
"COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match =",
"code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ):",
"], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ], ): try: if os.path.getsize(fullpath)",
"Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE = 100 *",
"= year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if len(end) == 2: end",
"--------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None,",
"under the Boost Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt",
"file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through",
"@CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False,",
"if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but it",
"= [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission to",
"'{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] #",
"CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # --------------------------------------------------------------------------- _script_fullpath =",
"output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year or",
"file_dm: with io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0]",
"None for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if not",
"done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r') as f: try: lines = f.read().split('\\n')",
"dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ]",
"'begin' capture; 'end' is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range",
"continue for index, line in enumerate(lines): for copyright_expr in COPYRIGHT_EXPRESSIONS: copyright_match = copyright_expr.match(line)",
"| Copyright <NAME> 2016-18. # | # | Distributed under the Boost Software",
"to process.\\n\".format(fullpath)) continue copyright_updated = [ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if",
"use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] # The",
"# --------------------------------------------------------------------------- dm.stream.write(\"Processing '{}'...\".format(fullpath)) with dm.stream.DoneManager( done_suffix_functor=DoneSuffix, ) as file_dm: with io.open(fullpath, 'r')",
"to have a copyright, but it isn't in an expected format ('{}') [0].\\n\".format(fullpath,",
"EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year = year or str(time.localtime()[0]) two_digit_year =",
"year or str(time.localtime()[0]) two_digit_year = str(int(year) % 100) updates = [ 0, ]",
"# --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager( display_exceptions=False, done_suffix_functor=GlobalDoneSuffix, ) as dm:",
"re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission to use, copy,",
"try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple) else f.newlines) or",
"COPYRIGHT_EXPRESSIONS = [ re.compile(r\".*?Copyright \\(c\\) (?P<copyright>\\S*).*\"), # Matches 'Copyright (c) 2011-18 <NAME>. Permission",
"if verbose: dm.stream.write(\"INFO: '{}' is too large to process.\\n\".format(fullpath)) continue copyright_updated = [",
"plural = inflect.engine() # --------------------------------------------------------------------------- @CommandLine.EntryPoint @CommandLine.FunctionConstraints( code_dir=CommandLine.DirectoryTypeInfo(), year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, )",
"--------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was updated *****\" # ---------------------------------------------------------------------------",
"Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy at",
"\"Generated\", lambda name: name[0] == '.', ], ): try: if os.path.getsize(fullpath) > MAX_FILE_SIZE:",
") line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright, line[copyright_match.end(\"copyright\"):], ) lines[index] = line",
"= \"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")],",
"directory of files looking for common copyright signatures. When one is encountered, it",
"it isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) !=",
"LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a",
"in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if not year_match: file_dm.stream.write(\"WARNING: '{}'",
"= copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None for",
"verbose: file_dm.stream.write(\"INFO: '{}' appears to be a binary file name cannot be processed.\\n\".format(fullpath))",
"plural.no(\"file\", updates[0]), plural.plural_verb(\"was\", updates[0]), ) # --------------------------------------------------------------------------- output_stream.write(\"Processing files in '{}'...\".format(code_dir)) with StreamDecorator(output_stream).DoneManager(",
"an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}'",
"isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4:",
"in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end == year: continue",
"\".pyc\", \".pyo\", \".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.',",
"in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING:",
"\"{}{}{}\".format( copyright[:year_match.start()], \"{}-{}\".format(begin, two_digit_year), copyright[year_match.end():], ) line = \"{}{}{}\".format( line[:copyright_match.start() + copyright_match.start(\"copyright\")], copyright,",
"'r') as f: try: lines = f.read().split('\\n') newline_char = (f.newlines[0] if isinstance(f.newlines, tuple)",
"http://www.boost.org/LICENSE_1_0.txt) # | # --------------------------------------------------------------------------- \"\"\"\\ Iterates through a directory of files looking",
"re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.' ] # The following expressions must",
"year=CommandLine.IntTypeInfo(min=1, max=10000, arity='?'), output_stream=None, ) def EntryPoint( code_dir, year=None, output_stream=sys.stdout, verbose=False, ): year",
"<NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"), # Matches 'Copyright <NAME> 2011.'",
"License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)",
"it isn't in an expected format ('{}') [2].\\n\".format(fullpath, line.strip())) continue if end ==",
"[ False, ] # --------------------------------------------------------------------------- def DoneSuffix(): if copyright_updated[0]: return \"***** Copyright was",
"1024 * 1024 # 100 Mb # --------------------------------------------------------------------------- plural = inflect.engine() # ---------------------------------------------------------------------------",
"# Matches 'Copyright (c) 2011-18 <NAME>. Permission to use, copy, ' re.compile(r\".*?Copyright (?P<copyright>[^\\.]+)\\..*\"),",
"str(((int(year) // 100) * 100) + int(end)) if len(begin) != 4: file_dm.stream.write(\"WARNING: '{}'",
"# | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | #",
"file_dm.stream.write(\"INFO: '{}' appears to be a binary file name cannot be processed.\\n\".format(fullpath)) continue",
"YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year",
"01/01/2016 06:12:15 PM # | # --------------------------------------------------------------------------- # | # | Copyright <NAME>",
"signatures. When one is encountered, it will be updated to include the current",
"('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have",
"time import traceback from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator",
"= 100 * 1024 * 1024 # 100 Mb # --------------------------------------------------------------------------- plural =",
"= True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager(): with io.open(fullpath, 'w', newline=newline_char) as f:",
"is encountered, it will be updated to include the current year. \"\"\" import",
"import time import traceback from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from",
"copyright signatures. When one is encountered, it will be updated to include the",
"range re.compile(r\"(?P<begin>\\d{4})\"), # Matches single year ] MAX_FILE_SIZE = 100 * 1024 *",
"but it isn't in an expected format ('{}') [1].\\n\".format(fullpath, line.strip())) continue if len(end)",
"# --------------------------------------------------------------------------- _script_fullpath = os.path.abspath(__file__) if \"python\" in sys.executable.lower() else sys.executable _script_dir, _script_name",
"\".obj\", \".pdb\", \".idb\", ], traverse_exclude_dir_names=[ \"Generated\", lambda name: name[0] == '.', ], ):",
"continue if len(end) != 4: file_dm.stream.write(\"WARNING: '{}' appears to have a copyright, but",
"will be updated to include the current year. \"\"\" import io import inflect",
"= year_match.group(\"begin\") end = year_match.group(\"end\") if \"end\" in year_match.groupdict() else begin if len(end)",
"for year_expr in YEAR_EXPRESSIONS: year_match = year_expr.search(copyright) if year_match: break if not year_match:",
"is optional. YEAR_EXPRESSIONS = [ re.compile(r\"(?P<begin>\\d{4})-(?P<end>\\d{2,4})\"), # Matches multi-year range re.compile(r\"(?P<begin>\\d{4})\"), # Matches",
"line[copyright_match.end(\"copyright\"):], ) lines[index] = line copyright_updated[0] = True if copyright_updated[0]: file_dm.stream.write(\"Updating...\") with file_dm.stream.DoneManager():",
"copyright_match = copyright_expr.match(line) if not copyright_match: continue copyright = copyright_match.group(\"copyright\") year_match = None"
] |
[
"matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0,",
"matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0]) plt.plot(xs[:,0], xs[:,1],",
"utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import",
"coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__",
"from __future__ import division from __future__ import print_function import numpy as np import",
"import division from __future__ import print_function import numpy as np import matplotlib matplotlib.use('Agg')",
"division from __future__ import print_function import numpy as np import matplotlib matplotlib.use('Agg') import",
"matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0])",
"from __future__ import print_function import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab",
"-*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from",
"def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0]) plt.plot(xs[:,0], xs[:,1], \"ro\") plt.savefig(file_path) plt.close()",
"numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path):",
"-*- from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0])",
"plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0]) plt.plot(xs[:,0], xs[:,1], \"ro\") plt.savefig(file_path)",
"__future__ import print_function import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as",
"as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure()",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0]) plt.plot(xs[:,0], xs[:,1], \"ro\")",
"import print_function import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt",
"print_function import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def",
"absolute_import from __future__ import division from __future__ import print_function import numpy as np",
"np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0,",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import numpy",
"__future__ import division from __future__ import print_function import numpy as np import matplotlib",
"import matplotlib.pylab as plt def save_figure(xs, file_path): plt.figure() plt.ylim([-2.0, 2.0]) plt.xlim([-2.0, 2.0]) plt.plot(xs[:,0],",
"import absolute_import from __future__ import division from __future__ import print_function import numpy as",
"# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division",
"import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt def save_figure(xs,"
] |
[
"models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user",
"def __unicode__(self): return u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes for",
"Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100,",
"return imeasure return None class Device(models.Model): \"\"\" UUID from devices \"\"\" created =",
"TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES",
"InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house",
"blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text =",
"reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption",
"target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self):",
"Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django",
"class Device(models.Model): \"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User,",
"= models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True)",
"scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication",
"u'%s %s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user =",
"Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house =",
"ordering = ('created',) # unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return u'%s",
"= 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact",
"models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True)",
"UUIDField(auto=True) class Meta: ordering = ('created',) unique_together = ('sender', 'created') def __unicode__(self): return",
"(CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH =",
"% (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for",
"\"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode",
"models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s",
"between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User,",
"2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image",
"django.db import models from django.forms import fields from django.forms import ValidationError from django.utils.encoding",
"UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links')",
"related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering =",
"\"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude",
"= ('created',) unique_together = ('sender', 'created') def __unicode__(self): return u'%s %s' % (self.text,",
"hex color code e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value) if value",
"return u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\"",
"((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text",
"= 'schien' import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from",
"\"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE =",
"between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter =",
"models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self):",
"Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks')",
"= 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True)",
"('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8,",
"models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def",
"import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.db import",
"= models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s - %s - %s\" %",
"int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return",
"= models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread,",
"#000000' } def clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u''",
"= { 'hex_error': u'This is an invalid color code. It must be a",
"return None class Device(models.Model): \"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user",
"models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house =",
"longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments",
"report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return",
"related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s %s",
"sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta:",
"models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True,",
"\"\"\" A measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80,",
"null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house') def __unicode__(self):",
"models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s - %s - %s\" % (self.redirect.user.username,",
"imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\" UUID from",
"models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024,",
"previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user =",
"models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together =",
"smart_unicode(value) value_length = len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise",
"product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class",
"fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if value_length != 7",
"value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self,",
"isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two users \"\"\"",
"object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model):",
"uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True,",
"\"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True)",
"= models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key",
"= ('user', 'house') def __unicode__(self): return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self):",
"= ('created',) # unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s'",
"'created') def __unicode__(self): return u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created =",
"2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI,",
"'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent",
"null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True)",
"= models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A",
"= models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1",
"= models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User,",
"owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude =",
"= generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True)",
"models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\"",
"string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\"",
"key = UUIDField(auto=True) class Meta: ordering = ('created',) unique_together = ('sender', 'created') def",
"self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if",
"class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False)",
"related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class House(models.Model):",
"Meta: ordering = ('created',) unique_together = ('user', 'house') def __unicode__(self): return u'%s %s'",
"% (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m =",
"% (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure =",
"unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key",
"\"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES,",
"= models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures')",
"if m > 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure",
"'text', 'timestamp') def __unicode__(self): return u'%s %s' % (self.text, self.user.username) @property def house(self):",
"models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s - %s -",
"HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving",
"\"\"\" Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender",
"from tinymce.models import HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models import ContentType",
"class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User,",
"= models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s %s %s\" %",
"return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home",
"UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\",",
"= models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True)",
"(self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text",
"= models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses",
"related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s",
"HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import",
"verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class",
"supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls =",
"return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two users \"\"\" user =",
"\"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\",",
"disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True,",
"} def clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u'' value",
"= models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True,",
"('user', 'house') def __unicode__(self): return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return",
"= models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True)",
"address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children",
"authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta:",
"(ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s =",
"\"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True)",
"e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return",
"text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver =",
"= models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template",
"def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase +",
"user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False)",
"\"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication",
"null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True)",
"verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self):",
"for x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between two",
"accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s =",
"str(7)} class UserProfile(models.Model): \"\"\" Message between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django",
"AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN,",
"return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model):",
"default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner",
"models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True)",
"value = smart_unicode(value) value_length = len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$',",
"imeasure return None class Device(models.Model): \"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True)",
"unique_together = ('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version",
"= models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a",
"OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY,",
"'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1,",
"class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type",
"super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length =",
"= models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, ) class",
"Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User,",
"(OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES,",
"1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact =",
"return u'%s %s' % (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def",
"( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE,",
"fields from django.forms import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField",
"(fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two users \"\"\" user",
"class Meta: ordering = ('created',) unique_together = ('sender', 'created') def __unicode__(self): return u'%s",
"((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type",
"import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an invalid color",
"= Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\"",
"ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') )",
"value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength':",
"+ string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model):",
"class Message(models.Model): \"\"\" Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text =",
"image = models.TextField() report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True)",
"\"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user')",
"('created',) unique_together = ('user', 'house') def __unicode__(self): return u'%s %s' % (self.house.id, self.text)",
"= 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility",
"(MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True,",
"%s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure",
"__author__ = 'schien' import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic",
"from django.db import models from django.forms import fields from django.forms import ValidationError from",
"thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering = ('created',)",
"( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open",
"def __unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True)",
"null=True, blank=True) def __unicode__(self): return u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\"",
"= models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s = 5",
"(AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True)",
"is an invalid color code. It must be a html hex color code",
"= models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False,",
"# urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s' % (self.pk,",
"choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL,",
"__unicode__(self): return u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses",
"Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\" UUID",
"related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name = models.TextField() is_renewable =",
"OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'),",
"\"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication",
"models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s = 5 AGE_70s",
"created = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes')",
"models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model): url =",
"authentication user\", related_name='links') def __unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url)",
"'timestamp') def __unicode__(self): return u'%s %s' % (self.text, self.user.username) @property def house(self): return",
"ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL,",
"UserProfile(models.Model): \"\"\" Message between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\",",
"= models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4",
"\"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH",
"!= 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget):",
"class Note(models.Model): \"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField()",
"and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL =",
"choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES =",
"timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together = ('user', 'house')",
"models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier",
"GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass",
"from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones')",
"= models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True,",
"InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\" UUID from devices \"\"\"",
"models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url",
"= models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField()",
"def __unicode__(self): return u'%s %s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\"",
"= models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house')",
"3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"),",
"(self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect =",
"blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s %s'",
"Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short =",
"\" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url",
"blank=True, max_length=400) def __unicode__(self): return u'%s %s %s' % (self.user.username, self.platform, self.version) class",
"models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def",
"import random import string import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import",
"= models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering",
"verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages')",
"\"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age =",
"message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created =",
"Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender =",
"'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3",
"value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if value_length",
"as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message =",
"= models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments =",
"= models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova =",
"= ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"),",
"verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering = ('created',)",
"value_length = len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error'])",
"random import string import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse",
"import HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes",
"children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY =",
"\"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW",
"created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House,",
"('sender', 'created') def __unicode__(self): return u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created",
"model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides",
"django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__ = 'schien' import re from",
"mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True) #",
"unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField()",
"(AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age",
") contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2",
"blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier =",
"must be a html hex color code e.g. #000000' } def clean(self, value):",
"user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name = models.TextField() is_renewable",
"UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an invalid color code.",
"'schien' import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models",
"max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model =",
"= models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1",
"AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES",
"message = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True,",
"HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an invalid color code. It must",
"(ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN",
"= 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"),",
"m = int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house,",
"User from django.db import models from django.forms import fields from django.forms import ValidationError",
"= 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping =",
"return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type',",
"Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1,",
"= models.TextField() report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def",
"verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class",
"GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True,",
"Provides a url key to compose a message as response \"\"\" message_key =",
"user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category",
"= 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW,",
"class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent =",
"import fields from django.forms import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import",
"return \"%s \" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self):",
"generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url",
"\"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address =",
"('created',) unique_together = ('sender', 'created') def __unicode__(self): return u'%s %s' % (self.text, self.sent)",
"return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message",
"__unicode__(self): return \"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model):",
"url key to compose a message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message",
"content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return",
"% (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication",
"= 1 class Message(models.Model): \"\"\" Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True)",
"blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6,",
"measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house =",
"Message between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter",
"= models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3",
"(TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0",
"\"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type =",
"= 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'),",
"def __unicode__(self): return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk':",
"class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an invalid color code. It",
"(self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200) description =",
"def __unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner =",
"measure(self): m = int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m) imeasure =",
"%s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User,",
"from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = {",
"((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s,",
"(AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT =",
"openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key to",
"related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering = ('created',) # unique_together =",
"models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED",
"AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"),",
"null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES = (",
"class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model):",
"def __unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together",
"( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True)",
"models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True)",
"= 3 AGE_50s = 5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN =",
"(TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE",
"u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars)",
"cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True,",
"7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if",
"self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8)",
"open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE =",
"class Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short",
"= 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday",
"re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return",
"pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID",
"self.target_url.url) class Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection",
"TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"),",
"{ 'hex_error': u'This is an invalid color code. It must be a html",
"blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,)",
"class Meta: unique_together = ('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,) class",
"0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR,",
"7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s = 6",
"class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def",
"class Meta: ordering = ('created',) unique_together = ('user', 'house') def __unicode__(self): return u'%s",
"age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW =",
"ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.db import models",
"(OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open =",
"class Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user",
"in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if value_length !=",
"class UserProfile(models.Model): \"\"\" Message between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication",
"= models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True,",
"<gh_stars>0 import random import string import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers",
"models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True)",
"CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1,",
"unique_together = ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time",
"@property def measure(self): m = int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m)",
"models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key =",
"widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two",
"from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an",
"= models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" %",
"color code. It must be a html hex color code e.g. #000000' }",
"u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User,",
"models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp",
"models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s",
"%s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created =",
"null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = (",
"MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping",
"return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return",
"self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost",
"related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase",
"research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model):",
"related_name='links') def __unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta:",
"authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400)",
"Meta: unique_together = ('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model):",
"= models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0",
"- %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans",
"models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model):",
"reverse from tinymce.models import HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models import",
"created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True,",
"code. It must be a html hex color code e.g. #000000' } def",
"= models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s - %s",
"(TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES,",
"platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True,",
"'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url =",
"models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering =",
"null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' %",
"created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self):",
"__unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together =",
"GenericRelation from django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__ = 'schien' import",
"House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address",
"= models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES =",
"blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls",
"= models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house') def __unicode__(self): return u'%s'",
"= 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI =",
"Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user =",
"2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None')",
"CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") )",
"= models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True,",
"two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False,",
"from django.forms import fields from django.forms import ValidationError from django.utils.encoding import smart_unicode from",
"%s' % (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django",
"a html hex color code e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value)",
"= models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms =",
"u'This is an invalid color code. It must be a html hex color",
"= 5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s =",
"Meta: ordering = ('created',) unique_together = ('sender', 'created') def __unicode__(self): return u'%s %s'",
"related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform =",
"0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and",
"Message(models.Model): \"\"\" Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField()",
"blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" % self.user.username class",
"month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key to compose a message",
"__unicode__(self): return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk})",
"= ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES,",
"= models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def",
"'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True)",
"= 0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s,",
"generic from django.contrib.auth.models import User from django.db import models from django.forms import fields",
"models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house') def",
"(self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8])",
"import reverse from tinymce.models import HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models",
"model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s %s' % (self.user.username,",
"0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"),",
"models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True)",
"django.contrib.auth.models import User from django.db import models from django.forms import fields from django.forms",
"MessageKey(models.Model): \"\"\" Provides a url key to compose a message as response \"\"\"",
"if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def",
"value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\"",
"user\", related_name='links') def __unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class",
"user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering",
"unique_together = ('sender', 'created') def __unicode__(self): return u'%s %s' % (self.text, self.sent) class",
"# timestamp = models.BigIntegerField() class Meta: ordering = ('created',) # unique_together = ('user',",
"return u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\" name =",
"models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver",
"\"\"\" Message between two users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile')",
"= smart_unicode(value) value_length = len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value):",
"def measure(self): m = int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m) imeasure",
"0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility =",
"= ('created',) unique_together = ('user', 'house') def __unicode__(self): return u'%s %s' % (self.house.id,",
"\"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user =",
"3 AGE_50s = 5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN = 0",
"contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES",
"models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django",
"from django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__ = 'schien' import re",
"models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True,",
"= models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True,",
"%s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user') class Click(models.Model):",
"self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True,",
"blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model",
"self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user =",
"u'%s %s' % (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self):",
"__unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls')",
"unique_together = ('user', 'house') def __unicode__(self): return u'%s %s' % (self.house.id, self.text) def",
"verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages')",
"models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400)",
"blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def",
"__unicode__(self): return u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user",
"% (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication",
"chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1 class",
"users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django",
"5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s = 2",
"ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1,",
"self).clean(value) if value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value)",
"= 8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES =",
"models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude",
"__unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object =",
"user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova",
"choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES =",
"House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if m > 0: measure =",
"= models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url",
"django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error':",
"= models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering",
"or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget,",
"measure category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s'",
"django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key",
"models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s'",
"ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'),",
"models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s",
"string import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from tinymce.models",
"supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product =",
"= UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\",",
"class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house",
"models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400)",
"user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp =",
"null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\"))",
"null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls",
"\"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5",
"authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent =",
"= 1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY,",
"= models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house",
"ordering = ('created',) unique_together = ('sender', 'created') def __unicode__(self): return u'%s %s' %",
"authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering = ('created',) #",
"year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key to compose a message as",
"blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0",
"u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9,",
"= models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') #",
"def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday",
"\"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User,",
"from django.contrib.auth.models import User from django.db import models from django.forms import fields from",
"% (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\",",
"class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model):",
"(AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s,",
"redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication",
"user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s - %s - %s\"",
"__unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\" name",
"\"Terrace\"), (TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR",
"\"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text =",
"max_length=400) def __unicode__(self): return u'%s %s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model):",
"key to compose a message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message =",
"= 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"),",
"user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True)",
"= GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s' % (self.pk, self.address) class",
"choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s = 5 AGE_70s =",
"\"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid =",
"1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT,",
"'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s",
"= models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together = ('user', 'house') def",
"{'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two users \"\"\" user = models.OneToOneField(User,",
"= models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2",
"verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name =",
"= models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children =",
"blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s' %",
"'house') def __unicode__(self): return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note',",
"models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID,",
"%s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user') class",
"return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if m > 0: measure",
"= HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User,",
"users \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False)",
"models from django.forms import fields from django.forms import ValidationError from django.utils.encoding import smart_unicode",
"code e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES:",
"= models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House,",
"%s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\"",
"null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return",
"models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH,",
"self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True) text =",
"class MessageKey(models.Model): \"\"\" Provides a url key to compose a message as response",
"__unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits):",
"sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django",
"report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True,",
"AGE_20s = 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s,",
"''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between",
"= models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,)",
"App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\"",
"max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s %s' %",
"2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\")",
"related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s",
"re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User",
"a url key to compose a message as response \"\"\" message_key = models.BigIntegerField(unique=True)",
"tinymce.models import HTMLField __author__ = 'schien' import re from django.contrib.contenttypes.models import ContentType from",
"= len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return",
"blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls =",
"= models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category =",
"models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES",
"(AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED",
"u'' value = smart_unicode(value) value_length = len(value) if value_length != 7 or not",
"@property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if m",
"= 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES =",
"related_name='messages') key = UUIDField(auto=True) class Meta: ordering = ('created',) unique_together = ('sender', 'created')",
"('created',) # unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s' %",
"models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY",
"\"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\"))",
"house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if m > 0:",
"AGE_50s = 5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s",
"__unicode__(self): return u'%s %s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\"",
"verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True,",
"models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s %s' %",
"null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s = 5 AGE_70s = 7",
"owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True)",
"= models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return",
"len(value) if value_length != 7 or not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value",
"max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self):",
"GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s' % (self.pk, self.address) class Note(models.Model):",
"'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL =",
"\"\"\" A measure category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self):",
"models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name",
"= ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\") )",
"related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL,",
"text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House,",
"\"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\",",
"('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True)",
"u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model):",
"max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version =",
"null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model): pass def",
"3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES = (",
"= models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True)",
"4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED,",
"range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between two users \"\"\" created",
"LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages',",
"category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' %",
"null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3",
"auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def",
"models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class",
"measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color",
"= models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024,",
"is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model): \"\"\"",
"= ('sender', 'created') def __unicode__(self): return u'%s %s' % (self.text, self.sent) class Favourite(models.Model):",
"% (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect",
"measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model):",
"self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile')",
"return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user",
"ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages =",
"def __unicode__(self): return \"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class",
"models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id =",
"= 2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH,",
"timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house') def __unicode__(self): return",
"self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL):",
"%s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\" created =",
"(OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1",
"user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s %s %s\"",
"(self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure)",
"'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL",
"= 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW,",
"class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True)",
"models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A measure",
"\"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A",
"TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE, \"Terrace\"), (TYPE_SEMI, \"Semi\")",
"\"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"),",
"= 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"),",
"models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE",
"adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True,",
"(TYPE_SEMI, \"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR =",
"= models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True,",
"import User from django.db import models from django.forms import fields from django.forms import",
"= ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField()",
"(self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\",",
"models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key to compose a",
"= models.BigIntegerField() class Meta: ordering = ('created',) # unique_together = ('user', 'text', 'timestamp')",
"user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research =",
"RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self):",
"type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH =",
"(self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text",
"choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"),",
"latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms",
"TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI",
"import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from tinymce.models import",
"% (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created = models.DateTimeField(auto_now_add=True)",
"blank=False) def __unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255,",
"import models from django.forms import fields from django.forms import ValidationError from django.utils.encoding import",
"% (self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200) description",
"models.FloatField(null=True) longitude = models.FloatField(null=True) adults = models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True)",
"class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in",
"invalid color code. It must be a html hex color code e.g. #000000'",
"models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp",
"__unicode__(self): return u'%s %s' % (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property",
"8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN,",
"verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s %s' % (self.created,",
"None class Device(models.Model): \"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user =",
"timestamp = models.BigIntegerField() class Meta: ordering = ('created',) # unique_together = ('user', 'text',",
"return u'' value = smart_unicode(value) value_length = len(value) if value_length != 7 or",
"1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL,",
"%s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django",
"TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"), (TYPE_DETACHED, \"Detached\"), (TYPE_BUNGALOW, \"Bungalow\"), (TYPE_TERRACE,",
"related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread",
"2 AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s,",
"from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__",
"receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread =",
"u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\" created",
"models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True) # urls =",
"import generic from django.contrib.auth.models import User from django.db import models from django.forms import",
"models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template =",
"models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp",
"(AGE_70s, \"1970s\"), (AGE_NEW, \"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1,",
"CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"),",
"ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class",
"models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400)",
"user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering = ('created',) # unique_together",
"url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType)",
"(self.measure.short,) class MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x",
"= models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages')",
"def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL,",
"unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s' % (self.text, self.user.username)",
"\"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure",
"'house') def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True)",
"blank=True) class Meta: unique_together = ('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,)",
"value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length",
"%s' % (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m",
"django.forms import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field):",
"class Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\",",
"house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',)",
"= models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True,",
") accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s",
"MessageThread(models.Model): pass def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size))",
"m > 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return",
"models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s %s %s\" % (self.user.username,",
"authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta:",
"user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp =",
") type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH",
"self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='favourites')",
"= ('user', 'house') def __unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version =",
"(self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013)) class",
"name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name, )",
"import string import datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from",
"text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp =",
"color code e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value) if value in",
"return \"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\"",
"be a html hex color code e.g. #000000' } def clean(self, value): super(HexColorField,",
"(ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN = 1",
"null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED =",
"if value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if",
"= models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True)",
"def clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u'' value =",
"(AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1",
"if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between two users",
"MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES,",
"return u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True) user =",
"verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def",
"bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY =",
"% (self.pk, self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True)",
"def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost =",
"\"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED =",
"class Meta: ordering = ('created',) # unique_together = ('user', 'text', 'timestamp') def __unicode__(self):",
"(self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house',",
"self.address) class Note(models.Model): \"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text =",
"html hex color code e.g. #000000' } def clean(self, value): super(HexColorField, self).clean(value) if",
"import GenericRelation from django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__ = 'schien'",
"# unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s' % (self.text,",
"\"%s \" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return",
"def house(self): return House.objects.get(pk=int(self.text[0:4])) @property def measure(self): m = int(self.text[5:8]) if m >",
"= InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\" UUID from devices",
"= 7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s =",
"= models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True,",
"= models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication",
"\"\"\" Provides a url key to compose a message as response \"\"\" message_key",
"two users \"\"\" created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending",
"name = models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7,",
"user\", related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together",
"django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.db import models from django.forms",
"models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s %s' % (self.user.username, self.platform, self.version)",
"import re from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import",
"Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2",
") class Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True)",
"django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.db",
"= GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return u'%s' % (self.measure.short,) class MessageThread(models.Model):",
"user = models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s",
"def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID =",
"class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True)",
"models.ForeignKey(User, verbose_name=\"sending django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\",",
"models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory,",
"'hex_error': u'This is an invalid color code. It must be a html hex",
"self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl,",
"authentication user\", related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key =",
"category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' %",
"CONTACT_NONE = 0 CONTACT_YEAR = 2 CONTACT_MONTH = 1 CONTACT_CHOICES = ( (CONTACT_NONE,",
"houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication",
"- %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time) class Scan(models.Model): \"\"\" Barcode scans \"\"\" created",
"u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\" name = models.CharField(max_length=200)",
"= ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), )",
"models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user', 'house') def __unicode__(self): return u'%s' %",
"blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s'",
"OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'),",
"(CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR",
"null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True,",
"models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True,",
"It must be a html hex color code e.g. #000000' } def clean(self,",
"get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True,",
"= models.IntegerField(null=True) children = models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True)",
"'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE, 'None') ) accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True) AGE_VICTORIAN =",
"AGE_30s = 3 AGE_50s = 5 AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN",
"Note(models.Model): \"\"\" Notes for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user",
"def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object",
"authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self):",
"color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html')",
"models.BigIntegerField() class Meta: ordering = ('created',) # unique_together = ('user', 'text', 'timestamp') def",
"models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40)",
"= 1 AGE_30s = 3 AGE_50s = 5 AGE_70s = 7 AGE_NEW =",
"related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s %s' % (self.created, self.user, self.message[:80])",
") open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE",
"import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This",
"RedirectUrl(models.Model): redirect_key = UUIDField(unique=True, auto=True) target_url = models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django",
"default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering = ('created',) unique_together = ('sender',",
"def __unicode__(self): return u'%s %s' % (self.text, self.sent) class Favourite(models.Model): created = models.DateTimeField(auto_now_add=True)",
"response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField()",
"= int(self.text[5:8]) if m > 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0]",
"TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type =",
"default_error_messages = { 'hex_error': u'This is an invalid color code. It must be",
"report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\"",
"DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between two users \"\"\" created =",
"AGE_VICTORIAN = 1 AGE_30s = 3 AGE_50s = 5 AGE_70s = 7 AGE_NEW",
"\"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color =",
"id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) DEFAULT_THREAD_ID = 1",
"models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" % self.user.username",
"related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def",
"(CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True)",
"created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=8) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans')",
"urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s' % (self.pk, self.address)",
"to compose a message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message)",
"in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between two users \"\"\"",
"self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class",
"django.forms import fields from django.forms import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields",
"(OPEN_SUNDAY, 'Sunday'), (OPEN_SATURDAY_AND_SUNDAY, 'Saturday and Sunday'), ) open = models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL",
"blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product",
"def __unicode__(self): return u'%s %s' % (self.text, self.user.username) @property def house(self): return House.objects.get(pk=int(self.text[0:4]))",
"return u'%s %s' % (self.house.id, self.text) def get_absolute_url(self): return reverse('web:note', kwargs={'pk': self.pk}) class",
"return \"%s %s %s\" % (self.user.username, self.redirect_key, self.target_url.url) class Meta: unique_together = ('target_url',",
"\"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return u'%s' % (self.name,",
"user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return",
"models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta: ordering =",
"smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is",
"content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class RedirectUrl(models.Model): redirect_key = UUIDField(unique=True,",
"url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return",
"A measure category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def __unicode__(self): return",
"django authentication user\", related_name='sent_messages') receiver = models.ForeignKey(User, verbose_name=\"receiving django authentication user\", related_name='received_messages') sent",
"MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image =",
"= models.ForeignKey(House, related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together",
"Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024)",
"5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI = 2",
"0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None class",
"models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering = ('created',) unique_together =",
"widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message between",
"= models.ForeignKey(TrackableURL, related_name='redirect_urls') user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return",
"1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY, 'Saturday'), (OPEN_SUNDAY, 'Sunday'),",
"u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile, verbose_name=\"home owner",
"blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls')",
"a message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model):",
"= models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\"",
"choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT = 5 TYPE_DETACHED = 1 TYPE_BUNGALOW = 4 TYPE_TERRACE =",
"1 AGE_30s = 3 AGE_50s = 5 AGE_70s = 7 AGE_NEW = 8",
"models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.url class",
"house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together = ('user',",
"= models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self): return",
"models.TextField() report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self):",
"2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'), (OPEN_SATURDAY,",
"house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text = models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024,",
"def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)} class UserProfile(models.Model): \"\"\" Message",
"models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s %s'",
"redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True,",
"models.IntegerField(null=True) bedrooms = models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY",
"django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages = { 'hex_error': u'This is an invalid",
"\"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR =",
"\"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES, default=CONTACT_NONE, null=True) MAPPING_MONTH = 1",
"from django.forms import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class",
"= GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls') product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL,",
"django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from tinymce.models import HTMLField __author__ =",
"= models.IntegerField(max_length=1, choices=MAPPING_CHOICES, null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True) # urls",
"AGE_60s = 6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"),",
"from django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.db import models from",
"= models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model): url",
"newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False) def __unicode__(self): return \"%s \"",
"from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User from",
"not re.match('^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value): raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)):",
"raise ValidationError(self.error_messages['hex_error']) return value def widget_attrs(self, widget): if isinstance(widget, (fields.TextInput)): return {'maxlength': str(7)}",
"= models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s",
"OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED,",
"\"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created",
"= models.DateField(default=datetime.date(day=26, month=9, year=2013)) class MessageKey(models.Model): \"\"\" Provides a url key to compose",
"time = models.DateTimeField(auto_now_add=True) user_agent = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return \"%s -",
"('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s' % (self.text, self.user.username) @property def",
"= models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return u'%s %s %s' % (self.user.username, self.platform,",
"= models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class Meta: ordering = ('created',) unique_together",
"self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id')",
"= 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES = ( (ACCESSIBILITY_FULL, 'Full'), (ACCESSIBILITY_PARTIAL, 'Partial'), (ACCESSIBILITY_NONE,",
"__unicode__(self): return u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday =",
"return reverse('web:note', kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True)",
"created = models.DateTimeField(auto_now_add=True) text = HTMLField() sender = models.ForeignKey(User, verbose_name=\"sending django authentication user\",",
"related_name='note') timestamp = models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together = ('user',",
"1 class Message(models.Model): \"\"\" Message between two users \"\"\" created = models.DateTimeField(auto_now_add=True) text",
"models.TextField(null=True, blank=True) supplier = models.CharField(max_length=1024, null=True, blank=True) supplier_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='supplier_urls')",
"x in range(size)) DEFAULT_THREAD_ID = 1 class Message(models.Model): \"\"\" Message between two users",
"1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR, \"Year\")) mapping = models.IntegerField(max_length=1,",
"A measure \"\"\" name = models.CharField(max_length=200) description = models.TextField(null=True) short = models.CharField(max_length=80, null=True)",
"an invalid color code. It must be a html hex color code e.g.",
"\"Semi\") ) type = models.IntegerField(max_length=1, choices=TYPE_CHOICES, null=True) CONTACT_NONE = 0 CONTACT_YEAR = 2",
"authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name = models.TextField()",
"profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults",
"version = models.CharField(null=True, blank=True, max_length=400) model = models.CharField(null=True, blank=True, max_length=400) def __unicode__(self): return",
"models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200, default='report/general_measure_text.html') def __unicode__(self): return u'%s' % (self.name,) class",
"models.IntegerField(max_length=1, choices=OPEN_CHOICES, null=True) ACCESSIBILITY_FULL = 1 ACCESSIBILITY_PARTIAL = 2 ACCESSIBILITY_NONE = 0 ACCESSIBILITY_CHOICES",
"= ( (CONTACT_NONE, \"None\"), (CONTACT_YEAR, \"Year\"), (CONTACT_MONTH, \"Month\") ) contact = models.IntegerField(max_length=1, choices=CONTACT_CHOICES,",
"message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message",
"blank=True) class Meta: ordering = ('created',) unique_together = ('user', 'house') def __unicode__(self): return",
"kwargs={'pk': self.pk}) class InstalledMeasure(models.Model): measure = models.ForeignKey(Measure) cost = models.IntegerField(null=True, blank=True) disruption =",
"= ('target_url', 'user') class Click(models.Model): redirect = models.ForeignKey(RedirectUrl, verbose_name=\"redirection url\", related_name='clicks') time =",
"= UUIDField(auto=True) class Meta: ordering = ('created',) unique_together = ('sender', 'created') def __unicode__(self):",
"% (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26, month=9, year=2013))",
"MeasureCategory(models.Model): \"\"\" A measure category \"\"\" name = models.TextField() is_renewable = models.BooleanField(default=False) def",
"= models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True,",
"= models.ForeignKey(User, verbose_name=\"django user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s %s'",
"measure=measure)[0] return imeasure return None class Device(models.Model): \"\"\" UUID from devices \"\"\" created",
"Device(models.Model): \"\"\" UUID from devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django",
"return u'%s %s %s' % (self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user",
"> 0: measure = Measure.objects.get(pk=m) imeasure = InstalledMeasure.objects.filter(house=self.house, measure=measure)[0] return imeasure return None",
"models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research = models.NullBooleanField(null=False, blank=False)",
"= models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True, blank=True) def __unicode__(self): return u'%s",
"null=True) def __unicode__(self): return \"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url, self.time)",
"user\", related_name='phones') uuid = models.CharField(null=True, blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform",
"blank=True, max_length=40) cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version",
"__unicode__(self): return \"%s \" % self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def",
"compose a message as response \"\"\" message_key = models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class",
"HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='home_owner_profile') class MeasureCategory(models.Model): \"\"\"",
"models.IntegerField(null=True) comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY",
"models.IntegerField(null=True, blank=True) disruption = models.IntegerField(null=True, blank=True) house = models.ForeignKey(House, null=True, blank=True, related_name='measures') report_text",
"import ValidationError from django.utils.encoding import smart_unicode from django_extensions.db.fields import UUIDField class HexColorField(fields.Field): default_error_messages",
"(self.user.username, self.platform, self.version) class HomeOwnerProfile(models.Model): \"\"\" \"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\",",
"OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES",
"related_name='received_messages') sent = models.BooleanField(default=False) thread = models.ForeignKey(MessageThread, default=DEFAULT_THREAD_ID, related_name='messages') key = UUIDField(auto=True) class",
"devices \"\"\" created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='phones') uuid",
"product = models.CharField(max_length=1024, null=True, blank=True) product_urls = GenericRelation(RelatedTrackableURL, null=True, blank=True, related_name='product_urls') def __unicode__(self):",
"related_name='favourites') house = models.ForeignKey(House, null=True) timestamp = models.BigIntegerField(null=True, blank=True) class Meta: unique_together =",
"6 AGE_CHOICES = ((AGE_VICTORIAN, \"Victorian\"), (AGE_30s, \"1930s\"), (AGE_50s, \"1950s\"), (AGE_70s, \"1970s\"), (AGE_NEW, \"New\"),",
"user\", related_name='log_messages', null=True, blank=True) def __unicode__(self): return u'%s %s %s' % (self.created, self.user,",
"TYPE_BUNGALOW = 4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi",
"datetime from django.contrib.contenttypes.generic import GenericRelation from django.core.urlresolvers import reverse from tinymce.models import HTMLField",
"__unicode__(self): return u'%s' % (self.name,) class House(models.Model): \"\"\" Houses \"\"\" owner = models.ForeignKey(HomeOwnerProfile,",
"def __unicode__(self): return u'%s' % (self.name, ) class Measure(models.Model): \"\"\" A measure \"\"\"",
"default=CONTACT_NONE, null=True) MAPPING_MONTH = 1 MAPPING_YEAR = 2 MAPPING_CHOICES = ((MAPPING_MONTH, \"Month\"), (MAPPING_YEAR,",
"blank=True) def __unicode__(self): return u'%s %s' % (self.pk, self.address) class Note(models.Model): \"\"\" Notes",
"clean(self, value): super(HexColorField, self).clean(value) if value in fields.EMPTY_VALUES: return u'' value = smart_unicode(value)",
"verbose_name=\"django authentication user\", related_name='links') def __unicode__(self): return \"%s %s %s\" % (self.user.username, self.redirect_key,",
"blank=True, null=True) def __unicode__(self): return \"%s - %s - %s\" % (self.redirect.user.username, self.redirect.target_url.url,",
"user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='scans') # timestamp = models.BigIntegerField() class Meta:",
"null=True) color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures') report_template = models.CharField(max_length=200,",
"for houses \"\"\" created = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(User, verbose_name=\"django",
"class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, verbose_name=\"django user\",",
"AGE_70s = 7 AGE_NEW = 8 AGE_GEORGIAN = 0 AGE_20s = 2 AGE_60s",
"= ('user', 'text', 'timestamp') def __unicode__(self): return u'%s %s' % (self.text, self.user.username) @property",
"% self.user.username class TrackableURL(models.Model): url = models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class",
"cordova = models.CharField(null=True, blank=True, max_length=400) platform = models.CharField(null=True, blank=True, max_length=400) version = models.CharField(null=True,",
"\"\"\" user = models.OneToOneField(User, verbose_name=\"django authentication user\", related_name='user_profile') newsletter = models.NullBooleanField(null=False, blank=False) research",
"= 3 OPEN_SUNDAY = 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES =",
"= models.TextField() user = models.ForeignKey(User, verbose_name=\"django authentication user\", related_name='notes') house = models.ForeignKey(House, related_name='note')",
"description = models.TextField(null=True) short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category",
"= 4 TYPE_TERRACE = 3 TYPE_SEMI = 2 TYPE_CHOICES = ((TYPE_MULTI_OCCUPANT, \"Multi Occupant\"),",
"models.BigIntegerField(null=True, blank=True) class Meta: ordering = ('created',) unique_together = ('user', 'house') def __unicode__(self):",
"= models.BigIntegerField(unique=True) previous_message = models.ForeignKey(Message) class LoggerMessage(models.Model): message = models.TextField() created = models.DateTimeField(auto_now_add=True)",
"Meta: ordering = ('created',) # unique_together = ('user', 'text', 'timestamp') def __unicode__(self): return",
"= models.URLField(max_length=255, unique=True) def __unicode__(self): return self.url class RelatedTrackableURL(TrackableURL): content_type = models.ForeignKey(ContentType) object_id",
"return u'%s' % (self.house.address,) class App(models.Model): model_version = models.CharField(max_length=8, unique=True) openday = models.DateField(default=datetime.date(day=26,",
"\"New\"), (AGE_GEORGIAN, \"Georgian\"), (AGE_20s, \"1920s\"), (AGE_60s, \"1960s\")) age = models.IntegerField(max_length=1, choices=AGE_CHOICES, null=True) TYPE_MULTI_OCCUPANT",
"short = models.CharField(max_length=80, null=True) color = models.CharField(max_length=7, null=True, blank=True) category = models.ForeignKey(MeasureCategory, related_name='measures')",
"comments = models.CharField(max_length=1024, null=True, blank=True) OPEN_SATURDAY_AND_SUNDAY = 3 OPEN_SUNDAY = 2 OPEN_SATURDAY =",
"related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) adults =",
"null=True) image = models.TextField() report_text = models.TextField(null=True, blank=True) # urls = GenericRelation(RelatedTrackableURL, null=True,",
"verbose_name=\"home owner profile\", related_name='house', null=True) address = models.CharField(max_length=1024) latitude = models.FloatField(null=True) longitude =",
"ordering = ('created',) unique_together = ('user', 'house') def __unicode__(self): return u'%s %s' %",
"= 2 OPEN_SATURDAY = 1 OPEN_CLOSED = 0 OPEN_CHOICES = ( (OPEN_CLOSED, 'Closed'),"
] |
[
"1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False)",
"= request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df",
"optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class + 1",
"1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0:",
"breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\",",
"import pandas as pd from flask import request, jsonify from pandas.io.json import json_normalize",
"\"Dressing\", 23: \"Go to the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd",
"\"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map",
"y_class = y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd",
"\"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17:",
"keras import pandas as pd from flask import request, jsonify from pandas.io.json import",
"actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is predicted to be",
"83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999,",
"@app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request body contains JSON if request.is_json:",
"y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\", 1: \"Act01\", 2:",
"print(prediction_result) # Return a string along with an HTTP status code return prediction_result,",
"app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the",
"y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps",
"# activity_map = {0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4:",
"\"Act24\"} activity_map = {0: \"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3:",
"at the table\", 22: \"Dressing\", 23: \"Go to the bed\", 24: \"Wake up\"}",
"int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted correctly! \" else: prediction_result",
"Parse the JSON into a Python dictionary req = request.get_json() sample_df = json_normalize(req)",
"flask from tensorflow import keras import pandas as pd from flask import request,",
"a Python dictionary req = request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df",
"into the washing machine\", 21: \"Work at the table\", 22: \"Dressing\", 23: \"Go",
"request.is_json: # Parse the JSON into a Python dictionary req = request.get_json() sample_df",
"snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play a videogame\", 12:",
"2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8:",
"= {0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5:",
"\"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat",
"the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put",
"({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted",
"= y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is predicted to be the",
"y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map",
"9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15:",
"\"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\", 1: \"Take medication\", 2: \"Prepare",
"Python dictionary req = request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df =",
"from flask import request, jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"]",
"sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped =",
"epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer,",
"SmartLab\", 11: \"Play a videogame\", 12: \"Relax on the sofa\", 13: \"Leave the",
"from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def",
"truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result",
"\"The new data point is predicted to be the activity {} ({}). The",
"13: \"Leave the SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put waste in",
"system predicted correctly! \" else: prediction_result += \"The system predicted wrong! \" print(prediction_result)",
"the activity {} ({}). The ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0],",
"if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted correctly! \" else: prediction_result +=",
"#sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:,",
"JSON into a Python dictionary req = request.get_json() sample_df = json_normalize(req) timesteps =",
"teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\", 20: \"Put washin into the",
"import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): #",
"-1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer =",
"\"The system predicted correctly! \" else: prediction_result += \"The system predicted wrong! \"",
"\"Eat a snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play a",
"activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result +=",
"prediction_result = \"The new data point is predicted to be the activity {}",
"\"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\",",
"ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])):",
"y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"])",
"activity_map = {0: \"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare",
"2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\",",
"code return prediction_result, 200 else: # The request body wasn't JSON so return",
"json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test",
"return prediction_result, 200 else: # The request body wasn't JSON so return a",
"return a 400 HTTP status code return \"Request was not JSON\", 400 app.run()",
"actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted correctly! \" else:",
"True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request body contains JSON if",
"\"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6:",
"+= \"The system predicted wrong! \" print(prediction_result) # Return a string along with",
"request, jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction',",
"{} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system",
"22: \"Dressing\", 23: \"Go to the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map)",
"def precict(): # Validate the request body contains JSON if request.is_json: # Parse",
"y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point",
"\"Relax on the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in the SmartLab\",",
"= pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\",",
"== int(y_test[0])): prediction_result += \"The system predicted correctly! \" else: prediction_result += \"The",
"= json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test,",
"= 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9,",
"timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test =",
"dishes\", 20: \"Put washin into the washing machine\", 21: \"Work at the table\",",
"washing machine\", 21: \"Work at the table\", 22: \"Dressing\", 23: \"Go to the",
"8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\",",
"the table\", 22: \"Dressing\", 23: \"Go to the bed\", 24: \"Wake up\"} predicted_class",
"\" print(prediction_result) # Return a string along with an HTTP status code return",
"up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The",
"if request.is_json: # Parse the JSON into a Python dictionary req = request.get_json()",
"get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class",
"body contains JSON if request.is_json: # Parse the JSON into a Python dictionary",
"toilet\", 19: \"Wash dishes\", 20: \"Put washin into the washing machine\", 21: \"Work",
"a videogame\", 12: \"Relax on the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit",
"HTTP status code return prediction_result, 200 else: # The request body wasn't JSON",
"\"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16:",
"\"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\", 20: \"Put washin into",
"+= \"The system predicted correctly! \" else: prediction_result += \"The system predicted wrong!",
"the JSON into a Python dictionary req = request.get_json() sample_df = json_normalize(req) timesteps",
"15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\",",
"the SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put waste in the bin\",",
"4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\",",
"the SmartLab\", 11: \"Play a videogame\", 12: \"Relax on the sofa\", 13: \"Leave",
"\"Wash dishes\", 20: \"Put washin into the washing machine\", 21: \"Work at the",
"x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model",
"be the activity {} ({}). The ground truth activity is {} ({}). \".format(predicted_class[0],",
"\"Go to the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float)",
"new data point is predicted to be the activity {} ({}). The ground",
"y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no",
"with an HTTP status code return prediction_result, 200 else: # The request body",
"= y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd =",
"videogame\", 12: \"Relax on the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in",
"\".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted correctly!",
"= flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request",
"pandas as pd from flask import request, jsonify from pandas.io.json import json_normalize app",
"int(y_test[0])): prediction_result += \"The system predicted correctly! \" else: prediction_result += \"The system",
"model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred",
"6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\",",
"12: \"Relax on the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in the",
"6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\", 10: \"Enter",
"predicted wrong! \" print(prediction_result) # Return a string along with an HTTP status",
"{0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\",",
"\"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\",",
"in the bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use the toilet\",",
"# The request body wasn't JSON so return a 400 HTTP status code",
"system predicted wrong! \" print(prediction_result) # Return a string along with an HTTP",
"({}). The ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0]",
"on the sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in the SmartLab\", 15:",
"3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8:",
"point is predicted to be the activity {} ({}). The ground truth activity",
"model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"])",
"22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\", 1:",
"pd from flask import request, jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__)",
"1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5:",
"18: \"Use the toilet\", 19: \"Wash dishes\", 20: \"Put washin into the washing",
"the SmartLab\", 15: \"Put waste in the bin\", 16: \"Wash hands\", 17: \"Brush",
"else: # The request body wasn't JSON so return a 400 HTTP status",
"a string along with an HTTP status code return prediction_result, 200 else: #",
"= y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is predicted",
"contains JSON if request.is_json: # Parse the JSON into a Python dictionary req",
"sample_df = json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float)",
"model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class",
"beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model",
"keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right",
"req = request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1)",
"\"Put washin into the washing machine\", 21: \"Work at the table\", 22: \"Dressing\",",
"\"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9:",
"table\", 22: \"Dressing\", 23: \"Go to the bed\", 24: \"Wake up\"} predicted_class =",
"y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is",
"{} ({}). The ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0]))",
"from tensorflow import keras import pandas as pd from flask import request, jsonify",
"status code return prediction_result, 200 else: # The request body wasn't JSON so",
":-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features)",
"= keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get",
"\"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\",",
"into a Python dictionary req = request.get_json() sample_df = json_normalize(req) timesteps = 40",
"jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST'])",
"17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", #",
"\"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play a videogame\", 12: \"Relax on",
"= True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request body contains JSON",
"9: \"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play a videogame\", 12: \"Relax",
"the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class =",
"\"The system predicted wrong! \" print(prediction_result) # Return a string along with an",
"# todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class =",
"\"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11:",
"# 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\",",
"= 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:,",
"16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22:",
"keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped)",
"3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", #",
"= {0: \"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\",",
"14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\",",
"18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\",",
"json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate",
"The ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] ==",
"\"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21:",
"to be the activity {} ({}). The ground truth activity is {} ({}).",
"bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash",
"schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])",
"wrong! \" print(prediction_result) # Return a string along with an HTTP status code",
"200 else: # The request body wasn't JSON so return a 400 HTTP",
"lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a",
"40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1],",
"5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\",",
"24: \"Act24\"} activity_map = {0: \"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\",",
"7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\",",
"import flask from tensorflow import keras import pandas as pd from flask import",
"methods=['POST']) def precict(): # Validate the request body contains JSON if request.is_json: #",
"precict(): # Validate the request body contains JSON if request.is_json: # Parse the",
"\"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare",
"data point is predicted to be the activity {} ({}). The ground truth",
"is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The",
"predicted to be the activity {} ({}). The ground truth activity is {}",
"19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"}",
"import request, jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True",
"\"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10:",
"= model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class,",
"10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", #",
"10: \"Enter the SmartLab\", 11: \"Play a videogame\", 12: \"Relax on the sofa\",",
"\"Put waste in the bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use",
"compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class",
"body wasn't JSON so return a 400 HTTP status code return \"Request was",
"sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features",
"request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df =",
"predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new",
"flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request body",
"\"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18:",
"Return a string along with an HTTP status code return prediction_result, 200 else:",
"hands\", 17: \"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\", 20: \"Put",
"23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\", 1: \"Take medication\", 2:",
"dictionary req = request.get_json() sample_df = json_normalize(req) timesteps = 40 #sample_df = sample_df.drop([\"TIMESTAMP\"],",
"activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\",",
"\"Visit in the SmartLab\", 15: \"Put waste in the bin\", 16: \"Wash hands\",",
"flask import request, jsonify from pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] =",
"12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\",",
"19: \"Wash dishes\", 20: \"Put washin into the washing machine\", 21: \"Work at",
"y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is predicted to be the activity",
"\"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\", 1: \"Take",
"to the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class",
"metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd",
"+ 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map =",
"string along with an HTTP status code return prediction_result, 200 else: # The",
"todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1)",
"wasn't JSON so return a 400 HTTP status code return \"Request was not",
"n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001,",
"activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\",",
"a snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play a videogame\",",
"JSON if request.is_json: # Parse the JSON into a Python dictionary req =",
"SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put waste in the bin\", 16:",
"\"Use the toilet\", 19: \"Wash dishes\", 20: \"Put washin into the washing machine\",",
"sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer",
"the toilet\", 19: \"Wash dishes\", 20: \"Put washin into the washing machine\", 21:",
"as pd from flask import request, jsonify from pandas.io.json import json_normalize app =",
"1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7:",
"sofa\", 13: \"Leave the SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put waste",
"else: prediction_result += \"The system predicted wrong! \" print(prediction_result) # Return a string",
"\"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20:",
"y_class[0], actual_class[0], int(y_test[0])) if(y_class[0] == int(y_test[0])): prediction_result += \"The system predicted correctly! \"",
"\"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24:",
"is predicted to be the activity {} ({}). The ground truth activity is",
"sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83",
"= keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred =",
"14: \"Visit in the SmartLab\", 15: \"Put waste in the bin\", 16: \"Wash",
"columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\", 1: \"Act01\",",
"TV\", 10: \"Enter the SmartLab\", 11: \"Play a videogame\", 12: \"Relax on the",
"11: \"Play a videogame\", 12: \"Relax on the sofa\", 13: \"Leave the SmartLab\",",
"\"Work at the table\", 22: \"Dressing\", 23: \"Go to the bed\", 24: \"Wake",
"\"Enter the SmartLab\", 11: \"Play a videogame\", 12: \"Relax on the sofa\", 13:",
"\"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\", 10: \"Enter the",
"\"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\",",
"correctly! \" else: prediction_result += \"The system predicted wrong! \" print(prediction_result) # Return",
"20: \"Put washin into the washing machine\", 21: \"Work at the table\", 22:",
"JSON so return a 400 HTTP status code return \"Request was not JSON\",",
"\"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12:",
"predicted correctly! \" else: prediction_result += \"The system predicted wrong! \" print(prediction_result) #",
"sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1,",
"\"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23:",
"model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class +",
"request body wasn't JSON so return a 400 HTTP status code return \"Request",
"activity {} ({}). The ground truth activity is {} ({}). \".format(predicted_class[0], y_class[0], actual_class[0],",
"y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd =",
"15: \"Put waste in the bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18:",
"\"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7:",
"\" else: prediction_result += \"The system predicted wrong! \" print(prediction_result) # Return a",
"prediction_result += \"The system predicted correctly! \" else: prediction_result += \"The system predicted",
"pandas.io.json import json_normalize app = flask.Flask(__name__) app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict():",
"pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\", 1:",
"{0: \"no activity\", 1: \"Take medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4:",
"11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\",",
"= y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data",
"24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result",
"tensorflow import keras import pandas as pd from flask import request, jsonify from",
"\"Act03\", 4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9:",
"\"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map = {0:",
"bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map)",
"optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo:",
"pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3:",
"medication\", 2: \"Prepare breakfast\", 3: \"Prepare lunch\", 4: \"Prepare dinner\", 5: \"Breakfast\", 6:",
"\"Leave the SmartLab\", 14: \"Visit in the SmartLab\", 15: \"Put waste in the",
"17: \"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\", 20: \"Put washin",
"prediction_result, 200 else: # The request body wasn't JSON so return a 400",
"13: \"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\",",
"timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model =",
"5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\",",
"The request body wasn't JSON so return a 400 HTTP status code return",
"7: \"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\",",
"the washing machine\", 21: \"Work at the table\", 22: \"Dressing\", 23: \"Go to",
"Validate the request body contains JSON if request.is_json: # Parse the JSON into",
"so return a 400 HTTP status code return \"Request was not JSON\", 400",
"= y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(), columns=[\"class\"]) #",
"\"Wash hands\", 17: \"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\", 20:",
"waste in the bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use the",
"\"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\", 10:",
"16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use the toilet\", 19: \"Wash dishes\",",
"\"Act07\", 8: \"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13:",
"\"Act08\", # 9: \"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14:",
"21: \"Work at the table\", 22: \"Dressing\", 23: \"Go to the bed\", 24:",
"\"Play a videogame\", 12: \"Relax on the sofa\", 13: \"Leave the SmartLab\", 14:",
"washin into the washing machine\", 21: \"Work at the table\", 22: \"Dressing\", 23:",
"\"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\",",
"beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) # todo: get right model model.compile(loss='categorical_crossentropy',",
"y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result = \"The new data point is predicted to",
"columns=[\"class\"]) # activity_map = {0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\",",
"\"Act13\", 14: \"Act14\", 15: \"Act15\", # 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19:",
"\"Act09\", 10: \"Act10\", 11: \"Act11\", 12: \"Act12\", 13: \"Act13\", 14: \"Act14\", 15: \"Act15\",",
"x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0],",
"# 23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no activity\", 1: \"Take medication\",",
"dinner\", 5: \"Breakfast\", 6: \"Lunch\", 7: \"Dinner\", 8: \"Eat a snack\", 9: \"Watch",
"in the SmartLab\", 15: \"Put waste in the bin\", 16: \"Wash hands\", 17:",
"app.config[\"DEBUG\"] = True @app.route('/api/prediction', methods=['POST']) def precict(): # Validate the request body contains",
"= sample_df.drop([\"TIMESTAMP\"], axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1]",
"n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5', compile=False) #",
"axis=1) sample_df = sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features =",
"activity_map = {0: \"no activity\", 1: \"Act01\", 2: \"Act02\", 3: \"Act03\", 4: \"Act04\",",
"8: \"Eat a snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\", 11: \"Play",
"= pd.DataFrame(y_test.tolist(), columns=[\"class\"]) # activity_map = {0: \"no activity\", 1: \"Act01\", 2: \"Act02\",",
"20: \"Act20\", 21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map =",
"y_pred.argmax(axis=-1) y_class = y_class + 1 y_pred_pd = pd.DataFrame(y_class, columns=[\"class\"]) y_test_pd = pd.DataFrame(y_test.tolist(),",
"\"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd = y_test_pd.astype(float) actual_class = y_test_pd[\"class\"].map(activity_map) prediction_result =",
"= x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004)",
"= sample_df.astype(float) x_test, y_test = sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped",
"# 16: \"Act16\", 17: \"Act17\", 18: \"Act18\", 19: \"Act19\", 20: \"Act20\", 21: \"Act21\",",
"an HTTP status code return prediction_result, 200 else: # The request body wasn't",
"# Parse the JSON into a Python dictionary req = request.get_json() sample_df =",
"4: \"Act04\", 5: \"Act05\", 6: \"Act06\", 7: \"Act07\", 8: \"Act08\", # 9: \"Act09\",",
"request body contains JSON if request.is_json: # Parse the JSON into a Python",
"the bin\", 16: \"Wash hands\", 17: \"Brush teeth\", 18: \"Use the toilet\", 19:",
"# Return a string along with an HTTP status code return prediction_result, 200",
"the request body contains JSON if request.is_json: # Parse the JSON into a",
"+ 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, schedule_decay=0.004) model = keras.models.load_model('models/CNN-1.h5',",
"along with an HTTP status code return prediction_result, 200 else: # The request",
"= \"The new data point is predicted to be the activity {} ({}).",
"21: \"Act21\", 22: \"Act22\", # 23: \"Act23\", 24: \"Act24\"} activity_map = {0: \"no",
"x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps + 1, n_features) optimizer = keras.optimizers.Nadam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,",
"23: \"Go to the bed\", 24: \"Wake up\"} predicted_class = y_pred_pd[\"class\"].map(activity_map) y_test_pd =",
"machine\", 21: \"Work at the table\", 22: \"Dressing\", 23: \"Go to the bed\",",
"\"Dinner\", 8: \"Eat a snack\", 9: \"Watch TV\", 10: \"Enter the SmartLab\", 11:",
"# Validate the request body contains JSON if request.is_json: # Parse the JSON",
"import keras import pandas as pd from flask import request, jsonify from pandas.io.json",
"right model model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc']) y_pred = model.predict(x_test_reshaped) y_class = y_pred.argmax(axis=-1) y_class =",
"prediction_result += \"The system predicted wrong! \" print(prediction_result) # Return a string along",
"SmartLab\", 15: \"Put waste in the bin\", 16: \"Wash hands\", 17: \"Brush teeth\",",
"= sample_df.iloc[:, :-1], sample_df.iloc[:, -1] n_features = 83 x_test_reshaped = x_test.values.reshape(x_test.shape[0], timesteps +"
] |
[
"1 if seen == ln: result.append(l) if r-l+1 == ln: char = word[l]",
"not word or not substr: return [] l = 0 r = -1",
"+= 1 char = word[r] if char in counts: counts[char] += 1 if",
"< len(word)-1: r += 1 char = word[r] if char in counts: counts[char]",
"word[r] if char in counts: counts[char] += 1 if counts[char] <= 0: seen",
"char = word[r] if char in counts: counts[char] += 1 if counts[char] <=",
"l = 0 r = -1 seen = 0 ln = len(substr) counts",
"= 0 ln = len(substr) counts = Counter(substr) counts = {char: -counts[char] for",
"+= 1 if char in counts: counts[char] -= 1 if counts[char] < 0:",
"or not substr: return [] l = 0 r = -1 seen =",
"ln = len(substr) counts = Counter(substr) counts = {char: -counts[char] for char in",
"l += 1 if char in counts: counts[char] -= 1 if counts[char] <",
"for char in substr} result = [] while r < len(word)-1: r +=",
"import Counter class Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time |",
"word: str, substr: str): \"\"\"O(n) time | O(1) space\"\"\" if not word or",
"result = [] while r < len(word)-1: r += 1 char = word[r]",
"counts: counts[char] += 1 if counts[char] <= 0: seen += 1 if seen",
"substr} result = [] while r < len(word)-1: r += 1 char =",
"ln: char = word[l] l += 1 if char in counts: counts[char] -=",
"1 char = word[r] if char in counts: counts[char] += 1 if counts[char]",
"if counts[char] <= 0: seen += 1 if seen == ln: result.append(l) if",
"= Counter(substr) counts = {char: -counts[char] for char in substr} result = []",
"-counts[char] for char in substr} result = [] while r < len(word)-1: r",
"class Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time | O(1) space\"\"\"",
"= {char: -counts[char] for char in substr} result = [] while r <",
"= 0 r = -1 seen = 0 ln = len(substr) counts =",
"if r-l+1 == ln: char = word[l] l += 1 if char in",
"{char: -counts[char] for char in substr} result = [] while r < len(word)-1:",
"<= 0: seen += 1 if seen == ln: result.append(l) if r-l+1 ==",
"in substr} result = [] while r < len(word)-1: r += 1 char",
"substr: str): \"\"\"O(n) time | O(1) space\"\"\" if not word or not substr:",
"1 if counts[char] <= 0: seen += 1 if seen == ln: result.append(l)",
"len(word)-1: r += 1 char = word[r] if char in counts: counts[char] +=",
"counts[char] <= 0: seen += 1 if seen == ln: result.append(l) if r-l+1",
"+= 1 if seen == ln: result.append(l) if r-l+1 == ln: char =",
"\"\"\"O(n) time | O(1) space\"\"\" if not word or not substr: return []",
"= [] while r < len(word)-1: r += 1 char = word[r] if",
"char in counts: counts[char] -= 1 if counts[char] < 0: seen -= 1",
"= len(substr) counts = Counter(substr) counts = {char: -counts[char] for char in substr}",
"r < len(word)-1: r += 1 char = word[r] if char in counts:",
"not substr: return [] l = 0 r = -1 seen = 0",
"counts = Counter(substr) counts = {char: -counts[char] for char in substr} result =",
"return [] l = 0 r = -1 seen = 0 ln =",
"char = word[l] l += 1 if char in counts: counts[char] -= 1",
"if seen == ln: result.append(l) if r-l+1 == ln: char = word[l] l",
"Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time | O(1) space\"\"\" if",
"r += 1 char = word[r] if char in counts: counts[char] += 1",
"ln: result.append(l) if r-l+1 == ln: char = word[l] l += 1 if",
"= word[l] l += 1 if char in counts: counts[char] -= 1 if",
"0: seen += 1 if seen == ln: result.append(l) if r-l+1 == ln:",
"word[l] l += 1 if char in counts: counts[char] -= 1 if counts[char]",
"from collections import Counter class Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n)",
"while r < len(word)-1: r += 1 char = word[r] if char in",
"O(1) space\"\"\" if not word or not substr: return [] l = 0",
"= word[r] if char in counts: counts[char] += 1 if counts[char] <= 0:",
"+= 1 if counts[char] <= 0: seen += 1 if seen == ln:",
"char in counts: counts[char] += 1 if counts[char] <= 0: seen += 1",
"if char in counts: counts[char] -= 1 if counts[char] < 0: seen -=",
"Counter(substr) counts = {char: -counts[char] for char in substr} result = [] while",
"time | O(1) space\"\"\" if not word or not substr: return [] l",
"len(substr) counts = Counter(substr) counts = {char: -counts[char] for char in substr} result",
"str, substr: str): \"\"\"O(n) time | O(1) space\"\"\" if not word or not",
"= -1 seen = 0 ln = len(substr) counts = Counter(substr) counts =",
"str): \"\"\"O(n) time | O(1) space\"\"\" if not word or not substr: return",
"findAnagrams(self, word: str, substr: str): \"\"\"O(n) time | O(1) space\"\"\" if not word",
"counts = {char: -counts[char] for char in substr} result = [] while r",
"seen = 0 ln = len(substr) counts = Counter(substr) counts = {char: -counts[char]",
"substr: return [] l = 0 r = -1 seen = 0 ln",
"seen == ln: result.append(l) if r-l+1 == ln: char = word[l] l +=",
"seen += 1 if seen == ln: result.append(l) if r-l+1 == ln: char",
"-1 seen = 0 ln = len(substr) counts = Counter(substr) counts = {char:",
"[] l = 0 r = -1 seen = 0 ln = len(substr)",
"Counter class Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time | O(1)",
"in counts: counts[char] += 1 if counts[char] <= 0: seen += 1 if",
"word or not substr: return [] l = 0 r = -1 seen",
"def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time | O(1) space\"\"\" if not",
"char in substr} result = [] while r < len(word)-1: r += 1",
"r = -1 seen = 0 ln = len(substr) counts = Counter(substr) counts",
"if char in counts: counts[char] += 1 if counts[char] <= 0: seen +=",
"== ln: result.append(l) if r-l+1 == ln: char = word[l] l += 1",
"== ln: char = word[l] l += 1 if char in counts: counts[char]",
"space\"\"\" if not word or not substr: return [] l = 0 r",
"| O(1) space\"\"\" if not word or not substr: return [] l =",
"0 ln = len(substr) counts = Counter(substr) counts = {char: -counts[char] for char",
"counts[char] += 1 if counts[char] <= 0: seen += 1 if seen ==",
"r-l+1 == ln: char = word[l] l += 1 if char in counts:",
"[] while r < len(word)-1: r += 1 char = word[r] if char",
"if not word or not substr: return [] l = 0 r =",
"counts: counts[char] -= 1 if counts[char] < 0: seen -= 1 return result",
"1 if char in counts: counts[char] -= 1 if counts[char] < 0: seen",
"in counts: counts[char] -= 1 if counts[char] < 0: seen -= 1 return",
"result.append(l) if r-l+1 == ln: char = word[l] l += 1 if char",
"0 r = -1 seen = 0 ln = len(substr) counts = Counter(substr)",
"collections import Counter class Solution: def findAnagrams(self, word: str, substr: str): \"\"\"O(n) time"
] |
[
"with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError: env = {}",
"local enviroment.\"\"\" import yaml try: with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader)",
"up local enviroment.\"\"\" import yaml try: with open('config.yml') as file: env = yaml.load(file,",
"yaml try: with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError: env",
"try: with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError: env =",
"enviroment.\"\"\" import yaml try: with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader) except",
"\"\"\"Set up local enviroment.\"\"\" import yaml try: with open('config.yml') as file: env =",
"<reponame>LeptoSpira/nautilus-chambers \"\"\"Set up local enviroment.\"\"\" import yaml try: with open('config.yml') as file: env",
"import yaml try: with open('config.yml') as file: env = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError:"
] |
[
"return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = []",
"ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup",
"is_network_error: return result = check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if",
"_sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [ result.get_kv()",
"= len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1])",
"并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error = False for cls in",
"Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser",
"is_network_error = False for cls in check_list: if not check_one(cls): req_failed_flag += 1",
"- checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def",
"single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error = False",
"= {k: (v1, v2) for k, v1, v2 in results if k !=",
"parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\") args = parser.parse_args() if args.force:",
"except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as",
"table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table)",
"if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor:",
"print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s",
"* fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_]",
"session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def",
"cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except",
"start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" % start_time)",
"False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2)",
"is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result =",
"as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before",
"# 可以的话, 使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen =",
"可以的话, 使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0])",
"= {x.__name__ for x in CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_",
"try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError,",
"for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen),",
"after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" %",
"( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen,",
"*kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to",
"% cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\")",
"CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check()",
"in session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids = saved_ids -",
"for k, v1, v2 in results if k != \"GoogleClangPrebuilt\"} try: # 可以的话,",
"req_failed_flag = 0 check_failed_list = [] is_network_error = False for cls in check_list:",
"from concurrent.futures import ThreadPoolExecutor from requests import exceptions from config import ( ENABLE_SENDMESSAGE,",
"Console from rich.table import Table console = Console() table = Table(show_header=True, header_style=\"bold magenta\")",
"# 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic =",
"for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], #",
"in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\",",
"lv_maxlen)) else: del rich from rich.console import Console from rich.table import Table console",
"except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines())",
"saved data as json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE = True",
"= [] is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return",
"except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None: time_num = time.time()",
"from check_list import CHECK_LIST from database import create_dbsession, Saved from logger import write_log_info,",
"exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error:",
"% ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" *",
"failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\"",
"running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname)",
"True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error",
")) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else:",
"key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x",
"cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str) cls_obj = cls()",
"check_one(cls) PAGE_CACHE.clear() print(\" - The next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL))",
"print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del",
"cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", )",
"for cls in check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag",
"check_list = [cls for cls in CHECK_LIST if not cls._skip] while True: start_time",
"rich from rich.console import Console from rich.table import Table console = Console() table",
"args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data() elif args.json: print(get_saved_json()) else:",
"def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def",
"fn_maxlen, \"-\" * lv_maxlen)) else: del rich from rich.console import Console from rich.table",
"(cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" %",
"\"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" *",
"def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\"",
"= _get_time_str() print(\" - \" + start_time) print(\" - Start...\") write_log_info(\"=\" * 64)",
"write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else:",
"\"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" %",
"console = Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest",
"= False for cls in check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls)",
"if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check()",
"req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True break else:",
"_THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM)",
"saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__ for x in",
"to database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message",
"after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database()",
"lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\"",
"x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\"",
"cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check will start at",
"result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession()",
"import traceback import sys import threading from concurrent.futures import ThreadPoolExecutor from requests import",
"fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) ))",
"ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from check_list import",
"id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\",",
"update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc()",
"lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\"",
"traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or",
"(\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del rich from",
"check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved",
"Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\"",
"custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running",
"+ start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" %",
"loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查",
"drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if",
"= threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session:",
"\"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\"",
"Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k, v1, v2 in results if",
"__name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send",
"parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send message to Telegram\",",
"Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值, #",
"def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error =",
"检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\",",
"Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen))",
"id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv",
"= Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\")",
"else single_thread_check check_list = [cls for cls in CHECK_LIST if not cls._skip] while",
"多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error",
"% cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\"",
"x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" *",
"( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from check_list",
"json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID !=",
"cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func",
"% (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\"",
"import sys import threading from concurrent.futures import ThreadPoolExecutor from requests import exceptions from",
"\"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len))",
"== id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user():",
"if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with",
"disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls = {cls_.__name__: cls_ for cls_",
"while True: start_time = _get_time_str() print(\" - \" + start_time) print(\" - Start...\")",
"import create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE =",
"fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" *",
"time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str =",
"as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for",
"% cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname)",
"if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls in CHECK_LIST if not",
"= [] is_network_error = False for cls in check_list: if not check_one(cls): req_failed_flag",
"not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True",
"before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func =",
"cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname,",
"id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del rich from rich.console import",
"parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\",",
"= {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not",
"{cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found",
"def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION)",
"+= 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True break else: req_failed_flag",
"is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again",
"# 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def _check_one(cls_): nonlocal check_failed_list,",
"\"--json\", help=\"Show saved data as json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE",
"time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls",
"cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname) if",
"], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results",
"Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check",
"% start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error:",
"\"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv =",
"is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if",
"% traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if",
"level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\")",
"is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: #",
"FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check()",
"= False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\")",
"max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen,",
"by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if",
"check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls = {cls_.__name__: cls_ for",
"exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string",
"print(\" - The next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of",
"[] is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result",
"cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed!",
":return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids = {x.ID for x in",
"True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run",
"check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned",
"import CHECK_LIST from database import create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log",
"cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True def single_thread_check(check_list):",
"level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time)",
"with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1,",
"create_dbsession() as session: saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__",
"cls in check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag ==",
"wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\"",
"return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID",
"req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list",
"check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as",
"kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\"",
"\"-\" * lv_maxlen)) else: del rich from rich.console import Console from rich.table import",
"print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for",
"ArgumentParser import json import time import traceback import sys import threading from concurrent.futures",
"Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for",
"checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text):",
"running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\"",
"(exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s",
"help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\") args",
"result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False,",
"(\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen),",
"% cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True def",
"x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): #",
"% (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something",
"lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen),",
"% cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname,",
"check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with",
"in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen))",
"cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list =",
"= parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False if",
"'%s' from CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False",
"from rich.console import Console from rich.table import Table console = Console() table =",
"time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None: time_num =",
"= 0 check_failed_list = [] is_network_error = False for cls in check_list: if",
"check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check will start at %s\\n\" %",
"will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): #",
"check_init import PAGE_CACHE from check_list import CHECK_LIST from database import create_dbsession, Saved from",
"if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif",
"message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\",",
"return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls",
"cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\" %",
"{k: (v1, v2) for k, v1, v2 in results if k != \"GoogleClangPrebuilt\"}",
"in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\" %",
"create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False",
"message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\",",
"help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all",
"if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\",",
"\"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" *",
"def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [ result.get_kv() for",
"threading from concurrent.futures import ThreadPoolExecutor from requests import exceptions from config import (",
"True: start_time = _get_time_str() print(\" - \" + start_time) print(\" - Start...\") write_log_info(\"=\"",
"return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup()",
"print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when",
"_abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time):",
"exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check",
"check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [",
"len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for",
"\"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen,",
"check_failed_list = [] is_network_error = False for cls in check_list: if not check_one(cls):",
"_sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None:",
"or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed",
"MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from check_list import CHECK_LIST from database",
"if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database &",
"CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one())",
"as json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost:",
"print(\"- %s no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" %",
"traceback import sys import threading from concurrent.futures import ThreadPoolExecutor from requests import exceptions",
"% cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname,",
"not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常,",
"check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check",
"again for failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The",
"json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE",
"user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num",
"False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except",
"- \" + start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at",
"kv_dic = {k: (v1, v2) for k, v1, v2 in results if k",
"args = parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False",
"multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def _check_one(cls_): nonlocal",
"import Console from rich.table import Table console = Console() table = Table(show_header=True, header_style=\"bold",
"= max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()])",
"def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is",
"from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK =",
"time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls = {cls_.__name__:",
"= cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check",
"True break else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): #",
"print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" % start_time) #",
"table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\":",
"data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\") args = parser.parse_args()",
"Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" %",
"help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\",",
"print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" *",
"is_network_error = True break else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def",
"* lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % (",
"5: is_network_error = True break else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error",
"False for cls in check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if",
"fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in",
"item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as",
"import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x",
"print_and_log(\"Check again for failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" -",
"print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string)",
"if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname) if not LESS_LOG:",
"from rich.table import Table console = Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\",",
"level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for cls in",
"failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s",
"cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can",
"{%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list =",
"sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\"",
"error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname,",
"{x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids",
"* id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del rich from rich.console",
"level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError",
"= {x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST}",
"\", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for",
"json import time import traceback import sys import threading from concurrent.futures import ThreadPoolExecutor",
"results if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except ImportError:",
"check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids =",
"items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\")",
"drop_ids = saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit()",
"loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show",
"in check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5:",
"= kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" *",
"True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True)",
"= database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD",
"# ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results =",
"else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回",
"\" + start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\"",
"for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check will start",
"is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def",
"= ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send message to Telegram\", action=\"store_true\")",
"or FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try:",
"Table console = Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\")",
"使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for",
"Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\"",
"send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\")",
"with create_dbsession() as session: return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda",
"write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return",
"import ThreadPoolExecutor from requests import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD,",
"fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\"",
"concurrent.futures import ThreadPoolExecutor from requests import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL,",
"_THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as",
"并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error if",
"database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else",
"show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic",
"x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据",
"% cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except",
"parser.add_argument(\"--force\", help=\"Force save to database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do",
"!= \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as",
"failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check",
"lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen))",
"_get_time_str(time_num=None, offset=0): if time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset))",
"found '%s' from CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache =",
"FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\"",
"def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2) if",
"start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network",
"magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_])",
"config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE",
"return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by",
"cls._skip] while True: start_time = _get_time_str() print(\" - \" + start_time) print(\" -",
"print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed!",
"\"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids = {x.ID for",
"if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error =",
"save to database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send",
"v1, v2 in results if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import",
"if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\"",
"!= \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(),",
"* lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" %",
"for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\"",
"is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def",
"try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" %",
"is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK:",
"= time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str",
"# loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or",
"%s no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname)",
"以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved),",
"check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False",
"# 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error = False for",
"drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\")",
"import Table console = Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full",
"traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE:",
"== 5: is_network_error = True break else: req_failed_flag = 0 _sleep(2) return check_failed_list,",
"为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合",
"level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except",
"The next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL)",
"%s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if",
"Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection error.\" %",
"= traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something",
"write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表,",
"when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" %",
"write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup():",
"in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) ))",
"logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock()",
"sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def",
"print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE:",
"in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\")",
"def _get_time_str(time_num=None, offset=0): if time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\",",
"以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\")",
"time import traceback import sys import threading from concurrent.futures import ThreadPoolExecutor from requests",
"KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None: time_num = time.time() return",
"fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" %",
"key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data():",
"check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy",
"style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if",
"= 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list =",
"session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids = saved_ids - checklist_ids",
"session: saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__ for x",
"exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check",
"print_and_log(\"%s check failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s",
"# 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for cls in check_failed_list: check_one(cls)",
"try: # 可以的话, 使用rich库 import rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen",
"= session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k, v1, v2",
"被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids = {x.ID for x in session.query(Saved).all()}",
"% \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls",
"[ result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\"",
"_get_time_str() print(\" - \" + start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start",
"Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running",
"= saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return",
"0 check_failed_list = [] is_network_error = False for cls in check_list: if not",
"start_time = _get_time_str() print(\" - \" + start_time) print(\" - Start...\") write_log_info(\"=\" *",
"loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy",
"session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k,",
"encoding: utf-8 from argparse import ArgumentParser import json import time import traceback import",
"1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True break else: req_failed_flag =",
"break else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常,",
"FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check:",
"rich except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in",
"time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str):",
"cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout:",
"* fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen)",
"def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls = {cls_.__name__: cls_",
"check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else:",
"import threading from concurrent.futures import ThreadPoolExecutor from requests import exceptions from config import",
"time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False):",
"对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear()",
"not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\",",
"= True break else: req_failed_flag = 0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list):",
"requests import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG )",
"action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop",
"error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" %",
"for x in CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_ in drop_ids:",
"= traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated()",
"at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with",
"{x.__name__ for x in CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_ in",
"rich.console import Console from rich.table import Table console = Console() table = Table(show_header=True,",
"( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\"",
"#!/usr/bin/env python3 # encoding: utf-8 from argparse import ArgumentParser import json import time",
"ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data()",
"to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\",",
"ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s",
"* lv_maxlen)) else: del rich from rich.console import Console from rich.table import Table",
"loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls in",
"ThreadPoolExecutor from requests import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM,",
"from argparse import ArgumentParser import json import time import traceback import sys import",
"custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except",
"& send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\",",
"cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no",
"以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k:",
"# encoding: utf-8 from argparse import ArgumentParser import json import time import traceback",
"PAGE_CACHE from check_list import CHECK_LIST from database import create_dbsession, Saved from logger import",
"cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no update\" % cls_obj.fullname) if not",
"print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\"",
"if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True def single_thread_check(check_list): #",
"check_failed_list, is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2) if not result: with",
"except ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()])",
"traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s:",
"level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname,",
"%H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls, str): cls_str = cls cls =",
"disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" %",
"parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\")",
"create_dbsession() as session: return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda x:",
"ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from check_list import CHECK_LIST from",
"failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update:",
"def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids =",
"cls_str = cls cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not",
"CHECK_LIST from database import create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log #",
"_abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d",
"CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str)",
"start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据",
"cls in CHECK_LIST if not cls._skip] while True: start_time = _get_time_str() print(\" -",
"\"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\",",
"of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps(",
"<reponame>Pzqqt/Whyred_Rom_Update_Checker<gh_stars>10-100 #!/usr/bin/env python3 # encoding: utf-8 from argparse import ArgumentParser import json import",
"v2 in results if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich",
"\"\"\" with create_dbsession() as session: saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids",
"LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止",
"id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser = ArgumentParser()",
"executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids",
")) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for",
"cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError):",
"(cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong",
"k, v1, v2 in results if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库",
"\"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show",
"has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string =",
"%s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check",
"if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data() elif args.json: print(get_saved_json())",
"LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from check_list import CHECK_LIST",
"if time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls,",
"single_thread_check check_list = [cls for cls in CHECK_LIST if not cls._skip] while True:",
"req_failed_flag == 5: is_network_error = True break else: req_failed_flag = 0 _sleep(2) return",
"v2) for k, v1, v2 in results if k != \"GoogleClangPrebuilt\"} try: #",
"is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items:",
"Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"-",
"table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_",
"0 _sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = []",
"help=\"Force save to database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not",
"cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\")",
"(v1, v2) for k, v1, v2 in results if k != \"GoogleClangPrebuilt\"} try:",
"= False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data() elif",
"cls cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise",
"len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one,",
"for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found '%s' from",
"except exceptions.ReadTimeout: print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s",
"wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s",
"in CHECK_LIST if not cls._skip] while True: start_time = _get_time_str() print(\" - \"",
") def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME,",
"= False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with",
"LESS_LOG ) from check_init import PAGE_CACHE from check_list import CHECK_LIST from database import",
"= False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result = check_one(cls_)",
"results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k, v1,",
"del rich from rich.console import Console from rich.table import Table console = Console()",
"\".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls",
"data as json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE = True if",
"threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids",
"check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json():",
"None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def check_one(cls, disable_pagecache=False): if isinstance(cls,",
"= check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10:",
"in results if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except",
"loop_check(): write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" %",
"import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from",
"nonlocal check_failed_list, is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2) if not result:",
"# 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return:",
"% ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest Version\".ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen,",
"cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found '%s'",
"items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list",
"action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one",
"%s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n!",
"id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return",
"except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else:",
"import ArgumentParser import json import time import traceback import sys import threading from",
"if is_network_error: return result = check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_)",
"Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ ==",
"not found '%s' from CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache",
"create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2)",
"Saved from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK",
"isinstance(cls, str): cls_str = cls cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str)",
"% (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_ in",
"sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt:",
"kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen,",
"table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__",
"write_log_info(\"Run database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \",",
"import PAGE_CACHE from check_list import CHECK_LIST from database import create_dbsession, Saved from logger",
"write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log(",
"executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database cleanup before start\")",
"# 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error!",
"print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" %",
"for x in session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids =",
"for failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next",
"强制单线程检查 print_and_log(\"Check again for failed items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\"",
"64) write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list,",
"== \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send message",
"multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls in CHECK_LIST if",
"when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message() else: print(\"- %s no",
"# 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [ result.get_kv() for result in",
"send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\")",
"except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except:",
"except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError:",
"\"GoogleClangPrebuilt\" ], # ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session:",
"for cls in CHECK_LIST if not cls._skip] while True: start_time = _get_time_str() print(\"",
"write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error",
"saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids",
"print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_",
"id_ in sorted(kv_dic.keys()): fn, lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen)",
"_abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def",
"as session: return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME)",
"in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check will start at %s\\n\"",
"if not cls._skip] while True: start_time = _get_time_str() print(\" - \" + start_time)",
"check failed!\" % cls_obj.fullname, level=\"warning\") else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has",
"write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\"",
"console.print(table) if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database",
"PAGE_CACHE.clear() print(\" - The next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End",
"ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\",",
"to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\",",
"rich.table import Table console = Console() table = Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\")",
"parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically loop check",
"database cleanup before start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids))",
"all items\", action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\",",
"in CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID ==",
"if k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except ImportError: id_maxlen",
"offset=0): if time_num is None: time_num = time.time() return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_num+offset)) def",
"cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string)",
"error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname,",
"lv = kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\"",
"argparse import ArgumentParser import json import time import traceback import sys import threading",
"parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\",",
"with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check(): write_log_info(\"Run database",
"check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines())",
"action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE =",
"[] is_network_error = False for cls in check_list: if not check_one(cls): req_failed_flag +=",
"in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ], # ensure_ascii=False, )",
"from check_init import PAGE_CACHE from check_list import CHECK_LIST from database import create_dbsession, Saved",
"- The next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\")",
"header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()): table.add_row(id_,",
"checking at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error =",
"% _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as",
"failed! Connection error.\" % cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed!",
"print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except:",
"result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True",
"with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list,",
"with create_dbsession() as session: saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids =",
"* id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full",
"loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data() elif args.json: print(get_saved_json()) else: parser.print_usage()",
"database import create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE",
"print(\" - \" + start_time) print(\" - Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking",
"_check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error: return result = check_one(cls_) time.sleep(2) if not",
"table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save",
"help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved",
"write_log_info(\"%s no update\" % cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag",
"= True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check: check_one(args.check,",
"check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True break",
"Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in sorted(kv_dic.keys()):",
"= cls cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if not cls:",
"for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" %",
"action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\") args = parser.parse_args() if",
"10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return",
"checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids = saved_ids - checklist_ids for",
"id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\"",
"Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for cls",
"no update\" % cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag =",
"from requests import exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG",
"if isinstance(cls, str): cls_str = cls cls = {cls_.__name__: cls_ for cls_ in",
"import time import traceback import sys import threading from concurrent.futures import ThreadPoolExecutor from",
"update\" % cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0",
"id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen =",
"(\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()):",
"else: if cls_obj.is_updated() or FORCE_UPDATE: print_and_log( \"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]),",
"not cls._skip] while True: start_time = _get_time_str() print(\" - \" + start_time) print(\"",
"k != \"GoogleClangPrebuilt\"} try: # 可以的话, 使用rich库 import rich except ImportError: id_maxlen =",
"if req_failed_flag == 5: is_network_error = True break else: req_failed_flag = 0 _sleep(2)",
"if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check",
"Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k, v1, v2 in results",
"from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import",
"session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort",
"from CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False try:",
"result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if result.ID != \"GoogleClangPrebuilt\" ],",
"no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return",
"failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed! Proxy error.\"",
"try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0): if time_num is None: time_num",
"help=\"Show saved data as json\", action=\"store_true\") args = parser.parse_args() if args.force: FORCE_UPDATE =",
"Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str) cls_obj = cls() if disable_pagecache:",
"else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for cls in check_failed_list:",
"if not cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str) cls_obj",
"if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error",
"database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids = {x.ID",
"kv_dic[id_] print(\"|%s|%s|%s|\" % ( id_.ljust(id_maxlen), fn.ljust(fn_maxlen), lv.ljust(lv_maxlen) )) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen,",
"as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string =",
"cls_ in CHECK_LIST}.get(cls_str) if not cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\"",
"import json import time import traceback import sys import threading from concurrent.futures import",
"return result = check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list)",
"check_list: if not check_one(cls): req_failed_flag += 1 check_failed_list.append(cls) if req_failed_flag == 5: is_network_error",
"_get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session:",
"return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error =",
"session: return json.dumps( [ result.get_kv() for result in sorted(session.query(Saved), key=lambda x: x.FULL_NAME) if",
"% cls_obj.fullname) return True def single_thread_check(check_list): # 单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list",
"% (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % (",
"Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to Telegram\", action=\"store_true\") parser.add_argument(\"-a\", \"--auto\", help=\"Automatically",
"\"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen), \"Latest",
"utf-8 from argparse import ArgumentParser import json import time import traceback import sys",
"from database import create_dbsession, Saved from logger import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息",
"= loop_check_func(check_list) if is_network_error: print_and_log(\"Network or proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目,",
"* 64) write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值",
"get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession() as session: return json.dumps( [ result.get_kv() for result",
"% (\"-\" * id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del rich",
">= 10: with _THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list)",
"not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error =",
"sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force",
"traceback_string = traceback.format_exc() print(traceback_string) write_log_warning(*traceback_string.splitlines()) print_and_log(\"%s check failed!\" % cls_obj.fullname, level=\"warning\") else: if",
"= [cls for cls in CHECK_LIST if not cls._skip] while True: start_time =",
"id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) print(\"|%s|%s|%s|\" % ( \"ID\".ljust(id_maxlen), \"Full Name\".ljust(fn_maxlen),",
"for id_ in sorted(kv_dic.keys()): table.add_row(id_, *kv_dic[id_]) console.print(table) if __name__ == \"__main__\": parser =",
"else: del rich from rich.console import Console from rich.table import Table console =",
"def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error = False def _check_one(cls_):",
"False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession()",
"proxy error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\")",
"write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check",
"= True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error def loop_check():",
"sys import threading from concurrent.futures import ThreadPoolExecutor from requests import exceptions from config",
"print_and_log(\"%s check failed! Timeout.\" % cls_obj.fullname, level=\"warning\") except (exceptions.SSLError, exceptions.ProxyError): print_and_log(\"%s check failed!",
"import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init import PAGE_CACHE from",
"_sleep(2) return check_failed_list, is_network_error def multi_thread_check(check_list): # 多线程模式下累计检查失败10项则判定为网络异常, 并在之后往线程池提交的任务中不再进行检查操作而是直接返回 check_failed_list = [] is_network_error",
"session.query(Saved).with_entities(Saved.ID, Saved.FULL_NAME, Saved.LATEST_VERSION) kv_dic = {k: (v1, v2) for k, v1, v2 in",
"else: print(\"- %s no update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\"",
"import write_log_info, write_log_warning, print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def",
"x in session.query(Saved).all()} checklist_ids = {x.__name__ for x in CHECK_LIST} drop_ids = saved_ids",
"traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong",
"items\") for cls in check_failed_list: check_one(cls) PAGE_CACHE.clear() print(\" - The next check will",
"level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\")",
"%s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def get_saved_json(): # 以json格式返回已保存的数据 with create_dbsession()",
"ensure_ascii=False, ) def show_saved_data(): # 以MySQL命令行风格打印已保存的数据 with create_dbsession() as session: results = session.query(Saved).with_entities(Saved.ID,",
"max([len(x[0]) for x in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\"",
"error! Sleep...\", level=\"warning\") else: # 对于检查失败的项目, 强制单线程检查 print_and_log(\"Check again for failed items\") for",
"result = check_one(cls_) time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >=",
"将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉 :return: 被删除的项目名字的集合 \"\"\" with create_dbsession() as session: saved_ids = {x.ID for x",
"\"-\" * fn_maxlen, \"-\" * lv_maxlen)) else: del rich from rich.console import Console",
"\"__main__\": parser = ArgumentParser() parser.add_argument(\"--force\", help=\"Force save to database & send message to",
"check_list import CHECK_LIST from database import create_dbsession, Saved from logger import write_log_info, write_log_warning,",
"next check will start at %s\\n\" % _get_time_str(offset=LOOP_CHECK_INTERVAL)) write_log_info(\"End of check\") _sleep(LOOP_CHECK_INTERVAL) def",
"update\" % cls_obj.fullname) if not LESS_LOG: write_log_info(\"%s no update\" % cls_obj.fullname) return True",
"parser.parse_args() if args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto:",
"cls_obj = cls() if disable_pagecache: cls_obj.enable_pagecache = False try: cls_obj.do_check() except exceptions.ReadTimeout: print_and_log(\"%s",
"x in CHECK_LIST} drop_ids = saved_ids - checklist_ids for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID",
"check failed! Proxy error.\" % cls_obj.fullname, level=\"warning\") except exceptions.ConnectionError: print_and_log(\"%s check failed! Connection",
"one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data",
"with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK: is_network_error = True with",
"exceptions from config import ( ENABLE_SENDMESSAGE, LOOP_CHECK_INTERVAL, ENABLE_MULTI_THREAD, MAX_THREADS_NUM, LESS_LOG ) from check_init",
"error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error), level=\"warning\") except: traceback_string = traceback.format_exc()",
"raise Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str) cls_obj = cls() if",
"ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls in CHECK_LIST if not cls._skip]",
"drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1)",
"in kv_dic.values()]) lv_maxlen = max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" *",
"ImportError: id_maxlen = len(max(kv_dic.keys(), key=len)) fn_maxlen = max([len(x[0]) for x in kv_dic.values()]) lv_maxlen",
"saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\") args =",
"= max([len(x[1]) for x in kv_dic.values()]) print(\"+%s+%s+%s+\" % (\"-\" * id_maxlen, \"-\" *",
"check_failed_list.append(cls) if req_failed_flag == 5: is_network_error = True break else: req_failed_flag = 0",
"database & send message to Telegram\", action=\"store_true\") parser.add_argument(\"--dontpost\", help=\"Do not send message to",
") from check_init import PAGE_CACHE from check_list import CHECK_LIST from database import create_dbsession,",
"cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when",
"args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show:",
"not cls: raise Exception(\"Can not found '%s' from CHECK_LIST!\" % cls_str) cls_obj =",
"check_failed_list = [] is_network_error = False def _check_one(cls_): nonlocal check_failed_list, is_network_error if is_network_error:",
"action=\"store_true\") parser.add_argument(\"-c\", \"--check\", help=\"Check one item\") parser.add_argument(\"-s\", \"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\",",
") try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print(\"\\n%s\\n! Something wrong when running after_check!\"",
"* fn_maxlen, \"-\" * lv_maxlen)) else: del rich from rich.console import Console from",
"write_log_warning(*traceback_string.splitlines()) write_log_warning(\"%s: Something wrong when running after_check!\" % cls_obj.fullname) cls_obj.write_to_database() if ENABLE_SENDMESSAGE: cls_obj.send_message()",
"* id_maxlen, \"-\" * fn_maxlen, \"-\" * lv_maxlen)) for id_ in sorted(kv_dic.keys()): fn,",
"print_and_log # 为True时将强制将数据保存至数据库并发送消息 FORCE_UPDATE = False _THREADING_LOCK = threading.Lock() def database_cleanup(): \"\"\" 将数据库中存在于数据库但不存在于CHECK_LIST的项目删除掉",
"cls_obj.fullname, level=\"warning\") except exceptions.HTTPError as error: print_and_log(\"%s check failed! %s.\" % (cls_obj.fullname, error),",
"as session: saved_ids = {x.ID for x in session.query(Saved).all()} checklist_ids = {x.__name__ for",
"time.sleep(2) if not result: with _THREADING_LOCK: check_failed_list.append(cls_) if len(check_failed_list) >= 10: with _THREADING_LOCK:",
"= Table(show_header=True, header_style=\"bold magenta\") table.add_column(\"ID\", style=\"dim\") table.add_column(\"Full Name\") table.add_column(\"Latest Version\") for id_ in",
"at %s\" % start_time) # loop_check_func必须返回两个值, # 检查失败的项目的列表, 以及是否为网络错误或代理错误的Bool值 check_failed_list, is_network_error = loop_check_func(check_list)",
"args.force: FORCE_UPDATE = True if args.dontpost: ENABLE_SENDMESSAGE = False if args.auto: loop_check() elif",
"print_and_log(str(text), level=\"warning\", custom_prefix=\"-\") sys.exit(1) def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try:",
"= multi_thread_check if ENABLE_MULTI_THREAD else single_thread_check check_list = [cls for cls in CHECK_LIST",
"False if args.auto: loop_check() elif args.check: check_one(args.check, disable_pagecache=True) elif args.show: show_saved_data() elif args.json:",
"str): cls_str = cls cls = {cls_.__name__: cls_ for cls_ in CHECK_LIST}.get(cls_str) if",
"start\") drop_ids = database_cleanup() write_log_info(\"Abandoned items: {%s}\" % \", \".join(drop_ids)) loop_check_func = multi_thread_check",
"def _abort_by_user(): return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user()",
"return _abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None,",
"CHECK_LIST if not cls._skip] while True: start_time = _get_time_str() print(\" - \" +",
"_THREADING_LOCK: is_network_error = True with ThreadPoolExecutor(MAX_THREADS_NUM) as executor: executor.map(_check_one, check_list) return check_failed_list, is_network_error",
"[cls for cls in CHECK_LIST if not cls._skip] while True: start_time = _get_time_str()",
"_abort(\"Abort by user\") def _sleep(sleep_time): try: time.sleep(sleep_time) except KeyboardInterrupt: _abort_by_user() def _get_time_str(time_num=None, offset=0):",
"for id_ in drop_ids: session.delete(session.query(Saved).filter(Saved.ID == id_).one()) session.commit() return drop_ids def _abort(text): print_and_log(str(text),",
"\"%s has update: %s\" % (cls_obj.fullname, cls_obj.info_dic[\"LATEST_VERSION\"]), custom_prefix=\">\", ) try: cls_obj.after_check() except: traceback_string",
"单线程模式下连续检查失败5项则判定为网络异常, 并提前终止 req_failed_flag = 0 check_failed_list = [] is_network_error = False for cls",
"- Start...\") write_log_info(\"=\" * 64) write_log_info(\"Start checking at %s\" % start_time) # loop_check_func必须返回两个值,",
"python3 # encoding: utf-8 from argparse import ArgumentParser import json import time import",
"\"--show\", help=\"Show saved data\", action=\"store_true\") parser.add_argument(\"-j\", \"--json\", help=\"Show saved data as json\", action=\"store_true\")"
] |
[
"\"How To Relieve Stress\": [\"Here are some tips to get rid of stress:\\n",
"current temperature in {0} is {1}\".format(place, update) return weather_report responses = { \"Hey",
"return alarm def melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody",
"[\"Cricket\"], \"What Is The National Game Of Scotland\": [\"Golf\"], \"What Is The National",
"len(name)): if i + 3 <= len(name)-1 and name[i].lower == 'who' and name[i+1].lower",
"'20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] return",
"a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special",
"Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\":",
"\"Play Me A Song\": bot_message = melody() elif message == \"Weather\": bot_message =",
"= weather_manager() elif message == \"Wikipedia\": bot_message = scrap() elif message == \"Translate\":",
"== '*': return int(request_d[key - 1]) * int(request_d[key + 1]) if value ==",
"int(request_d[key - 1]) * int(request_d[key + 1]) if value == '/': return int(request_d[key",
"- 1]) * int(request_d[key + 1]) if value == '/': return int(request_d[key -",
"\" \"4) Be positive\"], \"How To Relieve Stress\": [\"Here are some tips to",
"\"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"],",
"playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import",
"Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\":",
"if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and",
"\"great day ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\",",
"[\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief",
"Iran\": [\"Wrestling\"], \"What Is The National Game Of Hungary\": [\" Water Polo\"], \"What",
"= playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3')",
"= \"The current temperature in {0} is {1}\".format(place, update) return weather_report responses =",
"3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"I Feel",
"#capital of States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"],",
"{0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great",
"Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear from you\"],",
"bot_name = \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def send_message(message): response =",
"'18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th',",
"Of Hungary\": [\" Water Polo\"], \"What Is The National Game Of Cuba\": [\"Baseball\"],",
"Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"],",
"Prevent From Cold\": [\"Here are some Prevention methods \\n 1. Wash your hands",
"to as a viral upper respiratory tract infection. \" \"Symptoms of the common",
"Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of",
"day = now.day month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',",
"for key,value in request_d.items(): if value == '+': return int(request_d[key - 1]) +",
"value == '+': return int(request_d[key - 1]) + int(request_d[key + 1]) if value",
"\"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of",
"= \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in",
"int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if timings == \"pm\": alarmHour =",
"Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"],",
"alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4'",
"nice to hear from you\"], \"When Is Your Birthday\": [\"It's on June 2nd",
"'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd',",
"\"sorry one more time\", \"Sorry! again\"], \"Who Created You\": [\"I was developed by",
"alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1,",
"def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month =",
"import nltk from googletrans import Translator import sports from newspaper import Article bot_name",
"to hear from you\"], \"When Is Your Birthday\": [\"It's on June 2nd 2020\",",
"word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text =",
"Of Turkey\": [\"Oil Wrestling\"], \"What Is The National Game Of India\": [\" Field",
"\"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's",
"[\"Lacrosse\"], \"What Is The National Game Of Canada in Winter\": [\"Ice Hockey\"], \"What",
"are results \\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n",
"\\n 3. Avoid touching your eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms",
"requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current",
"\"Member Of Rajya Sabha\": [\"Selected by elected members of Legislative Assembly\"], \"Current Prime",
"win10toast from bs4 import BeautifulSoup import requests import re import nltk from googletrans",
"Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\":",
"matches['football'] else: cricket = \"no matches found\" return cricket def trans(): trans =",
"to get rid of stress:\\n 1) Listen some melody songs \\n 2) Exercise",
"'21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] return \"Today",
"\"What Is The National Game Of Argentina\": [\"Pato\"], \"What Is The National Game",
"on June 2nd 2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for",
"[\"Pato\"], \"What Is The National Game Of United States\": [\"Baseball\"], \"What Is The",
"Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief",
"'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1]",
"4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation in",
"Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"],",
"Of Iran\": [\"Wrestling\"], \"What Is The National Game Of Hungary\": [\" Water Polo\"],",
"the format HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module",
"\\n 7) Fever\"], \"How To Prevent From Cold\": [\"Here are some Prevention methods",
"\"Sorry! again\"], \"Who Created You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I",
"user_template = \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message",
"field questions \"Cold\": [\"The common cold is medically referred to as a viral",
"alex_speak(ask) audio = r.listen(source) data = '' try: data = r.recognize_google(audio) except sr.UnknownValueError():",
"throat\"], #Political questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\":",
"= calendar.day_name[today.weekday()] month = now.month day = now.day month_list = ['January', 'February', 'March',",
"[\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"],",
"bot_message = trans() elif message == \"Headlines\": bot_message = news_scrap() elif message ==",
"\"Symptoms For Throat Pain\": [\"1) Scratchy sensation in the throat \\n 2)Difficulty in",
"Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"],",
"Of Russia\": [\"Bandy\"], \"What Is The National Game Of Canada in Summer \":",
"professional\\n \" \"4) Be positive\"], \"How To Relieve Stress\": [\"Here are some tips",
"\"What Is Today Date\": [date_and_time()], \"What Is The Month\": [month()], \"What Is The",
"'22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] return \"Today is",
"Hockey\"], \"What Is The National Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False):",
"me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great meal\", \"Good",
"\"What Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game",
"for hobbies\\n 2) Avoid using Mobile Phone \\n 3) Get advise from mental",
"# Medical field questions \"Cold\": [\"The common cold is medically referred to as",
"Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\":",
"AM or PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date",
"Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West",
"Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of Argentina\": [\"Pato\"], \"What Is The",
"= time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or",
"in Winter\": [\"Ice Hockey\"], \"What Is The National Game Of Spain\": [\"Bull Fighting\"],",
"requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in soup.find_all('p'): text",
"\"What Is The National Game Of Iran\": [\"Wrestling\"], \"What Is The National Game",
"Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\":",
"alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import playsound melody =",
"[\"Here are results \\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion",
"bot_message = calculate(m) elif 'who is' in message: person = person_name(message) bot_message =",
"Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\":",
"return weather_report responses = { \"Hey Alex\": [\"Your bot is activating...\",\" Bot is",
"questions \"Cold\": [\"The common cold is medically referred to as a viral upper",
"return melody def weather_manager(): place = record_audio(\"Enter the name of place\") search =",
"National Game Of Canada in Summer \": [\"Lacrosse\"], \"What Is The National Game",
"notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp()",
"[\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister",
"Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home",
"elif message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time():",
"[\"Here are some tips to get rid of stress:\\n 1) Avoid Caffine and",
"\\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n",
"message == \"Live Score\": bot_message = sport_score() elif message == \"Exit\": breakpoint() else:",
"stuff \\n 3. Avoid touching your eyes,nose and mouth \\n 4. Stay away\"],",
"def alarm(): time = record_audio(\"Enter the Time in the format HH:MM\") time =",
"datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month",
"1]) - int(request_d[key + 1]) if value == '*': return int(request_d[key - 1])",
"os.remove(audio_file) alex_speak(\"What can I do for you\") while True: message = record_audio() send_message(message.title())",
"desti = desti[0:2] t = trans.translate( text, src=source, dest=desti ) return t.text def",
"bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What you have to",
"= r.listen(source) data = '' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except",
"= re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', ' ', text) sentences =",
"National Game Of Russia\": [\"Bandy\"], \"What Is The National Game Of Canada in",
"Get advise from mental health professional\\n \" \"4) Be positive\"], \"How To Relieve",
"'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers = ['1st',",
"Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of",
"[\"<NAME>\"], #capital of States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\":",
"the common cold may include cough, sore throat, low-grade fever, nasal congestion, runny",
"Cold\": [\"Here are some Prevention methods \\n 1. Wash your hands properly \\n",
"For Throat Pain\": [\"1) Scratchy sensation in the throat \\n 2)Difficulty in Swallowing",
"month = now.month day = now.day month_list = ['January', 'February', 'March', 'April', 'May',",
"def scrap(): search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url)",
"remainder message:\") time = str(input(\"Enter the timing in format HH:MM\")) date = str(input(\"Enter",
"Of England\": [\"Cricket\"], \"What Is The National Game Of Scotland\": [\"Golf\"], \"What Is",
"toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url",
"your wishes\",\"Thak you so much for thinking of me\", \"Thanks for making me",
"bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today()",
"Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\":",
"The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear from",
"tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file)",
"\\n 2. Disinfect your stuff \\n 3. Avoid touching your eyes,nose and mouth",
"time = str(input(\"Enter the timing in format HH:MM\")) date = str(input(\"Enter the remainder",
"3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"Feels Stressed\":",
"methods \\n 1. Wash your hands properly \\n 2. Disinfect your stuff \\n",
"'August', 'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th',",
"the ' + Numbers[day-1] def month(): now = datetime.datetime.now() month = now.month month_list",
"cricket = \"no matches found\" return cricket def trans(): trans = Translator() text",
"[\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu &",
"now = datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day",
"Cough \\n 4)Sore throat\"], #Political questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member",
"= ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th',",
"= desti.lower() desti = desti[0:2] t = trans.translate( text, src=source, dest=desti ) return",
"birthday\", \"I can't tell you how I enjoyed hearing from you\"], \"I Feel",
"Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation in the",
"'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time = time.ctime()",
"from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound",
"[\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister",
"bot_message = webbrowser.get().open(url) elif message == \"Find Location\": location = record_audio(\"City name\") url",
"Feel Stressed\": [\"Here are some tips to get rid of stress:\\n 1) Avoid",
"== \"pm\": alarmHour = alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour",
"\"Live Score\": bot_message = sport_score() elif message == \"Exit\": breakpoint() else: bot_message =",
"'28th', '29th', '30th', '31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+' the '",
"= 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score():",
"source = source.lower() source = source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower()",
"Melody songs\", \"I tired to play music but vain\", \"Sleep well\"], # Medical",
"\"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\":",
"notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !! Sweet dreams\", \"Good Night we",
") return t.text def scrap(): search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\"",
"National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of Bhutan\": [\"",
"Prevention methods \\n 1. Wash your hands properly \\n 2. Disinfect your stuff",
"int(request_d[key + 1]) if value == '/': return int(request_d[key - 1]) / int(request_d[key",
"your hands properly \\n 2. Disinfect your stuff \\n 3. Avoid touching your",
"format HH:MM\")) date = str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time =",
"article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports matches = sports.all_matches() match_invoked",
"BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in soup.find_all('p'): text += paragraph.text text",
"playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import playsound melody",
"re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d',",
"try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data",
"toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url)",
"Next day\"], \"What Is Today Date\": [date_and_time()], \"What Is The Month\": [month()], \"What",
"search\") if match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football': cricket",
"{place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update =",
"time = time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM",
"message:\") time = str(input(\"Enter the timing in format HH:MM\")) date = str(input(\"Enter the",
"'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football': cricket = matches['football'] else: cricket",
"cricket = matches['football'] else: cricket = \"no matches found\" return cricket def trans():",
"sr.Microphone() as source: if ask: alex_speak(ask) audio = r.listen(source) data = '' try:",
"take medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms For Cold\": [\"Here are",
"text.split() for i in range(0, len(name)): if i + 3 <= len(name)-1 and",
"runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad to har from you\", \"Please,",
"National Game Of United States\": [\"Baseball\"], \"What Is The National Game Of Afghanistan\":",
"The National Game Of England\": [\"Cricket\"], \"What Is The National Game Of Scotland\":",
"and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message =",
"3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"How To",
"\"What Is The National Game Of United States\": [\"Baseball\"], \"What Is The National",
"using Mobile Phone \\n 3) Get advise from mental health professional\\n \" \"4)",
"\"What Is The National Game Of England\": [\"Cricket\"], \"What Is The National Game",
"record_audio(\"Specify the sentence or word to be translated:\") source = record_audio(\"From Languages:\") source",
"& Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil",
"\"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States",
"mental health professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here are some tips",
"= r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string):",
"Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\":",
"Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"],",
"2020\", \"It's on June 2nd 2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank",
"[\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister",
"[\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister",
"Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\":",
"of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\":",
"int(request_d[key + 1]) def person_name(text): name = text.split() for i in range(0, len(name)):",
"= now.month day = now.day month_list = ['January', 'February', 'March', 'April', 'May', 'June',",
"[\"Here Some Melody songs\", \"I tired to play music but vain\", \"Sleep well\"],",
"'25th', '26th', '27th', '28th', '29th', '30th', '31st'] return \"Today is \"+weekday + '",
"3 <= len(name)-1 and name[i].lower == 'who' and name[i+1].lower == 'is': return name[i+2]+",
"Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"],",
"want to search\") if match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked ==",
"weather_report = \"The current temperature in {0} is {1}\".format(place, update) return weather_report responses",
"response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message = random.choice(responses[message])",
"nose, and sneezing.\"], \"I Have Cold\": [\"Sad to har from you\", \"Please, take",
"it becomes complicated\"], \"Symptoms For Cold\": [\"Here are results \\n 1)Runny nose \\n",
"record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2] t = trans.translate( text, src=source,",
"referred to as a viral upper respiratory tract infection. \" \"Symptoms of the",
"desti[0:2] t = trans.translate( text, src=source, dest=desti ) return t.text def scrap(): search",
"= \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m",
"nasal congestion, runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad to har from",
"Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\":",
"\"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister",
"\"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"],",
"National Game Of Argentina\": [\"Pato\"], \"What Is The National Game Of United States\":",
"Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"],",
"= str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time = time.split(\":\") date =",
"\\n 3)Talk to someone who cares you\", \"Here are few tips to get",
"int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year = int(date[2])",
"'31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1] def",
"\\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The 11Th President Of India\":",
"\\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes",
"\\n 2) Exercise regularly \\n 3) Get enough sleep and rest\", \"Follow these",
"= i + 1 for key,value in request_d.items(): if value == '+': return",
"someone who cares you\", \"Here are few tips to get rid of stress:\\n",
"Game Of Bhutan\": [\" Archery\"], \"What Is The National Game Of Sri Lanka\":",
"[\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister",
"Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of Bhutan\": [\" Archery\"],",
"timings == \"pm\": alarmHour = alarmHour + 12 while True: if alarmHour ==",
"'27th', '28th', '29th', '30th', '31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+' the",
"== \"Wikipedia\": bot_message = scrap() elif message == \"Translate\": bot_message = trans() elif",
"sport_score(): import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the game you want",
"Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"],",
"4)Sore throat\"], #Political questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya",
"message == \"Play Me A Song\": bot_message = melody() elif message == \"Weather\":",
"to get rid of stress:\\n 1) Avoid Caffine and Alcohol \\n 2) Get",
"making me feel special on my birthday\", \"I can't tell you how I",
"include cough, sore throat, low-grade fever, nasal congestion, runny nose, and sneezing.\"], \"I",
"\"Cold\": [\"The common cold is medically referred to as a viral upper respiratory",
"[\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\":",
"[\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister",
"National Game Of Cuba\": [\"Baseball\"], \"What Is The National Game Of Pakistan\": [\"Field",
"Wash your hands properly \\n 2. Disinfect your stuff \\n 3. Avoid touching",
"Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is The National",
"elif 'who is' in message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif",
"\"Good Morning\": [\"Good Morning have a great day\", \"great day ahead\", \"have a",
"Night\": [\"Good Night\", \"Good Night !! Sweet dreams\", \"Good Night we will meet",
"message: search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url)",
"Created You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed by",
"you\", \"Please, take rest from you\", \"Properly take medicines\", \"Consult doctor before it",
"Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\":",
"{1}\".format(place, update) return weather_report responses = { \"Hey Alex\": [\"Your bot is activating...\",\"",
"[\"Ice Hockey\"], \"What Is The National Game Of Spain\": [\"Bull Fighting\"], } def",
"songs \\n 2) Exercise regularly \\n 3) Get enough sleep and rest\", \"Follow",
"== 'is': return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the",
"appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation in the throat \\n",
"Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital",
"return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file",
"developed by Anandatirtha as a demo bot\"], \"What Is Your Name\": [\"My name",
"3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The 11Th President Of India\": [\"<NAME>\"],",
"for thinking of me\", \"Thanks for making me feel special on my birthday\",",
"Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief",
"calculate(m) elif 'who is' in message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2)",
"Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of",
"\\n 2) Get more sleep \\n 3)Talk to someone who cares you\", \"Here",
"alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def",
"Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"],",
"3 2 1\"], \"Good Morning\": [\"Good Morning have a great day\", \"great day",
"+ 3 <= len(name)-1 and name[i].lower == 'who' and name[i+1].lower == 'is': return",
"message == \"Translate\": bot_message = trans() elif message == \"Headlines\": bot_message = news_scrap()",
"bs4 import BeautifulSoup import requests import re import nltk from googletrans import Translator",
"= int(date[2]) if timings == \"pm\": alarmHour = alarmHour + 12 while True:",
"\"Good Afternoon after your great meal\", \"Good Afternoon don't forget to check notifications\"],",
"Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal",
"common cold is medically referred to as a viral upper respiratory tract infection.",
"to be translated:\") source = record_audio(\"From Languages:\") source = source.lower() source = source[0:2]",
"Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of",
"\"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister",
"Score\": bot_message = sport_score() elif message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"])",
"Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital",
"[\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister",
"\"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I",
"\"Good Night !! Sweet dreams\", \"Good Night we will meet Next day\"], \"What",
"to compute\") bot_message = calculate(m) elif 'who is' in message: person = person_name(message)",
"\"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"],",
"labs\"], \"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak you so much for",
"Fever\"], \"How To Prevent From Cold\": [\"Here are some Prevention methods \\n 1.",
"import calendar import time import webbrowser import wikipedia from gtts import gTTS import",
"[\"Oil Wrestling\"], \"What Is The National Game Of India\": [\" Field Hockey\"], \"What",
"desti = record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2] t = trans.translate(",
"webbrowser import wikipedia from gtts import gTTS import playsound import os import win10toast",
"[\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"],",
"Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of Bhutan\": [\" Archery\"], \"What",
"Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\":",
"\"Symptoms For Cold\": [\"Here are results \\n 1)Runny nose \\n 2)Sore throat \\n",
"\"What Is The National Game Of Canada in Summer \": [\"Lacrosse\"], \"What Is",
"message == \"Calculate\": m = record_audio(\"What you have to compute\") bot_message = calculate(m)",
"Game Of United States\": [\"Baseball\"], \"What Is The National Game Of Afghanistan\": [\"Buzkashi\"],",
"\"Set An Alarm\": bot_message = alarm() elif message == \"Play Me A Song\":",
"'September', 'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time = time.ctime() return local_time",
"int(request_d[key + 1]) if value == '*': return int(request_d[key - 1]) * int(request_d[key",
"Game Of England\": [\"Cricket\"], \"What Is The National Game Of Scotland\": [\"Golf\"], \"What",
"article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports matches = sports.all_matches()",
"datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10)",
"\"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital",
"doctor before it becomes complicated\"], \"Symptoms For Cold\": [\"Here are results \\n 1)Runny",
"advise from mental health professional\\n \" \"4) Be positive\"], \"I Feel Bored\": [\"Here",
"return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\")",
"= Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports matches",
"1]) def person_name(text): name = text.split() for i in range(0, len(name)): if i",
"match_invoked = record_audio(\"Enter the game you want to search\") if match_invoked == 'Cricket':",
"alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if",
"calendar.day_name[today.weekday()] month = now.month day = now.day month_list = ['January', 'February', 'March', 'April',",
"3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n 4)Sore",
"rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster =",
"sensation in the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\":",
"the sentence or word to be translated:\") source = record_audio(\"From Languages:\") source =",
"text) text = re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', ' ', text)",
"bot_message = melody() elif message == \"Weather\": bot_message = weather_manager() elif message ==",
"of States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital",
"elif message == \"Set An Remainder\": bot_message = remainder() elif message == \"Set",
"Game Of Russia\": [\"Bandy\"], \"What Is The National Game Of Canada in Summer",
"Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States in India",
"Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of",
"forget to check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !! Sweet dreams\",",
"nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time in the format",
"Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu",
"from you\"], \"When Is Your Birthday\": [\"It's on June 2nd 2020\", \"It's on",
"National Game Of Iran\": [\"Wrestling\"], \"What Is The National Game Of Hungary\": [\"",
"Be positive\"], \"How To Relieve Stress\": [\"Here are some tips to get rid",
"\"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is",
"Canada in Summer \": [\"Lacrosse\"], \"What Is The National Game Of Canada in",
"return local_time def calculate(message): message = message.split() i = 0 request_d = {}",
"def month(): now = datetime.datetime.now() month = now.month month_list = ['January', 'February', 'March',",
"Time in the format HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute =",
"National Game Of England\": [\"Cricket\"], \"What Is The National Game Of Scotland\": [\"Golf\"],",
"from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place =",
"int(request_d[key - 1]) + int(request_d[key + 1]) if value == '-': return int(request_d[key",
"' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time =",
"India\": [\" Field Hockey\"], \"What Is The National Game Of England\": [\"Cricket\"], \"What",
"melody def weather_manager(): place = record_audio(\"Enter the name of place\") search = f\"Weather",
"[ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear from you\"], \"When Is",
"Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"],",
"wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"],",
"datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return",
"3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To",
"weather_manager(): place = record_audio(\"Enter the name of place\") search = f\"Weather in {place}\"",
"= record_audio(\"Enter the game you want to search\") if match_invoked == 'Cricket': cricket",
"in message: search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message =",
"import BeautifulSoup import requests import re import nltk from googletrans import Translator import",
"from you\", \"Please, take rest from you\", \"Properly take medicines\", \"Consult doctor before",
"news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text",
"'4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th',",
"in range(0, len(name)): if i + 3 <= len(name)-1 and name[i].lower == 'who'",
"- 1]) - int(request_d[key + 1]) if value == '*': return int(request_d[key -",
"'26th', '27th', '28th', '29th', '30th', '31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+'",
"trans() elif message == \"Headlines\": bot_message = news_scrap() elif message == \"Live Score\":",
"the game you want to search\") if match_invoked == 'Cricket': cricket = matches['cricket']",
"[\"Field Hockey\"], \"What Is The National Game Of Brazil\": [\"Football\"], \"What Is The",
"alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module",
"Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of",
"\" \"4) Be positive\"], \"Feels Stressed\": [\"Here are some tips to get rid",
"Argentina\": [\"Pato\"], \"What Is The National Game Of United States\": [\"Baseball\"], \"What Is",
"Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief",
"\\n 3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"I",
"wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\": bot_message = remainder() elif message",
"bot_message = alarm() elif message == \"Play Me A Song\": bot_message = melody()",
"import datetime import calendar import time import webbrowser import wikipedia from gtts import",
"playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter the name",
"responses = { \"Hey Alex\": [\"Your bot is activating...\",\" Bot is Launcing 3",
"Hungary\": [\" Water Polo\"], \"What Is The National Game Of Cuba\": [\"Baseball\"], \"What",
"to search\") if match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football':",
"Meghalaya\": [\"Shillong\"], #national games \"What Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What",
"= record_audio(\"From Languages:\") source = source.lower() source = source[0:2] desti = record_audio(\"To Languages:\")",
"request_d = {} for req in message: request_d[i] = req i = i",
"location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url)",
"[\" Field Hockey\"], \"What Is The National Game Of England\": [\"Cricket\"], \"What Is",
"stress:\\n 1) Listen some melody songs \\n 2) Exercise regularly \\n 3) Get",
"June 2nd 2020\", \"It's on June 2nd 2020 at Rag labs\"], \"Happy Birthday",
"Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of",
"record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask) audio =",
"The National Game Of Russia\": [\"Bandy\"], \"What Is The National Game Of Canada",
"data = '' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error",
"cold is medically referred to as a viral upper respiratory tract infection. \"",
"Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\":",
"great meal\", \"Good Afternoon don't forget to check notifications\"], \"Good Night\": [\"Good Night\",",
"\"What Is The National Game Of Cuba\": [\"Baseball\"], \"What Is The National Game",
"[\"Good Morning have a great day\", \"great day ahead\", \"have a wonderful day\",",
"bot\"], \"What Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good",
"and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\":",
"these tips:\\n 1) Make time for hobbies\\n 2) Avoid using Mobile Phone \\n",
"gtts import gTTS import playsound import os import win10toast from bs4 import BeautifulSoup",
"Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\":",
"Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The National Game Of India\": [\"",
"= alarm() elif message == \"Play Me A Song\": bot_message = melody() elif",
"1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n",
"Translator() text = record_audio(\"Specify the sentence or word to be translated:\") source =",
"= BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in soup.find_all('p'): text += paragraph.text",
"text = re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm():",
"Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"],",
"text) text = re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', ' ', text)",
"of stress:\\n 1) Avoid Caffine and Alcohol \\n 2) Get more sleep \\n",
"Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu",
"int(request_d[key - 1]) / int(request_d[key + 1]) def person_name(text): name = text.split() for",
"West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"],",
"\\n 3) Get enough sleep and rest\", \"Follow these tips:\\n 1) Make time",
"\\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent From Cold\":",
"datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year:",
"2nd 2020\", \"It's on June 2nd 2020 at Rag labs\"], \"Happy Birthday Rag\":",
"[\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of",
"if match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football': cricket =",
"12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound",
"record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif message",
"in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\":",
"person_name(text): name = text.split() for i in range(0, len(name)): if i + 3",
"dest=desti ) return t.text def scrap(): search = record_audio(\"Enter the word\") url =",
"re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time =",
"message == \"Find Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location",
"i + 1 for key,value in request_d.items(): if value == '+': return int(request_d[key",
"'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th',",
"[\"It's on June 2nd 2020\", \"It's on June 2nd 2020 at Rag labs\"],",
"becomes complicated\"], \"Symptoms For Cold\": [\"Here are results \\n 1)Runny nose \\n 2)Sore",
"Cold\": [\"Here are results \\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n",
"viral upper respiratory tract infection. \" \"Symptoms of the common cold may include",
"who cares you\", \"Here are few tips to get rid of stress:\\n 1)",
"Is The National Game Of Hungary\": [\" Water Polo\"], \"What Is The National",
"\"I tired to play music but vain\", \"Sleep well\"], # Medical field questions",
"'who' and name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message",
"+ 1 for key,value in request_d.items(): if value == '+': return int(request_d[key -",
"playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter",
"\"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster",
"\"What Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\":",
"place = record_audio(\"Enter the name of place\") search = f\"Weather in {place}\" url",
"== \"Set An Remainder\": bot_message = remainder() elif message == \"Set An Alarm\":",
"return int(request_d[key - 1]) / int(request_d[key + 1]) def person_name(text): name = text.split()",
"wikipedia from gtts import gTTS import playsound import os import win10toast from bs4",
"matches['cricket'] elif match_invoked == 'Football': cricket = matches['football'] else: cricket = \"no matches",
"Brazil\": [\"Football\"], \"What Is The National Game Of Russia\": [\"Bandy\"], \"What Is The",
"Phone \\n 3) Get advise from mental health professional\\n \" \"4) Be positive\"],",
"= time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings =",
"\"I Feel Bored\": [\"Here Some Melody songs\", \"I tired to play music but",
"and Alcohol \\n 2) Get more sleep \\n 3)Talk to someone who cares",
"low-grade fever, nasal congestion, runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad to",
"date = date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour",
"update) return weather_report responses = { \"Hey Alex\": [\"Your bot is activating...\",\" Bot",
"\"I Feel Stressed\": [\"Here are some tips to get rid of stress:\\n 1)",
"my birthday\", \"I can't tell you how I enjoyed hearing from you\"], \"I",
"game you want to search\") if match_invoked == 'Cricket': cricket = matches['cricket'] elif",
"stress:\\n 1) Avoid Caffine and Alcohol \\n 2) Get more sleep \\n 3)Talk",
"Remainder_message = record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the timing in format",
"2nd 2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak",
"Translator import sports from newspaper import Article bot_name = \"Rag2020\" bot_template = \"{0}\"",
"National Game Of Sri Lanka\": [\"Volley ball\"], \"What Is The National Game Of",
"Is The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear",
"\"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great meal\", \"Good Afternoon don't",
"== \"Headlines\": bot_message = news_scrap() elif message == \"Live Score\": bot_message = sport_score()",
"[\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital",
"== \"Set An Alarm\": bot_message = alarm() elif message == \"Play Me A",
"\"What Is The National Game Of Scotland\": [\"Golf\"], \"What Is The National Game",
"Is The National Game Of Pakistan\": [\"Field Hockey\"], \"What Is The National Game",
"your eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches",
"== '+': return int(request_d[key - 1]) + int(request_d[key + 1]) if value ==",
"Exercise regularly \\n 3) Get enough sleep and rest\", \"Follow these tips:\\n 1)",
"= text.split() for i in range(0, len(name)): if i + 3 <= len(name)-1",
"the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text",
"Is The National Game Of England\": [\"Cricket\"], \"What Is The National Game Of",
"== \"Translate\": bot_message = trans() elif message == \"Headlines\": bot_message = news_scrap() elif",
"source = record_audio(\"From Languages:\") source = source.lower() source = source[0:2] desti = record_audio(\"To",
"Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear from you\"], \"When",
"a demo bot\"], \"What Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call me",
"cares you\", \"Here are few tips to get rid of stress:\\n 1) Listen",
"= str(input(\"Enter the timing in format HH:MM\")) date = str(input(\"Enter the remainder date",
"Languages:\") desti = desti.lower() desti = desti[0:2] t = trans.translate( text, src=source, dest=desti",
"Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States in",
"\"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses:",
"of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation in the throat",
"\"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message == \"Find Location\": location = record_audio(\"City",
"Alex\": [\"Your bot is activating...\",\" Bot is Launcing 3 2 1\"], \"Good Morning\":",
"alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if",
"properly \\n 2. Disinfect your stuff \\n 3. Avoid touching your eyes,nose and",
"= record_audio(\"What you have to compute\") bot_message = calculate(m) elif 'who is' in",
"timings_module = str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if timings_module == \"pm\":",
"Rag\": [\"Thank you for your wishes\",\"Thak you so much for thinking of me\",",
"5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation in the throat \\n 2)Difficulty",
"[\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source: if",
"== \"Find Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&'",
"= str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour",
"'8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th',",
"responses: bot_message = random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify the word\")",
"int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if timings_module ==",
"= record_audio(\"Enter the name of place\") search = f\"Weather in {place}\" url =",
"timings_module == \"pm\": alarmHour = alarmHour + 12 while True: if alarmHour ==",
"rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\",",
"enough sleep and rest\", \"Follow these tips:\\n 1) Make time for hobbies\\n 2)",
"your stuff \\n 3. Avoid touching your eyes,nose and mouth \\n 4. Stay",
"\"what's special today\"], \"Default\": [\"I can't get you\", \"sorry one more time\", \"Sorry!",
"as a demo bot\"], \"What Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call",
"and name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message =",
"to check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !! Sweet dreams\", \"Good",
"record_audio(\"Enter the Time in the format HH:MM\") time = time.split(\":\") alarmHour = int(time[0])",
"tips:\\n 1) Make time for hobbies\\n 2) Avoid using Mobile Phone \\n 3)",
"tract infection. \" \"Symptoms of the common cold may include cough, sore throat,",
"if value == '/': return int(request_d[key - 1]) / int(request_d[key + 1]) def",
"rid of stress:\\n 1) Listen some melody songs \\n 2) Exercise regularly \\n",
"away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"],",
"'+': return int(request_d[key - 1]) + int(request_d[key + 1]) if value == '-':",
"\"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now()",
"time for hobbies\\n 2) Avoid using Mobile Phone \\n 3) Get advise from",
"= sports.all_matches() match_invoked = record_audio(\"Enter the game you want to search\") if match_invoked",
"src=source, dest=desti ) return t.text def scrap(): search = record_audio(\"Enter the word\") url",
"by Anandatirtha as a demo bot\"], \"What Is Your Name\": [\"My name is",
"datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day = now.day month_list = ['January',",
"Avoid touching your eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms For Fever\":",
"ball\"], \"What Is The National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The",
"Is The National Game Of Brazil\": [\"Football\"], \"What Is The National Game Of",
"'5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th',",
"Is The Month\": [month()], \"What Is The Time Now\": [ time.ctime()], \"Thank You\":",
"Game Of Sri Lanka\": [\"Volley ball\"], \"What Is The National Game Of Turkey\":",
"positive\"], \"Feels Stressed\": [\"Here are some tips to get rid of stress:\\n 1)",
"requests import re import nltk from googletrans import Translator import sports from newspaper",
"r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in",
"{0} is {1}\".format(place, update) return weather_report responses = { \"Hey Alex\": [\"Your bot",
"mental health professional\\n \" \"4) Be positive\"], \"I Feel Bored\": [\"Here Some Melody",
"month_list[month-1] def current_time(): local_time = time.ctime() return local_time def calculate(message): message = message.split()",
"def trans(): trans = Translator() text = record_audio(\"Specify the sentence or word to",
"== \"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\": bot_message = scrap() elif",
"\"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of",
"def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file = 'audio-'",
"== datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message,",
"\\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss",
"except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts =",
"A Song\": bot_message = melody() elif message == \"Weather\": bot_message = weather_manager() elif",
"Morning have a great day\", \"great day ahead\", \"have a wonderful day\", \"Good",
"Birthday Rag\": [\"Thank you for your wishes\",\"Thak you so much for thinking of",
"Disinfect your stuff \\n 3. Avoid touching your eyes,nose and mouth \\n 4.",
"word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message == \"Find Location\":",
"Stressed\": [\"Here are some tips to get rid of stress:\\n 1) Avoid Caffine",
"hear from you\"], \"When Is Your Birthday\": [\"It's on June 2nd 2020\", \"It's",
"message.split() i = 0 request_d = {} for req in message: request_d[i] =",
"person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\":",
"sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the game you want to search\")",
"= { \"Hey Alex\": [\"Your bot is activating...\",\" Bot is Launcing 3 2",
"+ Numbers[day-1] def month(): now = datetime.datetime.now() month = now.month month_list = ['January',",
"Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of",
"[\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief",
"= BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in",
"tips to get rid of stress:\\n 1) Avoid Caffine and Alcohol \\n 2)",
"\"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of",
"scrap(): search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup",
"India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"],",
"Affairs\": [\"<NAME>\"], #capital of States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of",
"Rajya Sabha\": [\"Selected by elected members of Legislative Assembly\"], \"Current Prime Minister of",
"message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now",
"\"Thanks for making me feel special on my birthday\", \"I can't tell you",
"import Translator import sports from newspaper import Article bot_name = \"Rag2020\" bot_template =",
"\"Follow these tips:\\n 1) Make time for hobbies\\n 2) Avoid using Mobile Phone",
"Some Melody songs\", \"I tired to play music but vain\", \"Sleep well\"], #",
"url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\",",
"today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day = now.day month_list",
"Listen some melody songs \\n 2) Exercise regularly \\n 3) Get enough sleep",
"fever, nasal congestion, runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad to har",
"United States\": [\"Baseball\"], \"What Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is",
"Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent From Cold\": [\"Here are",
"bot is activating...\",\" Bot is Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning",
"\"What Is The National Game Of Pakistan\": [\"Field Hockey\"], \"What Is The National",
"Avoid using Mobile Phone \\n 3) Get advise from mental health professional\\n \"",
"Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat",
"data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def",
"url = \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\":",
"get you\", \"sorry one more time\", \"Sorry! again\"], \"Who Created You\": [\"I was",
"special on my birthday\", \"I can't tell you how I enjoyed hearing from",
"[\"Football\"], \"What Is The National Game Of Russia\": [\"Bandy\"], \"What Is The National",
"medically referred to as a viral upper respiratory tract infection. \" \"Symptoms of",
"'13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th',",
"Anandatirtha as a demo bot\"], \"What Is Your Name\": [\"My name is {0}\".format(bot_name),",
"'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\") while",
"is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your",
"+ 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and",
"Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of",
"'29th', '30th', '31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+' the ' +",
"message == \"Set An Remainder\": bot_message = remainder() elif message == \"Set An",
"text = re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', ' ', text) text",
"int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module = timings_module.lower()",
"name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter",
"Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"],",
"' '+month_list[month-1]+' the ' + Numbers[day-1] def month(): now = datetime.datetime.now() month =",
"\"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of",
"range(0, len(name)): if i + 3 <= len(name)-1 and name[i].lower == 'who' and",
"National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of Argentina\": [\"Pato\"],",
"June 2nd 2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for your",
"\"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of",
"'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th',",
"t.text def scrap(): search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r =",
"rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister",
"'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time",
"== datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def",
"= int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module =",
"elected members of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of",
"= news_scrap() elif message == \"Live Score\": bot_message = sport_score() elif message ==",
"\"The 11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected",
"PM or AM\")) timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour",
"f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report",
"Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"],",
"= trans.translate( text, src=source, dest=desti ) return t.text def scrap(): search = record_audio(\"Enter",
"Avoid Caffine and Alcohol \\n 2) Get more sleep \\n 3)Talk to someone",
"1]) if value == '-': return int(request_d[key - 1]) - int(request_d[key + 1])",
"for your wishes\",\"Thak you so much for thinking of me\", \"Thanks for making",
"The National Game Of Pakistan\": [\"Field Hockey\"], \"What Is The National Game Of",
"[\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\":",
"2 1\"], \"Good Morning\": [\"Good Morning have a great day\", \"great day ahead\",",
"Scratchy sensation in the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For",
"= f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for",
"Of Brazil\": [\"Football\"], \"What Is The National Game Of Russia\": [\"Bandy\"], \"What Is",
"for making me feel special on my birthday\", \"I can't tell you how",
"thinking of me\", \"Thanks for making me feel special on my birthday\", \"I",
"[\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister",
"win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories'",
"'24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] return \"Today is \"+weekday +",
"alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month",
"You\": [\"Welcome\", \"It's nice to hear from you\"], \"When Is Your Birthday\": [\"It's",
"Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital",
"[\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I can't get you\",",
"from gtts import gTTS import playsound import os import win10toast from bs4 import",
"'16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th',",
"r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts",
"int(request_d[key + 1]) if value == '-': return int(request_d[key - 1]) - int(request_d[key",
"len(name)-1 and name[i].lower == 'who' and name[i+1].lower == 'is': return name[i+2]+ ' '+",
"Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"],",
"melody() elif message == \"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\": bot_message",
"\"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital",
"= int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year =",
"now = datetime.datetime.now() month = now.month month_list = ['January', 'February', 'March', 'April', 'May',",
"playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\") while True: message = record_audio()",
"Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of",
"return int(request_d[key - 1]) + int(request_d[key + 1]) if value == '-': return",
"rest\", \"Follow these tips:\\n 1) Make time for hobbies\\n 2) Avoid using Mobile",
"but vain\", \"Sleep well\"], # Medical field questions \"Cold\": [\"The common cold is",
"= int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if timings == \"pm\": alarmHour",
"alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en')",
"time = record_audio(\"Enter the Time in the format HH:MM\") time = time.split(\":\") alarmHour",
"Is The National Game Of Canada in Summer \": [\"Lacrosse\"], \"What Is The",
"value == '*': return int(request_d[key - 1]) * int(request_d[key + 1]) if value",
"int(date[1]) rem_year = int(date[2]) if timings == \"pm\": alarmHour = alarmHour + 12",
"ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\",",
"Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of",
"tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\") while True: message",
"\"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's",
"\"Good Night\": [\"Good Night\", \"Good Night !! Sweet dreams\", \"Good Night we will",
"\"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I can't get",
"\"What Is The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to",
"Summer \": [\"Lacrosse\"], \"What Is The National Game Of Canada in Winter\": [\"Ice",
"Is The National Game Of Russia\": [\"Bandy\"], \"What Is The National Game Of",
"Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"],",
"3. Avoid touching your eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms For",
"Of Scotland\": [\"Golf\"], \"What Is The National Game Of Iran\": [\"Wrestling\"], \"What Is",
"me feel special on my birthday\", \"I can't tell you how I enjoyed",
"text = \"\" for paragraph in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]',",
"[\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\":",
"'3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th',",
"[\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister",
"Is The National Game Of Cuba\": [\"Baseball\"], \"What Is The National Game Of",
"on June 2nd 2020\", \"It's on June 2nd 2020 at Rag labs\"], \"Happy",
"article.nlp() return article.text def sport_score(): import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter",
"National Game Of India\": [\" Field Hockey\"], \"What Is The National Game Of",
"timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour + 12 while True: if",
"Lanka\": [\"Volley ball\"], \"What Is The National Game Of Turkey\": [\"Oil Wrestling\"], \"What",
"& Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\":",
"'19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st']",
"The National Game Of Hungary\": [\" Water Polo\"], \"What Is The National Game",
"Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"],",
"if value == '-': return int(request_d[key - 1]) - int(request_d[key + 1]) if",
"and name[i].lower == 'who' and name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3]",
"Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of",
"int(date[2]) if timings == \"pm\": alarmHour = alarmHour + 12 while True: if",
"Month\": [month()], \"What Is The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's",
"elif message == \"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\": bot_message =",
"alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year",
"if timings_module == \"pm\": alarmHour = alarmHour + 12 while True: if alarmHour",
"trans.translate( text, src=source, dest=desti ) return t.text def scrap(): search = record_audio(\"Enter the",
"have a great day\", \"great day ahead\", \"have a wonderful day\", \"Good Morning\"],",
"= 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\")",
"\"Thank You\": [\"Welcome\", \"It's nice to hear from you\"], \"When Is Your Birthday\":",
"Is The National Game Of Argentina\": [\"Pato\"], \"What Is The National Game Of",
"Field Hockey\"], \"What Is The National Game Of England\": [\"Cricket\"], \"What Is The",
"your great meal\", \"Good Afternoon don't forget to check notifications\"], \"Good Night\": [\"Good",
"random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I",
"12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date",
"\\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent",
"Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\":",
"text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time",
"health professional\\n \" \"4) Be positive\"], \"How To Relieve Stress\": [\"Here are some",
"cricket = matches['cricket'] elif match_invoked == 'Football': cricket = matches['football'] else: cricket =",
"\"Hey Alex\": [\"Your bot is activating...\",\" Bot is Launcing 3 2 1\"], \"Good",
"Is The National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The National Game",
"random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday =",
"Caffine and Alcohol \\n 2) Get more sleep \\n 3)Talk to someone who",
"return int(request_d[key - 1]) * int(request_d[key + 1]) if value == '/': return",
"timings = timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month",
"paragraph in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text",
"return \"Today is \"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1] def month():",
"= record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text,",
"\"What Is The National Game Of Sri Lanka\": [\"Volley ball\"], \"What Is The",
"desti.lower() desti = desti[0:2] t = trans.translate( text, src=source, dest=desti ) return t.text",
"Of Sri Lanka\": [\"Volley ball\"], \"What Is The National Game Of Turkey\": [\"Oil",
"Of Bhutan\": [\" Archery\"], \"What Is The National Game Of Sri Lanka\": [\"Volley",
"Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\":",
"Is The National Game Of Sri Lanka\": [\"Volley ball\"], \"What Is The National",
"\"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of",
"= f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text,",
"return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time in the format HH:MM\")",
"[\"Good Afternoon\", \"Good Afternoon after your great meal\", \"Good Afternoon don't forget to",
"def weather_manager(): place = record_audio(\"Enter the name of place\") search = f\"Weather in",
"r = sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask) audio = r.listen(source)",
"= gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string)",
"message == \"Set An Alarm\": bot_message = alarm() elif message == \"Play Me",
"activating...\",\" Bot is Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning have a",
"elif message == \"Live Score\": bot_message = sport_score() elif message == \"Exit\": breakpoint()",
"Birthday\": [\"It's on June 2nd 2020\", \"It's on June 2nd 2020 at Rag",
"have to compute\") bot_message = calculate(m) elif 'who is' in message: person =",
"elif message == \"Find Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" +",
"= now.month month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',",
"developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha as a demo",
"record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\")",
"To Prevent From Cold\": [\"Here are some Prevention methods \\n 1. Wash your",
"Canada in Winter\": [\"Ice Hockey\"], \"What Is The National Game Of Spain\": [\"Bull",
"Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief",
"= alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute ==",
"send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message =",
"now.day month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',",
"['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers",
"can't get you\", \"sorry one more time\", \"Sorry! again\"], \"Who Created You\": [\"I",
"sleep and rest\", \"Follow these tips:\\n 1) Make time for hobbies\\n 2) Avoid",
"int(request_d[key - 1]) - int(request_d[key + 1]) if value == '*': return int(request_d[key",
"search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup =",
"[\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister",
"[\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The",
"BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in {0}",
"India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States in India \"Capital",
"= now.day month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',",
"\"The current temperature in {0} is {1}\".format(place, update) return weather_report responses = {",
"few tips to get rid of stress:\\n 1) Listen some melody songs \\n",
"Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of",
"Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\":",
"[\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar &",
"[\"Kabaddi\"], \"What Is The National Game Of Argentina\": [\"Pato\"], \"What Is The National",
"games \"What Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National",
"\"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of",
"r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What",
"is \"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1] def month(): now =",
"Pakistan\": [\"Field Hockey\"], \"What Is The National Game Of Brazil\": [\"Football\"], \"What Is",
"\"What Is The National Game Of Brazil\": [\"Football\"], \"What Is The National Game",
"throat, low-grade fever, nasal congestion, runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad",
"for req in message: request_d[i] = req i = i + 1 for",
"import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the game you want to",
"= timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month =",
"From Cold\": [\"Here are some Prevention methods \\n 1. Wash your hands properly",
"Song\": bot_message = melody() elif message == \"Weather\": bot_message = weather_manager() elif message",
"[\"1) Scratchy sensation in the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms",
"', text) text = re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1])",
"\"Headlines\": bot_message = news_scrap() elif message == \"Live Score\": bot_message = sport_score() elif",
"sport_score() elif message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def",
"positive\"], \"How To Relieve Stress\": [\"Here are some tips to get rid of",
"Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national",
"month = now.month month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',",
"[\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is The National Game Of",
"the Time in the format HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute",
"Russia\": [\"Bandy\"], \"What Is The National Game Of Canada in Summer \": [\"Lacrosse\"],",
"Game Of Iran\": [\"Wrestling\"], \"What Is The National Game Of Hungary\": [\" Water",
"'10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd',",
"can't tell you how I enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here",
"rest from you\", \"Properly take medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms",
"!! Sweet dreams\", \"Good Night we will meet Next day\"], \"What Is Today",
"as a viral upper respiratory tract infection. \" \"Symptoms of the common cold",
"Game Of Argentina\": [\"Pato\"], \"What Is The National Game Of United States\": [\"Baseball\"],",
"Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and",
"Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief",
"[\"Buzkashi\"], \"What Is The National Game Of Bhutan\": [\" Archery\"], \"What Is The",
"India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"],",
"for paragraph in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text)",
"\"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"],",
"a viral upper respiratory tract infection. \" \"Symptoms of the common cold may",
"The National Game Of Argentina\": [\"Pato\"], \"What Is The National Game Of United",
"to play music but vain\", \"Sleep well\"], # Medical field questions \"Cold\": [\"The",
"breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now() today",
"= int(time[1]) timings_module = str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if timings_module",
"[\"The common cold is medically referred to as a viral upper respiratory tract",
"'December'] return month_list[month-1] def current_time(): local_time = time.ctime() return local_time def calculate(message): message",
"\"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\": bot_message = scrap() elif message",
"local_time def calculate(message): message = message.split() i = 0 request_d = {} for",
"random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\"",
"\"Symptoms of the common cold may include cough, sore throat, low-grade fever, nasal",
"in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text =",
"professional\\n \" \"4) Be positive\"], \"I Feel Bored\": [\"Here Some Melody songs\", \"I",
"take rest from you\", \"Properly take medicines\", \"Consult doctor before it becomes complicated\"],",
"1) Avoid Caffine and Alcohol \\n 2) Get more sleep \\n 3)Talk to",
"current_time(): local_time = time.ctime() return local_time def calculate(message): message = message.split() i =",
"the remainder date in format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings",
"Game Of Cuba\": [\"Baseball\"], \"What Is The National Game Of Pakistan\": [\"Field Hockey\"],",
"The National Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer()",
"AM\")) timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour + 12",
"\"What Is The National Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r",
"or AM\")) timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour +",
"remainder date in format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings =",
"sore throat, low-grade fever, nasal congestion, runny nose, and sneezing.\"], \"I Have Cold\":",
"Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"],",
"is {1}\".format(place, update) return weather_report responses = { \"Hey Alex\": [\"Your bot is",
"\\n 4)Sore throat\"], #Political questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member Of",
"found\" return cricket def trans(): trans = Translator() text = record_audio(\"Specify the sentence",
"elif 'Search' in message: search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search",
"Game Of Scotland\": [\"Golf\"], \"What Is The National Game Of Iran\": [\"Wrestling\"], \"What",
"', text) text = re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', ' ',",
"\\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping",
"for i in range(0, len(name)): if i + 3 <= len(name)-1 and name[i].lower",
"bot_template = \"{0}\" user_template = \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def",
"audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for",
"'July', 'August', 'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th',",
"[\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief",
"[\"Wrestling\"], \"What Is The National Game Of Hungary\": [\" Water Polo\"], \"What Is",
"Is The National Game Of India\": [\" Field Hockey\"], \"What Is The National",
"= respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message = random.choice(responses[message]) elif",
"import gTTS import playsound import os import win10toast from bs4 import BeautifulSoup import",
"Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief",
"local_time = time.ctime() return local_time def calculate(message): message = message.split() i = 0",
"Turkey\": [\"Oil Wrestling\"], \"What Is The National Game Of India\": [\" Field Hockey\"],",
"Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief",
"weekday = calendar.day_name[today.weekday()] month = now.month day = now.day month_list = ['January', 'February',",
"Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"],",
"in the format HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1])",
"source = source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2]",
"great day\", \"great day ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\",",
"The National Game Of Cuba\": [\"Baseball\"], \"What Is The National Game Of Pakistan\":",
"m = record_audio(\"What you have to compute\") bot_message = calculate(m) elif 'who is'",
"\"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1] def month(): now = datetime.datetime.now()",
"you so much for thinking of me\", \"Thanks for making me feel special",
"paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', ' ', text)",
"3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy",
"\"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of",
"== '/': return int(request_d[key - 1]) / int(request_d[key + 1]) def person_name(text): name",
"\"When Is Your Birthday\": [\"It's on June 2nd 2020\", \"It's on June 2nd",
"6)Sneezing \\n 7) Fever\"], \"How To Prevent From Cold\": [\"Here are some Prevention",
"text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', '",
"if i + 3 <= len(name)-1 and name[i].lower == 'who' and name[i+1].lower ==",
"[\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister",
"Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya",
"[\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief",
"we will meet Next day\"], \"What Is Today Date\": [date_and_time()], \"What Is The",
"special today\"], \"Default\": [\"I can't get you\", \"sorry one more time\", \"Sorry! again\"],",
"Stress\": [\"Here are some tips to get rid of stress:\\n 1) Avoid Caffine",
"Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief",
"2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The 11Th President",
"Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar",
"= record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the timing in format HH:MM\"))",
"= re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time",
"import win10toast from bs4 import BeautifulSoup import requests import re import nltk from",
"Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite",
"weather_manager() elif message == \"Wikipedia\": bot_message = scrap() elif message == \"Translate\": bot_message",
"Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital",
"\"How To Prevent From Cold\": [\"Here are some Prevention methods \\n 1. Wash",
"if timings == \"pm\": alarmHour = alarmHour + 12 while True: if alarmHour",
"Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief",
"Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil",
"speech_recognition as sr import datetime import calendar import time import webbrowser import wikipedia",
"matches = sports.all_matches() match_invoked = record_audio(\"Enter the game you want to search\") if",
"== 'Football': cricket = matches['football'] else: cricket = \"no matches found\" return cricket",
"For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For",
"\"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister",
"'+month_list[month-1]+' the ' + Numbers[day-1] def month(): now = datetime.datetime.now() month = now.month",
"Medical field questions \"Cold\": [\"The common cold is medically referred to as a",
"members of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra",
"nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing",
"\"What Is The National Game Of India\": [\" Field Hockey\"], \"What Is The",
"\"What Is The National Game Of Hungary\": [\" Water Polo\"], \"What Is The",
"webbrowser.get().open(url) elif message == \"Find Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\"",
"Numbers[day-1] def month(): now = datetime.datetime.now() month = now.month month_list = ['January', 'February',",
"= source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2] t",
"Wrestling\"], \"What Is The National Game Of India\": [\" Field Hockey\"], \"What Is",
"\"What Is The National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The National",
"match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football': cricket = matches['football']",
"rid of stress:\\n 1) Avoid Caffine and Alcohol \\n 2) Get more sleep",
"Winter\": [\"Ice Hockey\"], \"What Is The National Game Of Spain\": [\"Bull Fighting\"], }",
"Your Birthday\": [\"It's on June 2nd 2020\", \"It's on June 2nd 2020 at",
"Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal",
"The Month\": [month()], \"What Is The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\",",
"\"What Is The National Game Of Bhutan\": [\" Archery\"], \"What Is The National",
"'30th', '31st'] return \"Today is \"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1]",
"location +'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What you",
"\"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"],",
"bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\": bot_message = remainder()",
"= remainder() elif message == \"Set An Alarm\": bot_message = alarm() elif message",
"'15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th',",
"some Prevention methods \\n 1. Wash your hands properly \\n 2. Disinfect your",
"= str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute =",
"duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse()",
"return month_list[month-1] def current_time(): local_time = time.ctime() return local_time def calculate(message): message =",
"\"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of",
"\\n 2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The 11Th",
"def sport_score(): import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the game you",
"\"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\":",
"audio = r.listen(source) data = '' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\")",
"alarm(): time = record_audio(\"Enter the Time in the format HH:MM\") time = time.split(\":\")",
"'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd',",
"'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import",
"Of Home Affairs\": [\"<NAME>\"], #capital of States in India \"Capital Of Tripura\": [\"Agartala\"],",
"= matches['football'] else: cricket = \"no matches found\" return cricket def trans(): trans",
"more time\", \"Sorry! again\"], \"Who Created You\": [\"I was developed by Anandatirtha\", \"By",
"The National Game Of Scotland\": [\"Golf\"], \"What Is The National Game Of Iran\":",
"to someone who cares you\", \"Here are few tips to get rid of",
"== datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year ==",
"the remainder message:\") time = str(input(\"Enter the timing in format HH:MM\")) date =",
"Of Cuba\": [\"Baseball\"], \"What Is The National Game Of Pakistan\": [\"Field Hockey\"], \"What",
"[\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence",
"\"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister",
"- int(request_d[key + 1]) if value == '*': return int(request_d[key - 1]) *",
"Is The National Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r =",
"== datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3')",
"in Summer \": [\"Lacrosse\"], \"What Is The National Game Of Canada in Winter\":",
"while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date ==",
"weather_report responses = { \"Hey Alex\": [\"Your bot is activating...\",\" Bot is Launcing",
"True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day",
"Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief",
"\"By Anandatirtha\", \"I was developed by Anandatirtha as a demo bot\"], \"What Is",
"sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string,",
"timing in format HH:MM\")) date = str(input(\"Enter the remainder date in format DD/MM/YYYY\"))",
"Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message =",
"match_invoked == 'Football': cricket = matches['football'] else: cricket = \"no matches found\" return",
"Your Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\",",
"Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone()",
"\"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I can't get you\", \"sorry",
"return int(request_d[key - 1]) - int(request_d[key + 1]) if value == '*': return",
"Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha as a demo bot\"], \"What",
"get rid of stress:\\n 1) Listen some melody songs \\n 2) Exercise regularly",
"Have Cold\": [\"Sad to har from you\", \"Please, take rest from you\", \"Properly",
"respond(message): if message in responses: bot_message = random.choice(responses[message]) elif 'Search' in message: search",
"Remainder_message, duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download()",
"from mental health professional\\n \" \"4) Be positive\"], \"I Feel Bored\": [\"Here Some",
"in responses: bot_message = random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify the",
"message == \"Headlines\": bot_message = news_scrap() elif message == \"Live Score\": bot_message =",
"\"{0}\" user_template = \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if",
"value == '/': return int(request_d[key - 1]) / int(request_d[key + 1]) def person_name(text):",
"from bs4 import BeautifulSoup import requests import re import nltk from googletrans import",
"1) Make time for hobbies\\n 2) Avoid using Mobile Phone \\n 3) Get",
"sentences=2) elif message == \"Set An Remainder\": bot_message = remainder() elif message ==",
"alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute",
"from mental health professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here are some",
"[\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry",
"'' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\") return",
"States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of",
"i + 3 <= len(name)-1 and name[i].lower == 'who' and name[i+1].lower == 'is':",
"Bhutan\": [\" Archery\"], \"What Is The National Game Of Sri Lanka\": [\"Volley ball\"],",
"def respond(message): if message in responses: bot_message = random.choice(responses[message]) elif 'Search' in message:",
"= sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask) audio = r.listen(source) data",
"#national games \"What Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The",
"if value == '*': return int(request_d[key - 1]) * int(request_d[key + 1]) if",
"in the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating",
"= requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The",
"webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What you have to compute\") bot_message",
"Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\":",
"Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as",
"\"Consult doctor before it becomes complicated\"], \"Symptoms For Cold\": [\"Here are results \\n",
"'+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time = str(input(\"Enter",
"\"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister",
"Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of",
"Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital",
"The National Game Of Iran\": [\"Wrestling\"], \"What Is The National Game Of Hungary\":",
"Afternoon after your great meal\", \"Good Afternoon don't forget to check notifications\"], \"Good",
"The National Game Of Canada in Summer \": [\"Lacrosse\"], \"What Is The National",
"random import speech_recognition as sr import datetime import calendar import time import webbrowser",
"message: request_d[i] = req i = i + 1 for key,value in request_d.items():",
"\"Good Afternoon don't forget to check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night",
"'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def current_time():",
"11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected members",
"\"I can't tell you how I enjoyed hearing from you\"], \"I Feel Stressed\":",
"Game Of Canada in Summer \": [\"Lacrosse\"], \"What Is The National Game Of",
"[\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar",
"Night we will meet Next day\"], \"What Is Today Date\": [date_and_time()], \"What Is",
"[\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief",
"of me\", \"Thanks for making me feel special on my birthday\", \"I can't",
"remainder() elif message == \"Set An Alarm\": bot_message = alarm() elif message ==",
"alarmHour = alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute",
"Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough",
"\"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of",
"meal\", \"Good Afternoon don't forget to check notifications\"], \"Good Night\": [\"Good Night\", \"Good",
"+ int(request_d[key + 1]) if value == '-': return int(request_d[key - 1]) -",
"common cold may include cough, sore throat, low-grade fever, nasal congestion, runny nose,",
"def melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager():",
"[\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister",
"message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set An",
"'14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th',",
"article.text def sport_score(): import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the game",
"elif match_invoked == 'Football': cricket = matches['football'] else: cricket = \"no matches found\"",
"Sabha\": [\"Selected by elected members of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"],",
"\"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister",
"National Game Of Pakistan\": [\"Field Hockey\"], \"What Is The National Game Of Brazil\":",
"the word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message == \"Find",
"the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n",
"Game Of Canada in Winter\": [\"Ice Hockey\"], \"What Is The National Game Of",
"r.listen(source) data = '' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError():",
"= win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url =",
"import playsound import os import win10toast from bs4 import BeautifulSoup import requests import",
"= random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday",
"alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year",
"professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here are some tips to get",
"Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions",
"2) Get more sleep \\n 3)Talk to someone who cares you\", \"Here are",
"Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital",
"1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000)",
"def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask) audio",
"songs\", \"I tired to play music but vain\", \"Sleep well\"], # Medical field",
"Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"],",
"medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms For Cold\": [\"Here are results",
"Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister",
"or word to be translated:\") source = record_audio(\"From Languages:\") source = source.lower() source",
"import os import win10toast from bs4 import BeautifulSoup import requests import re import",
"bot_message def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month",
"National Game Of Hungary\": [\" Water Polo\"], \"What Is The National Game Of",
"url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\"",
"and rest\", \"Follow these tips:\\n 1) Make time for hobbies\\n 2) Avoid using",
"Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"],",
"matches found\" return cricket def trans(): trans = Translator() text = record_audio(\"Specify the",
"alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm =",
"value == '-': return int(request_d[key - 1]) - int(request_d[key + 1]) if value",
"= requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in soup.find_all('p'):",
"\\n 1. Wash your hands properly \\n 2. Disinfect your stuff \\n 3.",
"Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\":",
"1]) if value == '/': return int(request_d[key - 1]) / int(request_d[key + 1])",
"source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2] t =",
"was developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha as a",
"melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter the name of",
"Of Rajya Sabha\": [\"Selected by elected members of Legislative Assembly\"], \"Current Prime Minister",
"mouth \\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4)",
"Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"],",
"Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\":",
"= sport_score() elif message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message",
"Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief",
"Date\": [date_and_time()], \"What Is The Month\": [month()], \"What Is The Time Now\": [",
"To Relieve Stress\": [\"Here are some tips to get rid of stress:\\n 1)",
"\"What Is The Month\": [month()], \"What Is The Time Now\": [ time.ctime()], \"Thank",
"req i = i + 1 for key,value in request_d.items(): if value ==",
"import sports from newspaper import Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template",
"[\"Golf\"], \"What Is The National Game Of Iran\": [\"Wrestling\"], \"What Is The National",
"Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief",
"import re import nltk from googletrans import Translator import sports from newspaper import",
"\"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in {0} is",
"and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and",
"cold may include cough, sore throat, low-grade fever, nasal congestion, runny nose, and",
"message == \"Wikipedia\": bot_message = scrap() elif message == \"Translate\": bot_message = trans()",
"[\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon",
"i in range(0, len(name)): if i + 3 <= len(name)-1 and name[i].lower ==",
"\"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of",
"respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message = random.choice(responses[message]) elif 'Search'",
"- 1]) / int(request_d[key + 1]) def person_name(text): name = text.split() for i",
"Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"],",
"'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th',",
"Is Your Birthday\": [\"It's on June 2nd 2020\", \"It's on June 2nd 2020",
"Is The National Game Of Iran\": [\"Wrestling\"], \"What Is The National Game Of",
"elif message == \"Set An Alarm\": bot_message = alarm() elif message == \"Play",
"[\"Welcome\", \"It's nice to hear from you\"], \"When Is Your Birthday\": [\"It's on",
"'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def",
"def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message",
"message == \"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\": bot_message = scrap()",
"Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of",
"2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak you",
"Of United States\": [\"Baseball\"], \"What Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What",
"[\"Shillong\"], #national games \"What Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is",
"= \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message == \"Find Location\": location =",
"don't forget to check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !! Sweet",
"Cuba\": [\"Baseball\"], \"What Is The National Game Of Pakistan\": [\"Field Hockey\"], \"What Is",
"== \"Calculate\": m = record_audio(\"What you have to compute\") bot_message = calculate(m) elif",
"today\"], \"Default\": [\"I can't get you\", \"sorry one more time\", \"Sorry! again\"], \"Who",
"trans = Translator() text = record_audio(\"Specify the sentence or word to be translated:\")",
"\"Calculate\": m = record_audio(\"What you have to compute\") bot_message = calculate(m) elif 'who",
"7) Fever\"], \"How To Prevent From Cold\": [\"Here are some Prevention methods \\n",
"key,value in request_d.items(): if value == '+': return int(request_d[key - 1]) + int(request_d[key",
"Mobile Phone \\n 3) Get advise from mental health professional\\n \" \"4) Be",
"time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention PM or AM\"))",
"\"Who Created You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed",
"' ', text) text = re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return",
"[\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha as",
"The National Game Of Bhutan\": [\" Archery\"], \"What Is The National Game Of",
"= time.ctime() return local_time def calculate(message): message = message.split() i = 0 request_d",
"Bored\": [\"Here Some Melody songs\", \"I tired to play music but vain\", \"Sleep",
"0 request_d = {} for req in message: request_d[i] = req i =",
"by Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha as a demo bot\"],",
"= person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\": bot_message",
"[\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\":",
"name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif message ==",
"1]) if value == '*': return int(request_d[key - 1]) * int(request_d[key + 1])",
"Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def send_message(message): response",
"meet Next day\"], \"What Is Today Date\": [date_and_time()], \"What Is The Month\": [month()],",
"Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief",
"= \"\" for paragraph in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', '",
"<= len(name)-1 and name[i].lower == 'who' and name[i+1].lower == 'is': return name[i+2]+ '",
"much for thinking of me\", \"Thanks for making me feel special on my",
"Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of",
"[\" Archery\"], \"What Is The National Game Of Sri Lanka\": [\"Volley ball\"], \"What",
"Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of",
"url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def",
"= playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter the name of place\")",
"= desti[0:2] t = trans.translate( text, src=source, dest=desti ) return t.text def scrap():",
"Be positive\"], \"I Feel Bored\": [\"Here Some Melody songs\", \"I tired to play",
"translated:\") source = record_audio(\"From Languages:\") source = source.lower() source = source[0:2] desti =",
"check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !! Sweet dreams\", \"Good Night",
"Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"],",
"Sweet dreams\", \"Good Night we will meet Next day\"], \"What Is Today Date\":",
"import speech_recognition as sr import datetime import calendar import time import webbrowser import",
"datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message",
"datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day = now.day",
"month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',",
"\"Properly take medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms For Cold\": [\"Here",
"one more time\", \"Sorry! again\"], \"Who Created You\": [\"I was developed by Anandatirtha\",",
"results \\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body",
"sports from newspaper import Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template =",
"cricket def trans(): trans = Translator() text = record_audio(\"Specify the sentence or word",
"Of Canada in Winter\": [\"Ice Hockey\"], \"What Is The National Game Of Spain\":",
"eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle",
"date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour = int(time[0])",
"\" \"Symptoms of the common cold may include cough, sore throat, low-grade fever,",
"[date_and_time()], \"What Is The Month\": [month()], \"What Is The Time Now\": [ time.ctime()],",
"Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of Argentina\": [\"Pato\"], \"What Is",
"\": [\"Lacrosse\"], \"What Is The National Game Of Canada in Winter\": [\"Ice Hockey\"],",
"you\", \"sorry one more time\", \"Sorry! again\"], \"Who Created You\": [\"I was developed",
"upper respiratory tract infection. \" \"Symptoms of the common cold may include cough,",
"\"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I can't get you\", \"sorry one",
"Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\":",
"datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap():",
"Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\":",
"Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of Argentina\": [\"Pato\"], \"What",
"\"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is The National Game Of Bangladesh\":",
"elif message == \"Translate\": bot_message = trans() elif message == \"Headlines\": bot_message =",
"is Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning have a great day\",",
"place\") search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup",
"timings = str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute",
"5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent From Cold\": [\"Here",
"10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do",
"Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"],",
"i = 0 request_d = {} for req in message: request_d[i] = req",
"and sneezing.\"], \"I Have Cold\": [\"Sad to har from you\", \"Please, take rest",
"and mouth \\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches",
"\"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States in India \"Capital Of Tripura\":",
"you have to compute\") bot_message = calculate(m) elif 'who is' in message: person",
"\"\" for paragraph in soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ',",
"Hockey\"], \"What Is The National Game Of England\": [\"Cricket\"], \"What Is The National",
"'9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st',",
"\"Here are few tips to get rid of stress:\\n 1) Listen some melody",
"lang='en') r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file)",
"Sri Lanka\": [\"Volley ball\"], \"What Is The National Game Of Turkey\": [\"Oil Wrestling\"],",
"the timing in format HH:MM\")) date = str(input(\"Enter the remainder date in format",
"newspaper import Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def",
"complicated\"], \"Symptoms For Cold\": [\"Here are results \\n 1)Runny nose \\n 2)Sore throat",
"demo bot\"], \"What Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)],",
"hearing from you\"], \"I Feel Stressed\": [\"Here are some tips to get rid",
"[\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\":",
"[\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\":",
"as source: if ask: alex_speak(ask) audio = r.listen(source) data = '' try: data",
"' ', text) text = re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', '",
"soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature",
"Feel Bored\": [\"Here Some Melody songs\", \"I tired to play music but vain\",",
"import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter the",
"vain\", \"Sleep well\"], # Medical field questions \"Cold\": [\"The common cold is medically",
"is medically referred to as a viral upper respiratory tract infection. \" \"Symptoms",
"cough, sore throat, low-grade fever, nasal congestion, runny nose, and sneezing.\"], \"I Have",
"hands properly \\n 2. Disinfect your stuff \\n 3. Avoid touching your eyes,nose",
"else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now = datetime.datetime.now() today =",
"[\"Selected by elected members of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief",
"request_d[i] = req i = i + 1 for key,value in request_d.items(): if",
"= int(date[1]) rem_year = int(date[2]) if timings == \"pm\": alarmHour = alarmHour +",
"elif message == \"Calculate\": m = record_audio(\"What you have to compute\") bot_message =",
"Bot is Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning have a great",
"1]) + int(request_d[key + 1]) if value == '-': return int(request_d[key - 1])",
"Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\":",
"format HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module =",
"temperature in {0} is {1}\".format(place, update) return weather_report responses = { \"Hey Alex\":",
"text = re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', ' ', text) sentences",
"timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0]) rem_month = int(date[1])",
"sports.all_matches() match_invoked = record_audio(\"Enter the game you want to search\") if match_invoked ==",
"again\"], \"Who Created You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I was",
"Anandatirtha\", \"I was developed by Anandatirtha as a demo bot\"], \"What Is Your",
"= matches['cricket'] elif match_invoked == 'Football': cricket = matches['football'] else: cricket = \"no",
"ask: alex_speak(ask) audio = r.listen(source) data = '' try: data = r.recognize_google(audio) except",
"well\"], # Medical field questions \"Cold\": [\"The common cold is medically referred to",
"3)Talk to someone who cares you\", \"Here are few tips to get rid",
"The National Game Of India\": [\" Field Hockey\"], \"What Is The National Game",
"googletrans import Translator import sports from newspaper import Article bot_name = \"Rag2020\" bot_template",
"Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is The",
"questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by",
"regularly \\n 3) Get enough sleep and rest\", \"Follow these tips:\\n 1) Make",
"i = i + 1 for key,value in request_d.items(): if value == '+':",
"= webbrowser.get().open(url) elif message == \"Find Location\": location = record_audio(\"City name\") url =",
"= record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message",
"bot_message = weather_manager() elif message == \"Wikipedia\": bot_message = scrap() elif message ==",
"return cricket def trans(): trans = Translator() text = record_audio(\"Specify the sentence or",
"sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time in",
"date in format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter",
"= re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', ' ', text) text =",
"== 'who' and name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3] def remainder():",
"return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt')",
"Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good",
"Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\":",
"National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The National Game Of India\":",
"\"I was developed by Anandatirtha as a demo bot\"], \"What Is Your Name\":",
"Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"],",
"+ 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from",
"\" \"4) Be positive\"], \"I Feel Bored\": [\"Here Some Melody songs\", \"I tired",
"har from you\", \"Please, take rest from you\", \"Properly take medicines\", \"Consult doctor",
"import random import speech_recognition as sr import datetime import calendar import time import",
"time.ctime() return local_time def calculate(message): message = message.split() i = 0 request_d =",
"= date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour =",
"text) text = re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def",
"\"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of",
"of place\") search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url)",
"play music but vain\", \"Sleep well\"], # Medical field questions \"Cold\": [\"The common",
"= req i = i + 1 for key,value in request_d.items(): if value",
"Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source:",
"name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after",
"= ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']",
"= Translator() text = record_audio(\"Specify the sentence or word to be translated:\") source",
"you\"], \"I Feel Stressed\": [\"Here are some tips to get rid of stress:\\n",
"if ask: alex_speak(ask) audio = r.listen(source) data = '' try: data = r.recognize_google(audio)",
"Polo\"], \"What Is The National Game Of Cuba\": [\"Baseball\"], \"What Is The National",
"\"pm\": alarmHour = alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour and",
"in format HH:MM\")) date = str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time",
"= datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day =",
"\"Today is \"+weekday + ' '+month_list[month-1]+' the ' + Numbers[day-1] def month(): now",
"datetime.datetime.now() month = now.month month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July',",
"Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"],",
"[\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister",
"HH:MM\")) date = str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time = time.split(\":\")",
"+ 1]) if value == '/': return int(request_d[key - 1]) / int(request_d[key +",
"\"Set An Remainder\": bot_message = remainder() elif message == \"Set An Alarm\": bot_message",
"' ', text) text = re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', '",
"feel special on my birthday\", \"I can't tell you how I enjoyed hearing",
"\"Sleep well\"], # Medical field questions \"Cold\": [\"The common cold is medically referred",
"return t.text def scrap(): search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r",
"= '' try: data = r.recognize_google(audio) except sr.UnknownValueError(): alex_speak(\"Error\") except sr.RequestError(): alex_speak(\"Error 1\")",
"Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of",
"elif message == \"Wikipedia\": bot_message = scrap() elif message == \"Translate\": bot_message =",
"elif message == \"Headlines\": bot_message = news_scrap() elif message == \"Live Score\": bot_message",
"aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1) Scratchy sensation",
"' ', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter",
"congestion, runny nose, and sneezing.\"], \"I Have Cold\": [\"Sad to har from you\",",
"time\", \"Sorry! again\"], \"Who Created You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\",",
"search = record_audio(\"Enter the word\") url = f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup =",
"\"What Is The National Game Of Russia\": [\"Bandy\"], \"What Is The National Game",
"= melody() elif message == \"Weather\": bot_message = weather_manager() elif message == \"Wikipedia\":",
"bot_message = scrap() elif message == \"Translate\": bot_message = trans() elif message ==",
"True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import playsound",
"soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in {0} is {1}\".format(place, update) return",
"Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal",
"{} for req in message: request_d[i] = req i = i + 1",
"Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political questions \"The 11Th President Of",
"sr import datetime import calendar import time import webbrowser import wikipedia from gtts",
"or PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date =",
"\"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief",
"import time import webbrowser import wikipedia from gtts import gTTS import playsound import",
"you\", \"Properly take medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms For Cold\":",
"\"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"],",
"2. Disinfect your stuff \\n 3. Avoid touching your eyes,nose and mouth \\n",
"str(input(\"Enter the timing in format HH:MM\")) date = str(input(\"Enter the remainder date in",
"Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of",
"[\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\":",
"\"4) Be positive\"], \"How To Relieve Stress\": [\"Here are some tips to get",
"\"Find Location\": location = record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message",
"rem_date = int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if timings == \"pm\":",
"time import webbrowser import wikipedia from gtts import gTTS import playsound import os",
"person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\": bot_message =",
"/ int(request_d[key + 1]) def person_name(text): name = text.split() for i in range(0,",
"Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief",
"[\"Bandy\"], \"What Is The National Game Of Canada in Summer \": [\"Lacrosse\"], \"What",
"how I enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here are some tips",
"National Game Of Brazil\": [\"Football\"], \"What Is The National Game Of Russia\": [\"Bandy\"],",
"in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry",
"The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game Of Argentina\":",
"'Football': cricket = matches['football'] else: cricket = \"no matches found\" return cricket def",
"re import nltk from googletrans import Translator import sports from newspaper import Article",
"is' in message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message ==",
"[\"<NAME>\"], \"Chief Minister Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief",
"1]) / int(request_d[key + 1]) def person_name(text): name = text.split() for i in",
"\"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of",
"a great day\", \"great day ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\":",
"source.lower() source = source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower() desti =",
"gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file)",
"playsound import os import win10toast from bs4 import BeautifulSoup import requests import re",
"if value == '+': return int(request_d[key - 1]) + int(request_d[key + 1]) if",
"Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"], \"Chief",
"if message in responses: bot_message = random.choice(responses[message]) elif 'Search' in message: search =",
"name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time",
"[\"Your bot is activating...\",\" Bot is Launcing 3 2 1\"], \"Good Morning\": [\"Good",
"\"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of",
"import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import playsound",
"Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games",
"return article.text def sport_score(): import sports matches = sports.all_matches() match_invoked = record_audio(\"Enter the",
"[\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of",
"to har from you\", \"Please, take rest from you\", \"Properly take medicines\", \"Consult",
"str(input(\"Enter AM or PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1])",
"Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\":",
"Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar",
"Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief",
"record_audio(\"From Languages:\") source = source.lower() source = source[0:2] desti = record_audio(\"To Languages:\") desti",
"return bot_message def date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()]",
"Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What Is The National Game",
"get rid of stress:\\n 1) Avoid Caffine and Alcohol \\n 2) Get more",
"Alcohol \\n 2) Get more sleep \\n 3)Talk to someone who cares you\",",
"[\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of",
"\"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"],",
"= 0 request_d = {} for req in message: request_d[i] = req i",
"'23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] return \"Today is \"+weekday",
"me\", \"Thanks for making me feel special on my birthday\", \"I can't tell",
"nltk from googletrans import Translator import sports from newspaper import Article bot_name =",
"name of place\") search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r =",
"An Remainder\": bot_message = remainder() elif message == \"Set An Alarm\": bot_message =",
"alarmHour + 12 while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute:",
"Archery\"], \"What Is The National Game Of Sri Lanka\": [\"Volley ball\"], \"What Is",
"sneezing.\"], \"I Have Cold\": [\"Sad to har from you\", \"Please, take rest from",
"in message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message == \"Set",
"Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports matches =",
"of the common cold may include cough, sore throat, low-grade fever, nasal congestion,",
"after your great meal\", \"Good Afternoon don't forget to check notifications\"], \"Good Night\":",
"Throat Pain\": [\"1) Scratchy sensation in the throat \\n 2)Difficulty in Swallowing \\n",
"= record_audio(\"Specify the sentence or word to be translated:\") source = record_audio(\"From Languages:\")",
"== \"Live Score\": bot_message = sport_score() elif message == \"Exit\": breakpoint() else: bot_message",
"in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update",
"[\"<NAME>\"], \"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister",
"2) Avoid using Mobile Phone \\n 3) Get advise from mental health professional\\n",
"Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief",
"import wikipedia from gtts import gTTS import playsound import os import win10toast from",
"you\", \"Here are few tips to get rid of stress:\\n 1) Listen some",
"Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister Of Rajasthan\": [\"<NAME>\"],",
"article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports",
"= datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month day = now.day month_list =",
"rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message",
"The National Game Of Canada in Winter\": [\"Ice Hockey\"], \"What Is The National",
"you\"], \"When Is Your Birthday\": [\"It's on June 2nd 2020\", \"It's on June",
"The National Game Of Brazil\": [\"Football\"], \"What Is The National Game Of Russia\":",
"of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\":",
"\"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"], \"Ministry Of",
"dreams\", \"Good Night we will meet Next day\"], \"What Is Today Date\": [date_and_time()],",
"DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM or PM\"))",
"'6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th',",
"r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text weather_report =",
"[\"Sad to har from you\", \"Please, take rest from you\", \"Properly take medicines\",",
"trans(): trans = Translator() text = record_audio(\"Specify the sentence or word to be",
"For Cold\": [\"Here are results \\n 1)Runny nose \\n 2)Sore throat \\n 3)Cough",
"\"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief Minister Of Nagaland\": [\"<NAME>\"], \"Chief Minister Of",
"\"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response))",
"from you\"], \"I Feel Stressed\": [\"Here are some tips to get rid of",
"advise from mental health professional\\n \" \"4) Be positive\"], \"How To Relieve Stress\":",
"gTTS import playsound import os import win10toast from bs4 import BeautifulSoup import requests",
"\"I Have Cold\": [\"Sad to har from you\", \"Please, take rest from you\",",
"+search bot_message = webbrowser.get().open(url) elif message == \"Find Location\": location = record_audio(\"City name\")",
"'/': return int(request_d[key - 1]) / int(request_d[key + 1]) def person_name(text): name =",
"str(input(\"Mention PM or AM\")) timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour =",
"respiratory tract infection. \" \"Symptoms of the common cold may include cough, sore",
"1 for key,value in request_d.items(): if value == '+': return int(request_d[key - 1])",
"alex_speak(bot_template.format(response)) def respond(message): if message in responses: bot_message = random.choice(responses[message]) elif 'Search' in",
"\"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\": [\"<NAME>\"], \"Chief Minister",
"Of India\": [\" Field Hockey\"], \"What Is The National Game Of England\": [\"Cricket\"],",
"melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place",
"melody songs \\n 2) Exercise regularly \\n 3) Get enough sleep and rest\",",
"Of Sikkim\": [\"<NAME>\"], \"Chief Minister Of Tamil Nadu\": [\"<NAME>\"], \"Chief Minister Of Telangana\":",
"at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak you so",
"bot_message = remainder() elif message == \"Set An Alarm\": bot_message = alarm() elif",
"= timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour + 12 while True:",
"{ \"Hey Alex\": [\"Your bot is activating...\",\" Bot is Launcing 3 2 1\"],",
"message = message.split() i = 0 request_d = {} for req in message:",
"Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief",
"before it becomes complicated\"], \"Symptoms For Cold\": [\"Here are results \\n 1)Runny nose",
"[\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected members of Legislative Assembly\"], \"Current",
"in format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM",
"in request_d.items(): if value == '+': return int(request_d[key - 1]) + int(request_d[key +",
"if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm",
"Of Pakistan\": [\"Field Hockey\"], \"What Is The National Game Of Brazil\": [\"Football\"], \"What",
"f\"https://en.wikipedia.org/wiki/{search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph",
"elif message == \"Play Me A Song\": bot_message = melody() elif message ==",
"def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the timing",
"\"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister",
"[\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of Punjab\": [\"<NAME>\"], \"Chief Minister",
"[\"Volley ball\"], \"What Is The National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is",
"Get more sleep \\n 3)Talk to someone who cares you\", \"Here are few",
"+'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What you have",
"= scrap() elif message == \"Translate\": bot_message = trans() elif message == \"Headlines\":",
"text = record_audio(\"Specify the sentence or word to be translated:\") source = record_audio(\"From",
"I enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here are some tips to",
"Pain\": [\"1) Scratchy sensation in the throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"],",
"f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\")",
"Today Date\": [date_and_time()], \"What Is The Month\": [month()], \"What Is The Time Now\":",
"== \"Play Me A Song\": bot_message = melody() elif message == \"Weather\": bot_message",
"Hockey\"], \"What Is The National Game Of Brazil\": [\"Football\"], \"What Is The National",
"day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\":",
"Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\": [\"Zoramthanga\"], \"Chief",
"remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the timing in",
"music but vain\", \"Sleep well\"], # Medical field questions \"Cold\": [\"The common cold",
"Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th',",
"\"Wikipedia\": bot_message = scrap() elif message == \"Translate\": bot_message = trans() elif message",
"\"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\":",
"mental health professional\\n \" \"4) Be positive\"], \"How To Relieve Stress\": [\"Here are",
"time = time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings",
"'2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th',",
"Night\", \"Good Night !! Sweet dreams\", \"Good Night we will meet Next day\"],",
"[\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\":",
"Is Your Name\": [\"My name is {0}\".format(bot_name), \"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good",
"\"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of",
"enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here are some tips to get",
"\"It's on June 2nd 2020 at Rag labs\"], \"Happy Birthday Rag\": [\"Thank you",
"on my birthday\", \"I can't tell you how I enjoyed hearing from you\"],",
"Be positive\"], \"Feels Stressed\": [\"Here are some tips to get rid of stress:\\n",
"#Political questions \"The 11Th President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected",
"[\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\":",
"2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2) Burping \\n",
"datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from",
"t = trans.translate( text, src=source, dest=desti ) return t.text def scrap(): search =",
"+ ' '+month_list[month-1]+' the ' + Numbers[day-1] def month(): now = datetime.datetime.now() month",
"'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th',",
"= random.randint(1, 10000000) audio_file = 'audio-' +str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can",
"tips to get rid of stress:\\n 1) Listen some melody songs \\n 2)",
"+ location +'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What",
"3) Get enough sleep and rest\", \"Follow these tips:\\n 1) Make time for",
"Of Gujarat\": [\"Gandhinagar\"], \"Capital Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of",
"format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM or",
"word to be translated:\") source = record_audio(\"From Languages:\") source = source.lower() source =",
"== '-': return int(request_d[key - 1]) - int(request_d[key + 1]) if value ==",
"'who is' in message: person = person_name(message) bot_message = wikipedia.summary(person, sentences=2) elif message",
"soup.find_all('p'): text += paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+',",
"India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected members of Legislative Assembly\"],",
"= f\"https://www.google.com/search?&q={search}\" r = requests.get(url) soup = BeautifulSoup(r.text, \"html.parser\") update = soup.find(\"div\", class_=\"BNeawe\").text",
"2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7)",
"= calculate(m) elif 'who is' in message: person = person_name(message) bot_message = wikipedia.summary(person,",
"States\": [\"Baseball\"], \"What Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The",
"{0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great meal\", \"Good Afternoon",
"', text) sentences = nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the",
"playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return",
"\\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How",
"National Game Of Canada in Winter\": [\"Ice Hockey\"], \"What Is The National Game",
"== datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute and rem_date == datetime.datetime.now().day and rem_month ==",
"Of Uttaranchal\": [\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital",
"name[i].lower == 'who' and name[i+1].lower == 'is': return name[i+2]+ ' '+ name[i+3] def",
"rem_year = int(date[2]) if timings == \"pm\": alarmHour = alarmHour + 12 while",
"Minister Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of",
"', text) text = re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', ' ',",
"in message: request_d[i] = req i = i + 1 for key,value in",
"Afternoon\", \"Good Afternoon after your great meal\", \"Good Afternoon don't forget to check",
"day\"], \"What Is Today Date\": [date_and_time()], \"What Is The Month\": [month()], \"What Is",
"\"Call me {0}\".format(bot_name)], \"Good Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great meal\",",
"more sleep \\n 3)Talk to someone who cares you\", \"Here are few tips",
"day\", \"great day ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\",",
"Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"],",
"1) Listen some melody songs \\n 2) Exercise regularly \\n 3) Get enough",
"\"Capital Of Assam\": [\"Dispur\"], \"Capital Of Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\":",
"\"html.parser\") text = \"\" for paragraph in soup.find_all('p'): text += paragraph.text text =",
"notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article",
"int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if timings ==",
"== \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return bot_message def date_and_time(): now =",
"Languages:\") source = source.lower() source = source[0:2] desti = record_audio(\"To Languages:\") desti =",
"'-': return int(request_d[key - 1]) - int(request_d[key + 1]) if value == '*':",
"= random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify the word\") url =",
"Pradesh\": [\"<NAME>\"], \"Chief Minister Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of",
"def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article = Article(url) article.download() article.parse() nltk.download('punkt') article.nlp() return",
"4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of",
"Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of",
"in {0} is {1}\".format(place, update) return weather_report responses = { \"Hey Alex\": [\"Your",
"by elected members of Legislative Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister",
"request_d.items(): if value == '+': return int(request_d[key - 1]) + int(request_d[key + 1])",
"time.split(\":\") date = date.split(\"/\") timings = str(input(\"Enter AM or PM\")) timings = timings.lower()",
"except sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r",
"re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+', ' ', text) sentences = nltk.sent_tokenize(text)",
"England\": [\"Cricket\"], \"What Is The National Game Of Scotland\": [\"Golf\"], \"What Is The",
"record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message ==",
"date_and_time(): now = datetime.datetime.now() today = datetime.datetime.today() weekday = calendar.day_name[today.weekday()] month = now.month",
"\"Translate\": bot_message = trans() elif message == \"Headlines\": bot_message = news_scrap() elif message",
"'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time = time.ctime() return",
"= toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return notification_message def news_scrap(): url = 'https://www.indiatoday.in/top-stories' article =",
"update = soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in {0} is {1}\".format(place,",
"= message.split() i = 0 request_d = {} for req in message: request_d[i]",
"with sr.Microphone() as source: if ask: alex_speak(ask) audio = r.listen(source) data = ''",
"Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected members of Legislative",
"Make time for hobbies\\n 2) Avoid using Mobile Phone \\n 3) Get advise",
"\"Feels Stressed\": [\"Here are some tips to get rid of stress:\\n 1) Avoid",
"Game Of Hungary\": [\" Water Polo\"], \"What Is The National Game Of Cuba\":",
"search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif",
"[\" Water Polo\"], \"What Is The National Game Of Cuba\": [\"Baseball\"], \"What Is",
"def person_name(text): name = text.split() for i in range(0, len(name)): if i +",
"= source.lower() source = source[0:2] desti = record_audio(\"To Languages:\") desti = desti.lower() desti",
"record_audio(\"Enter the name of place\") search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\"",
"Of Jammu and Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister",
"Scotland\": [\"Golf\"], \"What Is The National Game Of Iran\": [\"Wrestling\"], \"What Is The",
"+= paragraph.text text = re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', ' ',",
"\\n 2)Sore throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n",
"= re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', ' ', text) text =",
"Afternoon don't forget to check notifications\"], \"Good Night\": [\"Good Night\", \"Good Night !!",
"Minister Of Assam\": [\"<NAME>\"], \"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\":",
"alarm def melody(): from playsound import playsound melody = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def",
"[\"<NAME>\"], \"Chief Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister",
"are few tips to get rid of stress:\\n 1) Listen some melody songs",
"Cold\": [\"Sad to har from you\", \"Please, take rest from you\", \"Properly take",
"Afternoon\": [\"Good Afternoon\", \"Good Afternoon after your great meal\", \"Good Afternoon don't forget",
"import Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def send_message(message):",
"Morning\": [\"Good Morning have a great day\", \"great day ahead\", \"have a wonderful",
"\"4) Be positive\"], \"I Feel Bored\": [\"Here Some Melody songs\", \"I tired to",
"touching your eyes,nose and mouth \\n 4. Stay away\"], \"Symptoms For Fever\": [\"1)Sweating",
"== 'Cricket': cricket = matches['cricket'] elif match_invoked == 'Football': cricket = matches['football'] else:",
"nltk.download('punkt') article.nlp() return article.text def sport_score(): import sports matches = sports.all_matches() match_invoked =",
"Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi there\", \"what's special today\"], \"Default\": [\"I can't",
"Get enough sleep and rest\", \"Follow these tips:\\n 1) Make time for hobbies\\n",
"= {} for req in message: request_d[i] = req i = i +",
"as sr import datetime import calendar import time import webbrowser import wikipedia from",
"' + Numbers[day-1] def month(): now = datetime.datetime.now() month = now.month month_list =",
"\"Chief Minister Of Odisha\": [\"<NAME>\"], \"Chief Minister Of Puducherry\": [\"<NAME>\"], \"Chief Minister Of",
"\\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent From Cold\": [\"Here are some",
"Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital",
"Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"],",
"= wikipedia.summary(person, sentences=2) elif message == \"Set An Remainder\": bot_message = remainder() elif",
"4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"], \"How To Prevent From",
"(sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time in the format HH:MM\") time",
"Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of",
"bot_message = sport_score() elif message == \"Exit\": breakpoint() else: bot_message = random.choice(responses[\"Default\"]) return",
"rem_month = int(date[1]) rem_year = int(date[2]) if timings == \"pm\": alarmHour = alarmHour",
"infection. \" \"Symptoms of the common cold may include cough, sore throat, low-grade",
"text, src=source, dest=desti ) return t.text def scrap(): search = record_audio(\"Enter the word\")",
"Me A Song\": bot_message = melody() elif message == \"Weather\": bot_message = weather_manager()",
"['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return",
"\"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak you so much for thinking",
"[\"Here are some Prevention methods \\n 1. Wash your hands properly \\n 2.",
"\"4) Be positive\"], \"Feels Stressed\": [\"Here are some tips to get rid of",
"now.month day = now.day month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July',",
"= record_audio(\"City name\") url = \"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif",
"'17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th',",
"The National Game Of Sri Lanka\": [\"Volley ball\"], \"What Is The National Game",
"= trans() elif message == \"Headlines\": bot_message = news_scrap() elif message == \"Live",
"\"What Is The National Game Of Bangladesh\": [\"Kabaddi\"], \"What Is The National Game",
"National Game Of Bhutan\": [\" Archery\"], \"What Is The National Game Of Sri",
"[\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\"",
"Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of",
"desti = desti.lower() desti = desti[0:2] t = trans.translate( text, src=source, dest=desti )",
"url = \"https://google.com/search?q=\" +search bot_message = webbrowser.get().open(url) elif message == \"Find Location\": location",
"2) Exercise regularly \\n 3) Get enough sleep and rest\", \"Follow these tips:\\n",
"'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers =",
"record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the timing in format HH:MM\")) date",
"message in responses: bot_message = random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify",
"[\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister",
"timings_module = timings_module.lower() if timings_module == \"pm\": alarmHour = alarmHour + 12 while",
"Of Canada in Summer \": [\"Lacrosse\"], \"What Is The National Game Of Canada",
"'is': return name[i+2]+ ' '+ name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder",
"def calculate(message): message = message.split() i = 0 request_d = {} for req",
"Is The National Game Of Canada in Winter\": [\"Ice Hockey\"], \"What Is The",
"= soup.find(\"div\", class_=\"BNeawe\").text weather_report = \"The current temperature in {0} is {1}\".format(place, update)",
"Is The National Game Of Scotland\": [\"Golf\"], \"What Is The National Game Of",
"+str(r)+'.mp4' tts.save(audio_file) print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\") while True:",
"advise from mental health professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here are",
"Game Of Brazil\": [\"Football\"], \"What Is The National Game Of Russia\": [\"Bandy\"], \"What",
"Of Gujarat\": [\"<NAME>\"], \"Chief Minister Of Haryana\": [\"<NAME>\"], \"Chief Minister Of Himachal Pradesh\":",
"some melody songs \\n 2) Exercise regularly \\n 3) Get enough sleep and",
"= nltk.sent_tokenize(text) return (sentences[0],sentences[1]) def alarm(): time = record_audio(\"Enter the Time in the",
"\"It's nice to hear from you\"], \"When Is Your Birthday\": [\"It's on June",
"\"Symptoms For Fever\": [\"1)Sweating 2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms",
"compute\") bot_message = calculate(m) elif 'who is' in message: person = person_name(message) bot_message",
"Of Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital",
"+ 1]) def person_name(text): name = text.split() for i in range(0, len(name)): if",
"print(audio_string) playsound.playsound(audio_file) os.remove(audio_file) alex_speak(\"What can I do for you\") while True: message =",
"name = text.split() for i in range(0, len(name)): if i + 3 <=",
"You\": [\"I was developed by Anandatirtha\", \"By Anandatirtha\", \"I was developed by Anandatirtha",
"Of Bihar\": [\"Patna\"], \"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\"",
"Of Delhi\": [\"<NAME>\"], \"Chief Minister Of Goa\": [\"<NAME>\"], \"Chief Minister Of Gujarat\": [\"<NAME>\"],",
"* int(request_d[key + 1]) if value == '/': return int(request_d[key - 1]) /",
"alarm() elif message == \"Play Me A Song\": bot_message = melody() elif message",
"re.sub(r'\\s+', ' ', text) text = re.sub(r'\\d', ' ', text) text = re.sub(r'\\s+',",
"An Alarm\": bot_message = alarm() elif message == \"Play Me A Song\": bot_message",
"\"https://google.ml/maps/place/\" + location +'/&' bot_message = webbrowser.get().open(url) elif message == \"Calculate\": m =",
"HH:MM\") time = time.split(\":\") alarmHour = int(time[0]) alarmMinute = int(time[1]) timings_module = str(input(\"Mention",
"health professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here are some tips to",
"the name of place\") search = f\"Weather in {place}\" url = f\"https://www.google.com/search?&q={search}\" r",
"Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"], \"Capital Of",
"- 1]) + int(request_d[key + 1]) if value == '-': return int(request_d[key -",
"class_=\"BNeawe\").text weather_report = \"The current temperature in {0} is {1}\".format(place, update) return weather_report",
"'12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th',",
"\"Capital Of Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of Uttaranchal\": [\"Dehradun\"],",
"National Game Of Scotland\": [\"Golf\"], \"What Is The National Game Of Iran\": [\"Wrestling\"],",
"scrap() elif message == \"Translate\": bot_message = trans() elif message == \"Headlines\": bot_message",
"[\"I can't get you\", \"sorry one more time\", \"Sorry! again\"], \"Who Created You\":",
"hobbies\\n 2) Avoid using Mobile Phone \\n 3) Get advise from mental health",
"while True: if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute: from playsound import",
"tell you how I enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here are",
"was developed by Anandatirtha as a demo bot\"], \"What Is Your Name\": [\"My",
"you want to search\") if match_invoked == 'Cricket': cricket = matches['cricket'] elif match_invoked",
"Home Affairs\": [\"<NAME>\"], #capital of States in India \"Capital Of Tripura\": [\"Agartala\"], \"Capital",
"National Game Of Spain\": [\"Bull Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with",
"\"Good Night we will meet Next day\"], \"What Is Today Date\": [date_and_time()], \"What",
"'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time = time.ctime() return local_time def",
"PM\")) timings = timings.lower() alarmHour = int(time[0]) alarmMinute = int(time[1]) rem_date = int(date[0])",
"\"Capital Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar & Jammu\"],",
"so much for thinking of me\", \"Thanks for making me feel special on",
"Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal",
"from googletrans import Translator import sports from newspaper import Article bot_name = \"Rag2020\"",
"Fighting\"], } def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source: if ask:",
"playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/nature-alarm-sounds.mp3') return melody def weather_manager(): place = record_audio(\"Enter the name of place\") search",
"Game Of India\": [\" Field Hockey\"], \"What Is The National Game Of England\":",
"sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask) audio = r.listen(source) data =",
"there\", \"what's special today\"], \"Default\": [\"I can't get you\", \"sorry one more time\",",
"time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice to hear from you\"], \"When Is Your",
"= record_audio(\"Enter the Time in the format HH:MM\") time = time.split(\":\") alarmHour =",
"Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\":",
"and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier() notification_message = toaster.show_toast(\"Pycharm\", Remainder_message, duration=10) return",
"\"no matches found\" return cricket def trans(): trans = Translator() text = record_audio(\"Specify",
"Is The National Game Of Bhutan\": [\" Archery\"], \"What Is The National Game",
"Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of",
"[\"Baseball\"], \"What Is The National Game Of Pakistan\": [\"Field Hockey\"], \"What Is The",
"'June', 'July', 'August', 'September', 'October', 'November', 'December'] Numbers = ['1st', '2nd', '3rd', '4th',",
"President Of India\": [\"<NAME>\"], \"Member Of Rajya Sabha\": [\"Selected by elected members of",
"Is The National Game Of United States\": [\"Baseball\"], \"What Is The National Game",
"day ahead\", \"have a wonderful day\", \"Good Morning\"], \"Hi\": [\"Hi\", \"Hello\", \"Hola\", \"Hi",
"'7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th',",
"str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time = time.split(\":\") date = date.split(\"/\")",
"[\"Baseball\"], \"What Is The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National",
"req in message: request_d[i] = req i = i + 1 for key,value",
"Night !! Sweet dreams\", \"Good Night we will meet Next day\"], \"What Is",
"[\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\": [\"Shillong\"], #national games \"What",
"\"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital Of Mizoram\": [\"Aizawl\"],",
"Uttar Pradesh\": [\"Lucknow\"], \"Capital Of Himachal Pradesh\": [\"Shimla\"], \"Capital Of Gujarat\": [\"Gandhinagar\"], \"Capital",
"\\n 3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"How",
"= \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\" def send_message(message): response = respond(message)",
"'*': return int(request_d[key - 1]) * int(request_d[key + 1]) if value == '/':",
"source: if ask: alex_speak(ask) audio = r.listen(source) data = '' try: data =",
"you how I enjoyed hearing from you\"], \"I Feel Stressed\": [\"Here are some",
"\"Please, take rest from you\", \"Properly take medicines\", \"Consult doctor before it becomes",
"data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r = random.randint(1, 10000000) audio_file =",
"are some Prevention methods \\n 1. Wash your hands properly \\n 2. Disinfect",
"calendar import time import webbrowser import wikipedia from gtts import gTTS import playsound",
"== datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster = win10toast.ToastNotifier()",
"1. Wash your hands properly \\n 2. Disinfect your stuff \\n 3. Avoid",
"import requests import re import nltk from googletrans import Translator import sports from",
"Of Argentina\": [\"Pato\"], \"What Is The National Game Of United States\": [\"Baseball\"], \"What",
"from newspaper import Article bot_name = \"Rag2020\" bot_template = \"{0}\" user_template = \"{1}\"",
"Water Polo\"], \"What Is The National Game Of Cuba\": [\"Baseball\"], \"What Is The",
"wishes\",\"Thak you so much for thinking of me\", \"Thanks for making me feel",
"Assembly\"], \"Current Prime Minister of India\":[\"<NAME>\"], \"Chief Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief",
"'November', 'December'] return month_list[month-1] def current_time(): local_time = time.ctime() return local_time def calculate(message):",
"[\"Good Night\", \"Good Night !! Sweet dreams\", \"Good Night we will meet Next",
"Remainder\": bot_message = remainder() elif message == \"Set An Alarm\": bot_message = alarm()",
"\"Hi there\", \"what's special today\"], \"Default\": [\"I can't get you\", \"sorry one more",
"record_audio(\"What you have to compute\") bot_message = calculate(m) elif 'who is' in message:",
"text = re.sub(r'\\[[0-9]*\\]', ' ', text) text = re.sub(r'\\s+', ' ', text) text",
"[\"Thank you for your wishes\",\"Thak you so much for thinking of me\", \"Thanks",
"= datetime.datetime.now() month = now.month month_list = ['January', 'February', 'March', 'April', 'May', 'June',",
"some tips to get rid of stress:\\n 1) Avoid Caffine and Alcohol \\n",
"Minister Of Andhra Pradesh\": [\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister",
"Get advise from mental health professional\\n \" \"4) Be positive\"], \"Feels Stressed\": [\"Here",
"Is Today Date\": [date_and_time()], \"What Is The Month\": [month()], \"What Is The Time",
"bot_message = news_scrap() elif message == \"Live Score\": bot_message = sport_score() elif message",
"from mental health professional\\n \" \"4) Be positive\"], \"How To Relieve Stress\": [\"Here",
"\"Default\": [\"I can't get you\", \"sorry one more time\", \"Sorry! again\"], \"Who Created",
"Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital Of",
"sleep \\n 3)Talk to someone who cares you\", \"Here are few tips to",
"soup = BeautifulSoup(r.text, \"html.parser\") text = \"\" for paragraph in soup.find_all('p'): text +=",
"BeautifulSoup import requests import re import nltk from googletrans import Translator import sports",
"are some tips to get rid of stress:\\n 1) Avoid Caffine and Alcohol",
"os import win10toast from bs4 import BeautifulSoup import requests import re import nltk",
"\"Chief Minister Of Bihar\": [\"<NAME>\"], \"Chief Minister Of Chhattisgarh\": [\"<NAME>\"], \"Chief Minister Of",
"= record_audio(\"To Languages:\") desti = desti.lower() desti = desti[0:2] t = trans.translate( text,",
"Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of Bhutan\": [\" Archery\"], \"What Is",
"throat \\n 3)Cough \\n 4)Congestion \\n 5)Body Achnes \\n 6)Sneezing \\n 7) Fever\"],",
"['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th',",
"import webbrowser import wikipedia from gtts import gTTS import playsound import os import",
"[\"Dehradun\"], \"Capital Of Nagaland\": [\"Kohima\"], \"Capital Of Tamil Nadu\": [\"Chennai\"], \"Capital Of Meghalaya\":",
"\"What Is The National Game Of Canada in Winter\": [\"Ice Hockey\"], \"What Is",
"\"Capital Of Mizoram\": [\"Aizawl\"], \"Capital Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"],",
"+ 1]) if value == '-': return int(request_d[key - 1]) - int(request_d[key +",
"else: cricket = \"no matches found\" return cricket def trans(): trans = Translator()",
"now.month month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',",
"sr.RequestError(): alex_speak(\"Error 1\") return data def alex_speak(audio_string): tts = gTTS(text=audio_string, lang='en') r =",
"positive\"], \"I Feel Bored\": [\"Here Some Melody songs\", \"I tired to play music",
"month(): now = datetime.datetime.now() month = now.month month_list = ['January', 'February', 'March', 'April',",
"is activating...\",\" Bot is Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning have",
"= \"{0}\" user_template = \"{1}\" def send_message(message): response = respond(message) alex_speak(bot_template.format(response)) def respond(message):",
"Minister Of Manipur\": [\"<NAME>\"], \"Chief Minister Of Meghalaya\": [\"<NAME>\"], \"Chief Minister Of Mizoram\":",
"name[i+3] def remainder(): Remainder_message = record_audio(\"Enter the remainder message:\") time = str(input(\"Enter the",
"The National Game Of Afghanistan\": [\"Buzkashi\"], \"What Is The National Game Of Bhutan\":",
"Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\":",
"\"Capital Of Tripura\": [\"Agartala\"], \"Capital Of Rajasthan\": [\"Jaipur\"], \"Capital Of Sikkim\": [\"Gangtok\"], \"Capital",
"[\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"], \"Chief",
"from you\", \"Properly take medicines\", \"Consult doctor before it becomes complicated\"], \"Symptoms For",
"will meet Next day\"], \"What Is Today Date\": [date_and_time()], \"What Is The Month\":",
"def current_time(): local_time = time.ctime() return local_time def calculate(message): message = message.split() i",
"= int(time[1]) rem_date = int(date[0]) rem_month = int(date[1]) rem_year = int(date[2]) if timings",
"2)Headaches 3)Muscle aches 4) Loss of appetite 5)Dehydration\"], \"Symptoms For Throat Pain\": [\"1)",
"[\"<NAME>\"], \"Ministry Of Home Affairs\": [\"<NAME>\"], #capital of States in India \"Capital Of",
"and alarmMinute == datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm",
"= webbrowser.get().open(url) elif message == \"Calculate\": m = record_audio(\"What you have to compute\")",
"\"Capital Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"],",
"The National Game Of United States\": [\"Baseball\"], \"What Is The National Game Of",
"Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\": [\"<NAME>\"],",
"news_scrap() elif message == \"Live Score\": bot_message = sport_score() elif message == \"Exit\":",
"For Acidity\": [\"1)Bloating \\n 2) Burping \\n 3)Dry Cough \\n 4)Sore throat\"], #Political",
"Of Chhattisgarh\": [\"Raipur\"], \"Capital Of Telangana\": [\" Hyderabad\"], \"Capital Of Assam\": [\"Dispur\"], \"Capital",
"[month()], \"What Is The Time Now\": [ time.ctime()], \"Thank You\": [\"Welcome\", \"It's nice",
"Alarm\": bot_message = alarm() elif message == \"Play Me A Song\": bot_message =",
"\\n 3) Get advise from mental health professional\\n \" \"4) Be positive\"], \"Feels",
"Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital Of",
"} def record_audio(ask=False): r = sr.Recognizer() with sr.Microphone() as source: if ask: alex_speak(ask)",
"Relieve Stress\": [\"Here are some tips to get rid of stress:\\n 1) Avoid",
"tired to play music but vain\", \"Sleep well\"], # Medical field questions \"Cold\":",
"health professional\\n \" \"4) Be positive\"], \"I Feel Bored\": [\"Here Some Melody songs\",",
"record_audio(\"Enter the game you want to search\") if match_invoked == 'Cricket': cricket =",
"and rem_date == datetime.datetime.now().day and rem_month == datetime.datetime.now().month and rem_year == datetime.datetime.now().year: toaster",
"+ 1]) if value == '*': return int(request_d[key - 1]) * int(request_d[key +",
"1]) * int(request_d[key + 1]) if value == '/': return int(request_d[key - 1])",
"The National Game Of Turkey\": [\"Oil Wrestling\"], \"What Is The National Game Of",
"\"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"], \"Chief Minister Of Maharashtra\": [\"<NAME>\"], \"Chief Minister",
"may include cough, sore throat, low-grade fever, nasal congestion, runny nose, and sneezing.\"],",
"sentence or word to be translated:\") source = record_audio(\"From Languages:\") source = source.lower()",
"Karnataka\": [\"<NAME>\"], \"Chief Minister Of Kerala\": [\"<NAME>\"], \"Chief Minister Of Madhya Pradesh\": [\"<NAME>\"],",
"calculate(message): message = message.split() i = 0 request_d = {} for req in",
"Of Uttarakhand\": [\"<NAME>\"], \"Chief Minister Of West Bengal\": [\"<NAME>\"], \"Defence Minster Of India\":",
"Kashmir\": [\"President's rule\"], \"Chief Minister Of Jharkhand\": [\"<NAME>\"], \"Chief Minister Of Karnataka\": [\"<NAME>\"],",
"Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief Minister Of Uttarakhand\": [\"<NAME>\"],",
"1\"], \"Good Morning\": [\"Good Morning have a great day\", \"great day ahead\", \"have",
"'Search' in message: search = record_audio(\"Specify the word\") url = \"https://google.com/search?q=\" +search bot_message",
"Game Of Pakistan\": [\"Field Hockey\"], \"What Is The National Game Of Brazil\": [\"Football\"],",
"you for your wishes\",\"Thak you so much for thinking of me\", \"Thanks for",
"be translated:\") source = record_audio(\"From Languages:\") source = source.lower() source = source[0:2] desti",
"[\"<NAME>\"], \"Chief Minister Of Tripura\": [\"<NAME>\"], \"Chief Minister Of Uttar Pradesh\": [\"<NAME>\"], \"Chief",
"Get advise from mental health professional\\n \" \"4) Be positive\"], \"I Feel Bored\":",
"'11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd',",
"Of Sikkim\": [\"Gangtok\"], \"Capital Of Arunachal Pradesh\": [\"Itanagar\"], \"Capital Of Maharasthtra\": [\"Mumbai\"], \"Capital",
"bot_message = random.choice(responses[message]) elif 'Search' in message: search = record_audio(\"Specify the word\") url",
"Of Haryana\": [\"Chandigarh\"], \"Capital Of Jammu & Kashmir\": [\" Srinagar & Jammu\"], \"Capital",
"Of Meghalaya\": [\"Shillong\"], #national games \"What Is The National Game Of Bangladesh\": [\"Kabaddi\"],",
"'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month_list[month-1] def current_time(): local_time =",
"date = str(input(\"Enter the remainder date in format DD/MM/YYYY\")) time = time.split(\":\") date",
"datetime import calendar import time import webbrowser import wikipedia from gtts import gTTS",
"throat \\n 2)Difficulty in Swallowing \\n 3)Sore\"], \"Symptoms For Acidity\": [\"1)Bloating \\n 2)",
"Rag labs\"], \"Happy Birthday Rag\": [\"Thank you for your wishes\",\"Thak you so much",
"of stress:\\n 1) Listen some melody songs \\n 2) Exercise regularly \\n 3)",
"Launcing 3 2 1\"], \"Good Morning\": [\"Good Morning have a great day\", \"great",
"[\"<NAME>\"], \"Chief Minister Of Arunachal Pradesh\": [\"<NAME>\"], \"Chief Minister Of Assam\": [\"<NAME>\"], \"Chief",
"== datetime.datetime.now().minute: from playsound import playsound alarm = playsound('C:/Users/Anandatirtha/PycharmProjects/Chat_ananda/the-purge-siren-ringtone.mp3') return alarm def melody():",
"= \"no matches found\" return cricket def trans(): trans = Translator() text ="
] |
[
"network but LOCATION data are NOT READY!\") # elif data_[5] == 1: #",
"'').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6)",
"= float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6)",
"MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def",
"self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging",
"self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_",
"self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t",
"float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp =",
"- t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n',",
"elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network",
"rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = ''",
"data . I could put the github link up if you want.\"\"\" self.ser.flushInput()",
"self.tag = Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used",
"MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE!",
"Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode",
"# Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif",
"= struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and data_[2] != 0: #",
"\"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1)",
"and LOCATION data are READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag is",
"rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',')",
"self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now()",
"using the +-2g scale). With regards to the getting the accelerometer readings to",
"by 2^6 ( as it is shifted) and then multiply it into 0.004",
"- t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test",
"= 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True':",
"# cc = self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could",
"geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\"",
"the accelerometer readings to the UART, I have written specific functions to read",
"__name__ == '__main__': try: dd = DecawaveDriver() dd.run() except rospy.ROSInterruptException: rospy.loginfo(\"[Decawave Driver]: Closed!\")",
"\"\"\" Read Acc Value: The values are raw values. So to convert them",
"to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray()",
"self.rate.sleep() # Main function if __name__ == '__main__': try: dd = DecawaveDriver() dd.run()",
"= rospy.Time.now() #while not 'acc' in cc: # cc = self.ser.readline() # if",
"CONNECTED to a UWB network but LOCATION data are NOT READY!\") # elif",
"return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to",
"== 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and LOCATION data",
"self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if",
"* 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') #",
"UWB network but LOCATION data are READY!\") # elif data_[5] == 0: #",
"bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def",
"= struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\")",
"rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0):",
"self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0):",
"int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial",
"self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag = Tag()",
"Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\")",
"READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to a UWB",
"self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t",
"I have written specific functions to read the data . I could put",
"rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and LOCATION data are READY!\\33[0m\") #",
"self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ',",
"0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test",
"rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp =",
"'acc' in cc: # cc = self.ser.readline() # if rospy.Time.now() - t >",
"time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if cc == '@\\x01\\x01': #",
"#self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function",
"Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput()",
"if data_[0] != 64 and data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet",
"Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') #",
"CONNECTED to a UWB network but LOCATION data are READY!\") # elif data_[5]",
"LOCATION data are READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT",
"a UWB network and LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\" Read",
"self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline()",
"device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21):",
"# self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y,",
"have to divide the values by 2^6 ( as it is shifted) and",
"self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ',",
"rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc =",
"self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y,",
"rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ == '__main__': try: dd =",
"UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode",
"def get_tag_acc(self): \"\"\" Read Acc Value: The values are raw values. So to",
"for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\")",
"= ', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now()",
"3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and LOCATION data are",
"= rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray,",
"MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ ==",
"elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network",
"from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver",
"network but LOCATION data are READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag",
"# Main function if __name__ == '__main__': try: dd = DecawaveDriver() dd.run() except",
"import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring",
"GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to be changed to",
"= rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not",
"self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL',",
"= rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ =",
"rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc",
"', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z",
"self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser =",
"self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag)",
"rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network but LOCATION data are READY!\")",
"self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag =",
"again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version =",
"data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network and",
"self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode",
"elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to a UWB network but",
"cc = self.ser.readline() print (cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not",
"rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0),",
"anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def",
"serial import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray,",
"= self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\")",
"# pass # status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if",
"a UWB network but LOCATION data are NOT READY!\") # elif data_[5] ==",
"NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The values are raw values.",
"while not 'acc' in cc: cc = self.ser.readline() if rospy.Time.now() - t >",
"It must to be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: #",
"to divide the values by 2^6 ( as it is shifted) and then",
"Mode #cc = '' #t = rospy.Time.now() #while not 'acc' in cc: #",
"Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if cc ==",
"== 0): pass cc = '' t = rospy.Time.now() while not 'DIST' in",
"', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04",
"\"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0')",
"at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors =",
"cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x =",
"self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' #",
"pass # status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0]",
"* 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag'",
"# self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z",
"Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_)",
"'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1)",
"0: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network and LOCATION data",
"Detected! Please reset the device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') #",
"# SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return",
"data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and LOCATION",
"getting the accelerometer readings to the UART, I have written specific functions to",
"# self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_",
"rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc)",
"if __name__ == '__main__': try: dd = DecawaveDriver() dd.run() except rospy.ROSInterruptException: rospy.loginfo(\"[Decawave Driver]:",
"= '' #t = rospy.Time.now() #while not 'acc' in cc: # cc =",
"rospy import tf import time import serial import struct from geometry_msgs.msg import PointStamped",
"* 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z",
"rospy.Time.now() #while not 'acc' in cc: # cc = self.ser.readline() # if rospy.Time.now()",
"# self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y",
"get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the",
"Status # while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() # data_ = struct.unpack('<BBBBBB',",
"could put the github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test",
"MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to be changed to SHELL",
"rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate',",
"LOCATION data are READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED",
"t = rospy.Time.now() while not 'acc' in cc: cc = self.ser.readline() if rospy.Time.now()",
"== 1: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network but LOCATION",
"bytearray(status)) # if data_[0] != 64 and data_[2] != 0: # rospy.logwarn(\"Get Status",
"rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to be changed to SHELL MODE!\\33[0m\")",
"- t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc:",
"SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL",
"# self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() #",
"I could put the github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') #",
"t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc:",
"raw values. So to convert them to g you first have to divide",
"cc: cc = self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get",
"status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64",
"network and LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value:",
"= \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART",
"rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0,",
"not 'acc' in cc: cc = self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5):",
"rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') #",
"self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate =",
"\"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters",
"Main function if __name__ == '__main__': try: dd = DecawaveDriver() dd.run() except rospy.ROSInterruptException:",
"data are READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to",
"is NOT CONNECTED to a UWB network but LOCATION data are READY!\") #",
"written specific functions to read the data . I could put the github",
"= [] self.tag = Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART",
"rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n',",
"self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t =",
"anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag,",
"rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self):",
"python import rospy import tf import time import serial import struct from geometry_msgs.msg",
"float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) *",
"# rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network but LOCATION data are",
"to g you first have to divide the values by 2^6 ( as",
"0): pass cc = self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice",
"#t = rospy.Time.now() #while not 'acc' in cc: # cc = self.ser.readline() #",
"rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status #",
"+-2g scale). With regards to the getting the accelerometer readings to the UART,",
"self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t =",
"UWB network and LOCATION data are READY!\\33[0m\") # elif data_[5] == 2: #",
"= ', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) *",
"the data . I could put the github link up if you want.\"\"\"",
"Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN'",
"get_tag_acc(self): \"\"\" Read Acc Value: The values are raw values. So to convert",
"', '').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) *",
"3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y =",
"to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ ==",
"to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput()",
"== 3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y",
"'' t = rospy.Time.now() while not 'DIST' in cc: cc = self.ser.readline() print",
"''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z =",
"self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected",
"is shifted) and then multiply it into 0.004 (assuming you are using the",
"'@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to be",
"Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput()",
"rospy.logwarn(\"Tag is CONNECTED to a UWB network but LOCATION data are NOT READY!\")",
"self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to",
"rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if",
"= float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6)",
"self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y =",
"0): pass cc = '' t = rospy.Time.now() while not 'DIST' in cc:",
"0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id =",
"# self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass # status =",
"queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster()",
"are raw values. So to convert them to g you first have to",
"get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3:",
"cc: cc = self.ser.readline() print (cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could",
"= self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\")",
"float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0)",
"network and LOCATION data are READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag",
"'/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10'))",
"Please reset the device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status",
"get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_",
"accelerometer readings to the UART, I have written specific functions to read the",
"as it is shifted) and then multiply it into 0.004 (assuming you are",
"to a UWB network and LOCATION data are READY!\\33[0m\") # elif data_[5] ==",
"github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() ==",
"', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput()",
"not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) ==",
"to a UWB network and LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\"",
"\"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(),",
"self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass # status = self.ser.readline()",
"= Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\"",
"0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp",
"# if data_[0] != 64 and data_[2] != 0: # rospy.logwarn(\"Get Status Failed!",
"import serial import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor,",
"while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) #",
"= ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04",
"Packet does not match!\") # print(\"%s\", data_) # if data_[5] == 3: #",
"run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ =",
"changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is",
"= self.ser.readline() print (cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get",
"!= 0: # rospy.logwarn(\"Get Status Failed! Packet does not match!\") # print(\"%s\", data_)",
"'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc =",
"> rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ',",
"to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on",
"So to convert them to g you first have to divide the values",
"gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0):",
"get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3:",
"# Test Mode #cc = '' #t = rospy.Time.now() #while not 'acc' in",
"rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown():",
"64 and data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet does not match!\")",
"self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel",
"Status Failed! Packet does not match!\") # print(\"%s\", data_) # if data_[5] ==",
"#def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass #",
"Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if cc == '@\\x01\\x01':",
"self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status',",
"= cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x",
"0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0,",
"the getting the accelerometer readings to the UART, I have written specific functions",
"[] self.tag = Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART Mode",
"while(self.ser.inWaiting() == 0): pass cc = '' t = rospy.Time.now() while not 'acc'",
"pass cc = '' t = rospy.Time.now() while not 'DIST' in cc: cc",
"data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB",
"the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() ==",
"''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r')",
"are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The values are raw",
"time import serial import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag,",
"', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def",
"# rospy.logwarn(\"Get Status Failed! Packet does not match!\") # print(\"%s\", data_) # if",
"= 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting()",
"\"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device and try again!\") def",
"data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x =",
"PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for",
"switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r')",
"rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc)",
"t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode",
"while not 'DIST' in cc: cc = self.ser.readline() print (cc) if rospy.Time.now() -",
"import rospy import tf import time import serial import struct from geometry_msgs.msg import",
"are READY!\\33[0m\") # elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to a",
"\"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode",
"if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\")",
"# elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB",
"self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for",
"0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ =",
". I could put the github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r')",
"== 0: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network and LOCATION",
"self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL",
"MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n',",
"timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\",",
"import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc",
"= Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART",
"# while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status))",
"pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration",
"self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') #",
"the UART, I have written specific functions to read the data . I",
"Test Mode #cc = '' #t = rospy.Time.now() #while not 'acc' in cc:",
"'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() ==",
"divide the values by 2^6 ( as it is shifted) and then multiply",
"AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br =",
"= self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC",
"for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ =",
"self.ser.readline() print (cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag",
"tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(),",
"def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21)",
"= int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to",
"'').split(',') #if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) *",
"rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1)",
"# rospy.logwarn(\"Tag is CONNECTED to a UWB network but LOCATION data are NOT",
"the +-2g scale). With regards to the getting the accelerometer readings to the",
"rospy.Time.now() while not 'acc' in cc: cc = self.ser.readline() if rospy.Time.now() - t",
"#!/usr/bin/env python import rospy import tf import time import serial import struct from",
"Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ =",
"queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer =",
"to be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE",
"Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t = rospy.Time.now() while",
"rospy.Time.now() while not 'DIST' in cc: cc = self.ser.readline() print (cc) if rospy.Time.now()",
"# elif data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to a UWB network",
"0.004 (assuming you are using the +-2g scale). With regards to the getting",
"function if __name__ == '__main__': try: dd = DecawaveDriver() dd.run() except rospy.ROSInterruptException: rospy.loginfo(\"[Decawave",
"def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_",
"accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x",
"self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which",
"int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s",
"= '' t = rospy.Time.now() while not 'DIST' in cc: cc = self.ser.readline()",
"', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id",
"self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z =",
"#self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel =",
"self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE!",
"data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = '' #t = rospy.Time.now() #while",
"0.04 self.accel.y = float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z =",
"#if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04",
"def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\")",
"'04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status",
"self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) #",
"= rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc,",
"rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose',",
"# Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if cc",
"to read the data . I could put the github link up if",
"rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1)",
"import time import serial import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import",
"Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_ == \"GENERIC\":",
"= rospy.Time.now() def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass",
"tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = '' #t = rospy.Time.now()",
"values by 2^6 ( as it is shifted) and then multiply it into",
"#self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if",
"== \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device and try again!\")",
"'acc' in cc: cc = self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could",
"''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self,",
"rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00')",
"which UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test",
"rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network and LOCATION data are NOT",
"regards to the getting the accelerometer readings to the UART, I have written",
"UART, I have written specific functions to read the data . I could",
"in cc: cc = self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not",
"21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\")",
"#self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ == '__main__': try: dd = DecawaveDriver()",
"'').replace('acc: ', '').split(',') #if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x = ',",
"struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\")",
"in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self):",
"\"Unknown Mode Detected! Please reset the device and try again!\") def get_tag_version(self): self.ser.flushInput()",
"data_[5] == 2: # rospy.logwarn(\"Tag is CONNECTED to a UWB network but LOCATION",
"mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0)",
"* 0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z",
"== 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor",
"#self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ == '__main__':",
"data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and data_[2] != 0:",
"# GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to be changed",
"have written specific functions to read the data . I could put the",
"self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location()",
"not match!\") # print(\"%s\", data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is",
"READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The values are raw values. So",
"# if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network",
"the values by 2^6 ( as it is shifted) and then multiply it",
"scale). With regards to the getting the accelerometer readings to the UART, I",
"= ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def get_tag_location(self):",
"#while not 'acc' in cc: # cc = self.ser.readline() # if rospy.Time.now() -",
"to convert them to g you first have to divide the values by",
"it into 0.004 (assuming you are using the +-2g scale). With regards to",
"= float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z = ',",
"self.anchors = AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel = Acc() def",
"0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if",
"you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc =",
"Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) #",
"# Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_",
"0: # rospy.logwarn(\"Get Status Failed! Packet does not match!\") # print(\"%s\", data_) #",
"a UWB network but LOCATION data are READY!\") # elif data_[5] == 0:",
"must to be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL",
"self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel",
"* 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer):",
"0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_",
"data_[0] != 64 and data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet does",
"while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware",
"self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while",
"import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def",
"DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port',",
"tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp =",
"== 0): pass cc = '' t = rospy.Time.now() while not 'acc' in",
"= rospy.Time.now() while not 'acc' in cc: cc = self.ser.readline() if rospy.Time.now() -",
"get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = ''",
"rospy.logwarn(\"Get Status Failed! Packet does not match!\") # print(\"%s\", data_) # if data_[5]",
"rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset",
"is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting()",
"CONNECTED to a UWB network and LOCATION data are READY!\\33[0m\") # elif data_[5]",
"'10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at",
"if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r')",
"len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 #",
"Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking",
"them to g you first have to divide the values by 2^6 (",
"docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_",
"UWB network but LOCATION data are NOT READY!\") # elif data_[5] == 1:",
"up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass",
"1: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network but LOCATION data",
"# elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB",
"Read Acc Value: The values are raw values. So to convert them to",
"values are raw values. So to convert them to g you first have",
"Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True')",
"while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown",
"(assuming you are using the +-2g scale). With regards to the getting the",
"g you first have to divide the values by 2^6 ( as it",
"print (cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\")",
"= self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get",
"= rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_,",
"#self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ == '__main__': try:",
"self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please",
"accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3: #",
"you are using the +-2g scale). With regards to the getting the accelerometer",
"not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = '' #t",
"NOT CONNECTED to a UWB network but LOCATION data are READY!\") # elif",
"#cc = '' #t = rospy.Time.now() #while not 'acc' in cc: # cc",
"link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0):",
"''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 #",
"functions to read the data . I could put the github link up",
"= \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_",
"# data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and data_[2] !=",
"anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200'))",
"readings to the UART, I have written specific functions to read the data",
"# self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag'",
"not 'acc' in cc: # cc = self.ser.readline() # if rospy.Time.now() - t",
"version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8],",
"on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if",
"3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y =",
"cc = '' t = rospy.Time.now() while not 'acc' in cc: cc =",
"Value: The values are raw values. So to convert them to g you",
"you first have to divide the values by 2^6 ( as it is",
"Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_",
"\"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id,",
"while(self.ser.inWaiting() == 0): pass cc = '' t = rospy.Time.now() while not 'DIST'",
"= float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id = 'tag' # self.accel.header.stamp",
"serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status()",
"if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc",
"# rospy.logwarn(\"Could not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if",
"t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ',",
"\"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode",
"', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04",
"With regards to the getting the accelerometer readings to the UART, I have",
"'').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04",
"= self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and",
"from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object):",
"rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br",
"SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput() if self.mode_",
"__init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ =",
"#self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel = Acc()",
"== \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell",
"= rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback)",
"rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ ==",
"anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating",
"self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the",
"* 0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 # self.accel.header.frame_id",
"specific functions to read the data . I could put the github link",
"= rospy.Time.now() while not 'DIST' in cc: cc = self.ser.readline() print (cc) if",
"Mode Detected! Please reset the device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00')",
"pass cc = '' t = rospy.Time.now() while not 'acc' in cc: cc",
"MODE! It must to be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else:",
"if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc",
"# print(\"%s\", data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to",
"> rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc",
"not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors)",
"== 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y = float(int(cc[1].replace('y",
"reset the device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting()",
"mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1)",
"rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass",
"rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep()",
"= 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass cc",
"\"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ =",
"== '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must to",
"but LOCATION data are NOT READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag",
"cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It must",
"SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\",",
"is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_ def switch_uart_mode(self): self.ser.flushInput()",
"# rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network and LOCATION data are",
"%i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = []",
"''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id =",
"elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device and",
"'04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): #",
"NOT READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED to",
"= cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x =",
"Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr,",
"Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_",
"try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version",
"data are READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED",
"cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ',",
"= ', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) *",
"= rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp",
"it is shifted) and then multiply it into 0.004 (assuming you are using",
"be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice",
"multiply it into 0.004 (assuming you are using the +-2g scale). With regards",
"= float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y = ',",
"'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in",
"def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0),",
"0): pass cc = '' t = rospy.Time.now() while not 'acc' in cc:",
"are NOT READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED",
"data are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The values are",
"AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False)",
"# Status # while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() # data_ =",
"data are NOT READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT",
"ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\"",
"= rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__ == '__main__': try: dd",
"if self.mode_ == \"GENERIC\": rospy.loginfo(\"\\33[96mChanging UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go",
"self.anchors.anchors = [] self.tag = Tag() self.accel = Acc() def get_uart_mode(self): \"\"\" Check",
"self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') # Test Mode time.sleep(0.1) while(self.ser.inWaiting() == 0): pass",
"values. So to convert them to g you first have to divide the",
"cc = self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not",
"'' t = rospy.Time.now() while not 'acc' in cc: cc = self.ser.readline() if",
"', '').split(',') #if len(cc) == 3: # self.accel.x = float(int(cc[0].replace('x = ', ''))/64.0)",
"class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting",
"cc = '' t = rospy.Time.now() while not 'DIST' in cc: cc =",
"Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer",
"len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y =",
"self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp =",
"self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors = [] self.tag",
"'DIST' in cc: cc = self.ser.readline() print (cc) if rospy.Time.now() - t >",
"cc: # cc = self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5): #",
"Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver',",
"data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3: # self.accel.x",
"# status = self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] !=",
"and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass",
"= '' t = rospy.Time.now() while not 'acc' in cc: cc = self.ser.readline()",
"'' #t = rospy.Time.now() #while not 'acc' in cc: # cc = self.ser.readline()",
"self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_ =",
"struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and data_[2] != 0: # rospy.logwarn(\"Get",
"rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_,",
"but LOCATION data are READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag is",
"\"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r')",
"== 0): pass cc = self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE",
"self.ser.readline() # data_ = struct.unpack('<BBBBBB', bytearray(status)) # if data_[0] != 64 and data_[2]",
"put the github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode",
"while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now()",
"READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED to a",
"SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\" return self.mode_",
"pass cc = self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is",
"not 'DIST' in cc: cc = self.ser.readline() print (cc) if rospy.Time.now() - t",
"rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\") self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_",
"shifted) and then multiply it into 0.004 (assuming you are using the +-2g",
"first have to divide the values by 2^6 ( as it is shifted)",
"then multiply it into 0.004 (assuming you are using the +-2g scale). With",
"= AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel = Acc() def get_uart_mode(self):",
"and LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The",
"# Initiate Serial self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\",",
"''))/64.0) * 0.04 # self.accel.z = float(int(cc[2].replace('z = ', ''))/64.0) * 0.04 #",
"# Status while(self.ser.inWaiting() < 21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version))",
"0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0,",
"else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\") self.mode_ = \"SHELL\"",
"on GENERIC MODE! It must to be changed to SHELL MODE!\\33[0m\") self.mode_ =",
"tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_) rospy.loginfo(\"\\33[96mInitiating Driver...\\33[0m\")",
"and then multiply it into 0.004 (assuming you are using the +-2g scale).",
"a UWB network and LOCATION data are READY!\\33[0m\") # elif data_[5] == 2:",
"Acc Value: The values are raw values. So to convert them to g",
"self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x,",
"anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate = rospy.Rate(self.rate_)",
"< 21): pass version = self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5],",
"def get_tag_location(self): self.ser.flushInput() self.ser.write(b'lec\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc =",
"self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', ''))",
"self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors:",
"NOT CONNECTED to a UWB network and LOCATION data are NOT READY!\") def",
"GENERIC MODE! It must to be changed to SHELL MODE!\\33[0m\") self.mode_ = \"GENERIC\"",
"in cc: cc = self.ser.readline() print (cc) if rospy.Time.now() - t > rospy.Duration(0.5):",
"self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer', Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2),",
"Failed! Packet does not match!\") # print(\"%s\", data_) # if data_[5] == 3:",
"if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc =",
"# Test Mode while(self.ser.inWaiting() == 0): pass cc = '' t = rospy.Time.now()",
"rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_ = 'UNKNOWN' self.ser.flushInput() self.ser.write(b'\\r') #",
"print(\"%s\", data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a",
"= int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate",
"CONNECTED to a UWB network and LOCATION data are NOT READY!\") def get_tag_acc(self):",
"read the data . I could put the github link up if you",
"= ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) * 0.04",
"not get accel data!\") #cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) ==",
"queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel)",
"self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z),",
"# if rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\")",
"Tag, Anchor, AnchorArray, Acc class DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self):",
"Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0):",
"data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED to a UWB network but",
"UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\") self.mode_ =",
"cc = self.ser.readline() if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on",
"= tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp",
"self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version()",
"2: # rospy.logwarn(\"Tag is CONNECTED to a UWB network but LOCATION data are",
"float(int(cc[0].replace('x = ', ''))/64.0) * 0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0)",
"is CONNECTED to a UWB network but LOCATION data are NOT READY!\") #",
"UWB network and LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc",
"the device and try again!\") def get_tag_version(self): self.ser.flushInput() self.ser.write(b'\\x15\\x00') # Status while(self.ser.inWaiting() <",
"to a UWB network but LOCATION data are NOT READY!\") # elif data_[5]",
"'115200')) self.tf_publisher_ = rospy.get_param('tf_publisher', 'True') self.rate_ = int(rospy.get_param('rate', '10')) # Initiate Serial self.ser",
"and data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet does not match!\") #",
"time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected!",
"def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_",
"0.04 # self.accel.y = float(int(cc[1].replace('y = ', ''))/64.0) * 0.04 # self.accel.z =",
"# rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and LOCATION data are READY!\\33[0m\")",
"want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting() == 0): pass cc = ''",
"self.tag_pub_ = rospy.Publisher('pose', Tag, queue_size=1) self.anchors_pub_ = rospy.Publisher('status', AnchorArray, queue_size=1) self.acc_pub_ = rospy.Publisher('accelerometer',",
"%s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors = AnchorArray() self.anchors.anchors",
"is CONNECTED to a UWB network and LOCATION data are READY!\\33[0m\") # elif",
"in cc: # cc = self.ser.readline() # if rospy.Time.now() - t > rospy.Duration(0.5):",
"self.accel.header.frame_id = 'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ ==",
"Acc, queue_size=1) self.timer = rospy.Timer(rospy.Duration(0.2), self.tf_callback) self.br = tf.TransformBroadcaster() while not rospy.is_shutdown(): self.get_tag_acc()",
"cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x",
"AnchorArray() self.anchors.anchors = [] self.tag = Tag() self.accel = Acc() def get_uart_mode(self): \"\"\"",
"get_tag_status(self): # self.ser.flushInput() # self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass # status",
"if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED to a UWB network and",
"import tf import time import serial import struct from geometry_msgs.msg import PointStamped from",
"self.ser.write(b'\\x32\\x00') # Status # while(self.ser.inWaiting()==0): # pass # status = self.ser.readline() # data_",
"are READY!\") # elif data_[5] == 0: # rospy.logwarn(\"Tag is NOT CONNECTED to",
"is on GENERIC MODE! It must to be changed to SHELL MODE!\\33[0m\") self.mode_",
"while(self.ser.inWaiting() == 0): pass cc = self.ser.readline() if cc == '@\\x01\\x01': # GENERIC",
"does not match!\") # print(\"%s\", data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag",
"self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = '' #t = rospy.Time.now() #while not",
"2^6 ( as it is shifted) and then multiply it into 0.004 (assuming",
"if cc == '@\\x01\\x01': # GENERIC MODE rospy.loginfo(\"\\33[96mDevice is on GENERIC MODE! It",
"get tag data!\") self.ser.flushInput() self.ser.write(b'\\r') # Test Mode #cc = '' #t =",
"= rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x, self.tag.y, self.tag.z), tf.transformations.quaternion_from_euler(0,",
"Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ = rospy.get_param('tf_publisher',",
"\"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is the gateway...\\33[0m\")",
"tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), \"tag\", \"world\") for anchor in self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z),",
"def get_uart_mode(self): \"\"\" Check UART Mode Used \"\"\" rospy.loginfo(\"\\33[96mChecking which UART mode is",
"the github link up if you want.\"\"\" self.ser.flushInput() self.ser.write(b'av\\r') # Test Mode while(self.ser.inWaiting()",
"match!\") # print(\"%s\", data_) # if data_[5] == 3: # rospy.loginfo(\"\\33[96mTag is CONNECTED",
"> rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',')",
"(cc) if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get tag data!\") self.ser.flushInput()",
"!= 64 and data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet does not",
"to a UWB network but LOCATION data are READY!\") # elif data_[5] ==",
"float(int(cc[1].replace('y = ', ''))>>6) * 0.04 self.accel.z = float(int(cc[2].replace('z = ', ''))>>6) *",
"convert them to g you first have to divide the values by 2^6",
"tf import time import serial import struct from geometry_msgs.msg import PointStamped from ros_decawave.msg",
"= serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode()",
"timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors",
"rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device and try again!\") def get_tag_version(self):",
"into 0.004 (assuming you are using the +-2g scale). With regards to the",
"self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device and try",
"READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag is NOT CONNECTED to a",
"self.mode_ = \"GENERIC\" else: # SHELL MODE rospy.loginfo(\"\\33[96mDevice is on SHELL MODE! Ok!\\33[0m\")",
"self.ser.read(21) data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware",
"self.anchors.anchors: self.br.sendTransform((anchor.x, anchor.y, anchor.z), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), anchor.header.frame_id, \"world\") def run(self): self.rate",
"'04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): # self.ser.flushInput() #",
"is NOT CONNECTED to a UWB network and LOCATION data are NOT READY!\")",
"t = rospy.Time.now() while not 'DIST' in cc: cc = self.ser.readline() print (cc)",
"LOCATION data are NOT READY!\") # elif data_[5] == 1: # rospy.logwarn(\"Tag is",
"self.ser.write(b'\\r') # Test Mode #cc = '' #t = rospy.Time.now() #while not 'acc'",
"The values are raw values. So to convert them to g you first",
"to the UART, I have written specific functions to read the data .",
"self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel data!\") cc",
"if len(cc) == 3: self.accel.x = float(int(cc[0].replace('x = ', ''))>>6) * 0.04 self.accel.y",
"( as it is shifted) and then multiply it into 0.004 (assuming you",
"are using the +-2g scale). With regards to the getting the accelerometer readings",
"to the getting the accelerometer readings to the UART, I have written specific",
"== 2: # rospy.logwarn(\"Tag is CONNECTED to a UWB network but LOCATION data",
"rospy.Time.now() - t > rospy.Duration(0.5): # rospy.logwarn(\"Could not get accel data!\") #cc =",
"cc = self.ser.readline() if rospy.Time.now() - t > rospy.Duration(0.5): rospy.logwarn(\"Could not get accel",
"= rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main function if __name__",
"DecawaveDriver(object): \"\"\" docstring for DecawaveDriver \"\"\" def __init__(self): rospy.init_node('decawave_driver', anonymous=False) # Getting Serial",
"data_ = struct.unpack('<BBBBBLBBLBBL', bytearray(version)) rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11],",
"= float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now()",
"rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode() self.switch_uart_mode() #self.get_tag_status() #self.get_tag_version() self.anchors =",
"Shell Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\":",
"pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode",
"rospy.init_node('decawave_driver', anonymous=False) # Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate',",
"rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self):",
"data_[2] != 0: # rospy.logwarn(\"Get Status Failed! Packet does not match!\") # print(\"%s\",",
"float(int(cc[2].replace('z = ', ''))>>6) * 0.04 self.accel.header.frame_id = 'tag' self.accel.header.stamp = rospy.Time.now() def",
"LOCATION data are NOT READY!\") def get_tag_acc(self): \"\"\" Read Acc Value: The values",
"self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() # Main",
"rospy.loginfo(\"\\33[96mFirmware Version:0x\"+format(data_[5], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mConfiguration Version:0x\"+format(data_[8], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96mHardware Version:0x\"+format(data_[11], '04X')+\"\\33[0m\") rospy.loginfo(\"\\33[96m--------------------------------\\33[0m\") #def get_tag_status(self): #",
"Mode while(self.ser.inWaiting() == 0): pass cc = '' t = rospy.Time.now() while not",
"#cc = cc.replace('\\r\\n', '').replace('acc: ', '').split(',') #if len(cc) == 3: # self.accel.x =",
"UART mode to SHELL MODE...\\33[0m\") self.ser.write(b'\\r\\r') # Go to Shell Mode while(self.ser.inWaiting()==0): pass",
"'')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\", \"Unknown Mode Detected! Please reset the device",
"Mode while(self.ser.inWaiting()==0): pass time.sleep(1.0) self.ser.flushInput() rospy.loginfo(\"\\33[96m%s\\33[0m\", self.ser.readline().replace('\\n', '')) elif self.mode_ == \"UNKNOWN\": rospy.logerr(\"%s\",",
"self.get_tag_acc() self.acc_pub_.publish(self.accel) #self.get_tag_location() #self.tag.header.stamp = rospy.Time.now() #self.tag_pub_.publish(self.tag) #self.anchors.header.stamp = rospy.Time.now() #self.anchors_pub_.publish(self.anchors) self.rate.sleep() #",
"self.ser = serial.Serial(self.port_, self.baudrate_, timeout=0.1) rospy.loginfo(\"\\33[96mConnected to %s at %i\\33[0m\", self.ser.portstr, self.baudrate_) self.get_uart_mode()",
"'tag' # self.accel.header.stamp = rospy.Time.now() def tf_callback(self, timer): if self.tf_publisher_ == 'True': self.br.sendTransform((self.tag.x,",
"Getting Serial Parameters self.port_ = rospy.get_param('port', '/dev/ttyACM0') self.baudrate_ = int(rospy.get_param('baudrate', '115200')) self.tf_publisher_ =",
"struct from geometry_msgs.msg import PointStamped from ros_decawave.msg import Tag, Anchor, AnchorArray, Acc class"
] |
[
"sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4 = string.hexdigits s",
"return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def keep_alive(): server = Thread(target=run)",
"Flask, jsonify, render_template, send_file, abort, redirect, url_for from threading import Thread import random",
"\"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image =",
"Image from io import BytesIO from flask import Flask, jsonify, render_template, send_file, abort,",
"BytesIO from flask import Flask, jsonify, render_template, send_file, abort, redirect, url_for from threading",
"import Image from io import BytesIO from flask import Flask, jsonify, render_template, send_file,",
"string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15))",
"@app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\":",
"{ \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" }",
"= string.ascii_letters s3 = string.digits s4 = string.hexdigits s = [] s.extend(list(s1)) #",
"return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4 = string.hexdigits s =",
"import Flask, jsonify, render_template, send_file, abort, redirect, url_for from threading import Thread import",
"url_for from threading import Thread import random import string app = Flask('') @app.route('/')",
"import random import string app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1",
"@app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4 =",
"threading import Thread import random import string app = Flask('') @app.route('/') def sup():",
"randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result =",
"def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points",
"s4 = string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 =",
"ImageFont, ImageDraw from PIL import Image from io import BytesIO from flask import",
"\"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run():",
"s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38))",
"app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 =",
"= [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 =",
"= ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text = a draw.text(points, text, \"black\",",
"draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404)",
"\"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\":",
"38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff,",
"ImageDraw from PIL import Image from io import BytesIO from flask import Flask,",
"string.ascii_letters s3 = string.digits s4 = string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2))",
"\"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\",",
"= \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s,",
"import string app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters",
"86, 29 text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg'",
"PIL import Image, ImageFont, ImageDraw from PIL import Image from io import BytesIO",
"def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff,",
"s1 = string.ascii_letters s3 = string.digits s4 = string.hexdigits s = [] s.extend(list(s1))",
"image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def",
"s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c():",
"from io import BytesIO from flask import Flask, jsonify, render_template, send_file, abort, redirect,",
"\"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a):",
"\"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw",
"\"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6))",
"text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def",
"= string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s,",
"import BytesIO from flask import Flask, jsonify, render_template, send_file, abort, redirect, url_for from",
"s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff",
"a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except:",
"from PIL import Image from io import BytesIO from flask import Flask, jsonify,",
"ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text = a draw.text(points,",
"points = 86, 29 text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file",
"imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points =",
"redirect, url_for from threading import Thread import random import string app = Flask('')",
"s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2",
"'./assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def keep_alive(): server",
"Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text",
"Image, ImageFont, ImageDraw from PIL import Image from io import BytesIO from flask",
"draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text =",
"Thread import random import string app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c'))",
"from PIL import Image, ImageFont, ImageDraw from PIL import Image from io import",
"= ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text = a",
"s3 = string.digits s4 = string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3))",
"jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\",",
"result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result)",
"\"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return",
"\"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg')",
"= string.digits s4 = string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4))",
"randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff =",
"result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\",",
"import Thread import random import string app = Flask('') @app.route('/') def sup(): return",
"font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text = a draw.text(points, text,",
"from threading import Thread import random import string app = Flask('') @app.route('/') def",
"= \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = {",
"image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080)",
"PIL import Image from io import BytesIO from flask import Flask, jsonify, render_template,",
"# s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\")",
"string.digits s4 = string.hexdigits s = [] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1",
"random import string app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 =",
"jsonify, render_template, send_file, abort, redirect, url_for from threading import Thread import random import",
"result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def",
"= \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\":",
"font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\",",
"<gh_stars>1-10 from PIL import Image, ImageFont, ImageDraw from PIL import Image from io",
"send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def keep_alive(): server = Thread(target=run) server.start()",
"render_template, send_file, abort, redirect, url_for from threading import Thread import random import string",
"} return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font",
"image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86,",
"abort, redirect, url_for from threading import Thread import random import string app =",
"result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"©",
"29 text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try:",
"= { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\"",
"f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image",
"\"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\": \"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}')",
"send_file, abort, redirect, url_for from threading import Thread import random import string app",
"= 86, 29 text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file =",
"35) points = 86, 29 text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg')",
"[] s.extend(list(s1)) # s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s,",
"try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def keep_alive(): server =",
"= a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return send_file(image_file)",
"string app = Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3",
"from flask import Flask, jsonify, render_template, send_file, abort, redirect, url_for from threading import",
"return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font =",
"def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4 = string.hexdigits",
"ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29 text = a draw.text(points, text, \"black\", font=font)",
"text = a draw.text(points, text, \"black\", font=font) image.save('./assets/Images/resulted_captcha.jpg') image_file = './assets/Images/resulted_captcha.jpg' try: return",
"Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image)",
"redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4 = string.hexdigits s = []",
"give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\":",
"= Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits",
"s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) randm1 = \"\".join(random.sample(s, 15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def",
"flask import Flask, jsonify, render_template, send_file, abort, redirect, url_for from threading import Thread",
"import Image, ImageFont, ImageDraw from PIL import Image from io import BytesIO from",
"Flask('') @app.route('/') def sup(): return redirect(url_for('give_the_c')) s1 = string.ascii_letters s3 = string.digits s4",
"= './assets/Images/resulted_captcha.jpg' try: return send_file(image_file) except: abort(404) def run(): app.run(host=\"0.0.0.0\", port=8080) def keep_alive():",
"@app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35)",
"6)) result = { \"asked_query\": result_random_Stuff, \"answer_to_captcha\": result_random_Stuff, \"img_url\": f\"https://Captcha-Image-Api.dhruvnation1.repl.co/captchame/{randm1}{result_random_Stuff}{randm2}\", \"font\": \"./assets/Font/arial.ttf\", \"credits\":",
"\"© Dhruv\" } return jsonify(result) @app.route(f'/captchame/{randm1}<string:a>{randm2}') def imagemal(a): image = Image.open('./assets/Images/captchimage.jpg') draw =",
"io import BytesIO from flask import Flask, jsonify, render_template, send_file, abort, redirect, url_for",
"= Image.open('./assets/Images/captchimage.jpg') draw = ImageDraw.Draw(image) font = ImageFont.truetype(\"./assets/Font/arial.ttf\", 35) points = 86, 29",
"15)) randm2 = \"\".join(random.sample(s, 38)) @app.route(\"/gimme/some/captcha\") def give_the_c(): result_random_Stuff = \"\".join(random.sample(s, 6)) result"
] |
[
"all_files[path] = True for path in all_files: # Snowflake LIST commands adds stage",
"hash_md5 = md5() with open(local_path, 'rb') as f: for chunk in iter(lambda: f.read(4096),",
"return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp:",
"ResolveResult.REPLACE def drop_object(self, row: dict): # One call deletes original file and MD5",
"_upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\":",
"f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path",
"e.snow_exc.errno == 2003: continue else: raise all_files = {} all_hashes = {} for",
"does not matter # Actual contents of marker pseudo-file is empty and come",
"\"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5() with open(local_path,",
"self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage does",
"destroy(self): # No need to delete stage files explicitly, files are destroyed automatically",
"StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class",
"directory does not matter # Actual contents of marker pseudo-file is empty and",
"file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5() with open(local_path, 'rb') as f:",
"marker pseudo-file is empty and come from zero-length BytesIO in file_stream md5_marker_path =",
"\"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def",
"for path in all_files: # Snowflake LIST commands adds stage name implicitly, which",
"import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) ->",
"one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def",
"bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return",
"with open(local_path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return",
"create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict):",
"def destroy(self): # No need to delete stage files explicitly, files are destroyed",
"f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need to delete stage",
"from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return",
"during planning if e.snow_exc.errno == 2003: continue else: raise all_files = {} all_hashes",
"stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self,",
"== 2003: continue else: raise all_files = {} all_hashes = {} for r",
"return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): # One call",
"exist or not authorized # Skip this error during planning if e.snow_exc.errno ==",
"all_hashes = {} for r in cur: path = Path(r['name']) if path.suffix ==",
"StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE",
"go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self,",
"path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in",
"Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT command, directory",
"all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint):",
"row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict):",
"PUT command, directory does not matter # Actual contents of marker pseudo-file is",
"is empty and come from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name +",
"\"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return",
"md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\":",
"== self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): #",
"ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if",
"authorized # Skip this error during planning if e.snow_exc.errno == 2003: continue else:",
"if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, })",
"ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): # One call deletes",
"in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need to",
"} return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp)",
"import BytesIO from hashlib import md5 from pathlib import Path from snowddl.blueprint import",
"Skip this error during planning if e.snow_exc.errno == 2003: continue else: raise all_files",
"removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and \"size\",",
"reliable due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path,",
"and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'],",
"f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): #",
"row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r}",
"One call deletes original file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\",",
"for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\",",
"# Snowflake LIST commands adds stage name implicitly, which should be removed stage_path",
"hash_md5.hexdigest() def destroy(self): # No need to delete stage files explicitly, files are",
"name implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST",
"self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint,",
"= Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True",
"deletes original file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\":",
"zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1",
"not exist or not authorized # Skip this error during planning if e.snow_exc.errno",
"this error during planning if e.snow_exc.errno == 2003: continue else: raise all_files =",
"str): hash_md5 = md5() with open(local_path, 'rb') as f: for chunk in iter(lambda:",
"# No need to delete stage files explicitly, files are destroyed automatically when",
"snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self)",
"LIST commands provides \"md5\" and \"size\", but it is not reliable due to",
"SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType:",
"not reliable due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\":",
"iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need to delete",
"all_files: # Snowflake LIST commands adds stage name implicitly, which should be removed",
"continue else: raise all_files = {} all_hashes = {} for r in cur:",
"raise all_files = {} all_hashes = {} for r in cur: path =",
"and \"size\", but it is not reliable due to encryption existing_objects[full_name] = {",
"Snowflake LIST commands provides \"md5\" and \"size\", but it is not reliable due",
"def drop_object(self, row: dict): # One call deletes original file and MD5 marker",
"get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp in",
"not matter # Actual contents of marker pseudo-file is empty and come from",
"return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", {",
"= {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur =",
"md5 from pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import",
"_md5_file(self, local_path: str): hash_md5 = md5() with open(local_path, 'rb') as f: for chunk",
"{} all_hashes = {} for r in cur: path = Path(r['name']) if path.suffix",
"not authorized # Skip this error during planning if e.snow_exc.errno == 2003: continue",
"commands adds stage name implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\"",
"as e: # Stage does not exist or not authorized # Skip this",
"\"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp:",
"drop_object(self, row: dict): # One call deletes original file and MD5 marker in",
"= Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\",",
"'rb') as f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def",
"True for path in all_files: # Snowflake LIST commands adds stage name implicitly,",
"def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def",
"def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\",",
"\"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path}",
"\"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5",
"it is not reliable due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\":",
"be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and",
"all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in all_files: # Snowflake",
"StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver):",
"= path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in all_files: # Snowflake LIST",
"{local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, })",
"self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): # One",
"MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], })",
"commands provides \"md5\" and \"size\", but it is not reliable due to encryption",
"continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as",
"}) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\",",
"cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: #",
"SnowDDLExecuteError as e: # Stage does not exist or not authorized # Skip",
"{ \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT",
"self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp:",
"in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\":",
"in cur: path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else:",
"StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\":",
"contents of marker pseudo-file is empty and come from zero-length BytesIO in file_stream",
"ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\":",
"self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent,",
"== '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in all_files:",
"Snowflake LIST commands adds stage name implicitly, which should be removed stage_path =",
"command, directory does not matter # Actual contents of marker pseudo-file is empty",
"of marker pseudo-file is empty and come from zero-length BytesIO in file_stream md5_marker_path",
"Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\":",
"\"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder",
"row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def",
"dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self,",
"}) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT command, directory does",
"= f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and \"size\", but it",
"return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return",
"\"md5\" and \"size\", but it is not reliable due to encryption existing_objects[full_name] =",
"if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row:",
"import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType",
"file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", {",
"f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\":",
"StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5']",
"all_files = {} all_hashes = {} for r in cur: path = Path(r['name'])",
"}) except SnowDDLExecuteError as e: # Stage does not exist or not authorized",
"bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if",
"dict): # One call deletes original file and MD5 marker in one go",
"= {} all_hashes = {} for r in cur: path = Path(r['name']) if",
"= True for path in all_files: # Snowflake LIST commands adds stage name",
"Actual contents of marker pseudo-file is empty and come from zero-length BytesIO in",
"\"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5()",
"row: dict): # One call deletes original file and MD5 marker in one",
"bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5() with",
"= md5() with open(local_path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b\"\"):",
"AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self):",
"{} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST",
"but it is not reliable due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name,",
"{ \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self):",
"_upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT command, directory does not matter",
"or not authorized # Skip this error during planning if e.snow_exc.errno == 2003:",
"encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return",
"\"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1",
"def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp",
"import md5 from pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error",
"try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e:",
"BytesIO from hashlib import md5 from pathlib import Path from snowddl.blueprint import StageBlueprint,",
"= self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage",
"path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] =",
"\"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT command,",
"from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver,",
"-> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values():",
"}, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5() with open(local_path, 'rb') as",
"# One call deletes original file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE",
"AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path:",
"provides \"md5\" and \"size\", but it is not reliable due to encryption existing_objects[full_name]",
"from hashlib import md5 from pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint",
"and come from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT",
"hashlib import md5 from pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from",
"# Stage does not exist or not authorized # Skip this error during",
"path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in all_files: # Snowflake LIST commands",
"call deletes original file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", {",
"StageFileBlueprint): # Placeholder path for PUT command, directory does not matter # Actual",
"original file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'],",
"stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and \"size\", but",
"should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\"",
"from io import BytesIO from hashlib import md5 from pathlib import Path from",
"stage name implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake",
"bp: StageFileBlueprint): # Placeholder path for PUT command, directory does not matter #",
"snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE",
"{ \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage does not exist",
"return ResolveResult.REPLACE def drop_object(self, row: dict): # One call deletes original file and",
"f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 =",
"Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import",
"Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for",
"for PUT command, directory does not matter # Actual contents of marker pseudo-file",
"marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return",
"matter # Actual contents of marker pseudo-file is empty and come from zero-length",
"def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT command, directory does not",
"delete stage files explicitly, files are destroyed automatically when stage is gone pass",
"StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for",
"'.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for path in all_files: #",
"path in all_files: # Snowflake LIST commands adds stage name implicitly, which should",
"# Snowflake LIST commands provides \"md5\" and \"size\", but it is not reliable",
"class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {}",
"existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects",
"for r in cur: path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] =",
"existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE",
"AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint):",
"{ \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): #",
"def get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue",
"BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE",
"get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try:",
"md5() with open(local_path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk)",
"@{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def",
"come from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path}",
"from pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError",
"Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str): hash_md5 = md5() with open(local_path, 'rb')",
"2003: continue else: raise all_files = {} all_hashes = {} for r in",
"open(local_path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest()",
"self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): # One call deletes original",
"not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except",
"implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands",
"self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent,",
"import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver",
"PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def",
"hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need to delete stage files explicitly,",
"bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for PUT",
"else: raise all_files = {} all_hashes = {} for r in cur: path",
"{} for r in cur: path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')]",
"self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name,",
"self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path):",
"compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp) self._upload_md5_marker(bp)",
"# Skip this error during planning if e.snow_exc.errno == 2003: continue else: raise",
"snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult,",
"except SnowDDLExecuteError as e: # Stage does not exist or not authorized #",
"due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None),",
"@{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint):",
"ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files:",
"bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name,",
"path for PUT command, directory does not matter # Actual contents of marker",
"full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and \"size\", but it is not",
"io import BytesIO from hashlib import md5 from pathlib import Path from snowddl.blueprint",
"ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects =",
"None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp)",
"to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), }",
"chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need",
"{local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, },",
"<reponame>littleK0i/SnowDDL<gh_stars>10-100 from io import BytesIO from hashlib import md5 from pathlib import Path",
"# Actual contents of marker pseudo-file is empty and come from zero-length BytesIO",
"@{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO())",
"in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\": row['stage_path'], }) return ResolveResult.DROP",
"existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur",
"if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path] = True for path",
"def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE self._upload_file(bp)",
"Placeholder path for PUT command, directory does not matter # Actual contents of",
"OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp:",
"r in cur: path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.')",
"e: # Stage does not exist or not authorized # Skip this error",
"PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{bp.local_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self,",
"{ \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self, local_path: str):",
"planning if e.snow_exc.errno == 2003: continue else: raise all_files = {} all_hashes =",
"need to delete stage files explicitly, files are destroyed automatically when stage is",
"from snowddl.error import SnowDDLExecuteError from snowddl.resolver.abc_resolver import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def",
"import AbstractResolver, ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def",
"LIST commands adds stage name implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\"",
"Stage does not exist or not authorized # Skip this error during planning",
"return hash_md5.hexdigest() def destroy(self): # No need to delete stage files explicitly, files",
"stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", {",
"f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides \"md5\" and \"size\", but it is",
"\"size\", but it is not reliable due to encryption existing_objects[full_name] = { \"stage_name\":",
"local_path: str): hash_md5 = md5() with open(local_path, 'rb') as f: for chunk in",
"# Placeholder path for PUT command, directory does not matter # Actual contents",
"return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects = {} for stage_bp in self.config.get_blueprints_by_type(StageBlueprint).values(): if not",
"ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] == self._md5_file(bp.local_path): return ResolveResult.NOCHANGE",
"b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No need to delete stage files",
"return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return",
"pseudo-file is empty and come from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name",
"ResolveResult, ObjectType class StageFileResolver(AbstractResolver): def get_object_type(self) -> ObjectType: return ObjectType.STAGE_FILE def get_existing_objects(self): existing_objects",
"file and MD5 marker in one go self.engine.execute_safe_ddl(\"REMOVE @{stage_name:i}{stage_path:r}\", { \"stage_name\": row['stage_name'], \"stage_path\":",
"\"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage does not exist or",
"= { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def",
"in all_files: # Snowflake LIST commands adds stage name implicitly, which should be",
"in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\",",
"else: all_files[path] = True for path in all_files: # Snowflake LIST commands adds",
"is not reliable due to encryption existing_objects[full_name] = { \"stage_name\": stage_bp.full_name, \"stage_path\": stage_path,",
"\"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }) def _upload_md5_marker(self, bp: StageFileBlueprint): # Placeholder path for",
"stage_bp.full_name, \"stage_path\": stage_path, \"original_md5\": all_hashes.get(path, None), } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint)",
"to delete stage files explicitly, files are destroyed automatically when stage is gone",
"from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r}",
"self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row: dict): if row['original_md5'] ==",
"row['stage_path'], }) return ResolveResult.DROP def _upload_file(self, bp: StageFileBlueprint): self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE",
"for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self): # No",
"stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage does not exist or not",
"No need to delete stage files explicitly, files are destroyed automatically when stage",
"+ f\".{self._md5_file(bp.local_path)}.md5\" self.engine.execute_safe_ddl(\"PUT {local_path} @{stage_name:i}{stage_target:r} PARALLEL=1 OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name,",
"empty and come from zero-length BytesIO in file_stream md5_marker_path = Path(bp.local_path).name + f\".{self._md5_file(bp.local_path)}.md5\"",
"pathlib import Path from snowddl.blueprint import StageBlueprint, StageFileBlueprint from snowddl.error import SnowDDLExecuteError from",
"cur: path = Path(r['name']) if path.suffix == '.md5': all_hashes[path.with_suffix('').with_suffix('')] = path.suffixes[-2].lstrip('.') else: all_files[path]",
"adds stage name implicitly, which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" #",
"which should be removed stage_path = f\"/{path.relative_to(path.parts[0])}\" full_name=f\"{stage_bp.full_name}({stage_path})\" # Snowflake LIST commands provides",
"@{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError as e: # Stage does not",
"OVERWRITE=TRUE AUTO_COMPRESS=FALSE\", { \"local_path\": f\"file://{md5_marker_path}\", \"stage_name\": bp.stage_name, \"stage_target\": Path(bp.stage_path).parent, }, file_stream=BytesIO()) def _md5_file(self,",
"= {} for r in cur: path = Path(r['name']) if path.suffix == '.md5':",
"does not exist or not authorized # Skip this error during planning if",
"def _md5_file(self, local_path: str): hash_md5 = md5() with open(local_path, 'rb') as f: for",
"self._upload_md5_marker(bp) return ResolveResult.REPLACE def drop_object(self, row: dict): # One call deletes original file",
"def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self, bp: StageFileBlueprint, row:",
"as f: for chunk in iter(lambda: f.read(4096), b\"\"): hash_md5.update(chunk) return hash_md5.hexdigest() def destroy(self):",
"stage_bp.upload_stage_files: continue try: cur = self.engine.execute_meta(\"LIST @{stage_name:i}\", { \"stage_name\": stage_bp.full_name, }) except SnowDDLExecuteError",
"get_blueprints(self): return self.config.get_blueprints_by_type(StageFileBlueprint) def create_object(self, bp: StageFileBlueprint): self._upload_file(bp) self._upload_md5_marker(bp) return ResolveResult.CREATE def compare_object(self,",
"if e.snow_exc.errno == 2003: continue else: raise all_files = {} all_hashes = {}",
"error during planning if e.snow_exc.errno == 2003: continue else: raise all_files = {}"
] |
[
"params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'],",
"self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number",
"class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda",
"cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({'server.socket_port': 9090}) cherrypy.engine.start()",
"params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] =",
"'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({'server.socket_port': 9090})",
"= requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if",
"self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if",
"float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf",
"sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots',",
"key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)),",
"self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[]",
"self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if",
"if __name__ == '__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True",
"return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\"",
"0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else:",
"= { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf)",
"int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if",
"self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda",
"uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if",
"__name__ == '__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True }",
"self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"])",
"self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\"",
"json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params:",
"and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__))",
"i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"])",
"self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf = { '/':",
"params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\":",
"if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations']",
"x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\"",
"self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf =",
"return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in",
"conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/',",
"in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\" for i in",
"x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"])",
"i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json()",
"cherrypy import json import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0:",
"== '__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } }",
"k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)),",
"0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else:",
"reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in",
"<filename>lab3/es3/to_bike_webservice.py import cherrypy import json import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params):",
"i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json()",
"x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else:",
"set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)):",
"k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True)",
"BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x:",
"in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if",
"params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"],",
"\"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False)",
"= sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return",
"json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and",
"len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json()",
"in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if",
"sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda",
"self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\"",
"in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots}",
"'/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host': '0.0.0.0'})",
"x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else:",
"\"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\" for i",
"int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True)",
"= sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda",
"import json import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data",
"GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data",
"range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if",
"reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data",
"if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data =",
"k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True)",
"self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if",
"if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)),",
"key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)),",
"else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N):",
"in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0",
"0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i",
"not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and",
"return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in",
"self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District",
"uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"])",
"'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({'server.socket_port': 9090}) cherrypy.engine.start() cherrypy.engine.block()",
"self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes',",
"if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] =",
"in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[]",
"key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots',",
"uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if",
"if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\":",
"x.__dict__)) if __name__ == '__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on':",
"key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x:",
"@cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if",
"params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'],",
"json import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data =",
"requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return",
"and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__':",
"requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params:",
"return \"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005)",
"x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"])",
"sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes',",
"float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if",
"def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\":",
"for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data =",
"if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10",
"= requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else:",
"= sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k:",
"json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params:",
"if uri[0]==\"order_bikes\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10",
"int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if",
"= requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in",
"in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] =",
"else: return \"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and",
"x: x.__dict__)) if __name__ == '__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),",
"if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] =",
"self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'],",
"0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\":",
"self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf = {",
"reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations']",
"else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N):",
"int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for",
"((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x:",
"reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations']",
"0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\":",
"params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] =",
"\"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and",
"key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x:",
"self.lon=float(params[\"lon\"]) else: return \"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005",
"\"N\" in params: self.N=int(params[\"N\"]) else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations']",
"if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)),",
"reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"order_bikes\": self.json_data",
"'__main__': conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(),",
"range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return",
"else: self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k:",
"for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data =",
"for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"])",
"0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i",
"sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k:",
"and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__",
"self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda",
"int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True)",
"params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\":",
"\"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\"",
"self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i])",
"params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])):",
"k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)),",
"import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json()",
"= sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return",
"= sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k:",
"{ 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({'server.socket_port':",
"import cherrypy import json import requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if",
"= sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda",
"self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"],",
"if \"lat\" and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not",
"and \"lon\" in params: self.lat=float(params[\"lat\"]) self.lon=float(params[\"lon\"]) else: return \"District number not set\" for",
"self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda",
"\"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots', 0)), reverse=False)",
"if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations']",
"reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for i in",
"exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__))",
"int(k.get('empty_slots', 0)), reverse=True) else: self.json_data['network']['stations'] = sorted(self.json_data[\"network\"][\"stations\"], key=lambda k: int(k.get('empty_slots', 0)), reverse=True) for",
"x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in",
"if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0 if \"lat\" and \"lon\" in params:",
"key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes',",
"range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if uri[0]==\"count_bikes_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.bikes=0 self.slots=0",
"if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda",
"sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=False) if params[\"order\"]==\"descend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k:",
"{ '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True } } cherrypy.tree.mount(BikeSharing(), '/', conf) cherrypy.config.update({'server.socket_host':",
"k: int(k.get('empty_slots', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data[\"network\"][\"stations\"][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__))",
"json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf = { '/': { 'request.dispatch':",
"self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i])",
"requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return json.loads(json.dumps(self.json_data,default=lambda x: x.__dict__)) if uri[0]==\"order_slots\": self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() self.json_out=[] if \"N\"",
"k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__))",
"return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ == '__main__': conf = { '/': {",
"requests class BikeSharing(): exposed=True @cherrypy.tools.json_out() def GET(self,*uri,**params): if len(uri)==0: self.json_data = requests.get(\"https://api.citybik.es/v2/networks/to-bike\").json() return",
"self.N=10 if \"order\" in params: if params[\"order\"]==\"ascend\": self.json_data['network']['stations'] = sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('empty_slots',",
"sorted(self.json_data['network']['stations'], key=lambda k: int(k.get('free_bikes', 0)), reverse=True) for i in range(0,self.N): self.json_out.append(self.json_data['network']['stations'][i]) return json.loads(json.dumps(self.json_out,default=lambda",
"(float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01 and float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])>self.lon-0.01)): self.bikes+=int(self.json_data[\"network\"][\"stations\"][i][\"free_bikes\"]) self.slots+=int(self.json_data[\"network\"][\"stations\"][i][\"empty_slots\"]) self.json_out={\"latitude\":float(params[\"lat\"]),\"longitude\":float(params[\"lon\"]),\"bikes\":self.bikes,\"slots\":self.slots} return json.loads(json.dumps(self.json_out,default=lambda x: x.__dict__)) if __name__ ==",
"number not set\" for i in range(0,len(self.json_data[\"network\"][\"stations\"])): if ((float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])<self.lat+0.005 and float(self.json_data[\"network\"][\"stations\"][i][\"latitude\"])>self.lat-0.005) and (float(self.json_data[\"network\"][\"stations\"][i][\"longitude\"])<self.lon+0.01"
] |
[
"= float(input('Informe a temperatura em °C: ')) coversao = graus * 1.8 +",
"a temperatura em °C: ')) coversao = graus * 1.8 + 32 print(f'A",
"float(input('Informe a temperatura em °C: ')) coversao = graus * 1.8 + 32",
"graus = float(input('Informe a temperatura em °C: ')) coversao = graus * 1.8",
"coversao = graus * 1.8 + 32 print(f'A temperatura de {graus:.1f}°C corresponde a",
"°C: ')) coversao = graus * 1.8 + 32 print(f'A temperatura de {graus:.1f}°C",
"temperatura em °C: ')) coversao = graus * 1.8 + 32 print(f'A temperatura",
"= graus * 1.8 + 32 print(f'A temperatura de {graus:.1f}°C corresponde a {coversao:.1f}°F!')",
"')) coversao = graus * 1.8 + 32 print(f'A temperatura de {graus:.1f}°C corresponde",
"em °C: ')) coversao = graus * 1.8 + 32 print(f'A temperatura de"
] |
[
"PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty #for",
"you're feelng feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg') #",
"#camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty #for i",
"# for if you're feelng feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg'",
"camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng",
"feelng feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg') # camera.start_recording('/home/pi/video.h264')",
"#camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty #for i in range(5) sleep(15)",
"#camera = picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for",
"#for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg') # camera.start_recording('/home/pi/video.h264') #camera.wait_recording(10) #camera.stop_recording()",
"from picamera import PiCamera from time import sleep #camera = picamera.PiCamera() camera =",
"for if you're feelng feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i)",
"i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg') # camera.start_recording('/home/pi/video.h264') #camera.wait_recording(10) #camera.stop_recording() camera.stop_preview()",
"if you're feelng feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg')",
"sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() #",
"from time import sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080)",
"(1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty #for i in range(5)",
"import PiCamera from time import sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution",
"= (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty #for i in",
"picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're",
"<gh_stars>0 from picamera import PiCamera from time import sleep #camera = picamera.PiCamera() camera",
"= PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if you're feelng feisty",
"camera.start_preview() # for if you're feelng feisty #for i in range(5) sleep(15) #",
"picamera import PiCamera from time import sleep #camera = picamera.PiCamera() camera = PiCamera()",
"= picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview() # for if",
"import sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg') camera.start_preview()",
"time import sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution = (1920x1080) #camera.capture('Test.jpg')",
"feisty #for i in range(5) sleep(15) # camera.capture('/home/pi/capture%s.jpg' %i) camera.capture('/home/pi/capture1.jpg') # camera.start_recording('/home/pi/video.h264') #camera.wait_recording(10)",
"PiCamera from time import sleep #camera = picamera.PiCamera() camera = PiCamera() #camera.resolution ="
] |
[
"qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\",",
"\"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display =",
"django.contrib.contenttypes.admin import GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification",
"= [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def",
"list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self,",
"\"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",)",
"\"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering =",
"\"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering",
"class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter",
"here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def get_queryset(self, request): qs",
"\"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines",
"models.Notification extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template)",
"Register your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def",
"from django.contrib import admin from . import models from .models import Notification from",
"def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display =",
"return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\",",
"ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class",
"@admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,)",
"class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\",",
"[ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines",
"models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def get_queryset(self, request):",
"\"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines =",
"class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering",
"EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter",
"\"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\",",
"qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\",",
"django.contrib import admin from . import models from .models import Notification from django.contrib.contenttypes.admin",
"class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ]",
"\"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request)",
"] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def",
"import GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra",
"[ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\",",
"qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter",
"qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\",",
"import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline):",
"\"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\")",
"GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra =",
"\"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request):",
"\"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines =",
"= (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\",",
"get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\",",
"super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\",",
"= (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\",",
"(\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display",
"= (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin):",
"= (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request):",
"@admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ]",
"= (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs",
"import models from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your",
"(NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage)",
"def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display =",
"= super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\",",
"DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter =",
"\"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin):",
"(\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",)",
"\"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,)",
"return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\")",
"(\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display",
"(NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage)",
"list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\",",
"@admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter =",
"from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your models here.",
"import admin from . import models from .models import Notification from django.contrib.contenttypes.admin import",
"get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [",
"request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\",",
"= super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\",",
"super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\",",
"ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\",",
"# Register your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0",
"list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [",
"\"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering",
"request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\",",
"(\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs",
"admin from . import models from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline",
"@admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\",",
"class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def get_queryset(self, request): qs =",
"= (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin):",
"\"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class",
".models import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your models here. class",
"list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter =",
"= (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering =",
"= super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\",",
"super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"]",
"from django.contrib.contenttypes.admin import GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline): model =",
"0 def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin): list_display",
"ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class",
"inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return",
"\"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs =",
"\"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,)",
"(\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs =",
"\"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request)",
"= models.Notification extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\")",
"qs.prefetch_related(\"notify\") @admin.register(models.EmailMessage) class EmailMessageAdmin(admin.ModelAdmin): list_display = [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\",",
"qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines =",
"list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering",
"TemplateAdmin(admin.ModelAdmin): list_display = (\"name\", \"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\")",
"= [ \"subject\", \"sender\", \"receivers\", \"cc\", \"content_subtype\", \"content\", \"created_at\", ] list_filter = (\"subject\",",
"\"description\", \"code\", \"title\", \"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage)",
"WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering =",
"\"text\", \"kwargs\") list_filter = (\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display",
"\"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",)",
"request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\",",
"\"content\", \"created_at\", ] list_filter = (\"subject\", \"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering =",
"extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class",
"= 0 def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"to\") @admin.register(models.Template) class TemplateAdmin(admin.ModelAdmin):",
"\"created_at\", ] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def",
"def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display =",
"[\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self,",
"model = models.Notification extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) return",
"from . import models from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline #",
"] list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self,",
"return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines",
"= [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\", ] list_filter = (\"title\", \"created_at\")",
"models from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your models",
"get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\") @admin.register(models.WebsocketMessage) class WebsocketMessageAdmin(admin.ModelAdmin): list_display = [\"title\",",
"\"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs",
"list_filter = (\"title\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request):",
"(\"name\", \"code\") ordering = (\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\",",
"= (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.prefetch_related(\"notify\")",
"(\"name\",) @admin.register(models.DingDingMessage) class DingDingMessageAdmin(admin.ModelAdmin): list_display = [ \"title\", \"content\", \"at_mobiles\", \"is_at_all\", \"extra\", \"created_at\",",
"list_display = [\"title\", \"content\", \"msgtype\", \"groups\", \"created_at\"] inlines = (NotificationAdmin,) ordering = (\"-id\",)",
"Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register your models here. class NotificationAdmin(GenericTabularInline): model",
"\"content_subtype\", \"created_at\") inlines = (NotificationAdmin,) ordering = (\"-id\",) def get_queryset(self, request): qs =",
"NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def get_queryset(self, request): qs = super().get_queryset(request)",
"your models here. class NotificationAdmin(GenericTabularInline): model = models.Notification extra = 0 def get_queryset(self,",
". import models from .models import Notification from django.contrib.contenttypes.admin import GenericTabularInline # Register"
] |
[
"for action, child in node.children.items()) action = np.random.choice([action for action, child in node.children.items()",
"max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self, value): if self.maximum > self.minimum:",
"reversed(search_path): node.value_sum += value #if node.to_play == to_play else -value node.visit_count += 1",
"if save: game.plot_toolpath(save = True, folder = config.logdir, filename = filename) game.close() return",
"value): if self.maximum > self.minimum: return (value - self.minimum) / (self.maximum - self.minimum)",
"def backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum += value #if",
"game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder = config.logdir, filename = filename) game.close()",
"temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions)",
"temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return",
"self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state,",
"value = node.reward + self.config.discount * value class Node: def __init__(self, prior): self.visit_count",
"root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward",
"n in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac) + n",
"0 return self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward =",
"Node: def __init__(self, prior): self.visit_count = 0 self.prior = prior self.value_sum = 0",
"dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction",
"elif temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1",
"= visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action class",
"root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node =",
"= [] self.child_visits = [] self.root_values = [] def store_search_statistics(self, root, action_space): if",
"observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions,",
"= game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while (not done",
"(1 - frac) + n * frac class GameHistory: def __init__(self): self.observation_history =",
"in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else 0 for a",
"None: sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a",
"parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i",
"def store_search_statistics(self, root, action_space): if root is not None: sum_visits = sum(child.visit_count for",
"_, reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state)",
"0 return prior_score + value_score def backpropagate(self, search_path, value, min_max_stats): for node in",
"as np import torch import math import ray import copy import networks import",
"> 0: value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else: value_score",
"len(self.children) > 0 def value(self): if self.visit_count == 0: return 0 return self.value_sum",
"if temperature == 0 else True) action = select_action(root, temperature if len(game_history.action_history) <",
"GameHistory: def __init__(self): self.observation_history = [] self.action_history = [] self.reward_history = [] self.child_visits",
"self.config.discount * node.value()) value = node.reward + self.config.discount * value class Node: def",
"value) self.minimum = min(self.minimum, value) def normalize(self, value): if self.maximum > self.minimum: return",
"child.reward + self.config.discount * child.value() ) else: value_score = 0 return prior_score +",
"sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in",
"= actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts",
"True, folder = config.logdir, filename = filename) game.close() return game_history def select_action(node, temperature):",
"min_max_stats): for node in reversed(search_path): node.value_sum += value #if node.to_play == to_play else",
"parent = search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value",
"= 0 def expanded(self): return len(self.children) > 0 def value(self): if self.visit_count ==",
"= reward self.hidden_state = hidden_state policy = {} for a in actions: try:",
"p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys())",
"np import torch import math import ray import copy import networks import global_config",
"> self.minimum: return (value - self.minimum) / (self.maximum - self.minimum) return value if",
"= max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self, value): if self.maximum >",
"game_history = GameHistory() game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation =",
"exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node = root search_path",
"reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path,",
"= MCTS(config).run(model, observation, game.actions, False if temperature == 0 else True) action =",
"MCTS(config).run(model, observation, game.actions, False if temperature == 0 else True) action = select_action(root,",
"visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self, config):",
"prior_score + value_score def backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum",
"self.root_values = [] def store_search_statistics(self, root, action_space): if root is not None: sum_visits",
"== 0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions) else:",
"self.children = {} self.hidden_state = None self.reward = 0 def expanded(self): return len(self.children)",
"__init__(self, prior): self.visit_count = 0 self.prior = prior self.value_sum = 0 self.children =",
"node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action",
"= ( math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init",
"self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value)",
"child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else 0 for",
"import torch import math import ray import copy import networks import global_config def",
"value #if node.to_play == to_play else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount",
"+ self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count)",
") + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score =",
"if temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action =",
"visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS:",
"<= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if temperature == 0 else",
"config): self.config = config def run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0)",
"{} self.hidden_state = None self.reward = 0 def expanded(self): return len(self.children) > 0",
"= np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a, n in zip(actions, noise):",
"try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\")",
"networks import global_config def play_one_game(model, env_func, config, temperature, save=False, filename = ''): game_history",
"game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save",
"math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c",
"add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac =",
"done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if temperature",
"return action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count",
"= config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done =",
"game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while (not done and len(game_history.action_history) <=",
"game_history.reward_history.append(0) done = False with torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves):",
"= 0.0 for action, p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha,",
"self.backpropagate( search_path, value, min_max_stats ) return root def select_child(self, node, min_max_stats): max_ucb =",
"play_one_game(model, env_func, config, temperature, save=False, filename = ''): game_history = GameHistory() game =",
"backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum += value #if node.to_play",
") return root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for",
"action, child in node.children.items()) action = np.random.choice([action for action, child in node.children.items() if",
"policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state policy = {} for a",
"= self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference(",
"observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while (not",
"in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac) + n *",
"action, node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state",
"frac = exploration_fraction for a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior *",
"hidden_state): self.reward = reward self.hidden_state = hidden_state policy = {} for a in",
"prior_score = pb_c * child.prior if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward",
"actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts **",
"GameHistory() game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0)",
"for child in node.children.values()] ) actions = [action for action in node.children.keys()] if",
"+ n * frac class GameHistory: def __init__(self): self.observation_history = [] self.action_history =",
"def select_action(node, temperature): visit_counts = np.array( [child.visit_count for child in node.children.values()] ) actions",
"for node in reversed(search_path): node.value_sum += value #if node.to_play == to_play else -value",
"value) def normalize(self, value): if self.maximum > self.minimum: return (value - self.minimum) /",
"self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score",
"temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done, _ = game.step(action)",
"actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a,",
"with torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation,",
"torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions,",
"def __init__(self, prior): self.visit_count = 0 self.prior = prior self.value_sum = 0 self.children",
"search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum += value #if node.to_play ==",
"zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac) + n * frac",
"1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count +",
"self.hidden_state = None self.reward = 0 def expanded(self): return len(self.children) > 0 def",
"self.visit_count = 0 self.prior = prior self.value_sum = 0 self.children = {} self.hidden_state",
"float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value) def",
"else 0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for i in",
"[node] while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value,",
"= list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a, n",
"- self.minimum) / (self.maximum - self.minimum) return value if global_config.use_ray: play_one_game = ray.remote(play_one_game)",
"in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has",
"def ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base +",
"class GameHistory: def __init__(self): self.observation_history = [] self.action_history = [] self.reward_history = []",
"select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items())",
"0: return 0 return self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits, hidden_state):",
"node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward + self.config.discount",
"min_max_stats) for action, child in node.children.items()) action = np.random.choice([action for action, child in",
"has been approximated\") policy[a] = 0.0 for action, p in policy.items(): self.children[action] =",
"else True) action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation,",
"def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum =",
"= root search_path = [node] while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node)",
"min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else: value_score = 0 return prior_score",
"math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c * child.prior if child.visit_count >",
"np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self, config): self.config = config def",
"0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum",
"temperature == 0 else True) action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold",
"for action, child in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action,",
"float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution",
"model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for",
"in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder = config.logdir,",
"[i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats",
"len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if temperature == 0",
"visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action",
"min_max_stats ) return root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats)",
"= min(self.minimum, value) def normalize(self, value): if self.maximum > self.minimum: return (value -",
"MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum",
"self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\")",
"min(self.minimum, value) def normalize(self, value): if self.maximum > self.minimum: return (value - self.minimum)",
"for action in node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature",
"_ = game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if",
"search_path = [node] while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent =",
"def value(self): if self.visit_count == 0: return 0 return self.value_sum / self.visit_count def",
"pb_c * child.prior if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward + self.config.discount",
"= {} for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except",
"range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return root def",
"def __init__(self): self.observation_history = [] self.action_history = [] self.reward_history = [] self.child_visits =",
"return len(self.children) > 0 def value(self): if self.visit_count == 0: return 0 return",
"visit_counts = np.array( [child.visit_count for child in node.children.values()] ) actions = [action for",
"''): game_history = GameHistory() game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation",
"= visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution )",
"MinMaxStats() for _ in range(self.config.num_simulations): node = root search_path = [node] while node.expanded():",
"import math import ray import copy import networks import global_config def play_one_game(model, env_func,",
"game.close() return game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count for child in",
"for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning:",
"policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\") policy[a]",
"else 0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self):",
"torch import math import ray import copy import networks import global_config def play_one_game(model,",
"0 def value(self): if self.visit_count == 0: return 0 return self.value_sum / self.visit_count",
"len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i",
"return prior_score + value_score def backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path):",
"action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self, config): self.config =",
"reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation)",
"= False with torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves): root =",
"action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count +",
"self.config.discount * child.value() ) else: value_score = 0 return prior_score + value_score def",
"= search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value =",
"+ self.config.discount * node.value()) value = node.reward + self.config.discount * value class Node:",
"policy[a] = 0.0 for action, p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self,",
"Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions))",
"temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 /",
"* child.value() ) else: value_score = 0 return prior_score + value_score def backpropagate(self,",
"root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else 0 for a in",
"+= value #if node.to_play == to_play else -value node.visit_count += 1 min_max_stats.update(node.reward +",
"is not None: sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits",
"action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution =",
"action_space): if root is not None: sum_visits = sum(child.visit_count for child in root.children.values())",
"prior has been approximated\") policy[a] = 0.0 for action, p in policy.items(): self.children[action]",
"if root is not None: sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count",
"window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with",
"0 else True) action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0)",
"+ self.config.discount * child.value() ) else: value_score = 0 return prior_score + value_score",
"search_path, value, min_max_stats ) return root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node,",
"max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items()) action = np.random.choice([action for action,",
"= (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward,",
"value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward",
"min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c =",
"self.reward = reward self.hidden_state = hidden_state policy = {} for a in actions:",
"value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward,",
"if self.maximum > self.minimum: return (value - self.minimum) / (self.maximum - self.minimum) return",
"self.child_visits = [] self.root_values = [] def store_search_statistics(self, root, action_space): if root is",
"networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state,",
"= [] self.action_history = [] self.reward_history = [] self.child_visits = [] self.root_values =",
"node.reward + self.config.discount * value class Node: def __init__(self, prior): self.visit_count = 0",
"child in node.children.values()] ) actions = [action for action in node.children.keys()] if temperature",
"reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, )",
"in node.children.items()) action = np.random.choice([action for action, child in node.children.items() if self.ucb_score(node, child,",
"def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child in",
"observation, legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state",
"run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward,",
"game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder = config.logdir, filename = filename)",
"[i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True,",
"i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return",
"+ 1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count",
"game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save =",
"= reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate(",
"self.config = config def run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0) observation",
"action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum =",
") actions = [action for action in node.children.keys()] if temperature == 0: action",
"done = False with torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves): root",
"def play_one_game(model, env_func, config, temperature, save=False, filename = ''): game_history = GameHistory() game",
"done, _ = game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward)",
"( math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init )",
"actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been",
"root.children else 0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def",
"env_func, config, temperature, save=False, filename = ''): game_history = GameHistory() game = env_func(max_steps",
"/ self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state =",
"i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder =",
"[child.visit_count for child in node.children.values()] ) actions = [action for action in node.children.keys()]",
"sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else",
"range(self.config.num_simulations): node = root search_path = [node] while node.expanded(): action, node = self.select_child(node,",
"import copy import networks import global_config def play_one_game(model, env_func, config, temperature, save=False, filename",
"else: visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution / sum(",
"p=visit_count_distribution) return action class MCTS: def __init__(self, config): self.config = config def run(self,",
"= model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i",
"except OverflowError: print(\"Warning: prior has been approximated\") policy[a] = 0.0 for action, p",
"game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder = config.logdir, filename =",
"to_play else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value =",
"if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self, parent, child,",
"return 0 return self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward",
"def expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state policy",
"select_action(node, temperature): visit_counts = np.array( [child.visit_count for child in node.children.values()] ) actions =",
"= self.children[a].prior * (1 - frac) + n * frac class GameHistory: def",
"def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac",
"in node.children.values()] ) actions = [action for action in node.children.keys()] if temperature ==",
"self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c *",
"class MCTS: def __init__(self, config): self.config = config def run(self, model, observation, legal_actions,",
"def __init__(self, config): self.config = config def run(self, model, observation, legal_actions, add_exploration_noise): root",
"= select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done, _",
"+= 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward + self.config.discount *",
"for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else 0",
"game.actions, False if temperature == 0 else True) action = select_action(root, temperature if",
"actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state policy = {}",
"node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state =",
"for _ in range(self.config.num_simulations): node = root search_path = [node] while node.expanded(): action,",
"child, min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base",
"for action, p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions",
") min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node = root search_path =",
"self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha]",
"0.0 for action, p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction):",
"/ sum_visits if a in root.children else 0 for a in action_space]) self.root_values.append(root.value())",
"= Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] *",
"node in reversed(search_path): node.value_sum += value #if node.to_play == to_play else -value node.visit_count",
"= [] self.reward_history = [] self.child_visits = [] self.root_values = [] def store_search_statistics(self,",
"= float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value)",
"else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def",
"hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item() node.expand(",
"store_search_statistics(self, root, action_space): if root is not None: sum_visits = sum(child.visit_count for child",
"self.value_sum = 0 self.children = {} self.hidden_state = None self.reward = 0 def",
"np.array( [child.visit_count for child in node.children.values()] ) actions = [action for action in",
"+ self.config.discount * value class Node: def __init__(self, prior): self.visit_count = 0 self.prior",
"value_score def backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum += value",
"> 0 def value(self): if self.visit_count == 0: return 0 return self.value_sum /",
"max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items()) action = np.random.choice([action",
"-float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value) self.minimum =",
"import global_config def play_one_game(model, env_func, config, temperature, save=False, filename = ''): game_history =",
"self.children[a].prior = self.children[a].prior * (1 - frac) + n * frac class GameHistory:",
"node.value_sum += value #if node.to_play == to_play else -value node.visit_count += 1 min_max_stats.update(node.reward",
"reward, policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state policy = {} for",
"been approximated\") policy[a] = 0.0 for action, p in policy.items(): self.children[action] = Node(p)",
"a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior",
"add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node",
"temperature, save=False, filename = ''): game_history = GameHistory() game = env_func(max_steps = config.max_moves,",
"pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c * child.prior if",
"print(\"Warning: prior has been approximated\") policy[a] = 0.0 for action, p in policy.items():",
"def run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _,",
"save=False, filename = ''): game_history = GameHistory() game = env_func(max_steps = config.max_moves, window_size",
"0 self.children = {} self.hidden_state = None self.reward = 0 def expanded(self): return",
"action class MCTS: def __init__(self, config): self.config = config def run(self, model, observation,",
"min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device),",
"math import ray import copy import networks import global_config def play_one_game(model, env_func, config,",
"a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\")",
"1) prior_score = pb_c * child.prior if child.visit_count > 0: value_score = min_max_stats.normalize(",
"+ 1) prior_score = pb_c * child.prior if child.visit_count > 0: value_score =",
"action = np.random.choice([action for action, child in node.children.items() if self.ucb_score(node, child, min_max_stats) ==",
"True) action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward,",
"OverflowError: print(\"Warning: prior has been approximated\") policy[a] = 0.0 for action, p in",
"np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a, n in zip(actions, noise): self.children[a].prior",
"value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self, value): if",
"a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac) +",
"self.action_history = [] self.reward_history = [] self.child_visits = [] self.root_values = [] def",
"root, action_space): if root is not None: sum_visits = sum(child.visit_count for child in",
"__init__(self): self.observation_history = [] self.action_history = [] self.reward_history = [] self.child_visits = []",
"0 self.prior = prior self.value_sum = 0 self.children = {} self.hidden_state = None",
"global_config def play_one_game(model, env_func, config, temperature, save=False, filename = ''): game_history = GameHistory()",
"observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action)",
"= Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward =",
"= pb_c * child.prior if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward +",
"def normalize(self, value): if self.maximum > self.minimum: return (value - self.minimum) / (self.maximum",
"node = root search_path = [node] while node.expanded(): action, node = self.select_child(node, min_max_stats)",
"for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats )",
"parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base + 1) /",
"torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i in",
"{} for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError:",
"*= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c * child.prior if child.visit_count",
"MCTS: def __init__(self, config): self.config = config def run(self, model, observation, legal_actions, add_exploration_noise):",
"node.children.values()] ) actions = [action for action in node.children.keys()] if temperature == 0:",
"prior): self.visit_count = 0 self.prior = prior self.value_sum = 0 self.children = {}",
"hidden_state policy = {} for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] -",
"game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count for child in node.children.values()] )",
"game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while (not done and len(game_history.action_history)",
"class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self, value):",
"= 0 self.prior = prior self.value_sum = 0 self.children = {} self.hidden_state =",
"* len(actions)) frac = exploration_fraction for a, n in zip(actions, noise): self.children[a].prior =",
"== float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 / temperature)",
"node.value()) value = node.reward + self.config.discount * value class Node: def __init__(self, prior):",
"False if temperature == 0 else True) action = select_action(root, temperature if len(game_history.action_history)",
"return action class MCTS: def __init__(self, config): self.config = config def run(self, model,",
"= hidden_state policy = {} for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0]",
"max_ucb]) return action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log(",
"node.to_play == to_play else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value())",
"self.minimum: return (value - self.minimum) / (self.maximum - self.minimum) return value if global_config.use_ray:",
"else: value_score = 0 return prior_score + value_score def backpropagate(self, search_path, value, min_max_stats):",
"self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state",
"reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward =",
"node.children.items()) action = np.random.choice([action for action, child in node.children.items() if self.ucb_score(node, child, min_max_stats)",
"config def run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device))",
"else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward",
"import networks import global_config def play_one_game(model, env_func, config, temperature, save=False, filename = ''):",
"action in node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature ==",
"visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action",
"config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if temperature == 0 else True)",
"node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base",
"node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value,",
"= [] def store_search_statistics(self, root, action_space): if root is not None: sum_visits =",
"folder = config.logdir, filename = filename) game.close() return game_history def select_action(node, temperature): visit_counts",
"/ temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution)",
"== 0: return 0 return self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits,",
"* value class Node: def __init__(self, prior): self.visit_count = 0 self.prior = prior",
"== 0 else True) action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else",
"in root.children else 0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats:",
"pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base ) +",
"import numpy as np import torch import math import ray import copy import",
"hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise(",
"= 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\") policy[a] =",
"node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self, parent,",
"+ value_score def backpropagate(self, search_path, value, min_max_stats): for node in reversed(search_path): node.value_sum +=",
"if self.visit_count == 0: return 0 return self.value_sum / self.visit_count def expand(self, actions,",
"root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats()",
"= max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items()) action = np.random.choice([action for",
"= ''): game_history = GameHistory() game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1])",
"in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise",
"return (value - self.minimum) / (self.maximum - self.minimum) return value if global_config.use_ray: play_one_game",
"game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation)",
"policy = {} for a in actions: try: policy[a] = 1/sum(torch.exp(policy_logits[0] - policy_logits[0][a]))",
"save: game.plot_toolpath(save = True, folder = config.logdir, filename = filename) game.close() return game_history",
"= GameHistory() game = env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation = game.reset()",
"[action for action in node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)] elif",
"= model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha,",
"== to_play else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value",
"child.value() ) else: value_score = 0 return prior_score + value_score def backpropagate(self, search_path,",
"< config.temperature_threshold else 0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for",
"* frac class GameHistory: def __init__(self): self.observation_history = [] self.action_history = [] self.reward_history",
"= -float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value) self.minimum",
"reward self.hidden_state = hidden_state policy = {} for a in actions: try: policy[a]",
"self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children else 0 for a in action_space])",
"noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a, n in zip(actions,",
"_ in range(self.config.num_simulations): node = root search_path = [node] while node.expanded(): action, node",
"np.random.choice([action for action, child in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return",
"and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if temperature ==",
"len(actions)) frac = exploration_fraction for a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior",
"min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base )",
"select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done, _ =",
"- policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\") policy[a] = 0.0 for",
"self.minimum = min(self.minimum, value) def normalize(self, value): if self.maximum > self.minimum: return (value",
"numpy as np import torch import math import ray import copy import networks",
"legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state =",
"0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)])",
"= MinMaxStats() for _ in range(self.config.num_simulations): node = root search_path = [node] while",
"[] self.reward_history = [] self.child_visits = [] self.root_values = [] def store_search_statistics(self, root,",
"= {} self.hidden_state = None self.reward = 0 def expanded(self): return len(self.children) >",
"(child.visit_count + 1) prior_score = pb_c * child.prior if child.visit_count > 0: value_score",
"policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _",
"-value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward +",
"= np.array( [child.visit_count for child in node.children.values()] ) actions = [action for action",
"observation, game.actions, False if temperature == 0 else True) action = select_action(root, temperature",
"self.hidden_state = hidden_state policy = {} for a in actions: try: policy[a] =",
"== max_ucb]) return action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c = (",
"[] self.root_values = [] def store_search_statistics(self, root, action_space): if root is not None:",
"self.minimum = float(\"inf\") def update(self, value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum,",
"value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else: value_score = 0",
"= True, folder = config.logdir, filename = filename) game.close() return game_history def select_action(node,",
"config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False",
"= sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if a in root.children",
"/ (child.visit_count + 1) prior_score = pb_c * child.prior if child.visit_count > 0:",
"np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution /",
"value, min_max_stats): for node in reversed(search_path): node.value_sum += value #if node.to_play == to_play",
") pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c * child.prior",
"child in node.children.items()) action = np.random.choice([action for action, child in node.children.items() if self.ucb_score(node,",
"Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item()",
"0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"): action = np.random.choice(actions) else: visit_count_distribution",
"policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise:",
"return self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward",
"policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return root def select_child(self, node,",
"config.temperature_threshold else 0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root, [i for i",
"self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self, parent, child, min_max_stats):",
") self.backpropagate( search_path, value, min_max_stats ) return root def select_child(self, node, min_max_stats): max_ucb",
"= exploration_fraction for a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1",
"self.config.discount * value class Node: def __init__(self, prior): self.visit_count = 0 self.prior =",
"actions = [action for action in node.children.keys()] if temperature == 0: action =",
"def expanded(self): return len(self.children) > 0 def value(self): if self.visit_count == 0: return",
"env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done",
"in range(self.config.num_simulations): node = root search_path = [node] while node.expanded(): action, node =",
"1/sum(torch.exp(policy_logits[0] - policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\") policy[a] = 0.0",
"= np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution",
"False with torch.no_grad(): while (not done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model,",
"if a in root.children else 0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None)",
") action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self, config): self.config",
"self.prior = prior self.value_sum = 0 self.children = {} self.hidden_state = None self.reward",
"ray import copy import networks import global_config def play_one_game(model, env_func, config, temperature, save=False,",
"reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats =",
"value(self): if self.visit_count == 0: return 0 return self.value_sum / self.visit_count def expand(self,",
"while (not done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False",
"(torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits,",
"visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution",
"in reversed(search_path): node.value_sum += value #if node.to_play == to_play else -value node.visit_count +=",
"value class Node: def __init__(self, prior): self.visit_count = 0 self.prior = prior self.value_sum",
"min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward + self.config.discount * value class",
"exploration_fraction): actions = list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for",
"min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node = root search_path = [node]",
"* (1 - frac) + n * frac class GameHistory: def __init__(self): self.observation_history",
"root search_path = [node] while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent",
"if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations):",
"= [node] while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2]",
"node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items()) action",
"= networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits,",
"__init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self, value): self.maximum = max(self.maximum,",
"* node.value()) value = node.reward + self.config.discount * value class Node: def __init__(self,",
"update(self, value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self, value):",
"while node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward,",
"/ self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1)",
"min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child in node.children.items()) action =",
"self.value_sum / self.visit_count def expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state",
"- frac) + n * frac class GameHistory: def __init__(self): self.observation_history = []",
"return game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count for child in node.children.values()]",
"dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in range(self.config.num_simulations): node = root",
"list(self.children.keys()) noise = np.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for a, n in",
"a in root.children else 0 for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class",
"model, observation, legal_actions, add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits,",
"__init__(self, config): self.config = config def run(self, model, observation, legal_actions, add_exploration_noise): root =",
") value = networks.support_to_scalar(value).item() reward = reward.item() node.expand( [i for i in range(self.config.action_space_size)],",
"noise): self.children[a].prior = self.children[a].prior * (1 - frac) + n * frac class",
"self.observation_history = [] self.action_history = [] self.reward_history = [] self.child_visits = [] self.root_values",
"self.reward_history = [] self.child_visits = [] self.root_values = [] def store_search_statistics(self, root, action_space):",
"= None self.reward = 0 def expanded(self): return len(self.children) > 0 def value(self):",
"class Node: def __init__(self, prior): self.visit_count = 0 self.prior = prior self.value_sum =",
"= np.random.choice([action for action, child in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb])",
"filename) game.close() return game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count for child",
"= config.logdir, filename = filename) game.close() return game_history def select_action(node, temperature): visit_counts =",
"0 def expanded(self): return len(self.children) > 0 def value(self): if self.visit_count == 0:",
"if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done, _ = game.step(action) game_history.store_search_statistics(root,",
"self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum = float(\"inf\") def update(self,",
"expand(self, actions, reward, policy_logits, hidden_state): self.reward = reward self.hidden_state = hidden_state policy =",
"child.visit_count > 0: value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else:",
"(parent.visit_count + self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *=",
"= [] self.root_values = [] def store_search_statistics(self, root, action_space): if root is not",
"filename = ''): game_history = GameHistory() game = env_func(max_steps = config.max_moves, window_size =",
"(value - self.minimum) / (self.maximum - self.minimum) return value if global_config.use_ray: play_one_game =",
"child, min_max_stats) for action, child in node.children.items()) action = np.random.choice([action for action, child",
"in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self,",
"reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return root def select_child(self,",
"action, child in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action]",
"sum_visits if a in root.children else 0 for a in action_space]) self.root_values.append(root.value()) else:",
"(1 / temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action = np.random.choice(actions,",
"if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value() )",
"reward = reward.item() node.expand( [i for i in range(self.config.action_space_size)], reward, policy_logits, hidden_state, )",
"filename = filename) game.close() return game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count",
"config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while",
"child.prior if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value()",
"for a in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum =",
"sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self,",
"[] self.child_visits = [] self.root_values = [] def store_search_statistics(self, root, action_space): if root",
"= config def run(self, model, observation, legal_actions, add_exploration_noise): root = Node(0) observation =",
"search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item()",
"expanded(self): return len(self.children) > 0 def value(self): if self.visit_count == 0: return 0",
"in range(self.config.action_space_size)], reward, policy_logits, hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return root",
"for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder",
"= 0 self.children = {} self.hidden_state = None self.reward = 0 def expanded(self):",
"[] self.action_history = [] self.reward_history = [] self.child_visits = [] self.root_values = []",
"action = np.random.choice(actions) else: visit_count_distribution = visit_counts ** (1 / temperature) visit_count_distribution =",
"copy import networks import global_config def play_one_game(model, env_func, config, temperature, save=False, filename =",
"for a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac)",
"= prior self.value_sum = 0 self.children = {} self.hidden_state = None self.reward =",
"#if node.to_play == to_play else -value node.visit_count += 1 min_max_stats.update(node.reward + self.config.discount *",
") else: value_score = 0 return prior_score + value_score def backpropagate(self, search_path, value,",
"in node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)] elif temperature == float(\"inf\"):",
"game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad(): while (not done and",
"** (1 / temperature) visit_count_distribution = visit_count_distribution / sum( visit_count_distribution ) action =",
"ucb_score(self, parent, child, min_max_stats): pb_c = ( math.log( (parent.visit_count + self.config.pb_c_base + 1)",
"= 0 return prior_score + value_score def backpropagate(self, search_path, value, min_max_stats): for node",
"reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for",
"def update(self, value): self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self,",
"= game.step(action) game_history.store_search_statistics(root, [i for i in range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save:",
"approximated\") policy[a] = 0.0 for action, p in policy.items(): self.children[action] = Node(p) def",
"import ray import copy import networks import global_config def play_one_game(model, env_func, config, temperature,",
"self.visit_count == 0: return 0 return self.value_sum / self.visit_count def expand(self, actions, reward,",
"add_exploration_noise): root = Node(0) observation = (torch.tensor(observation).float().unsqueeze(0).to(next(model.parameters()).device)) _, reward, policy_logits, hidden_state = model.initial_inference(observation)",
"action = select_action(root, temperature if len(game_history.action_history) < config.temperature_threshold else 0) observation, reward, done,",
"prior self.value_sum = 0 self.children = {} self.hidden_state = None self.reward = 0",
"config, temperature, save=False, filename = ''): game_history = GameHistory() game = env_func(max_steps =",
"= config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0) done = False with torch.no_grad():",
"policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise =",
"root = MCTS(config).run(model, observation, game.actions, False if temperature == 0 else True) action",
"self.config.pb_c_base + 1) / self.config.pb_c_base ) + self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) /",
"= node.reward + self.config.discount * value class Node: def __init__(self, prior): self.visit_count =",
"frac) + n * frac class GameHistory: def __init__(self): self.observation_history = [] self.action_history",
"None self.reward = 0 def expanded(self): return len(self.children) > 0 def value(self): if",
"game.plot_toolpath(save = True, folder = config.logdir, filename = filename) game.close() return game_history def",
"search_path.append(node) parent = search_path[-2] value, reward, policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), )",
"hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats = MinMaxStats() for _ in",
"not None: sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count / sum_visits if",
"= reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction, ) min_max_stats",
"/ sum( visit_count_distribution ) action = np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def",
"= min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else: value_score = 0 return",
"= env_func(max_steps = config.max_moves, window_size = config.observation_shape[1]) observation = game.reset() game_history.action_history.append(0) game_history.observation_history.append(observation) game_history.reward_history.append(0)",
"frac class GameHistory: def __init__(self): self.observation_history = [] self.action_history = [] self.reward_history =",
"temperature): visit_counts = np.array( [child.visit_count for child in node.children.values()] ) actions = [action",
"policy_logits, hidden_state = model.recurrent_inference( parent.hidden_state, torch.tensor([[action]]).to(parent.hidden_state.device), ) value = networks.support_to_scalar(value).item() reward = reward.item()",
"self.maximum = max(self.maximum, value) self.minimum = min(self.minimum, value) def normalize(self, value): if self.maximum",
"self.maximum > self.minimum: return (value - self.minimum) / (self.maximum - self.minimum) return value",
"exploration_fraction for a, n in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 -",
"node.expanded(): action, node = self.select_child(node, min_max_stats) search_path.append(node) parent = search_path[-2] value, reward, policy_logits,",
"(not done and len(game_history.action_history) <= config.max_moves): root = MCTS(config).run(model, observation, game.actions, False if",
"* child.prior if child.visit_count > 0: value_score = min_max_stats.normalize( child.reward + self.config.discount *",
"= np.random.choice(actions, p=visit_count_distribution) return action class MCTS: def __init__(self, config): self.config = config",
"0: value_score = min_max_stats.normalize( child.reward + self.config.discount * child.value() ) else: value_score =",
"n * frac class GameHistory: def __init__(self): self.observation_history = [] self.action_history = []",
"self.reward = 0 def expanded(self): return len(self.children) > 0 def value(self): if self.visit_count",
"hidden_state, ) self.backpropagate( search_path, value, min_max_stats ) return root def select_child(self, node, min_max_stats):",
"= [action for action in node.children.keys()] if temperature == 0: action = actions[np.argmax(visit_counts)]",
"in action_space]) self.root_values.append(root.value()) else: self.root_values.append(None) class MinMaxStats: def __init__(self): self.maximum = -float(\"inf\") self.minimum",
"config.logdir, filename = filename) game.close() return game_history def select_action(node, temperature): visit_counts = np.array(",
"value_score = 0 return prior_score + value_score def backpropagate(self, search_path, value, min_max_stats): for",
"self.children[a].prior * (1 - frac) + n * frac class GameHistory: def __init__(self):",
"child in node.children.items() if self.ucb_score(node, child, min_max_stats) == max_ucb]) return action, node.children[action] def",
"+ self.config.pb_c_init ) pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) prior_score = pb_c",
"[] def store_search_statistics(self, root, action_space): if root is not None: sum_visits = sum(child.visit_count",
"normalize(self, value): if self.maximum > self.minimum: return (value - self.minimum) / (self.maximum -",
"value, min_max_stats ) return root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child,",
"child, min_max_stats) == max_ucb]) return action, node.children[action] def ucb_score(self, parent, child, min_max_stats): pb_c",
"range(config.action_space_size)]) game_history.action_history.append(action) game_history.observation_history.append(observation) game_history.reward_history.append(reward) if save: game.plot_toolpath(save = True, folder = config.logdir, filename",
"return root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action,",
"model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if add_exploration_noise: root.add_exploration_noise( dirichlet_alpha=self.config.root_dirichlet_alpha, exploration_fraction=self.config.root_exploration_fraction,",
"action, p in policy.items(): self.children[action] = Node(p) def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions =",
"root def select_child(self, node, min_max_stats): max_ucb = max(self.ucb_score(node, child, min_max_stats) for action, child",
"policy_logits[0][a])) except OverflowError: print(\"Warning: prior has been approximated\") policy[a] = 0.0 for action,",
"1 min_max_stats.update(node.reward + self.config.discount * node.value()) value = node.reward + self.config.discount * value",
"= filename) game.close() return game_history def select_action(node, temperature): visit_counts = np.array( [child.visit_count for",
"reward, policy_logits, hidden_state = model.initial_inference(observation) reward = reward.item() root.expand(legal_actions, reward, policy_logits, hidden_state) if",
"root is not None: sum_visits = sum(child.visit_count for child in root.children.values()) self.child_visits.append([root.children[a].visit_count /"
] |
[
"import csv from smtplib import SMTPException from django.core.management.base import BaseCommand from django.core.mail import",
"Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A',",
"= EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de l'envoi des mails",
"import io import csv from smtplib import SMTPException from django.core.management.base import BaseCommand from",
"csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage(",
"de l'application - mail test\"), \"Test de l'envoi des mails depuis l'application BVC.\",",
"import BaseCommand from django.core.mail import EmailMessage from django.conf import settings from bvc import",
"EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de l'envoi des mails depuis",
"**options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email =",
"from django.core.mail import EmailMessage from django.conf import settings from bvc import utils class",
"BaseCommand from django.core.mail import EmailMessage from django.conf import settings from bvc import utils",
"from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.conf import settings from",
"handle(self, *args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',])",
"des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv') if",
"settings from bvc import utils class Command(BaseCommand): def handle(self, *args, **options): csvfile =",
"import SMTPException from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.conf import",
"'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de",
"csv from smtplib import SMTPException from django.core.management.base import BaseCommand from django.core.mail import EmailMessage",
"import EmailMessage from django.conf import settings from bvc import utils class Command(BaseCommand): def",
"writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application",
"smtplib import SMTPException from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.conf",
"writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"),",
"mail test\"), \"Test de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [],",
"utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de l'envoi des mails depuis l'application",
"class Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col",
"*args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email",
"= io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage",
"de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(),",
"l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv')",
"csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail",
"\"Test de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv',",
"django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.conf import settings from bvc",
"BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv') if not email.send(): raise SMTPException()",
"SMTPException from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.conf import settings",
"django.core.mail import EmailMessage from django.conf import settings from bvc import utils class Command(BaseCommand):",
"test\"), \"Test de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], )",
"django.conf import settings from bvc import utils class Command(BaseCommand): def handle(self, *args, **options):",
"bvc import utils class Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO() writer",
"B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de l'envoi",
"from django.conf import settings from bvc import utils class Command(BaseCommand): def handle(self, *args,",
"= csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application -",
"io import csv from smtplib import SMTPException from django.core.management.base import BaseCommand from django.core.mail",
"io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de",
"import settings from bvc import utils class Command(BaseCommand): def handle(self, *args, **options): csvfile",
"A', 'Col B',]) email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test",
"l'application - mail test\"), \"Test de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER,",
"email = EmailMessage( utils.format_mail_subject(\"Démarrage de l'application - mail test\"), \"Test de l'envoi des",
"mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv') if not",
"def handle(self, *args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile) writer.writerow(['Col A', 'Col",
"from smtplib import SMTPException from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from",
"import utils class Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO() writer =",
"- mail test\"), \"Test de l'envoi des mails depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER],",
"l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv') if not email.send(): raise",
"EmailMessage from django.conf import settings from bvc import utils class Command(BaseCommand): def handle(self,",
"depuis l'application BVC.\", settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], [], ) email.attach('test.csv', csvfile.getvalue(), 'text/csv') if not email.send():",
"from bvc import utils class Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO()",
"utils class Command(BaseCommand): def handle(self, *args, **options): csvfile = io.StringIO() writer = csv.writer(csvfile)"
] |
[
"vispy import app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import",
"vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg,",
"ny, nx = vol.shape mid = ny // 2 vol1 = vol[:, :mid,",
"import logging import os import imageio import numpy as np from vispy import",
"create view box view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256",
"= 240 axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0 /",
"folder exists pass psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average",
"axis.update() # render rotation movie \"\"\" n_steps = 240 axis = [0, 0,",
"as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average",
"dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists pass psf_avg =",
"axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0))",
"mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2] # preview_volume((vol, )) # main()",
"True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50,",
"numpy as np from vispy import app, scene from vispy.color.colormap import BaseColormap, Colormap,",
"for i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)]",
"3] /= 100 cmap = Colormap(color) for i, vol in enumerate(vols): volume =",
"genereate colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color =",
"psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average)",
"= vol.shape mid = ny // 2 vol1 = vol[:, :mid, :] vol2",
"volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera(",
"axis.transform = affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button ==",
"view.camera.flip = (False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s =",
"color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0 color[:, 3] /=",
"sample import cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average",
"/ n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im = canvas.render()",
"imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close()",
"parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip = (False, True, True)",
"if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1,",
"= 1024, 1024 canvas.show() # create view box view = canvas.central_widget.add_view() # genereate",
"+ sample) / 2 except TypeError: psf_average = sample import cupy as cp",
"os import imageio import numpy as np from vispy import app, scene from",
"BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore",
"from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols,",
"axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine =",
"import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ ==",
"cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\",",
"# link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging:",
"assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera",
"360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im =",
"ny // 2 vol1 = vol[:, :mid, :] vol2 = vol[:, mid:, :]",
"alphas, alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color =",
"%(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import",
"color = np.array(color) color[0, :] = 0 color[:, 3] /= 100 cmap =",
"colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[",
"= scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign",
"= 0 nz, ny, nx = vol.shape mid = ny // 2 vol1",
"logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io",
"= [f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir,",
"utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None):",
"for c in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample)",
"view box view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256 alphas",
"\"\"\" import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol",
"= None for i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c",
"psfs = psf_avg(vol, return_coords=True) psf_average = None for i, (sample, coord) in enumerate(psfs):",
"psf_average = sample import cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import",
"auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std =",
"view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)}",
"scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip = (False, True,",
"volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0",
"imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol = cp.asarray(vol) from",
"TypeError: psf_average = sample import cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure",
"volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform =",
"vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger =",
"= STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform = affine",
"view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50,",
"box view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256 alphas =",
"from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger",
"\"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for",
"vol.shape mid = ny // 2 vol1 = vol[:, :mid, :] vol2 =",
"50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform = affine # link",
"imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average + sample) / 2 except TypeError:",
"import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy",
"if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\",",
"coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average",
"alphas, alphas, alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color",
"\"\"\" n_steps = 240 axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle =",
"vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method =",
"alphas, alphas, alphas, alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap",
"if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0,",
"axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer",
"shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create view box",
"scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform = affine # link with",
"] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color",
"= sample import cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast",
"AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0 color[:, 3] /= 100 cmap",
"= np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas ] cmap",
"vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0)))",
"vol[:, :mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0),",
"(avg - std)] = 0 nz, ny, nx = vol.shape mid = ny",
"2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera",
"axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50,",
"extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root,",
"import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\"",
"in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average",
"= cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average)",
") volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts:",
"affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and",
"\"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i])",
"PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas =",
"= vol.mean(), vol.std() vol[vol < (avg - std)] = 0 nz, ny, nx",
"with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll,",
"auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype)",
"preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5,",
"np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import",
"from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import",
"sample) try: psf_average = (psf_average + sample) / 2 except TypeError: psf_average =",
"ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists pass",
"import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1)",
"FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items(): logger.info(key) dst_dir",
"cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average)",
"n_colors) color = np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color) \"\"\"",
"= (False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50,",
"i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def",
"= (psf_average + sample) / 2 except TypeError: psf_average = sample import cupy",
"= 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im",
"(0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2] # preview_volume((vol, )) #",
"50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\" n_steps = 240",
"= 256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas,",
"np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp",
"f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average + sample) / 2 except",
"import numpy as np from vispy import app, scene from vispy.color.colormap import BaseColormap,",
"0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for",
"utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size",
"imageio import numpy as np from vispy import app, scene from vispy.color.colormap import",
"= scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2,",
"# render rotation movie \"\"\" n_steps = 240 axis = [0, 0, 0]",
"# axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1))",
"vol1 = vol[:, :mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0,",
"try: os.mkdir(dst_dir) except: # folder exists pass psf_avg = PSFAverage((97, 97, 97)) psfs",
"# assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera =",
"camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip =",
"def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol",
"@canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0,",
"n_steps = 240 axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0",
"fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\"",
"exists pass psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average =",
"color = np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color) \"\"\" from",
"= vol[:, :mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid,",
"(psf_average + sample) / 2 except TypeError: psf_average = sample import cupy as",
"logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists pass psf_avg",
"[f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname),",
"2 except TypeError: psf_average = sample import cupy as cp psf_average = cp.asarray(psf_average)",
"import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0 color[:,",
"\"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :]",
"0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\" n_steps = 240 axis",
"import PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas",
"in enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord) fname",
"fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype)",
"= np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol < (avg",
"= Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene,",
"utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0",
"vol2), ((0, -mid, 0), (0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2]",
"vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(),",
"100 cmap = Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume( vol,",
"im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds =",
"cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol",
"step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps):",
"render rotation movie \"\"\" n_steps = 240 axis = [0, 0, 0] logger.debug(\"..",
"= scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix()",
"0 nz, ny, nx = vol.shape mid = ny // 2 vol1 =",
"s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform =",
"ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items():",
"from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if",
"= AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0 color[:, 3] /= 100",
"level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"]",
"- std)] = 0 nz, ny, nx = vol.shape mid = ny //",
"axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine",
"emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if",
":] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid,",
"in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\"",
"auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR)",
"/= 100 cmap = Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume(",
"cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol =",
"logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024",
"0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001))",
"except: # folder exists pass psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol,",
"import cupy as cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average =",
"# genereate colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color",
"preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create view",
"= auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs",
"= ny // 2 vol1 = vol[:, :mid, :] vol2 = vol[:, mid:,",
"0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol < (avg - std)]",
"except TypeError: psf_average = sample import cupy as cp psf_average = cp.asarray(psf_average) from",
"[0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\",",
"STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def",
"depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene,",
"vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif')",
"imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast",
"print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol < (avg - std)] = 0",
"i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)] coord",
"0, 0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24)",
"np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol < (avg -",
"i, vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method",
"in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"):",
"affine = s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event):",
"import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from",
"os.mkdir(dst_dir) except: # folder exists pass psf_avg = PSFAverage((97, 97, 97)) psfs =",
"= np.array(color) color[0, :] = 0 color[:, 3] /= 100 cmap = Colormap(color)",
"= logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show()",
"FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024,",
"canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors)",
"(False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50),",
"vol.std() vol[vol < (avg - std)] = 0 nz, ny, nx = vol.shape",
"n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas,",
"from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\")",
"return_coords=True) psf_average = None for i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\"",
"from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] =",
"writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\")",
"import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol =",
"logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key)",
"vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy",
"vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage",
"color[0, :] = 0 color[:, 3] /= 100 cmap = Colormap(color) for i,",
") view.camera = camera view.camera.flip = (False, True, True) view.camera.reset() # axis axis",
"coord = [f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\"",
"enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform",
"canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread,",
"< (avg - std)] = 0 nz, ny, nx = vol.shape mid =",
"2 vol1 = vol[:, :mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2),",
"= psf_avg(vol, return_coords=True) psf_average = None for i, (sample, coord) in enumerate(psfs): coord",
"scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create view box view = canvas.central_widget.add_view()",
"= vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0))) #",
"0), (0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2] # preview_volume((vol, ))",
"= cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install(",
"break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s",
"cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol)",
"240 axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps",
"= FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items(): logger.info(key)",
"1)) affine = s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect def",
"1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0,",
"0 color[:, 3] /= 100 cmap = Colormap(color) for i, vol in enumerate(vols):",
"coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import",
"scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera",
"alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\")",
"read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in ds.items(): logger.info(key) dst_dir =",
"# create view box view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors =",
"and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0,",
"0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() #",
"logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol",
"psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING)",
"rotation movie \"\"\" n_steps = 240 axis = [0, 0, 0] logger.debug(\".. rendering\")",
"key) try: os.mkdir(dst_dir) except: # folder exists pass psf_avg = PSFAverage((97, 97, 97))",
"= PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average = None for i,",
"vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure",
"app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key,",
"writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"])",
"fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average + sample) /",
"as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol",
"for i, vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False )",
"utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__",
"scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2,",
"\"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from",
"97)) psfs = psf_avg(vol, return_coords=True) psf_average = None for i, (sample, coord) in",
"psf_average = (psf_average + sample) / 2 except TypeError: psf_average = sample import",
"volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform",
"= scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create view box view =",
"\"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas,",
"psf_avg(vol, return_coords=True) psf_average = None for i, (sample, coord) in enumerate(psfs): coord =",
"= canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0, 1.0,",
"cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol =",
"import os import imageio import numpy as np from vispy import app, scene",
"logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i",
"rendering\") step_angle = 360.0 / n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in",
"AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0, :] = 0 color[:, 3]",
"True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50,",
"= cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol",
"logging import os import imageio import numpy as np from vispy import app,",
"canvas.size = 1024, 1024 canvas.show() # create view box view = canvas.central_widget.add_view() #",
"writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle,",
"alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas ]",
"datefmt=\"%H:%M:%S\" ) from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio",
"sample) / 2 except TypeError: psf_average = sample import cupy as cp psf_average",
"1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol < (avg - std)] =",
"print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol",
"(0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50,",
"1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\"",
"5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera =",
"vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std() vol[vol <",
"elevation=30.0 ) view.camera = camera view.camera.flip = (False, True, True) view.camera.reset() # axis",
"key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: #",
"1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth,",
"vol[vol < (avg - std)] = 0 nz, ny, nx = vol.shape mid",
":mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0,",
"import app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform",
"0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render",
"nz, ny, nx = vol.shape mid = ny // 2 vol1 = vol[:,",
"# folder exists pass psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True)",
"on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation,",
"color[:, 3] /= 100 cmap = Colormap(color) for i, vol in enumerate(vols): volume",
"vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder",
"def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1))",
"in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists",
"from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol,",
"(1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update()",
"coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol =",
"cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\",",
"vol, cmap=cmap, parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5))",
"name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip = (False, True, True) view.camera.reset() #",
"fname), sample) try: psf_average = (psf_average + sample) / 2 except TypeError: psf_average",
"import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol = cp.asarray(vol)",
"1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color)",
"app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from",
"view.camera = camera view.camera.flip = (False, True, True) view.camera.reset() # axis axis =",
"found\") for key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir)",
"io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import",
"psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\": import",
"vol[:, mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0))) # vol",
"= auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std",
"import imageio import numpy as np from vispy import app, scene from vispy.color.colormap",
"(0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie",
"preview_volume(psf_average) break if __name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s",
"= camera view.camera.flip = (False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view)",
"utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0,",
"mid:, :] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0))) # vol =",
"enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord) fname =",
"std = vol.mean(), vol.std() vol[vol < (avg - std)] = 0 nz, ny,",
"== \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" )",
"cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color =",
"psf_average = None for i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for",
"volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) #",
"view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors = 256 alphas = np.linspace(0.0,",
"psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average = None for",
"avg, std = vol.mean(), vol.std() vol[vol < (avg - std)] = 0 nz,",
"= scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip = (False,",
"s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button",
"camera view.camera.flip = (False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s",
"= Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color)",
"ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore",
"for key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try: os.mkdir(dst_dir) except:",
":] = 0 color[:, 3] /= 100 cmap = Colormap(color) for i, vol",
"= np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color) \"\"\" from utoolbox.data.io.amira",
"c in reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try:",
"std)] = 0 nz, ny, nx = vol.shape mid = ny // 2",
"97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average = None for i, (sample, coord)",
"%(levelname)s %(message)s\", datefmt=\"%H:%M:%S\" ) from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\"",
"from vispy import app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms",
"file(s) found\") for key, vol in ds.items(): logger.info(key) dst_dir = os.path.join(root, key) try:",
"None for i, (sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c in",
"scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera",
"movie \"\"\" n_steps = 240 axis = [0, 0, 0] logger.debug(\".. rendering\") step_angle",
"Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import",
"np from vispy import app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from",
"fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip = (False, True, True) view.camera.reset()",
"scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform",
"axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0))",
"vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol)",
"Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap, parent=view.scene, emulate_texture=False",
"= np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as",
"range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds",
"event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0,",
"= \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average +",
"= s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if",
"= affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1",
"canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create view box view",
"cmap = Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume( vol, cmap=cmap,",
"(sample, coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)] coord =",
"for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run()",
"= f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average + sample) / 2",
"50, 50, 1)) affine = s.as_matrix() axis.transform = affine # link with camera",
"0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\" n_steps",
"Colormap(color) \"\"\" from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap(\"volrenGlow.am\") color = np.array(color) color[0,",
"== 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0))",
"= \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False) if shifts: volume.transform =",
"reversed(coord)] coord = \"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average =",
"= os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists pass psf_avg = PSFAverage((97,",
"try: psf_average = (psf_average + sample) / 2 except TypeError: psf_average = sample",
"event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1,",
") from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol",
"scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray from vispy.visuals.transforms import STTransform from utoolbox.analysis.psf_average",
"\"-\".join(coord) fname = f\"psf_{i:03d}_{coord}.tif\" imageio.volwrite(os.path.join(dst_dir, fname), sample) try: psf_average = (psf_average + sample)",
"vol.mean(), vol.std() vol[vol < (avg - std)] = 0 nz, ny, nx =",
"os.path.join(root, key) try: os.mkdir(dst_dir) except: # folder exists pass psf_avg = PSFAverage((97, 97,",
"50, 1)) affine = s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect",
"PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average = None for i, (sample,",
"STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform = affine #",
"/ 2 except TypeError: psf_average = sample import cupy as cp psf_average =",
"1024, 1024 canvas.show() # create view box view = canvas.central_widget.add_view() # genereate colormap",
"axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s)",
"= 0 color[:, 3] /= 100 cmap = Colormap(color) for i, vol in",
"axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\" n_steps =",
"-mid, 0), (0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2] # preview_volume((vol,",
"= imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import",
"shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\",",
"50.0)) axis.update() # render rotation movie \"\"\" n_steps = 240 axis = [0,",
"1024 canvas.show() # create view box view = canvas.central_widget.add_view() # genereate colormap \"\"\"",
"logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() #",
"((0, -mid, 0), (0, mid, 0))) # vol = vol[:, fc00:db20:35b:7399::5, ::2] #",
"np.array(color) color[0, :] = 0 color[:, 3] /= 100 cmap = Colormap(color) for",
"auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break if __name__ == \"__main__\":",
"// 2 vol1 = vol[:, :mid, :] vol2 = vol[:, mid:, :] preview_volume((vol1,",
"axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation",
"import FolderDatastore logger = logging.getLogger(__name__) def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size =",
"mid = ny // 2 vol1 = vol[:, :mid, :] vol2 = vol[:,",
"canvas.show() # create view box view = canvas.central_widget.add_view() # genereate colormap \"\"\" n_colors",
"= cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype) avg, std = vol.mean(), vol.std()",
"import STTransform from utoolbox.analysis.psf_average import PSFAverage from utoolbox.data.datastore import FolderDatastore logger = logging.getLogger(__name__)",
"= [0, 0, 0] logger.debug(\".. rendering\") step_angle = 360.0 / n_steps writer =",
"__name__ == \"__main__\": import coloredlogs logging.getLogger(\"tifffile\").setLevel(logging.ERROR) logging.getLogger(\"matplotlib\").setLevel(logging.WARNING) coloredlogs.install( level=\"DEBUG\", fmt=\"%(asctime)s %(levelname)s %(message)s\", datefmt=\"%H:%M:%S\"",
"256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas",
"= scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 )",
"parent=view.scene, emulate_texture=False ) volume.method = \"translucent\" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state(\"translucent\", depth_test=False)",
"from vispy import io vol = np.load(io.load_data_file(\"brain/mri.npz\"))[\"data\"] print(vol.dtype) \"\"\" import imageio vol =",
"axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie \"\"\" n_steps = 240 axis =",
"camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0,",
"nx = vol.shape mid = ny // 2 vol1 = vol[:, :mid, :]",
"np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas ] cmap =",
"cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average = cp.asnumpy(psf_average) preview_volume(psf_average) break",
"<filename>workspace/extract_psf.py import logging import os import imageio import numpy as np from vispy",
"main(root=\"fusion_psf\"): ds = FolderDatastore(root, read_func=imageio.volread, extensions=[\"tif\"]) logger.info(f\"{len(ds)} file(s) found\") for key, vol in",
"cp psf_average = cp.asarray(psf_average) from utoolbox.exposure import auto_contrast psf_average = auto_contrast(psf_average) psf_average =",
":] preview_volume((vol1, vol2), ((0, -mid, 0), (0, mid, 0))) # vol = vol[:,",
"= imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis)",
"link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset()",
"coord) in enumerate(psfs): coord = [f\"{c:04d}\" for c in reversed(coord)] coord = \"-\".join(coord)",
"camera camera = scene.cameras.TurntableCamera( parent=view.scene, fov=60.0, name=\"Arcball\", elevation=30.0 ) view.camera = camera view.camera.flip",
"as np from vispy import app, scene from vispy.color.colormap import BaseColormap, Colormap, ColorArray",
"\"\"\" import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') \"\"\" import cupy as cp vol =",
"n_steps writer = imageio.get_writer(\"t1-head_split_rotate.mp4\", fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im)",
"pass psf_avg = PSFAverage((97, 97, 97)) psfs = psf_avg(vol, return_coords=True) psf_average = None",
"= canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() \"\"\" app.run() def main(root=\"fusion_psf\"): ds = FolderDatastore(root,",
"def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys=\"interactive\") canvas.size = 1024, 1024 canvas.show() # create"
] |
[
"python # -*- coding: utf-8 -*- \"\"\"Example to show the new marker styles\"\"\"",
"fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark",
"to show the new marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import",
"coding: utf-8 -*- \"\"\"Example to show the new marker styles\"\"\" import matplotlib.pyplot as",
"# -*- coding: utf-8 -*- \"\"\"Example to show the new marker styles\"\"\" import",
"show the new marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D",
"\"\"\"Example to show the new marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl",
"in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker) ax.set_xlim(-1, len(markers)) ax.set_ylim(-1,",
"= plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es',",
"marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker) ax.set_xlim(-1, len(markers)) ax.set_ylim(-1, 1) plt.show()",
"markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark in",
"plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers",
"['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark in enumerate(markers): marker",
"marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12,",
"#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\"Example to show the new marker",
"styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3))",
"as plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111)",
"'es', 'rex', 'rc'] for ix, mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark,",
"'rex', 'rc'] for ix, mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none',",
"for ix, mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker)",
"fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx',",
"ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for",
"enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker) ax.set_xlim(-1, len(markers)) ax.set_ylim(-1, 1)",
"= fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix,",
"new marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig =",
"plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex',",
"'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark in enumerate(markers): marker = Line2D([ix],",
"'rc'] for ix, mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k')",
"sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap',",
"'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark in enumerate(markers): marker =",
"mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker) ax.set_xlim(-1, len(markers))",
"'rsx', 'es', 'rex', 'rc'] for ix, mark in enumerate(markers): marker = Line2D([ix], [0],",
"utf-8 -*- \"\"\"Example to show the new marker styles\"\"\" import matplotlib.pyplot as plt",
"ix, mark in enumerate(markers): marker = Line2D([ix], [0], marker=mark, fillstyle='none', color='k') ax.add_line(marker) ax.set_xlim(-1,",
"the new marker styles\"\"\" import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig",
"-*- coding: utf-8 -*- \"\"\"Example to show the new marker styles\"\"\" import matplotlib.pyplot",
"3)) ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc']",
"matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax =",
"= ['ap', 'an', 'psx', 'rsx', 'es', 'rex', 'rc'] for ix, mark in enumerate(markers):",
"import matplotlib.pyplot as plt from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax",
"import Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap', 'an',",
"from sajou.plot.lines_mpl import Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers =",
"Line2D fig = plt.figure(figsize=(12, 3)) ax = fig.add_subplot(111) markers = ['ap', 'an', 'psx',",
"-*- \"\"\"Example to show the new marker styles\"\"\" import matplotlib.pyplot as plt from"
] |
[
"self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class",
"Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used",
") logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on",
"= [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on",
"self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab",
"strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\",",
"self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings",
"sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\"",
"on {page_name}\") for string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string,",
"\"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err) assert len(self.err_list) ==",
"\"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"],",
"Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\",",
"operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify",
"strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search",
"expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self):",
"Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\",",
"Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\",",
"<reponame>prsurve/ocs-ci<gh_stars>0 import logging from ocs_ci.ocs.ui.base_ui import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils",
"Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\",",
"page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\",",
"import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework",
"OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify",
"\"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def",
"logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def __init__(self,",
"page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\",",
"All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings(",
"from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation",
"tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\"",
"\"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\"",
"page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in strings_on_page: sample =",
"in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True):",
"self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify",
"list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\"",
"Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total",
"Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\",",
"on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab =",
"\"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab",
"func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def",
"User Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list",
"from ocs_ci.framework import config from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator):",
"in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\")",
"Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs",
"\"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object",
"operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage",
"Args: strings_on_page (list): list of strings on page page_name (str): the name of",
"\"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err)",
"Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\"",
"import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import constants logger =",
"TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class",
"def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [",
"Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform",
"Contain Strings Args: strings_on_page (list): list of strings on page page_name (str): the",
"self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self):",
"OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify",
"[\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify",
"locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import",
"Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings(",
"ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab",
"\"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in strings_on_page: sample = TimeoutSampler(",
"\"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator",
"self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\",",
"installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator on Installed",
") if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self): \"\"\"",
"string not found on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page()",
"Strings Args: strings_on_page (list): list of strings on page page_name (str): the name",
"= logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def __init__(self, driver):",
"import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\"",
"= list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page UI",
"def verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform =",
"tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" )",
"self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab",
"Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings(",
"page_name (str): the name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\")",
"of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in strings_on_page:",
"logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS",
"\"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc =",
"Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in",
"config from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface",
"def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"]",
"Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage",
"Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab,",
"strings on page page_name (str): the name of the page \"\"\" logger.info(f\"verify {strings_on_page}",
"if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self): \"\"\" Verification",
"__init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def",
"page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page (list): list of strings on",
"\"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page",
"constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"])",
"strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab =",
"self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab",
") logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\",",
"operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self,",
"logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"]",
"self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on",
"self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings(",
"strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on",
"self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page,",
"logging from ocs_ci.ocs.ui.base_ui import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version,",
"PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import",
") def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab =",
"strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string}",
"= TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not",
"Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list()",
"ocs_ci.framework import config from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\"",
"locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"])",
"strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab",
"strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args:",
"self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page()",
"[\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS",
"constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def",
"\"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS operator\")",
"[\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent",
"self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page()",
"tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\"",
"self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator on Installed Operators\")",
"tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab,",
"\"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page",
"strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"])",
"list of strings on page page_name (str): the name of the page \"\"\"",
"\"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\",",
"[ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on",
"Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" )",
"[\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\")",
"self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\")",
"import logging from ocs_ci.ocs.ui.base_ui import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import",
"Storage\", ) logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab",
"page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab",
"on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" )",
"driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self):",
"sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string",
"button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total",
"Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\"",
"self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster",
"get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import constants logger = logging.getLogger(__name__)",
"self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw",
"button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def",
"platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency",
"ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium",
"text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify",
"\"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS operator\")",
"operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator on",
"self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab",
"= [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\"",
"from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config",
"ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version =",
") def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page (list):",
"for string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if",
"self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page()",
"\"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity",
"UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err) assert len(self.err_list)",
"Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", )",
"[\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS",
"Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err) assert",
"import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs",
"verify_persistent_storage_page(self): \"\"\" Verify Persistent Storage Page \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"persistent_storage_tab\"]) strings_object_service_tab = [ \"IOPS\",",
") logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\",",
"\"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self):",
"(str): the name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for",
"\"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS operator\")",
"logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ]",
"operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab =",
") def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator",
"the name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string",
"[\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS",
"on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" )",
"page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\",",
"\"\"\" Verify Page Contain Strings Args: strings_on_page (list): list of strings on page",
"on page page_name (str): the name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist",
"strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab =",
"super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\"",
"self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All",
"OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container",
"platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"])",
"def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\")",
"{page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err",
"verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list:",
"= [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS",
"= [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on",
"Details tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\"",
"verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page (list): list of",
"found on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot()",
"exist on {page_name}\") for string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text,",
"OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" )",
"from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import constants",
"tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\"",
"\"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS",
"instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab,",
"logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab",
"ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from",
"= [ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ]",
"\"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"])",
"strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab =",
"Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list = list() self.validation_loc",
"logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"]",
"Container Storage\", ) logger.info(\"Click on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details",
"] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"])",
"name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in",
"OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs operator",
"self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err) assert len(self.err_list) == 0,",
"tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\"",
"ocs_ci.ocs.ui.base_ui import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from",
"Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS",
"get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service",
"operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket",
"page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\",",
"string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not",
"Page Contain Strings Args: strings_on_page (list): list of strings on page page_name (str):",
"logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings(",
"self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page()",
") logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\",",
"logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver)",
"on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" )",
"logger.info(\"Verify Details tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab,",
"Verify Page Contain Strings Args: strings_on_page (list): list of strings on page page_name",
"(list): list of strings on page page_name (str): the name of the page",
"locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform",
"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\"",
"on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab,",
"on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" )",
"= [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\" Verify",
"not found on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs()",
"[ \"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings(",
"\"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click",
"of strings on page page_name (str): the name of the page \"\"\" logger.info(f\"verify",
"\"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if",
"on {page_name}\") def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for",
"strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab =",
"\"IOPS\", \"Latency\", \"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab,",
"\"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"])",
"= config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click",
"\"\"\" User Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version()",
"strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances",
"= locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"])",
"strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab",
"self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in self.err_list: logger.error(err) assert len(self.err_list) == 0, f\"{self.err_list}\"",
"Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS:",
"the page \"\"\" logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in strings_on_page: sample",
"strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab",
"page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\",",
"config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on",
"on ocs operator on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\")",
"self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab =",
"logger.info(\"Verify All instances tab on OCS operator\") self.do_click(self.validation_loc[\"osc_all_instances_tab\"]) strings_all_instances_tab = [\"Phase\", \"Ready\", \"Status\"]",
") logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\",",
"strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page (list): list of strings",
"Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify",
"if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service button\") self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data",
"timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on",
"Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab,",
"sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\")",
"def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page (list): list",
"OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"]) strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def",
"verify_object_service_page(self): \"\"\" Verify Object Service Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower()",
"self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store",
"operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing",
"{page_name}\") for string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, )",
"Page UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click",
"self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object Service Page",
"strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [",
"on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify",
"Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab,",
"\"Throughput\", \"Recovery\", \"Utilization\", \"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" )",
"operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription tab",
"strings_object_service_tab = [\"Total Reads\", \"Total Writes\"] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"object_service\" ) def verify_persistent_storage_page(self): \"\"\"",
"logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift Container Storage\", ) logger.info(\"Click on ocs",
"self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on Object Service",
"def verification_ui(self): \"\"\" Verification UI \"\"\" self.verify_object_service_page() self.verify_persistent_storage_page() self.verify_ocs_operator_tabs() self.take_screenshot() for err in",
"on Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab = [\"Description\",",
"\"Status\"] self.verify_page_contain_strings( strings_on_page=strings_all_instances_tab, page_name=\"all_instances_tab\" ) logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"])",
"Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys( locator=self.validation_loc[\"search_ocs_installed\"], text=\"OpenShift",
"Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"]",
"on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\"",
"page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain Strings Args: strings_on_page",
"TimeoutSampler( timeout=3, sleep=1, func=self.check_element_text, expected_text=string, ) if not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found",
"= get_ocp_version() self.err_list = list() self.validation_loc = locators[self.ocp_version][\"validation\"] def verify_object_service_page(self): \"\"\" Verify Object",
"import config from ocs_ci.ocs import constants logger = logging.getLogger(__name__) class ValidationUI(PageNavigator): \"\"\" User",
") logger.info(\"Verify Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\",",
"self.do_click(self.validation_loc[\"object_service_button\"]) logger.info(\"Click on Data Resiliency button\") self.do_click(self.validation_loc[\"data_resiliency_button\"]) strings_object_service_tab = [\"Total Reads\", \"Total Writes\"]",
"strings_on_page (list): list of strings on page page_name (str): the name of the",
"logger.info(f\"verify {strings_on_page} exist on {page_name}\") for string in strings_on_page: sample = TimeoutSampler( timeout=3,",
"ocs_ci.utility.utils import get_ocp_version, TimeoutSampler from ocs_ci.framework import config from ocs_ci.ocs import constants logger",
"verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS operator installed\") self.do_send_keys(",
"page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\" Verify OCS Operator Tabs \"\"\" self.navigate_installed_operators_page() logger.info(\"Search OCS",
"UI \"\"\" self.navigate_overview_page() self.do_click(self.validation_loc[\"object_service_tab\"]) platform = config.ENV_DATA.get(\"platform\").lower() if platform in constants.ON_PREM_PLATFORMS: logger.info(\"Click on",
"\"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name): \"\"\" Verify Page Contain",
"not sample.wait_for_func_status(result=True): self.err_list.append(f\"{string} string not found on {page_name}\") def verification_ui(self): \"\"\" Verification UI",
"Installed Operators\") self.do_click(locator=self.validation_loc[\"ocs_operator_installed\"]) logger.info(\"Verify Details tab on OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\",",
"= [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_storage_cluster_tab, page_name=\"storage_cluster_tab\" ) logger.info(\"Verify Backing Store tab on",
"strings_bucket_class_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_bucket_class_tab, page_name=\"bucket_class_tab\" ) def verify_page_contain_strings(self, strings_on_page, page_name):",
"\"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab on OCS operator\")",
"logger.info(\"Verify Storage Cluster tab on OCS operator\") self.do_click(self.validation_loc[\"osc_storage_cluster_tab\"]) strings_storage_cluster_tab = [\"Phase\", \"Ready\", \"Status\"]",
"{strings_on_page} exist on {page_name}\") for string in strings_on_page: sample = TimeoutSampler( timeout=3, sleep=1,",
"from ocs_ci.ocs.ui.base_ui import PageNavigator from ocs_ci.ocs.ui.views import locators from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler",
"class ValidationUI(PageNavigator): \"\"\" User Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version",
"Backing Store tab on OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings(",
"page page_name (str): the name of the page \"\"\" logger.info(f\"verify {strings_on_page} exist on",
"OCS operator\") strings_details_tab = [\"Description\", \"Succeeded\", \"openshift-storage\"] self.verify_page_contain_strings( strings_on_page=strings_details_tab, page_name=\"details_tab\" ) logger.info(\"Verify Subscription",
"= [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings( strings_on_page=strings_subscription_tab, page_name=\"subscription_tab\" ) logger.info(\"Verify All instances tab",
"Subscription tab on OCS operator\") self.do_click(self.validation_loc[\"osc_subscription_tab\"]) strings_subscription_tab = [ \"Healthy\", \"openshift-storage\", ] self.verify_page_contain_strings(",
"Interface Validation Selenium \"\"\" def __init__(self, driver): super().__init__(driver) self.ocp_version = get_ocp_version() self.err_list =",
"\"Used Capacity Breakdown\", \"Raw Capacity\", ] self.verify_page_contain_strings( strings_on_page=strings_object_service_tab, page_name=\"persistent_storage\" ) def verify_ocs_operator_tabs(self): \"\"\"",
"\"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify Bucket Class tab on OCS operator\") self.do_click(self.validation_loc[\"osc_bucket_class_tab\"])",
"OCS operator\") self.do_click(self.validation_loc[\"osc_backing_store_tab\"]) strings_backing_store_tab = [\"Phase\", \"Ready\", \"Status\"] self.verify_page_contain_strings( strings_on_page=strings_backing_store_tab, page_name=\"backing_store_tab\" ) logger.info(\"Verify"
] |
[
"= 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] =",
"op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\")",
"self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image):",
"def detect_pose(self, image): datum = op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if",
"min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks",
"config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"]",
"= peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ):",
") y = y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x,",
"self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords =",
"config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir +",
"plt from headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir",
"1 j += 1 continue if curr_beat < curr_motion: # increment beats j",
"mec=\"black\", ) if debug_bpm: # skip every 10 frames for bpm plot for",
"self.frame_idx += 1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords,",
"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks",
"= 0 aligned_beats = [] while i < len(motion) and j < len(beats):",
"+ \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit =",
"0 aligned_beats = [] while i < len(motion) and j < len(beats): curr_motion",
"\"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0: return",
"enumerate(detected_poses): if ( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1]))",
"frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self,",
"> OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if",
"i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0: continue",
"[int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames",
"in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0: continue bop_times, bpm",
"self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords =",
"return 60 / beat_step def align_beats_motion(beats, motion, thresh): i = 0 j =",
"= [int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] *",
"config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper =",
"if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j +=",
"numpy import sys import scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt",
"frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y =",
"= bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size > 2: text_x = (",
"= 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for",
"peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30",
"is not None: poses_of_interest = [] # collect (x, y) coordinates of the",
"raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame)",
"* self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum()",
"len(beats): curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh:",
"0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 /",
"0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False",
"in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if ( keypoint",
"y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid()",
"{0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum]))",
"config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i)",
"if beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope",
"self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration =",
"for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) >",
"+ \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in",
"= numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y /",
"= beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1",
"j = 0 aligned_beats = [] while i < len(motion) and j <",
"frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe def find_peaks(self): min_coord =",
"def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\")",
"find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as",
"op class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence = 0.5 def",
"0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config)",
"emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses",
"plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time",
"+= 1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord)",
"config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start()",
"frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times,",
"debug_bpm: # skip every 10 frames for bpm plot for i, bop_bpm_hist in",
"= y_norm self.frame_idx += 1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords",
"poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y",
"y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe",
"median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe def find_peaks(self):",
"# collect (x, y) coordinates of the head, median across the first object_limit",
"= 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\"",
"image): datum = op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret:",
"median_y = median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx +=",
"> 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 )",
"\"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0: return 0 m_res =",
"plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size ==",
"peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", )",
"= op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't",
"object_limit = 3 min_confidence = 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ):",
"detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if (",
"y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration)",
"plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)),",
"head, median across the first object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit",
"max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats):",
"{} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6",
"config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"]",
"* self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames",
"i += 1 j += 1 continue if curr_beat < curr_motion: # increment",
"find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for",
"0 self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints",
"0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size",
"import sys import scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from",
"not None: poses_of_interest = [] # collect (x, y) coordinates of the head,",
"= [] # collect (x, y) coordinates of the head, median across the",
"= m_res.slope return 60 / beat_step def align_beats_motion(beats, motion, thresh): i = 0",
"self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest = [] # collect (x, y)",
"op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames)",
"1 continue if curr_beat < curr_motion: # increment beats j += 1 elif",
"= image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints,",
"if x.size > 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) /",
"i < len(motion) and j < len(beats): curr_motion = motion[i] curr_beat = beats[j]",
"y = y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y,",
"frames for bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i",
"wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks",
"= [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration",
"if i % debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist x =",
"the head, median across the first object_limit objects for detected_poses in multiple_detected_poses[ :",
"bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip",
"return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is",
"if curr_beat < curr_motion: # increment beats j += 1 elif curr_beat >",
"y_norm self.frame_idx += 1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords =",
"= int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration",
"from headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir =",
"- frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y = max(y) + 0.03",
"matplotlib.pyplot as plt from headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path =",
"text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y =",
"import DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir",
"= median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe def",
"0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper",
"curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion,",
"j += 1 continue if curr_beat < curr_motion: # increment beats j +=",
"d in enumerate(detected_poses): if ( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ):",
"= 0 j = 0 aligned_beats = [] while i < len(motion) and",
"text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show()",
"[] # collect (x, y) coordinates of the head, median across the first",
"OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if ( keypoint in self.keypoints and",
"y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords)",
"from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\")",
"= 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] =",
"adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks",
"- curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1 continue",
"= self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest = [] # collect (x,",
"not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe",
"find_closest(frame_times, bop_times) if x.size > 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] -",
"n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\"",
"i % debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times,",
"= \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] =",
"multiple_detected_poses is not None: poses_of_interest = [] # collect (x, y) coordinates of",
"y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0:",
"for keypoint, d in enumerate(detected_poses): if ( keypoint in self.keypoints and d[2] >",
"x.size > 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2",
"= self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if",
"plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0,",
"import pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence",
"scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import DEFAULTS",
"config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"]",
"datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not",
"]: for keypoint, d in enumerate(detected_poses): if ( keypoint in self.keypoints and d[2]",
"i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx =",
"numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every",
"= 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] =",
"motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks =",
"from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import DEFAULTS from",
"good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks)",
"debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\")",
"numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\",",
"# wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4))",
"for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if",
"= scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 / beat_step def align_beats_motion(beats, motion,",
"scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import DEFAULTS from headbang.util",
"openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default",
"= median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1",
"0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 / beat_step def",
"OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence = 0.5 def __init__( self,",
": OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if ( keypoint in self.keypoints",
"[OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration *",
"median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration,",
"objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses):",
"axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx]",
"def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3",
"None: poses_of_interest = [] # collect (x, y) coordinates of the head, median",
"enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0: continue bop_times, bpm =",
"bpm_from_beats(beats): if beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step =",
"import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import DEFAULTS from headbang.util import",
"= {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] =",
"motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i",
"self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\",",
"= ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y = y_coords[x]",
"import matplotlib.pyplot as plt from headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path",
"self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords)",
"curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i +=",
"not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm",
"<= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1 continue if curr_beat",
"int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration",
"4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False,",
"+= 1 continue if curr_beat < curr_motion: # increment beats j += 1",
"sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit",
"in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0",
"debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y",
"self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames",
"continue if curr_beat < curr_motion: # increment beats j += 1 elif curr_beat",
"1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir",
"min_confidence = 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {}",
"# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return",
"/ beat_step def align_beats_motion(beats, motion, thresh): i = 0 j = 0 aligned_beats",
"): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)):",
"return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets",
"(frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y = max(y) +",
"= numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks =",
"= numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords,",
"import numpy import sys import scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as",
"bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size > 2: text_x =",
"config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"]",
"in enumerate(detected_poses): if ( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0],",
"skip every 10 frames for bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip]",
"+ (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y = max(y)",
"\"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector:",
"2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y",
"y) coordinates of the head, median across the first object_limit objects for detected_poses",
"OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not",
"multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in enumerate(detected_poses): if ( keypoint in",
"numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y / frame.shape[0]",
"= numpy.nan object_limit = 3 min_confidence = 0.5 def __init__( self, n_frames, frame_duration,",
"numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history,",
"self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector",
"continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size > 2:",
"plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords =",
"bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size > 2: text_x = ( frame_times[x[-2]]",
"= frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def",
"first object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d",
"0 j = 0 aligned_beats = [] while i < len(motion) and j",
"): if i % debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist x",
"keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest)",
"2 ) y = y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\")",
"self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks,",
"self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\")",
"numpy.nan object_limit = 3 min_confidence = 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"],",
"keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] =",
"self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData",
"d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0)",
"frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest = []",
"bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized",
"median across the first object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]:",
"sys import scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params",
"= openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for",
"% debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times)",
"plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every 10",
"= numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip",
"self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints))",
"= 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"]",
"every 10 frames for bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ):",
"> 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized",
"text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0: return 0 m_res",
"self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] =",
"beats j += 1 elif curr_beat > curr_motion: i += 1 return aligned_beats",
"config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"]",
"thresh): i = 0 j = 0 aligned_beats = [] while i <",
"peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def",
"poses_of_interest = [] # collect (x, y) coordinates of the head, median across",
"self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration =",
"frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x],",
"= numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks #",
"bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size > 2: text_x",
"< curr_motion: # increment beats j += 1 elif curr_beat > curr_motion: i",
"(x, y) coordinates of the head, median across the first object_limit objects for",
"bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist",
"object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint, d in",
"and j < len(beats): curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion -",
"multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest = [] #",
"peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y coordinate",
"process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest =",
"if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] =",
"import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose",
"# increment beats j += 1 elif curr_beat > curr_motion: i += 1",
"= \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class",
"x = find_closest(frame_times, bop_times) if x.size > 2: text_x = ( frame_times[x[-2]] +",
"as plt from headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\"",
"/ 2 ) y = y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y,",
"beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return",
"10 frames for bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if",
"openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op",
"for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx",
"for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0:",
"11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median",
"\"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05",
"plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times =",
"openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan",
"d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y =",
"return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 / beat_step",
"= 3 min_confidence = 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config",
"detect_pose(self, image): datum = op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not",
"outframe = self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest = [] # collect",
"beat_step = m_res.slope return 60 / beat_step def align_beats_motion(beats, motion, thresh): i =",
"= motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat))",
"= op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames =",
"0: continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size >",
"coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot(",
"beats[j] if numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j",
"headbang.params import DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path",
"\"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every 10 frames for bpm",
"plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip !=",
"self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum =",
"collect (x, y) coordinates of the head, median across the first object_limit objects",
"openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i",
"if debug_bpm: # skip every 10 frames for bpm plot for i, bop_bpm_hist",
"numpy.abs(curr_motion - curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1",
"frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every 10 frames",
"# skip every 10 frames for bpm plot for i, bop_bpm_hist in enumerate(",
"while i < len(motion) and j < len(beats): curr_motion = motion[i] curr_beat =",
"/ frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return outframe def find_peaks(self): min_coord",
"curr_beat)) i += 1 j += 1 continue if curr_beat < curr_motion: #",
"class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence = 0.5 def __init__(",
"= False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints",
"\"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")]",
"): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\"",
"(s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks() y_coords",
"are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks =",
"for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData = image ret",
"+ 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if",
"return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1) plt.title(\"normalized median y",
"\"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3",
"ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def",
"median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y",
"numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords,",
"scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 / beat_step def align_beats_motion(beats, motion, thresh):",
"self.opWrapper.configure(config) self.opWrapper.start() self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords",
"debug_bpm_frame_skip != 0: continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if",
"= \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] =",
"headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import",
"False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython() self.opWrapper.configure(config) self.opWrapper.start() self.keypoints =",
"numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/",
"y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every 10 frames for",
"ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe =",
"coordinates of the head, median across the first object_limit objects for detected_poses in",
"undef_coord_default = numpy.nan object_limit = 3 min_confidence = 0.5 def __init__( self, n_frames,",
"__init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"]",
"= numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm",
"= 0 config[\"disable_blending\"] = False config[\"model_folder\"] = openpose_dir + \"/models/\" self.opWrapper = op.WrapperPython()",
"( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest =",
"( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]]) / 2 ) y = y_coords[x] text_y",
"= self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self,",
"config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"]",
"across the first object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for",
"coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks",
"def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not None: poses_of_interest",
"keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData = image ret =",
"curr_beat < curr_motion: # increment beats j += 1 elif curr_beat > curr_motion:",
"self.find_peaks() y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm:",
"config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0 config[\"disable_blending\"] = False config[\"model_folder\"]",
"poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1]",
"0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] = 0",
"peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]]",
"3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3",
"+= 1 j += 1 continue if curr_beat < curr_motion: # increment beats",
"plt.show() def bpm_from_beats(beats): if beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats)",
"bop_times) if x.size > 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]] - frame_times[x[-2]])",
"align_beats_motion(beats, motion, thresh): i = 0 j = 0 aligned_beats = [] while",
"< len(motion) and j < len(beats): curr_motion = motion[i] curr_beat = beats[j] if",
"60 / beat_step def align_beats_motion(beats, motion, thresh): i = 0 j = 0",
"if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses,",
"i = 0 j = 0 aligned_beats = [] while i < len(motion)",
"in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords",
"aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1 continue if curr_beat < curr_motion:",
"for bpm plot for i, bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i %",
"len(motion) and j < len(beats): curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion",
"= y_coords[x] text_y = max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm))))",
"numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx",
"curr_beat) <= thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1 continue if",
"image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData",
"m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60 / beat_step def align_beats_motion(beats,",
"OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData = image",
"self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame):",
"as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence = 0.5",
") if debug_bpm: # skip every 10 frames for bpm plot for i,",
"plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times = numpy.arange(0.0, self.total_duration, self.frame_duration) peaks = self.find_peaks()",
"import scipy from scipy.signal import find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import",
"nan=min_coord) # wavelets are good for peaks # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ peaks = find_peaks_cwt(adjusted_y_coords, numpy.arange(2,",
"= openpose_install_path sys.path.append(openpose_dir + \"/build/python/openpose\") import pyopenpose as op class OpenposeDetector: undef_coord_default =",
"< len(beats): curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat) <=",
"median_coords[1] y_norm = median_y / frame.shape[0] self.all_y_coords[self.frame_idx] = y_norm self.frame_idx += 1 return",
"find_peaks_cwt import matplotlib.pyplot as plt from headbang.params import DEFAULTS from headbang.util import find_closest",
"= find_closest(frame_times, bop_times) if x.size > 2: text_x = ( frame_times[x[-2]] + (frame_times[x[-1]]",
"bop_bpm_hist in enumerate( bop_bpm_plot_history[:-debug_bpm_frame_skip] ): if i % debug_bpm_frame_skip != 0: continue bop_times,",
"= max(y) + 0.03 plt.plot(frame_times[x], y, \"r\") plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def",
"= find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords(",
"DEFAULTS from headbang.util import find_closest openpose_install_path = \"/home/sevagh/thirdparty-repos/openpose\" openpose_dir = openpose_install_path sys.path.append(openpose_dir +",
"= self.frame_duration * self.n_frames print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum",
"m_res.slope return 60 / beat_step def align_beats_motion(beats, motion, thresh): i = 0 j",
"frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] = 3 config[\"net_resolution\"] = \"320x320\" config[\"model_pose\"]",
"curr_motion: # increment beats j += 1 elif curr_beat > curr_motion: i +=",
"j < len(beats): curr_motion = motion[i] curr_beat = beats[j] if numpy.abs(curr_motion - curr_beat)",
"pyopenpose as op class OpenposeDetector: undef_coord_default = numpy.nan object_limit = 3 min_confidence =",
"and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest = numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest,",
"!= 0: continue bop_times, bpm = bop_bpm_hist x = find_closest(frame_times, bop_times) if x.size",
"1 return outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) #",
"[] while i < len(motion) and j < len(beats): curr_motion = motion[i] curr_beat",
"markevery=peaks, mec=\"black\", ) if debug_bpm: # skip every 10 frames for bpm plot",
"numpy.asarray(poses_of_interest) median_coords = numpy.median(poses_of_interest, axis=0) if not numpy.any(numpy.isnan(median_coords)): median_y = median_coords[1] y_norm =",
"datum = op.Datum() datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise",
"y_coords = numpy.asarray(self.all_y_coords) plt.plot( frame_times, y_coords, \"-D\", markevery=peaks, mec=\"black\", ) if debug_bpm: #",
"thresh: aligned_beats.append(min(curr_motion, curr_beat)) i += 1 j += 1 continue if curr_beat <",
"outframe def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are",
"): plt.figure(1) plt.title(\"normalized median y coordinate motion\") plt.xlabel(\"time (s)\") plt.ylabel(\"normalized y coordinate\") frame_times",
"self.keypoints = [int(i) for i in keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default]",
"def bpm_from_beats(beats): if beats.size == 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step",
"datum.cvInputData = image ret = self.opWrapper.emplaceAndPop(op.VectorDatum([datum])) if not ret: raise ValueError(\"couldn't emplaceAndPop\") return",
"== 0: return 0 m_res = scipy.stats.linregress(numpy.arange(len(beats)), beats) beat_step = m_res.slope return 60",
"0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config = {} config[\"logging_level\"] =",
"= [] while i < len(motion) and j < len(beats): curr_motion = motion[i]",
"keypoints.split(\",\")] self.n_frames = int(n_frames) self.all_y_coords = [OpenposeDetector.undef_coord_default] * self.n_frames self.frame_idx = 0 self.frame_duration",
"print(\"Started OpenposeDetector for keypoints {0}\".format(self.keypoints)) def detect_pose(self, image): datum = op.Datum() datum.cvInputData =",
"find_peaks_cwt(adjusted_y_coords, numpy.arange(2, 4)) peaks = peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self,",
"beats) beat_step = m_res.slope return 60 / beat_step def align_beats_motion(beats, motion, thresh): i",
"self.n_frames self.frame_idx = 0 self.frame_duration = frame_duration self.total_duration = self.frame_duration * self.n_frames print(\"Started",
"of the head, median across the first object_limit objects for detected_poses in multiple_detected_poses[",
"increment beats j += 1 elif curr_beat > curr_motion: i += 1 return",
"if ( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence ): poses_of_interest.append((d[0], d[1])) poses_of_interest",
"beat_step def align_beats_motion(beats, motion, thresh): i = 0 j = 0 aligned_beats =",
"ValueError(\"couldn't emplaceAndPop\") return datum.poseKeypoints, datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if",
"keypoint, d in enumerate(detected_poses): if ( keypoint in self.keypoints and d[2] > OpenposeDetector.min_confidence",
"\"320x320\" config[\"model_pose\"] = \"BODY_25\" config[\"alpha_pose\"] = 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1",
"def find_peaks(self): min_coord = numpy.nanmin(self.all_y_coords) adjusted_y_coords = numpy.nan_to_num(self.all_y_coords, nan=min_coord) # wavelets are good",
"def align_beats_motion(beats, motion, thresh): i = 0 j = 0 aligned_beats = []",
"3 min_confidence = 0.5 def __init__( self, n_frames, frame_duration, keypoints=DEFAULTS[\"pose_keypoints\"], ): config =",
"aligned_beats = [] while i < len(motion) and j < len(beats): curr_motion =",
"the first object_limit objects for detected_poses in multiple_detected_poses[ : OpenposeDetector.object_limit ]: for keypoint,",
"datum.cvOutputData def process_frame(self, frame): multiple_detected_poses, outframe = self.detect_pose(frame) if multiple_detected_poses is not None:",
"= 0.6 config[\"scale_gap\"] = 0.3 config[\"scale_number\"] = 1 config[\"render_threshold\"] = 0.05 config[\"num_gpu_start\"] =",
"peaks[numpy.where(numpy.diff(peaks) > 11)[0]] return peaks def plot_ycoords( self, bop_bpm_plot_history, debug_bpm=False, debug_bpm_frame_skip=30 ): plt.figure(1)",
"if multiple_detected_poses is not None: poses_of_interest = [] # collect (x, y) coordinates",
"plt.text(text_x, text_y, \"{0}\".format(int(round(bpm)))) plt.grid() plt.show() def bpm_from_beats(beats): if beats.size == 0: return 0",
"motion, thresh): i = 0 j = 0 aligned_beats = [] while i"
] |
[
"B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1],",
"import pylab as plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import",
"return if 1: Q = [] q = {} q[\"files_dir\"] = \".\" q[\"level\"]",
"transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm",
"\"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ==============================================================================",
"#np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] =",
"max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$',",
"savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"])",
"\"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni",
"\"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"]",
"verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False)",
"\"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from",
"11, 3) vmax = savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds, c):",
"0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10)",
"Q = [] q = {} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"]",
"Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x,",
"import sys cmd_folder = \"../../../vis\" # nopep8 if cmd_folder not in sys.path: #",
"data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"]",
"pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes,",
"1 ny = yn.size - 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1,",
"return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy",
"{\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] =",
"q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"]",
"{\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()]",
"gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES",
"x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x,",
"= ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def",
"join the data nx = xn.size - 1 ny = yn.size - 1",
"horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax",
"0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::,",
"[[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] =",
"dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] = False",
"= ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds,",
"vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right',",
"= xn.size - 1 ny = yn.size - 1 fig = plt.figure(figsize=(3,3)) gs",
"2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y,",
"plt.close(fig) return if 1: Q = [] q = {} q[\"files_dir\"] = \".\"",
"q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"]",
"ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975,",
"horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields",
"11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"]",
"J[nx::, ny::] = ni vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm",
"fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2,",
"scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3)",
"\"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\"",
"= frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max =",
"ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c):",
"= frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D =",
"vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right',",
"np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max)",
"= ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz",
"ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min",
"= frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn))",
"m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx",
"abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left',",
"r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2)",
"axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\")",
"= savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds, c): x, r =",
"get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1],",
"data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y =",
"axes = [] # join the data nx = xn.size - 1 ny",
"transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False)",
"nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories import",
"horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1)",
"# MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin",
"0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big,",
"= fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny]",
"data nx = xn.size - 1 ny = yn.size - 1 fig =",
"{} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"},",
"= ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes,",
"= data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max =",
"ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes,",
"in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300,",
"verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J",
"D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x",
"q[\"plot\"] = plot q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"] = 20",
"q = {} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density,",
"1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]);",
"J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J,",
"np.meshgrid(y, x) axes = [] # join the data nx = xn.size -",
"= ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()]",
"numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\":",
"q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]]",
"# ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11,",
"cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom',",
"yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne",
"densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] =",
"ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name,",
"= np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) #",
"\"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax):",
"# ============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import",
"fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm =",
"J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$',",
"MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin =",
"= \"../../../vis\" # nopep8 if cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder)",
"frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y,",
"q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"]",
"============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter",
"cmd_folder = \"../../../vis\" # nopep8 if cmd_folder not in sys.path: # nopep8 sys.path.insert(0,",
"frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y,",
"vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min))",
"fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y,",
"smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax =",
"3) vmax = savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds, c): x,",
"+ Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz}",
"= savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3) return vmin, vmax def",
"\"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni =",
"D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min",
"pylab as plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec",
"plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES #",
"MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin,",
"= [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ]",
"np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::,",
"plot q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] =",
"= data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y",
"= frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B =",
"[] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"]",
"r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for",
"Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)}",
"bbox_inches=\"tight\") plt.close(fig) return if 1: Q = [] q = {} q[\"files_dir\"] =",
"============================================================================== def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3)",
"def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0],",
"data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min =",
"[4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] = []",
"= np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big,",
"from tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories import pylab as plt",
"the data nx = xn.size - 1 ny = yn.size - 1 fig",
"fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx,",
"False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] = \"none\" #{\"smooth\":smooth_limits} Q.append(q) make_all(Q)",
"J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025,",
"get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data,",
"= data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min =",
"[ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"]",
"0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx,",
"J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J =",
"if 1: Q = [] q = {} q[\"files_dir\"] = \".\" q[\"level\"] =",
"= [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = []",
"True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ============================================================================== def",
"fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q = [] q = {}",
"import make_all, get_particle_trajectories import pylab as plt import numpy as np from mpl_toolkits.axes_grid1",
"q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt,",
"fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) #",
"y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big",
"[\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"]",
"savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3) return vmin,",
"= data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min =",
"q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] =",
"cmd_folder) from tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories import pylab as",
"return vmin, vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m =",
"= \".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\",",
"sys cmd_folder = \"../../../vis\" # nopep8 if cmd_folder not in sys.path: # nopep8",
"= yn.size - 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01)",
"c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1],",
"J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min, ni_min) vmax",
"\"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt",
"c): x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2",
"ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q = []",
"[\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin, vmax): from scipy.signal",
"np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\":",
"= 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] =",
"- 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax =",
"= [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt)",
"= min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin,",
"ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3)",
"= False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] =",
"= [] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False",
"= [] q = {} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] =",
"frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()]",
"= ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx =",
"r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny]",
"r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def",
"\"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt = 0.005",
"\"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE MOVIES # ============================================================================== def smooth_limits(vmin,",
"= gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J",
"q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] = \"none\" #{\"smooth\":smooth_limits} Q.append(q) make_all(Q) print(\"DONE\")",
"[] q = {} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] = [",
"grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x,",
"ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin",
"make_mov import make_all, get_particle_trajectories import pylab as plt import numpy as np from",
"{\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt = 0.005 ##",
"ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\")",
"ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D",
"hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan",
"transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J =",
"[0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"]",
"= max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$',",
"3) return vmin, vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m",
"vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$',",
"\"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"]",
"ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes,",
"+ \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"]",
"20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0],",
"in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov import",
"# fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x,",
"J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm",
"0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2,",
"def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()]",
"0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx,",
"r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) #",
"= max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025,",
"data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"]",
"xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max",
"Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn =",
"def smooth_limits(vmin, vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax",
"= frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x =",
"vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node')",
"if cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie",
"# nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories",
"q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"}",
"J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni",
"B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x",
"def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return",
"ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx,",
"J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big =",
"0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min, ni_min) vmax =",
"\".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"},",
"make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) #",
"q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11",
"y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes = [] #",
"sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories import pylab",
"= plot q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"]",
"matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== #",
"-1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz,",
"np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min,",
"max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left',",
"= True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] =",
"sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov import make_all,",
"ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz =",
"= [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] = False",
"\"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1],",
"= [] # join the data nx = xn.size - 1 ny =",
"frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()]",
"1: Q = [] q = {} q[\"files_dir\"] = \".\" q[\"level\"] = -1",
"verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2)",
"ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan",
"fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] =",
"\"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\")",
"nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx,",
"= np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm =",
"not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from make_mov",
"make_all, get_particle_trajectories import pylab as plt import numpy as np from mpl_toolkits.axes_grid1 import",
"q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] =",
"= data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min =",
"ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if",
"= np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin =",
"xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes = []",
"vmax): from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax,",
"frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"]",
"J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J,",
"np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\")",
"= np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min,",
"min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax)",
"nx = xn.size - 1 ny = yn.size - 1 fig = plt.figure(figsize=(3,3))",
"import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]})",
"ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top',",
"output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"]",
"ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025,",
"# join the data nx = xn.size - 1 ny = yn.size -",
"np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] =",
"dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"]",
"J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne)",
"y, x = np.meshgrid(y, x) axes = [] # join the data nx",
"x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0], \"y\":x[1], \"value\":r/m}",
"vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top',",
"y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975,",
"= False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] = \"none\" #{\"smooth\":smooth_limits} Q.append(q)",
"tile_movie from make_mov import make_all, get_particle_trajectories import pylab as plt import numpy as",
"= \"movie\" dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] +",
"vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975,",
"x = np.meshgrid(y, x) axes = [] # join the data nx =",
"vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max),",
"verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in",
"q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] = \"none\" #{\"smooth\":smooth_limits}",
"np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] = np.rot90(B.T,3) big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x,",
"return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\")",
"# number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx,",
"D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max",
"x = np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x)",
"B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1], xn))",
"plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec",
"q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] =",
"x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c):",
"ny = yn.size - 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01,",
"as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True,",
"11, 3) return vmin, vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x,",
"pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny]",
"= plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) #",
"= ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::, 0:ny] =",
"2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1:",
"pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom',",
"= np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min, ni_min) vmax = max(ne_max,",
"frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"]",
"# nopep8 if cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov",
"- 1 ny = yn.size - 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1,",
"# fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q = [] q",
"0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] =",
"= np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes",
"import tile_movie from make_mov import make_all, get_particle_trajectories import pylab as plt import numpy",
"] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"] =",
"= np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes = [] # join",
"True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] = 300 q[\"normalize\"] = \"none\"",
"= ax.pcolormesh(x, y, J, vmin=vmin, vmax=vmax) ax.text(0.025, 0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10)",
"y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) ax.text(0.975,",
"2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny]",
"ny::] = ni vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm =",
"\"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot",
"vmax = savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds, c): x, r",
"ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min",
"= np.meshgrid(y, x) axes = [] # join the data nx = xn.size",
"tile_mov import tile_movie from make_mov import make_all, get_particle_trajectories import pylab as plt import",
"Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def",
"2*ny))*np.nan J[0:nx, 0:ny] = np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J",
"\"../../../vis\" # nopep8 if cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from",
"nopep8 if cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import",
"np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes = [] # join the",
"= np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan",
"ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max",
"ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig)",
"{\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return",
"\"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return",
"q[\"name\"] = \"movie\" dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"]",
"{\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] = \"movie\" dt =",
"0.975, r'$n_e$', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.975, r'$n_i$', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10)",
"data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"]",
"vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3) return vmin, vmax",
"data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()]",
"gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J =",
"{\"x\":x[0], \"y\":x[1], \"value\":r/m} def get_D_mag(ds, c): x, Dx = ds.get(\"x_D-field\") x, Dy =",
"cmd_folder not in sys.path: # nopep8 sys.path.insert(0, cmd_folder) from tile_mov import tile_movie from",
"axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2)",
"= -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"},",
"\"movie\" dt = 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\"",
"= frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max =",
"as plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as",
"0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0,",
"ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025, 0.025, r'$\\left|\\vec{D}\\right|$', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=10)",
"from make_mov import make_all, get_particle_trajectories import pylab as plt import numpy as np",
"\"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0],",
"import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3) return",
"vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y, J,",
"q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True q[\"only_frames\"] =",
"for ax in axes: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout()",
"np.rot90(D.T,2) pcm = ax.pcolormesh(x, y, J, vmin=D_min, vmax=D_max) J = np.zeros((2*nx, 2*ny))*np.nan J[nx::,",
"= 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"] = True",
"c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name):",
"= 0.005 ## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] =",
"plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn = data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min",
"np.concatenate((-xn[::-1][0:-1], xn)) y = np.concatenate((-yn[::-1][0:-1], yn)) y, x = np.meshgrid(y, x) axes =",
"yn.size - 1 fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax",
"fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q = [] q =",
"ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q =",
"= q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"]",
"= frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x =",
"wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities J = np.zeros((2*nx, 2*ny))*np.nan #",
"get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"], grid='node') return {\"x\":x[0],",
"x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn",
"{\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag, \"tag\":\"D\"}, {\"func\":get_Bz, \"tag\":\"B\"} ] q[\"plot\"] = plot q[\"name\"] =",
"= data[\"nd-ion\"][\"y\"][()] ni = data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne =",
"return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn =",
"J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3)",
"np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max)",
"xn.size - 1 ny = yn.size - 1 fig = plt.figure(figsize=(3,3)) gs =",
"as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ============================================================================== # MAKE",
"## q[\"framerate\"] = 20 q[\"mov_save\"] = q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0]",
"ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max",
"[] # join the data nx = xn.size - 1 ny = yn.size",
"2) ax.set_ylim(-2, 2) ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return",
"get_particle_trajectories import pylab as plt import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable",
"x) axes = [] # join the data nx = xn.size - 1",
"from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\",",
"[] q[\"cores\"] = 11 q[\"time_span\"] = [] #np.arange(1.95,2+dt, dt) q[\"force_data\"] = False q[\"force_frames\"]",
"q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density,",
"= {} q[\"files_dir\"] = \".\" q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\",",
"fig = plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax)",
"import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({",
"dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q = [] q = {} q[\"files_dir\"]",
"mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\":",
"frame[\"D\"][\"max\"] B = data[\"B\"][\"value\"][()] B_min = frame[\"B\"][\"min\"] B_max = frame[\"B\"][\"max\"] x = np.concatenate((-xn[::-1][0:-1],",
"from scipy.signal import savgol_filter vmin = savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11,",
"= ni vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x,",
"ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 + Dy**2)} def get_Bz(ds,",
"frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"]",
"ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max = frame[\"D\"][\"max\"] B",
"horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=10) # fields J = np.zeros((2*nx, 2*ny))*np.nan J[0:nx, 0:ny] =",
"= np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::]",
"def get_Bz(ds, c): x, Bz = ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame,",
"\"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"]",
"# J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::] = np.rot90(ne) # J[nx::, 0:ny] =",
"ds.get(\"z_B-field\") return {\"x\":x[0], \"y\":x[1], \"value\":Bz} def plot(frame, data, output_name): xn = data[\"nd-ion\"][\"x\"][()] yn",
"False q[\"force_frames\"] = True q[\"only_frames\"] = False q[\"redo_streaks\"] = False q[\"dpi\"] = 300",
"ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes: ax.set_xlim(-2, 2)",
"import matplotlib.gridspec as gridspec plt.rcParams.update({ \"text.usetex\": True, \"font.family\": \"sans-serif\", \"font.sans-serif\": [\"Helvetica\"]}) # ==============================================================================",
"big = max(abs(B_max), abs(B_min)) pcm = ax.pcolormesh(x, y, J, vmin=-big, vmax=big, cmap=\"bwr\") ax.text(0.025,",
"= [[0,0], [4,4]] q[\"file_include\"] = [\"TRMI.plt\"] q[\"file_exclude\"] = [] q[\"cores\"] = 11 q[\"time_span\"]",
"q[\"level\"] = -1 q[\"get\"] = [ {\"func\":get_number_density, \"tag\":\"nd-ion\", \"component\":\"ion\"}, {\"func\":get_number_density, \"tag\":\"nd-electron\", \"component\":\"electron\"}, {\"func\":get_D_mag,",
"ni vmin = min(ne_min, ni_min) vmax = max(ne_max, ni_max) pcm = ax.pcolormesh(x, y,",
"q[\"files_dir\"] + \"/mov\" q[\"offset\"] = [0.0, 0.0] q[\"xy_limits\"] = [[0,0], [4,4]] q[\"file_include\"] =",
"x, Dx = ds.get(\"x_D-field\") x, Dy = ds.get(\"y_D-field\") return {\"x\":x[0], \"y\":x[1], \"value\":np.sqrt(Dx**2 +",
"data[\"nd-ion\"][\"value\"][()] ni_min = frame[\"nd-ion\"][\"min\"] ni_max = frame[\"nd-ion\"][\"max\"] ne = data[\"nd-electron\"][\"value\"][()] ne_min = frame[\"nd-electron\"][\"min\"]",
"vmin, vmax def get_number_density(ds, c): x, r = ds.get(\"rho-%s\"%c[\"component\"]) x, m = ds.get(\"mass-%s\"%c[\"component\"],",
"gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number densities",
"plt.figure(figsize=(3,3)) gs = gridspec.GridSpec(ncols=1, nrows=1, hspace=0.01, wspace=0.01) ax = fig.add_subplot(gs[0,0]); axes.append(ax) # number",
"transform=ax.transAxes, fontsize=10) ax.text(0.975, 0.025, r'$B_z$', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes, fontsize=10) for ax in axes:",
"# J[nx::, 0:ny] = np.rot90(ni.T,3) J[nx::, ny::] = ni vmin = min(ne_min, ni_min)",
"= frame[\"nd-electron\"][\"min\"] ne_max = frame[\"nd-electron\"][\"max\"] D = data[\"D\"][\"value\"][()] D_min = frame[\"D\"][\"min\"] D_max =",
"yn)) y, x = np.meshgrid(y, x) axes = [] # join the data",
"number densities J = np.zeros((2*nx, 2*ny))*np.nan # J[0:nx, 0:ny] = np.rot90(ne.T,2) J[0:nx, ny::]",
"savgol_filter(vmin, 11, 3) vmax = savgol_filter(vmax, 11, 3) return vmin, vmax def get_number_density(ds,",
"ax.set_aspect(1) ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) # fig.tight_layout() fig.savefig(output_name, dpi=300, bbox_inches=\"tight\") plt.close(fig) return if 1: Q"
] |
[
"False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list =",
"!= 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'],",
"= boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try:",
"checks['id'] + ' --- ' + checks['name']) traceback.print_exc() continue for k1, v1 in",
"elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)]",
"{'success': True} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while",
"4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list} except BaseException as e:",
"not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']),",
"err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required",
"+checks['name']) continue return {'success': True} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some",
"err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium",
"traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION',",
"dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status']",
"while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION',",
"for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available':",
"check_summary_list} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating",
"}) except BaseException as e: print('Failed to get check: ' + checks['id'] +",
"v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return",
"'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required to generate this report.\"} return",
"check: ' + checks['id'] + ' --- ' + checks['name']) traceback.print_exc() continue for",
"botocore.exceptions import ClientError import traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support') def",
"import boto3_helper, context_helper from botocore.exceptions import ClientError import traceback class Support: def __init__(self):",
"ClientError import traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try:",
"== 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1,",
"except BaseException as e: print('Failed to get check: ' + checks['id'] + '",
"'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription",
"' + checks['name']) print(\"Not able to refresh the trusted adviser check: \" +",
"checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except",
"and len(v1) != 0: for dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)]",
"'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2)",
"check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed':",
"True, 'response': check_summary_list} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred",
"len(v1) != 0: for dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] =",
"+ checks['id'] + ' --- ' + checks['name']) traceback.print_exc() continue for k1, v1",
"able to refresh the trusted adviser check: \" + traceback.format_exc() + \": Check",
"is required to generate this report.\"} return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str}",
"checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check: '",
"2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1,",
"'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3)",
"str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed",
"[] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored':",
"+ traceback.format_exc() + \": Check name:\" +checks['name']) continue return {'success': True} except BaseException",
"!= 0: for dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1,",
"self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check: ' + checks['name']) print(\"Not able",
"if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)]",
"traceback.format_exc() + \": Check name:\" +checks['name']) continue return {'success': True} except BaseException as",
"\" + traceback.format_exc() + \": Check name:\" +checks['name']) continue return {'success': True} except",
"3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response':",
"Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for",
"to refresh the trusted adviser check: \" + traceback.format_exc() + \": Check name:\"",
"check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name':",
"+ \": Check name:\" +checks['name']) continue return {'success': True} except BaseException as e:",
"dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] =",
"context_helper from botocore.exceptions import ClientError import traceback class Support: def __init__(self): self.client =",
"print('Failed to get check: ' + checks['id'] + ' --- ' + checks['name'])",
"str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to get",
"' --- ' + checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if",
"str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to get check: '",
"'message': \"AWS Premium Support Subscription is required to generate this report.\"} return {'success':",
"boto3_helper, context_helper from botocore.exceptions import ClientError import traceback class Support: def __init__(self): self.client",
"self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0]",
"(dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list} except BaseException as",
"def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks",
"ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not",
"Check name:\" +checks['name']) continue return {'success': True} except BaseException as e: err_str =",
"check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as",
"try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as",
"v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else:",
"traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks =",
"v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list} except",
"check: \" + traceback.format_exc() + \": Check name:\" +checks['name']) continue return {'success': True}",
"ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check: ' + checks['name'])",
"== 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x:",
"{} for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] !=",
"= (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success':",
"'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to get check: ' +",
"class Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en')",
"= {} for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status']",
"continue for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) !=",
"{'success': True, 'response': check_summary_list} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception",
"boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id'])",
"as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return",
"refresh the trusted adviser check: \" + traceback.format_exc() + \": Check name:\" +checks['name'])",
"generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message':",
"Subscription is required to generate this report.\"} return {'success': False, 'error_code': 'EXCEPTION', 'message':",
"in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check: ' +",
"= (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status']",
"' + checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict,",
"= self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']]",
"as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if",
"BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str)",
"def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']:",
"+ checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list))",
"for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check:",
"list)) and len(v1) != 0: for dict_val_v1 in v1: if dict_val_v1['status'] == 'error':",
"in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] ==",
"isinstance(v1, (dict, list)) and len(v1) != 0: for dict_val_v1 in v1: if dict_val_v1['status']",
"refresh check: ' + checks['name']) print(\"Not able to refresh the trusted adviser check:",
"in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) != 0: for dict_val_v1 in",
"== 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1,",
"True} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing",
"try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']: try: check_summary",
"checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks",
"try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not in",
"err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return {'success': False,",
"name:\" +checks['name']) continue return {'success': True} except BaseException as e: err_str = traceback.format_exc()",
"exception occurred while refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str}",
"the trusted adviser check: \" + traceback.format_exc() + \": Check name:\" +checks['name']) continue",
"1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok':",
"exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False,",
"(dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] ==",
"while refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self):",
"e: print('Cannot refresh check: ' + checks['name']) print(\"Not able to refresh the trusted",
"for dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif",
"from botocore.exceptions import ClientError import traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support')",
"traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return",
"as e: print('Cannot refresh check: ' + checks['name']) print(\"Not able to refresh the",
"{'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list",
"{'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required to generate",
"--- ' + checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if isinstance(v1,",
"str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to get check: ' + checks['id']",
"checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed':",
"= (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)]",
"'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for",
"context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message':",
"checks['name']) print(\"Not able to refresh the trusted adviser check: \" + traceback.format_exc() +",
"from autobot_helpers import boto3_helper, context_helper from botocore.exceptions import ClientError import traceback class Support:",
"return {'success': True, 'response': check_summary_list} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some",
"checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = []",
"except ClientError as e: print('Cannot refresh check: ' + checks['name']) print(\"Not able to",
"return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required to",
"refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError",
"' + checks['id'] + ' --- ' + checks['name']) traceback.print_exc() continue for k1,",
"v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) != 0: for dict_val_v1",
"checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if",
"print('Cannot refresh check: ' + checks['name']) print(\"Not able to refresh the trusted adviser",
"err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks =",
"try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh check: ' + checks['name']) print(\"Not",
"generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']: try:",
"as e: print('Failed to get check: ' + checks['id'] + ' --- '",
"'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e:",
"continue return {'success': True} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception",
"occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code':",
"(dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True,",
"(dict, list)) and len(v1) != 0: for dict_val_v1 in v1: if dict_val_v1['status'] ==",
"'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to get check:",
"return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en')",
"dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] =",
"'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException as e: print('Failed to",
"else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list}",
"Support Subscription is required to generate this report.\"} return {'success': False, 'error_code': 'EXCEPTION',",
"self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot refresh",
"e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException'",
"'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), }) except BaseException",
"check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) != 0: for dict_val_v1 in v1:",
"'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks",
"k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) != 0: for",
"v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list} except BaseException as e: err_str",
"'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status':",
"check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list:",
"in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged':",
"check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']),",
"traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1)",
"= self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e: print('Cannot",
"report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS",
"elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4)",
"'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {}",
"if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'],",
"for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and len(v1) != 0:",
"x: x[1]) return {'success': True, 'response': check_summary_list} except BaseException as e: err_str =",
"ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']: try: check_summary =",
"check_summary_list = {} for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if",
"BaseException as e: print('Failed to get check: ' + checks['id'] + ' ---",
"= traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str:",
"import traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks",
"= [] check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']),",
"import ClientError import traceback class Support: def __init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self):",
"except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\",",
"adviser check: \" + traceback.format_exc() + \": Check name:\" +checks['name']) continue return {'success':",
"to get check: ' + checks['id'] + ' --- ' + checks['name']) traceback.print_exc()",
"refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def generate_report(self): try:",
"get check: ' + checks['id'] + ' --- ' + checks['name']) traceback.print_exc() continue",
"Premium Support Subscription is required to generate this report.\"} return {'success': False, 'error_code':",
"__init__(self): self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in",
"\": Check name:\" +checks['name']) continue return {'success': True} except BaseException as e: err_str",
"return {'success': True} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred",
"ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except ClientError as e:",
"self.client = boto3_helper.get_client('support') def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']:",
"+ ' --- ' + checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items():",
"in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is",
"v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning': v1[v1.index(dict_val_v1)] = (dict_val_v1, 2) elif",
"err_str} def generate_report(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in",
"\"AWS Premium Support Subscription is required to generate this report.\"} return {'success': False,",
"except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\",",
"occurred while refreshing checks=%s\", err_str) return {'success': False, 'error_code': 'EXCEPTION', 'message': err_str} def",
"trusted adviser check: \" + traceback.format_exc() + \": Check name:\" +checks['name']) continue return",
"checks['name']) traceback.print_exc() continue for k1, v1 in check_summary_list.items(): if isinstance(v1, (dict, list)) and",
"(dict_val_v1, 2) elif dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] =",
"'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda x: x[1])",
"0: for dict_val_v1 in v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1)",
"= traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return {'success': False, 'error_code':",
"self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] =",
"err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in",
"False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required to generate this",
"+ checks['name']) print(\"Not able to refresh the trusted adviser check: \" + traceback.format_exc()",
"if isinstance(v1, (dict, list)) and len(v1) != 0: for dict_val_v1 in v1: if",
"ClientError as e: print('Cannot refresh check: ' + checks['name']) print(\"Not able to refresh",
"print(\"Not able to refresh the trusted adviser check: \" + traceback.format_exc() + \":",
"= self.client.describe_trusted_advisor_checks(language='en') check_summary_list = {} for checks in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries(",
"BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str)",
"context_helper.logger().exception(\"Some exception occurred while generating report=%s\", err_str) if 'SubscriptionRequiredException' in err_str: return {'success':",
"if 'SubscriptionRequiredException' in err_str: return {'success': False, 'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support",
"autobot_helpers import boto3_helper, context_helper from botocore.exceptions import ClientError import traceback class Support: def",
"if check_summary['status'] != 'not_available': if checks['category'] not in check_summary_list: check_summary_list[checks['category']] = [] check_summary_list[checks['category']].append({",
"check: ' + checks['name']) print(\"Not able to refresh the trusted adviser check: \"",
"= (dict_val_v1, 4) v1.sort(key=lambda x: x[1]) return {'success': True, 'response': check_summary_list} except BaseException",
"'error_code': 'NO_PREMIUM_SUBSCRIPTION', 'message': \"AWS Premium Support Subscription is required to generate this report.\"}",
"e: print('Failed to get check: ' + checks['id'] + ' --- ' +",
"in ta_checks['checks']: try: check_summary = self.client.describe_trusted_advisor_check_summaries( checkIds=[checks['id']])['summaries'][0] if check_summary['status'] != 'not_available': if checks['category']",
"'response': check_summary_list} except BaseException as e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while",
"check_summary_list[checks['category']].append({ 'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']),",
"def refresh_checks(self): try: ta_checks = self.client.describe_trusted_advisor_checks(language='en') for checks in ta_checks['checks']: try: self.client.refresh_trusted_advisor_check(checkId=checks['id']) except",
"dict_val_v1['status'] == 'ok': v1[v1.index(dict_val_v1)] = (dict_val_v1, 3) else: v1[v1.index(dict_val_v1)] = (dict_val_v1, 4) v1.sort(key=lambda",
"e: err_str = traceback.format_exc() context_helper.logger().exception(\"Some exception occurred while refreshing checks=%s\", err_str) return {'success':",
"v1: if dict_val_v1['status'] == 'error': v1[v1.index(dict_val_v1)] = (dict_val_v1, 1) elif dict_val_v1['status'] == 'warning':",
"x[1]) return {'success': True, 'response': check_summary_list} except BaseException as e: err_str = traceback.format_exc()",
"'name': checks['name'], 'status': check_summary['status'], 'resourcesProcessed': str(check_summary['resourcesSummary']['resourcesProcessed']), 'resourcesFlagged': str(check_summary['resourcesSummary']['resourcesFlagged']), 'resourcesSuppressed': str(check_summary['resourcesSummary']['resourcesSuppressed']), 'resourcesIgnored': str(check_summary['resourcesSummary']['resourcesIgnored']), })"
] |
[
"https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"]) print(\"====================\") print(\"Access",
"from kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request",
"kitesettings from kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token =",
"kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data = kite.generate_session(request_token,",
"KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"])",
"import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \")",
"request_token = input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"]) print(\"====================\") print(\"Access Token:",
"input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"]) print(\"====================\") print(\"Access Token: \", data[\"access_token\"])",
"kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token:",
"= KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret)",
"# https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"]) print(\"====================\")",
"= input(\"Request Token: \") data = kite.generate_session(request_token, kitesettings.api_secret) kite.set_access_token(data[\"access_token\"]) print(\"====================\") print(\"Access Token: \",",
"import kitesettings from kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token",
"logging import kitesettings from kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa",
"KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data",
"logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) # https://kite.zerodha.com/connect/login?v=4&API_KEY=Q8JPzjkt8ftXgqvmXa request_token = input(\"Request Token: \") data =",
"import logging import kitesettings from kiteconnect import KiteConnect logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(kitesettings.API_KEY) #"
] |
[
"from datetime import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format",
"None) -> str: assert datefmt is None # static format time_stamp = datetime.fromtimestamp(record.created)",
"formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) -> str: assert datefmt is",
"datetime import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time",
"typing import Union from datetime import datetime from logging import Formatter, LogRecord class",
"datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO",
"Format time in ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None]",
"\"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) -> str: assert",
"import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in",
"None] = None) -> str: assert datefmt is None # static format time_stamp",
"def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) -> str: assert datefmt",
"ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) ->",
"= None) -> str: assert datefmt is None # static format time_stamp =",
"from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601",
"datefmt: Union[str, None] = None) -> str: assert datefmt is None # static",
"import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\" def",
"8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None) -> str:",
"time in ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None] =",
"BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt:",
"Union[str, None] = None) -> str: assert datefmt is None # static format",
"logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\"",
"class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\" def formatTime(self, record: LogRecord,",
"LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\" def formatTime(self, record:",
"in ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str, None] = None)",
"-> str: assert datefmt is None # static format time_stamp = datetime.fromtimestamp(record.created) return",
"Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\" Format time in ISO 8601 \"\"\" def formatTime(self,",
"Union from datetime import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter): \"\"\"",
"from typing import Union from datetime import datetime from logging import Formatter, LogRecord",
"\"\"\" Format time in ISO 8601 \"\"\" def formatTime(self, record: LogRecord, datefmt: Union[str,",
"record: LogRecord, datefmt: Union[str, None] = None) -> str: assert datefmt is None",
"str: assert datefmt is None # static format time_stamp = datetime.fromtimestamp(record.created) return time_stamp.astimezone().isoformat()",
"LogRecord, datefmt: Union[str, None] = None) -> str: assert datefmt is None #",
"import Union from datetime import datetime from logging import Formatter, LogRecord class BalsaFormatter(Formatter):"
] |
[
"= {} for file in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)]",
"def last_file(path, extension): directory = os.scandir(path) dict_file = {} for file in directory:",
"datetime, timezone # Function that will return the most recent file from a",
"last_file(path, extension): directory = os.scandir(path) dict_file = {} for file in directory: if",
"= file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example a = last_file('C:/Users/user/Downloads', 'exe') print(a)",
"datetime import datetime, timezone # Function that will return the most recent file",
"from a directory, filtering by extension def last_file(path, extension): directory = os.scandir(path) dict_file",
"file in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file",
"in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file =",
"<reponame>CarlosPetrikov/random_python_functions import os from datetime import datetime, timezone # Function that will return",
"{} for file in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] =",
"extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example a =",
"= os.scandir(path) dict_file = {} for file in directory: if file.name[-3:] in (extension.lower(),",
"extension): directory = os.scandir(path) dict_file = {} for file in directory: if file.name[-3:]",
"will return the most recent file from a directory, filtering by extension def",
"import os from datetime import datetime, timezone # Function that will return the",
"most recent file from a directory, filtering by extension def last_file(path, extension): directory",
"import datetime, timezone # Function that will return the most recent file from",
"by extension def last_file(path, extension): directory = os.scandir(path) dict_file = {} for file",
"file from a directory, filtering by extension def last_file(path, extension): directory = os.scandir(path)",
"recent file from a directory, filtering by extension def last_file(path, extension): directory =",
"for file in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name",
"timezone # Function that will return the most recent file from a directory,",
"# Function that will return the most recent file from a directory, filtering",
"os from datetime import datetime, timezone # Function that will return the most",
"dict_file = {} for file in directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime,",
"from datetime import datetime, timezone # Function that will return the most recent",
"return the most recent file from a directory, filtering by extension def last_file(path,",
"in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example",
"if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return",
"file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]]",
"dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example a = last_file('C:/Users/user/Downloads',",
"extension def last_file(path, extension): directory = os.scandir(path) dict_file = {} for file in",
"(extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example a",
"Function that will return the most recent file from a directory, filtering by",
"that will return the most recent file from a directory, filtering by extension",
"tz=timezone.utc)] = file.name time_file = sorted(dict_file) return dict_file[time_file[-1]] #Example a = last_file('C:/Users/user/Downloads', 'exe')",
"filtering by extension def last_file(path, extension): directory = os.scandir(path) dict_file = {} for",
"the most recent file from a directory, filtering by extension def last_file(path, extension):",
"os.scandir(path) dict_file = {} for file in directory: if file.name[-3:] in (extension.lower(), extension.upper()):",
"directory = os.scandir(path) dict_file = {} for file in directory: if file.name[-3:] in",
"a directory, filtering by extension def last_file(path, extension): directory = os.scandir(path) dict_file =",
"directory, filtering by extension def last_file(path, extension): directory = os.scandir(path) dict_file = {}",
"directory: if file.name[-3:] in (extension.lower(), extension.upper()): dict_file[datetime.fromtimestamp(file.stat().st_mtime, tz=timezone.utc)] = file.name time_file = sorted(dict_file)"
] |
[
"I almost died. from collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity):",
"just return -1. else: return -1 def set(self, key, value): \"\"\" :type key:",
"prevCount + 1 # Set the new amount. self.count[key] = newCount # Delete",
"= defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap = capacity def get(self,",
"the new amount. self.count[key] = newCount # Delete the key from the previous",
"self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap = capacity def",
"int :rtype: int \"\"\" # If the key exists. Make sure to put",
"def get(self, key): \"\"\" :type key: int :rtype: int \"\"\" # If the",
"OrderedDict()) # Capacity of the LFU. self.cap = capacity def get(self, key): \"\"\"",
"associated to this key. return self.dic[key] # If the key doesn't exists, just",
"from a key 2 (as in two times used), get the keys that",
"grouping is now empty, erase it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount]",
"update the value associated to this key. self.dic[key] = value # If the",
"from the grouping of keys used that times. del self.reverse[leastAmount][leastKey] # If there",
"will be updated. if self.dic.get(key) is not None: # Times used previously. prevCount",
"key has been used. self.count = {} # Keys grouped by amount of",
"2 (as in two times used), get the keys that have been #",
"to put \"is not None\" otherwise a 0 Value # will make the",
"key by accessing with the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] #",
"called as such: # obj = LFUCache(capacity) # param_1 = obj.get(key) # obj.set(key,value)",
":type key: int :rtype: int \"\"\" # If the key exists. Make sure",
"times used. newCount = prevCount + 1 # Set the new amount. self.count[key]",
"self.dic[key] = value self.count[key] = 1 self.reverse[1][key] = True # Your LFUCache object",
"to False. if self.dic.get(key) is not None: # Update the amount of times",
":type capacity: int \"\"\" # From key to value. self.dic = {} #",
"are no more keys for this count, delete the count. if len(self.reverse[leastAmount]) ==",
"exists, just return -1. else: return -1 def set(self, key, value): \"\"\" :type",
"previously. prevCount = self.count[key] # New amount of times used. newCount = prevCount",
"Capacity of the LFU. self.cap = capacity def get(self, key): \"\"\" :type key:",
"into the new grouping of times used. self.reverse[newCount][key] = True # Now update",
"exists... else: # If capacity will be exceeded, erase the currently least used",
"If the key exists. Make sure to put \"is not None\" otherwise a",
"\"\"\" # From key to value. self.dic = {} # Times a key",
"put \"is not None\" otherwise a 0 Value # will make the condition",
"used. del self.reverse[prevCount][key] # If that grouping is now empty, erase it too.",
"From key to value. self.dic = {} # Times a key has been",
"self.reverse[prevCount] # Insert key into the new grouping of times used. self.reverse[newCount][key] =",
"a 0 Value # will make the condition evaluate to False. if self.dic.get(key)",
"del self.reverse[prevCount] # Insert key into the new grouping of times used. self.reverse[newCount][key]",
"if self.dic.get(key) is not None: # Times used previously. prevCount = self.count[key] #",
"Used cache. GODDAMN I almost died. from collections import OrderedDict, defaultdict class LFUCache(object):",
"amount, lets get the least amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now,",
"= value # If the value doesn't exists... else: # If capacity will",
"{} # Keys grouped by amount of usage. # e.g. from a key",
"of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict, lets",
"so that it will be updated. if self.dic.get(key) is not None: # Times",
"# If there are no more keys for this count, delete the count.",
"= prevCount + 1 self.count[key] = newCount # Delete the key from the",
"an OrderedDict, lets get the least freq # used key by accessing with",
"(the insertion). if len(self.dic) + 1 <= self.cap: self.dic[key] = value self.count[key] =",
"Times a key has been used. self.count = {} # Keys grouped by",
"value self.count[key] = 1 self.reverse[1][key] = True # Your LFUCache object will be",
"is not None: # Times used previously. prevCount = self.count[key] # New amount",
"= True # Return the value associated to this key. return self.dic[key] #",
"\"\"\" # Check that the value exists, so that it will be updated.",
"uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from the grouping of",
"be exceeded, erase the currently least used one. if len(self.dic) == self.cap and",
"the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from",
"of times used. del self.reverse[prevCount][key] # If that grouping is now empty, erase",
"e.g. from a key 2 (as in two times used), get the keys",
"Times used previously. prevCount = self.count[key] # New amount of times used. newCount",
"erase it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key into",
"it will be updated. if self.dic.get(key) is not None: # Times used previously.",
"that grouping is now empty, erase it too. if len(self.reverse[prevCount]) == 0: del",
"key from the previous grouping of times used. del self.reverse[prevCount][key] # If that",
"else: return -1 def set(self, key, value): \"\"\" :type key: int :type value:",
"the key from the previous grouping of times used. del self.reverse[prevCount][key] # If",
":type key: int :type value: int :rtype: void \"\"\" # Check that the",
"self.reverse[prevCount][key] # If that grouping is now empty, erase it too. if len(self.reverse[prevCount])",
"newCount = prevCount + 1 self.count[key] = newCount # Delete the key from",
"value. del self.dic[leastKey] # Now, insert the new key, with a single usage",
"# Delete the LFU key and its value. del self.dic[leastKey] # Now, insert",
"0 Value # will make the condition evaluate to False. if self.dic.get(key) is",
"self.dic.get(key) is not None: # Update the amount of times key has been",
"the currently least used one. if len(self.dic) == self.cap and len(self.reverse) > 0:",
"key has been used. prevCount = self.count[key] newCount = prevCount + 1 self.count[key]",
"leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from the grouping of keys used",
"individual amount of uses for the LFU key. del self.count[leastKey] # Delete the",
"= value self.count[key] = 1 self.reverse[1][key] = True # Your LFUCache object will",
"for the LFU key. del self.count[leastKey] # Delete the LFU key and its",
"used. self.reverse[newCount][key] = True # Now update the value associated to this key.",
"count, delete the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the",
"amount of times key has been used. prevCount = self.count[key] newCount = prevCount",
"self.reverse[leastAmount] # Delete the individual amount of uses for the LFU key. del",
"least used one. if len(self.dic) == self.cap and len(self.reverse) > 0: # Because",
"now empty, erase it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert",
"amount. self.count[key] = newCount # Delete the key from the previous grouping of",
"this key. return self.dic[key] # If the key doesn't exists, just return -1.",
"if len(self.dic) == self.cap and len(self.reverse) > 0: # Because the \"reverse\" (from",
"self.count[key] # New amount of times used. newCount = prevCount + 1 #",
"Because the \"reverse\" (from count to keys) dict groups keys # by accessed",
"+ 1 <= self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key] = True",
"its value. del self.dic[leastKey] # Now, insert the new key, with a single",
"is not None: # Update the amount of times key has been used.",
"be instantiated and called as such: # obj = LFUCache(capacity) # param_1 =",
"the previous grouping of times used. del self.reverse[prevCount][key] # If that grouping is",
"Implement a Least Frequently Used cache. GODDAMN I almost died. from collections import",
"key: int :type value: int :rtype: void \"\"\" # Check that the value",
"the key exists. Make sure to put \"is not None\" otherwise a 0",
"the LFU. self.cap = capacity def get(self, key): \"\"\" :type key: int :rtype:",
"\"is not None\" otherwise a 0 Value # will make the condition evaluate",
"self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key] = True # Your LFUCache",
"# Set the new amount. self.count[key] = newCount # Delete the key from",
"with the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number",
"self.count[leastKey] # Delete the LFU key and its value. del self.dic[leastKey] # Now,",
"this key. self.dic[key] = value # If the value doesn't exists... else: #",
"(Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache. GODDAMN I almost",
"Keys grouped by amount of usage. # e.g. from a key 2 (as",
"# Insert key into the new grouping of times used. self.reverse[newCount][key] = True",
"True # Your LFUCache object will be instantiated and called as such: #",
"currently least used one. if len(self.dic) == self.cap and len(self.reverse) > 0: #",
"in two times used), get the keys that have been # used that",
"leastAmount = sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict, lets get the",
"the least freq # used key by accessing with the leastAmount of uses",
"# e.g. from a key 2 (as in two times used), get the",
"the grouping of keys used that times. del self.reverse[leastAmount][leastKey] # If there are",
"# by accessed amount, lets get the least amount of uses. leastAmount =",
"key, with a single usage (the insertion). if len(self.dic) + 1 <= self.cap:",
"to value. self.dic = {} # Times a key has been used. self.count",
"times used. self.reverse[newCount][key] = True # Return the value associated to this key.",
"the LFU key and its value. del self.dic[leastKey] # Now, insert the new",
"this is an OrderedDict, lets get the least freq # used key by",
"value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from the grouping of keys",
"# Return the value associated to this key. return self.dic[key] # If the",
"prevCount = self.count[key] # New amount of times used. newCount = prevCount +",
"lets get the least amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because",
"accessed amount, lets get the least amount of uses. leastAmount = sorted(self.reverse.keys())[0] #",
"= sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict, lets get the least",
"= self.count[key] newCount = prevCount + 1 self.count[key] = newCount # Delete the",
"capacity will be exceeded, erase the currently least used one. if len(self.dic) ==",
"the value associated to this key. self.dic[key] = value # If the value",
"almost died. from collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\"",
"used previously. prevCount = self.count[key] # New amount of times used. newCount =",
"self.count[key] = 1 self.reverse[1][key] = True # Your LFUCache object will be instantiated",
"If the value doesn't exists... else: # If capacity will be exceeded, erase",
"def __init__(self, capacity): \"\"\" :type capacity: int \"\"\" # From key to value.",
"doesn't exists... else: # If capacity will be exceeded, erase the currently least",
"that much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap",
"a Least Frequently Used cache. GODDAMN I almost died. from collections import OrderedDict,",
"not None: # Times used previously. prevCount = self.count[key] # New amount of",
"# If the value doesn't exists... else: # If capacity will be exceeded,",
"{} # Times a key has been used. self.count = {} # Keys",
"import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int \"\"\"",
"OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int \"\"\" #",
"If the key doesn't exists, just return -1. else: return -1 def set(self,",
"return -1. else: return -1 def set(self, key, value): \"\"\" :type key: int",
"value # If the value doesn't exists... else: # If capacity will be",
"get(self, key): \"\"\" :type key: int :rtype: int \"\"\" # If the key",
"self.count = {} # Keys grouped by amount of usage. # e.g. from",
"capacity: int \"\"\" # From key to value. self.dic = {} # Times",
"that have been # used that much times. self.reverse = defaultdict(lambda: OrderedDict()) #",
"more keys for this count, delete the count. if len(self.reverse[leastAmount]) == 0: del",
"\"\"\" :type key: int :type value: int :rtype: void \"\"\" # Check that",
"grouping of keys used that times. del self.reverse[leastAmount][leastKey] # If there are no",
"Now, insert the new key, with a single usage (the insertion). if len(self.dic)",
"there are no more keys for this count, delete the count. if len(self.reverse[leastAmount])",
"two times used), get the keys that have been # used that much",
"= prevCount + 1 # Set the new amount. self.count[key] = newCount #",
"times key has been used. prevCount = self.count[key] newCount = prevCount + 1",
"Now, because this is an OrderedDict, lets get the least freq # used",
"associated to this key. self.dic[key] = value # If the value doesn't exists...",
"Return the value associated to this key. return self.dic[key] # If the key",
"# If capacity will be exceeded, erase the currently least used one. if",
"del self.reverse[leastAmount] # Delete the individual amount of uses for the LFU key.",
"grouping of times used. del self.reverse[prevCount][key] # If that grouping is now empty,",
"new amount. self.count[key] = newCount # Delete the key from the previous grouping",
"key. return self.dic[key] # If the key doesn't exists, just return -1. else:",
"= True # Now update the value associated to this key. self.dic[key] =",
"keys) dict groups keys # by accessed amount, lets get the least amount",
"amount of uses for the LFU key. del self.count[leastKey] # Delete the LFU",
"== 0: del self.reverse[leastAmount] # Delete the individual amount of uses for the",
"int :type value: int :rtype: void \"\"\" # Check that the value exists,",
"# Now update the value associated to this key. self.dic[key] = value #",
"object will be instantiated and called as such: # obj = LFUCache(capacity) #",
"len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the individual amount of uses for",
"= capacity def get(self, key): \"\"\" :type key: int :rtype: int \"\"\" #",
"grouped by amount of usage. # e.g. from a key 2 (as in",
"0: del self.reverse[prevCount] # Insert key into the new grouping of times used.",
"If capacity will be exceeded, erase the currently least used one. if len(self.dic)",
"of times used. self.reverse[newCount][key] = True # Now update the value associated to",
"# Implement a Least Frequently Used cache. GODDAMN I almost died. from collections",
"# 460 - LFU Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently",
"a single usage (the insertion). if len(self.dic) + 1 <= self.cap: self.dic[key] =",
"the new key, with a single usage (the insertion). if len(self.dic) + 1",
"None\" otherwise a 0 Value # will make the condition evaluate to False.",
"self.reverse[newCount][key] = True # Now update the value associated to this key. self.dic[key]",
"of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from the grouping",
"amount of usage. # e.g. from a key 2 (as in two times",
"# If the key exists. Make sure to put \"is not None\" otherwise",
"be updated. if self.dic.get(key) is not None: # Times used previously. prevCount =",
"len(self.dic) == self.cap and len(self.reverse) > 0: # Because the \"reverse\" (from count",
"to keys) dict groups keys # by accessed amount, lets get the least",
"empty, erase it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key",
"<reponame>Zubieta/CPP<gh_stars>1-10 # 460 - LFU Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least",
"one. if len(self.dic) == self.cap and len(self.reverse) > 0: # Because the \"reverse\"",
"grouping of times used. self.reverse[newCount][key] = True # Return the value associated to",
"Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache. GODDAMN I",
"capacity def get(self, key): \"\"\" :type key: int :rtype: int \"\"\" # If",
"# Now, because this is an OrderedDict, lets get the least freq #",
"self.dic = {} # Times a key has been used. self.count = {}",
"this count, delete the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete",
"is an OrderedDict, lets get the least freq # used key by accessing",
"LFU key and its value. del self.dic[leastKey] # Now, insert the new key,",
"died. from collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type",
"exceeded, erase the currently least used one. if len(self.dic) == self.cap and len(self.reverse)",
"= True # Your LFUCache object will be instantiated and called as such:",
"self.dic.get(key) is not None: # Times used previously. prevCount = self.count[key] # New",
"used. prevCount = self.count[key] newCount = prevCount + 1 self.count[key] = newCount #",
"= 1 self.reverse[1][key] = True # Your LFUCache object will be instantiated and",
"make the condition evaluate to False. if self.dic.get(key) is not None: # Update",
"= newCount # Delete the key from the previous grouping of times used.",
"Delete the key from the previous grouping of times used. del self.reverse[prevCount][key] #",
"by accessed amount, lets get the least amount of uses. leastAmount = sorted(self.reverse.keys())[0]",
"new grouping of times used. self.reverse[newCount][key] = True # Now update the value",
"LFU. self.cap = capacity def get(self, key): \"\"\" :type key: int :rtype: int",
"== 0: del self.reverse[prevCount] # Insert key into the new grouping of times",
"to this key. return self.dic[key] # If the key doesn't exists, just return",
"amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict,",
"= (self.reverse[leastAmount].keys())[0] # Delete that number from the grouping of keys used that",
"1 self.reverse[1][key] = True # Your LFUCache object will be instantiated and called",
"least amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this is an",
"None: # Update the amount of times key has been used. prevCount =",
"# If the key doesn't exists, just return -1. else: return -1 def",
"<= self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key] = True # Your",
"exists, so that it will be updated. if self.dic.get(key) is not None: #",
"# https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache. GODDAMN I almost died.",
"a key 2 (as in two times used), get the keys that have",
"key to value. self.dic = {} # Times a key has been used.",
"condition evaluate to False. if self.dic.get(key) is not None: # Update the amount",
"int :rtype: void \"\"\" # Check that the value exists, so that it",
"len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key into the new grouping of",
"sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict, lets get the least freq",
"it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key into the",
"key doesn't exists, just return -1. else: return -1 def set(self, key, value):",
"used that times. del self.reverse[leastAmount][leastKey] # If there are no more keys for",
"get the least amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this",
"https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache. GODDAMN I almost died. from",
"used one. if len(self.dic) == self.cap and len(self.reverse) > 0: # Because the",
":rtype: void \"\"\" # Check that the value exists, so that it will",
"None: # Times used previously. prevCount = self.count[key] # New amount of times",
"(as in two times used), get the keys that have been # used",
"= self.count[key] # New amount of times used. newCount = prevCount + 1",
"# If that grouping is now empty, erase it too. if len(self.reverse[prevCount]) ==",
"# Now, insert the new key, with a single usage (the insertion). if",
"updated. if self.dic.get(key) is not None: # Times used previously. prevCount = self.count[key]",
"(self.reverse[leastAmount].keys())[0] # Delete that number from the grouping of keys used that times.",
"times used. del self.reverse[prevCount][key] # If that grouping is now empty, erase it",
"del self.dic[leastKey] # Now, insert the new key, with a single usage (the",
"value exists, so that it will be updated. if self.dic.get(key) is not None:",
"def set(self, key, value): \"\"\" :type key: int :type value: int :rtype: void",
"if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the individual amount of uses",
"a key has been used. self.count = {} # Keys grouped by amount",
"key into the new grouping of times used. self.reverse[newCount][key] = True # Now",
"used. self.count = {} # Keys grouped by amount of usage. # e.g.",
"doesn't exists, just return -1. else: return -1 def set(self, key, value): \"\"\"",
"key 2 (as in two times used), get the keys that have been",
"prevCount = self.count[key] newCount = prevCount + 1 self.count[key] = newCount # Delete",
"used key by accessing with the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0]",
"the keys that have been # used that much times. self.reverse = defaultdict(lambda:",
"the key doesn't exists, just return -1. else: return -1 def set(self, key,",
"insertion). if len(self.dic) + 1 <= self.cap: self.dic[key] = value self.count[key] = 1",
"the new grouping of times used. self.reverse[newCount][key] = True # Return the value",
"New amount of times used. newCount = prevCount + 1 # Set the",
"otherwise a 0 Value # will make the condition evaluate to False. if",
"keys # by accessed amount, lets get the least amount of uses. leastAmount",
"LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int \"\"\" # From key to",
"else: # If capacity will be exceeded, erase the currently least used one.",
"keys for this count, delete the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount]",
"key): \"\"\" :type key: int :rtype: int \"\"\" # If the key exists.",
"# Delete that number from the grouping of keys used that times. del",
"have been # used that much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity",
"1 self.count[key] = newCount # Delete the key from the previous grouping of",
"from the previous grouping of times used. del self.reverse[prevCount][key] # If that grouping",
"LFU key. del self.count[leastKey] # Delete the LFU key and its value. del",
"If there are no more keys for this count, delete the count. if",
"# From key to value. self.dic = {} # Times a key has",
"= {} # Keys grouped by amount of usage. # e.g. from a",
"self.cap and len(self.reverse) > 0: # Because the \"reverse\" (from count to keys)",
"the \"reverse\" (from count to keys) dict groups keys # by accessed amount,",
"get the least freq # used key by accessing with the leastAmount of",
"times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap = capacity",
"+ 1 # Set the new amount. self.count[key] = newCount # Delete the",
"self.cap = capacity def get(self, key): \"\"\" :type key: int :rtype: int \"\"\"",
"# Check that the value exists, so that it will be updated. if",
"del self.count[leastKey] # Delete the LFU key and its value. del self.dic[leastKey] #",
"self.count[key] newCount = prevCount + 1 self.count[key] = newCount # Delete the key",
"not None: # Update the amount of times key has been used. prevCount",
"accessing with the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that",
"# Capacity of the LFU. self.cap = capacity def get(self, key): \"\"\" :type",
"the LFU key. del self.count[leastKey] # Delete the LFU key and its value.",
"the least amount of uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this is",
"void \"\"\" # Check that the value exists, so that it will be",
"False. if self.dic.get(key) is not None: # Update the amount of times key",
"Delete that number from the grouping of keys used that times. del self.reverse[leastAmount][leastKey]",
"value: int :rtype: void \"\"\" # Check that the value exists, so that",
"of the LFU. self.cap = capacity def get(self, key): \"\"\" :type key: int",
"> 0: # Because the \"reverse\" (from count to keys) dict groups keys",
"- LFU Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache.",
"# Update the amount of times key has been used. prevCount = self.count[key]",
"will be instantiated and called as such: # obj = LFUCache(capacity) # param_1",
"that number from the grouping of keys used that times. del self.reverse[leastAmount][leastKey] #",
"# Because the \"reverse\" (from count to keys) dict groups keys # by",
"exists. Make sure to put \"is not None\" otherwise a 0 Value #",
"and its value. del self.dic[leastKey] # Now, insert the new key, with a",
"defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap = capacity def get(self, key):",
"evaluate to False. if self.dic.get(key) is not None: # Update the amount of",
"the condition evaluate to False. if self.dic.get(key) is not None: # Update the",
"of uses for the LFU key. del self.count[leastKey] # Delete the LFU key",
"del self.reverse[prevCount][key] # If that grouping is now empty, erase it too. if",
"erase the currently least used one. if len(self.dic) == self.cap and len(self.reverse) >",
"return -1 def set(self, key, value): \"\"\" :type key: int :type value: int",
"If that grouping is now empty, erase it too. if len(self.reverse[prevCount]) == 0:",
"# will make the condition evaluate to False. if self.dic.get(key) is not None:",
"# Keys grouped by amount of usage. # e.g. from a key 2",
"and called as such: # obj = LFUCache(capacity) # param_1 = obj.get(key) #",
"too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key into the new",
"# New amount of times used. newCount = prevCount + 1 # Set",
"to this key. self.dic[key] = value # If the value doesn't exists... else:",
"value. self.dic = {} # Times a key has been used. self.count =",
"Least Frequently Used cache. GODDAMN I almost died. from collections import OrderedDict, defaultdict",
"used. self.reverse[newCount][key] = True # Return the value associated to this key. return",
"the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the individual amount",
"True # Now update the value associated to this key. self.dic[key] = value",
"previous grouping of times used. del self.reverse[prevCount][key] # If that grouping is now",
"LFU Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used cache. GODDAMN",
"delete the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the individual",
"value): \"\"\" :type key: int :type value: int :rtype: void \"\"\" # Check",
"int \"\"\" # From key to value. self.dic = {} # Times a",
"self.dic[leastKey] # Now, insert the new key, with a single usage (the insertion).",
"self.reverse[1][key] = True # Your LFUCache object will be instantiated and called as",
"by accessing with the leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete",
"set(self, key, value): \"\"\" :type key: int :type value: int :rtype: void \"\"\"",
"value doesn't exists... else: # If capacity will be exceeded, erase the currently",
"int \"\"\" # If the key exists. Make sure to put \"is not",
"used), get the keys that have been # used that much times. self.reverse",
"no more keys for this count, delete the count. if len(self.reverse[leastAmount]) == 0:",
"key and its value. del self.dic[leastKey] # Now, insert the new key, with",
"key: int :rtype: int \"\"\" # If the key exists. Make sure to",
"by amount of usage. # e.g. from a key 2 (as in two",
"# Your LFUCache object will be instantiated and called as such: # obj",
"cache. GODDAMN I almost died. from collections import OrderedDict, defaultdict class LFUCache(object): def",
"self.reverse[newCount][key] = True # Return the value associated to this key. return self.dic[key]",
"0: del self.reverse[leastAmount] # Delete the individual amount of uses for the LFU",
"has been used. self.count = {} # Keys grouped by amount of usage.",
"is now empty, erase it too. if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] #",
"= {} # Times a key has been used. self.count = {} #",
"value associated to this key. self.dic[key] = value # If the value doesn't",
"and len(self.reverse) > 0: # Because the \"reverse\" (from count to keys) dict",
"keys that have been # used that much times. self.reverse = defaultdict(lambda: OrderedDict())",
"Now update the value associated to this key. self.dic[key] = value # If",
"count to keys) dict groups keys # by accessed amount, lets get the",
"the individual amount of uses for the LFU key. del self.count[leastKey] # Delete",
"OrderedDict, lets get the least freq # used key by accessing with the",
"Make sure to put \"is not None\" otherwise a 0 Value # will",
"key exists. Make sure to put \"is not None\" otherwise a 0 Value",
"of times used. self.reverse[newCount][key] = True # Return the value associated to this",
"been used. self.count = {} # Keys grouped by amount of usage. #",
"get the keys that have been # used that much times. self.reverse =",
"return self.dic[key] # If the key doesn't exists, just return -1. else: return",
"Delete the individual amount of uses for the LFU key. del self.count[leastKey] #",
"defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int \"\"\" # From",
"# Times a key has been used. self.count = {} # Keys grouped",
"instantiated and called as such: # obj = LFUCache(capacity) # param_1 = obj.get(key)",
"freq # used key by accessing with the leastAmount of uses value. leastKey",
"True # Return the value associated to this key. return self.dic[key] # If",
":type value: int :rtype: void \"\"\" # Check that the value exists, so",
"# used key by accessing with the leastAmount of uses value. leastKey =",
"Insert key into the new grouping of times used. self.reverse[newCount][key] = True #",
"usage. # e.g. from a key 2 (as in two times used), get",
"capacity): \"\"\" :type capacity: int \"\"\" # From key to value. self.dic =",
"times. del self.reverse[leastAmount][leastKey] # If there are no more keys for this count,",
"Check that the value exists, so that it will be updated. if self.dic.get(key)",
"== self.cap and len(self.reverse) > 0: # Because the \"reverse\" (from count to",
"len(self.dic) + 1 <= self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key] =",
"of usage. # e.g. from a key 2 (as in two times used),",
"prevCount + 1 self.count[key] = newCount # Delete the key from the previous",
"1 # Set the new amount. self.count[key] = newCount # Delete the key",
"the value exists, so that it will be updated. if self.dic.get(key) is not",
"for this count, delete the count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] #",
"# Delete the individual amount of uses for the LFU key. del self.count[leastKey]",
"+ 1 self.count[key] = newCount # Delete the key from the previous grouping",
"least freq # used key by accessing with the leastAmount of uses value.",
"self.dic[key] # If the key doesn't exists, just return -1. else: return -1",
"uses for the LFU key. del self.count[leastKey] # Delete the LFU key and",
"if len(self.dic) + 1 <= self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key]",
"__init__(self, capacity): \"\"\" :type capacity: int \"\"\" # From key to value. self.dic",
"len(self.reverse) > 0: # Because the \"reverse\" (from count to keys) dict groups",
"Delete the LFU key and its value. del self.dic[leastKey] # Now, insert the",
"groups keys # by accessed amount, lets get the least amount of uses.",
"if len(self.reverse[prevCount]) == 0: del self.reverse[prevCount] # Insert key into the new grouping",
"keys used that times. del self.reverse[leastAmount][leastKey] # If there are no more keys",
"number from the grouping of keys used that times. del self.reverse[leastAmount][leastKey] # If",
"with a single usage (the insertion). if len(self.dic) + 1 <= self.cap: self.dic[key]",
"self.dic[key] = value # If the value doesn't exists... else: # If capacity",
"the value doesn't exists... else: # If capacity will be exceeded, erase the",
"new grouping of times used. self.reverse[newCount][key] = True # Return the value associated",
"much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the LFU. self.cap =",
"amount of times used. newCount = prevCount + 1 # Set the new",
"LFUCache object will be instantiated and called as such: # obj = LFUCache(capacity)",
"Update the amount of times key has been used. prevCount = self.count[key] newCount",
"del self.reverse[leastAmount][leastKey] # If there are no more keys for this count, delete",
"insert the new key, with a single usage (the insertion). if len(self.dic) +",
"Value # will make the condition evaluate to False. if self.dic.get(key) is not",
"been # used that much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of",
"will be exceeded, erase the currently least used one. if len(self.dic) == self.cap",
"self.count[key] = newCount # Delete the key from the previous grouping of times",
"leastAmount of uses value. leastKey = (self.reverse[leastAmount].keys())[0] # Delete that number from the",
"sure to put \"is not None\" otherwise a 0 Value # will make",
"self.reverse[leastAmount][leastKey] # If there are no more keys for this count, delete the",
"Frequently Used cache. GODDAMN I almost died. from collections import OrderedDict, defaultdict class",
"dict groups keys # by accessed amount, lets get the least amount of",
"value associated to this key. return self.dic[key] # If the key doesn't exists,",
"\"\"\" # If the key exists. Make sure to put \"is not None\"",
"not None\" otherwise a 0 Value # will make the condition evaluate to",
"new key, with a single usage (the insertion). if len(self.dic) + 1 <=",
"newCount # Delete the key from the previous grouping of times used. del",
"if self.dic.get(key) is not None: # Update the amount of times key has",
"class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int \"\"\" # From key",
"GODDAMN I almost died. from collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self,",
"\"\"\" :type key: int :rtype: int \"\"\" # If the key exists. Make",
"Set the new amount. self.count[key] = newCount # Delete the key from the",
"of keys used that times. del self.reverse[leastAmount][leastKey] # If there are no more",
"# Delete the key from the previous grouping of times used. del self.reverse[prevCount][key]",
"the value associated to this key. return self.dic[key] # If the key doesn't",
"single usage (the insertion). if len(self.dic) + 1 <= self.cap: self.dic[key] = value",
"that times. del self.reverse[leastAmount][leastKey] # If there are no more keys for this",
"usage (the insertion). if len(self.dic) + 1 <= self.cap: self.dic[key] = value self.count[key]",
"used that much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the LFU.",
"that it will be updated. if self.dic.get(key) is not None: # Times used",
"times used), get the keys that have been # used that much times.",
"0: # Because the \"reverse\" (from count to keys) dict groups keys #",
"\"reverse\" (from count to keys) dict groups keys # by accessed amount, lets",
"will make the condition evaluate to False. if self.dic.get(key) is not None: #",
"key. self.dic[key] = value # If the value doesn't exists... else: # If",
"grouping of times used. self.reverse[newCount][key] = True # Now update the value associated",
"-1. else: return -1 def set(self, key, value): \"\"\" :type key: int :type",
"-1 def set(self, key, value): \"\"\" :type key: int :type value: int :rtype:",
"newCount = prevCount + 1 # Set the new amount. self.count[key] = newCount",
"key, value): \"\"\" :type key: int :type value: int :rtype: void \"\"\" #",
"of times key has been used. prevCount = self.count[key] newCount = prevCount +",
"that the value exists, so that it will be updated. if self.dic.get(key) is",
"uses. leastAmount = sorted(self.reverse.keys())[0] # Now, because this is an OrderedDict, lets get",
"from collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity:",
"\"\"\" :type capacity: int \"\"\" # From key to value. self.dic = {}",
"lets get the least freq # used key by accessing with the leastAmount",
"count. if len(self.reverse[leastAmount]) == 0: del self.reverse[leastAmount] # Delete the individual amount of",
"460 - LFU Cache (Hard) # https://leetcode.com/problems/lfu-cache/ # Implement a Least Frequently Used",
"times used. self.reverse[newCount][key] = True # Now update the value associated to this",
"# Times used previously. prevCount = self.count[key] # New amount of times used.",
":rtype: int \"\"\" # If the key exists. Make sure to put \"is",
"used. newCount = prevCount + 1 # Set the new amount. self.count[key] =",
"been used. prevCount = self.count[key] newCount = prevCount + 1 self.count[key] = newCount",
"key. del self.count[leastKey] # Delete the LFU key and its value. del self.dic[leastKey]",
"Your LFUCache object will be instantiated and called as such: # obj =",
"key into the new grouping of times used. self.reverse[newCount][key] = True # Return",
"1 <= self.cap: self.dic[key] = value self.count[key] = 1 self.reverse[1][key] = True #",
"collections import OrderedDict, defaultdict class LFUCache(object): def __init__(self, capacity): \"\"\" :type capacity: int",
"of times used. newCount = prevCount + 1 # Set the new amount.",
"(from count to keys) dict groups keys # by accessed amount, lets get",
"has been used. prevCount = self.count[key] newCount = prevCount + 1 self.count[key] =",
"the amount of times key has been used. prevCount = self.count[key] newCount =",
"the new grouping of times used. self.reverse[newCount][key] = True # Now update the",
"because this is an OrderedDict, lets get the least freq # used key",
"# used that much times. self.reverse = defaultdict(lambda: OrderedDict()) # Capacity of the",
"into the new grouping of times used. self.reverse[newCount][key] = True # Return the"
] |
[
"\"Not a valid dataset folder, cannot find types.json in the input directory\") with",
"/ \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f: for video in",
"== '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory",
"open(str(in_path / \"all.csv\"), \"w\") as f: for video in files: v_split = str(video).split('/')",
"+ input_dir) if not (in_path / \"types.json\"): raise ValueError( \"Not a valid dataset",
"continue if not (in_path / folder).exists(): raise ValueError( \"Not a valid dataset folder,",
"folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path /",
"label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args",
"f: for video in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\"",
"\" + input_dir) if not (in_path / \"types.json\"): raise ValueError( \"Not a valid",
"label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str,",
"as f: self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\",",
"\"Not a valid dataset folder, cannot find category directory\", folder) else: print(str(in_path /",
"a valid dataset folder, cannot find category directory\", folder) else: print(str(in_path / folder),",
"not in_path.exists(): raise ValueError(\"Input directory does not exist: \" + input_dir) if not",
"prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path') args_parsed = args.parse_args() prepare",
"import Path from glob import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config",
"Path from glob import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config =",
"self.config = config def run(self, input_dir: str): in_path = Path(input_dir) if not in_path.exists():",
"self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video",
"files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if",
"'__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path')",
"directory\") with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types = json.load(f) for folder,",
"folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path / folder).exists(): raise ValueError( \"Not a",
"(in_path / folder).exists(): raise ValueError( \"Not a valid dataset folder, cannot find category",
"input_dir: str): in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does not",
"default=None, type=str, required=True, help='input directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input)",
"path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input) # python src/utils/prepare2.py -i data/orig-front-videos",
"def run(self, input_dir: str): in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory",
"with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types = json.load(f) for folder, cls_num",
"glob import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config def",
"in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path / folder).exists(): raise",
"if not (in_path / folder).exists(): raise ValueError( \"Not a valid dataset folder, cannot",
"ValueError( \"Not a valid dataset folder, cannot find types.json in the input directory\")",
"'--input', default=None, type=str, required=True, help='input directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed)",
"in the input directory\") with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types =",
"category directory\", folder) else: print(str(in_path / folder), \"mapping to class\", cls_num) files =",
"cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path / folder).exists():",
"as f: for video in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s",
"not (in_path / \"types.json\"): raise ValueError( \"Not a valid dataset folder, cannot find",
"directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input) # python src/utils/prepare2.py -i",
"raise ValueError( \"Not a valid dataset folder, cannot find category directory\", folder) else:",
"types.json in the input directory\") with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types",
"not (in_path / folder).exists(): raise ValueError( \"Not a valid dataset folder, cannot find",
"\"mapping to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path /",
"v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__",
"def __init__(self, config: argparse.Namespace): self.config = config def run(self, input_dir: str): in_path =",
"raise ValueError(\"Input directory does not exist: \" + input_dir) if not (in_path /",
"in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does not exist: \"",
"self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue",
"print(\"Skipping\", folder) continue if not (in_path / folder).exists(): raise ValueError( \"Not a valid",
"folder) continue if not (in_path / folder).exists(): raise ValueError( \"Not a valid dataset",
"from pathlib import Path from glob import glob class DatasetPrepare: def __init__(self, config:",
"does not exist: \" + input_dir) if not (in_path / \"types.json\"): raise ValueError(",
"Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does not exist: \" + input_dir)",
"if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path / folder).exists(): raise ValueError( \"Not",
"str): in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does not exist:",
"required=True, help='input directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input) # python",
"if not (in_path / \"types.json\"): raise ValueError( \"Not a valid dataset folder, cannot",
"\"types.json\"), \"r\") as f: self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items(): if",
"/ \"all.csv\"), \"w\") as f: for video in files: v_split = str(video).split('/') label",
"cannot find types.json in the input directory\") with open(str(in_path / \"types.json\"), \"r\") as",
"if not in_path.exists(): raise ValueError(\"Input directory does not exist: \" + input_dir) if",
"open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types = json.load(f) for folder, cls_num in",
"the input directory\") with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types = json.load(f)",
"__name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input",
"config def run(self, input_dir: str): in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input",
"\"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f: for video in files:",
"= self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args =",
"valid dataset folder, cannot find types.json in the input directory\") with open(str(in_path /",
"str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__':",
"= argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path') args_parsed =",
"json from pathlib import Path from glob import glob class DatasetPrepare: def __init__(self,",
"a valid dataset folder, cannot find types.json in the input directory\") with open(str(in_path",
"directory does not exist: \" + input_dir) if not (in_path / \"types.json\"): raise",
"f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare')",
"cannot find category directory\", folder) else: print(str(in_path / folder), \"mapping to class\", cls_num)",
"if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True,",
"ValueError( \"Not a valid dataset folder, cannot find category directory\", folder) else: print(str(in_path",
"(in_path / \"types.json\"): raise ValueError( \"Not a valid dataset folder, cannot find types.json",
"print(str(in_path / folder), \"mapping to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True)",
"self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path / folder).exists(): raise ValueError(",
"not exist: \" + input_dir) if not (in_path / \"types.json\"): raise ValueError( \"Not",
"glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f: for video",
"__init__(self, config: argparse.Namespace): self.config = config def run(self, input_dir: str): in_path = Path(input_dir)",
"from glob import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config",
"dataset folder, cannot find category directory\", folder) else: print(str(in_path / folder), \"mapping to",
"\"w\") as f: for video in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]]",
"% (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input',",
"with open(str(in_path / \"all.csv\"), \"w\") as f: for video in files: v_split =",
"json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not",
"= glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f: for",
"to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"),",
"argparse.Namespace): self.config = config def run(self, input_dir: str): in_path = Path(input_dir) if not",
"= config def run(self, input_dir: str): in_path = Path(input_dir) if not in_path.exists(): raise",
"exist: \" + input_dir) if not (in_path / \"types.json\"): raise ValueError( \"Not a",
"DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config def run(self, input_dir: str): in_path",
"files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f:",
"find category directory\", folder) else: print(str(in_path / folder), \"mapping to class\", cls_num) files",
"class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config def run(self, input_dir: str):",
"import argparse import json from pathlib import Path from glob import glob class",
"glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config def run(self, input_dir:",
"config: argparse.Namespace): self.config = config def run(self, input_dir: str): in_path = Path(input_dir) if",
"input directory\") with open(str(in_path / \"types.json\"), \"r\") as f: self.cls_types = json.load(f) for",
"in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label))",
"for video in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" %",
"import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace): self.config = config def run(self,",
"folder, cannot find category directory\", folder) else: print(str(in_path / folder), \"mapping to class\",",
"(\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None,",
"type=str, required=True, help='input directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input) #",
"pathlib import Path from glob import glob class DatasetPrepare: def __init__(self, config: argparse.Namespace):",
"\"all.csv\"), \"w\") as f: for video in files: v_split = str(video).split('/') label =",
"argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path') args_parsed = args.parse_args()",
"folder, cannot find types.json in the input directory\") with open(str(in_path / \"types.json\"), \"r\")",
"f: self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder)",
"run(self, input_dir: str): in_path = Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does",
"folder) else: print(str(in_path / folder), \"mapping to class\", cls_num) files = glob(str(in_path /",
"ValueError(\"Input directory does not exist: \" + input_dir) if not (in_path / \"types.json\"):",
"args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path') args_parsed",
"class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\")",
"dataset folder, cannot find types.json in the input directory\") with open(str(in_path / \"types.json\"),",
"help='input directory path') args_parsed = args.parse_args() prepare = DatasetPrepare(args_parsed) prepare.run(args_parsed.input) # python src/utils/prepare2.py",
"argparse import json from pathlib import Path from glob import glob class DatasetPrepare:",
"/ folder).exists(): raise ValueError( \"Not a valid dataset folder, cannot find category directory\",",
"<filename>src/utils/prepare2.py import argparse import json from pathlib import Path from glob import glob",
"args.add_argument('-i', '--input', default=None, type=str, required=True, help='input directory path') args_parsed = args.parse_args() prepare =",
"= Path(input_dir) if not in_path.exists(): raise ValueError(\"Input directory does not exist: \" +",
"video in files: v_split = str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]),",
"raise ValueError( \"Not a valid dataset folder, cannot find types.json in the input",
"input_dir) if not (in_path / \"types.json\"): raise ValueError( \"Not a valid dataset folder,",
"\"types.json\"): raise ValueError( \"Not a valid dataset folder, cannot find types.json in the",
"valid dataset folder, cannot find category directory\", folder) else: print(str(in_path / folder), \"mapping",
"folder), \"mapping to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path",
"%d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ == '__main__': args = argparse.ArgumentParser(description='Video prepare') args.add_argument('-i',",
"= str(video).split('/') label = self.cls_types[v_split[-2]] f.write(\"%s %d\\n\" % (\"/\".join(v_split[-2:]), label)) if __name__ ==",
"for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if not (in_path",
"\"r\") as f: self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"):",
"cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as",
"/ \"types.json\"), \"r\") as f: self.cls_types = json.load(f) for folder, cls_num in self.cls_types.items():",
"else: print(str(in_path / folder), \"mapping to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"),",
"/ folder), \"mapping to class\", cls_num) files = glob(str(in_path / \"**/*.mp4\"), recursive=True) with",
"directory\", folder) else: print(str(in_path / folder), \"mapping to class\", cls_num) files = glob(str(in_path",
"import json from pathlib import Path from glob import glob class DatasetPrepare: def",
"= json.load(f) for folder, cls_num in self.cls_types.items(): if folder.startswith(\"Unused\"): print(\"Skipping\", folder) continue if",
"/ \"types.json\"): raise ValueError( \"Not a valid dataset folder, cannot find types.json in",
"recursive=True) with open(str(in_path / \"all.csv\"), \"w\") as f: for video in files: v_split",
"find types.json in the input directory\") with open(str(in_path / \"types.json\"), \"r\") as f:",
"folder).exists(): raise ValueError( \"Not a valid dataset folder, cannot find category directory\", folder)",
"in_path.exists(): raise ValueError(\"Input directory does not exist: \" + input_dir) if not (in_path"
] |
[
"servers as nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR",
"downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON = \"BOOST_BUTTON\"",
"= 120 DOWNSIZE_PERIOD = 7 # Number of days before downsizing. REBOOT_BUTTON =",
"= 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2",
"python client library doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\"",
"for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\"",
"VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR",
"= 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT =",
"30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT",
"DOWNSIZE_PERIOD = 7 # Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON",
"\"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\"",
"10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240",
"REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS",
"RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" #",
"= 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120",
"are more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING",
"VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED =",
"SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...) NO_VM =",
"= 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS =",
"VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN])",
"VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES",
"ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT",
"SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT",
"300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60",
"VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number of days",
"= 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number",
"REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS",
"1 ERROR = -1 # These are Openstack Nova server status values that",
"REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN",
"REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE",
"RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more",
"VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180",
"are Openstack Nova server status values that the # python client library doesn't",
"\"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...) NO_VM = VM_DELETED =",
"client library doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT",
"SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR = -1 # These are Openstack",
"\"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are",
"VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\"",
"These are Openstack Nova server status values that the # python client library",
"= \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN =",
"server status values that the # python client library doesn't define constants for.",
"CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME",
"= \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES =",
"= VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED",
"= \"VERIFY_RESIZE\" # (There are more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING",
"REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS",
"VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN",
"= -1 # These are Openstack Nova server status values that the #",
"= 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD =",
"\"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED,",
"NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY",
"# These are Openstack Nova server status values that the # python client",
"# python client library doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD =",
"VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS =",
"= \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED",
"VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\"",
"ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE",
"= \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR =",
"60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\"",
"RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED",
"\"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30",
"as nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR =",
"DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME =",
"= 1 ERROR = -1 # These are Openstack Nova server status values",
"2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7",
"= \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN =",
"VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD",
"= 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10",
"= \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...)",
"= \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE =",
"180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120",
"values that the # python client library doesn't define constants for. ACTIVE =",
"= \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR = -1 # These",
"status values that the # python client library doesn't define constants for. ACTIVE",
"VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING",
"SCRIPT_OKAY = 1 ERROR = -1 # These are Openstack Nova server status",
"\"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\"",
"= 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS =",
"7 # Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\"",
"= 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED =",
"\"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...) NO_VM",
"VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS",
"nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10",
"10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number of",
"Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON =",
"ERROR = -1 # These are Openstack Nova server status values that the",
"BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE",
"= \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME =",
"INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT =",
"REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS",
"= nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES =",
"define constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD",
"Openstack Nova server status values that the # python client library doesn't define",
"= \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE =",
"= \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT =",
"= VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\"",
"\"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON = \"BOOST_BUTTON\" DOWNSIZE_BUTTON = \"DOWNSIZE_BUTTON\"",
"= 7 # Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON =",
"\"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT =",
"\"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM,",
"-1 # These are Openstack Nova server status values that the # python",
"\"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY = \"VM_Okay\" VM_SUPERSIZED =",
"REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES",
"\"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT",
"= \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON = \"BOOST_BUTTON\" DOWNSIZE_BUTTON =",
"Nova server status values that the # python client library doesn't define constants",
"more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING =",
"...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\"",
"= 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS =",
"INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 #",
"from novaclient.v2 import servers as nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY",
"\"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\"",
"\"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING,",
"VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300",
"\"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR = -1 # These are",
"import servers as nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1",
"frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD =",
"REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON = \"BOOST_BUTTON\" DOWNSIZE_BUTTON",
"= \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There",
"= 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED =",
"DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT =",
"0 SCRIPT_OKAY = 1 ERROR = -1 # These are Openstack Nova server",
"doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\"",
"30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT",
"= \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT",
"\"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\"",
"VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS",
"5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180",
"that the # python client library doesn't define constants for. ACTIVE = \"ACTIVE\"",
"novaclient.v2 import servers as nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY =",
"= 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY =",
"5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME",
"nova_servers LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR = -1",
"\"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\"",
"LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS",
"INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD",
"VM_ERROR = \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING,",
"before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON =",
"VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...) NO_VM = VM_DELETED = \"No_VM\"",
"RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY",
"nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS = 10 REBOOT_CONFIRM_RETRIES = 5",
"180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30",
"= INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT = 120 INSTANCE_LAUNCH_TIMEOUT = 120",
"# (There are more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING",
"CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5 DELETION_TIMEOUT = 30 INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT",
"LINUX = \"linux\" SCRIPT_ERROR = 0 SCRIPT_OKAY = 1 ERROR = -1 #",
"120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number of days before downsizing.",
"library doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT =",
"VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS =",
"= 0 SCRIPT_OKAY = 1 ERROR = -1 # These are Openstack Nova",
"\"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\"",
"= \"VM_Error\" VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY,",
"\"VERIFY_RESIZE\" # (There are more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING =",
"= 10 REBOOT_CONFIRM_RETRIES = 5 REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS =",
"INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number of days before downsizing. REBOOT_BUTTON",
"INSTANCE_DELETION_RETRY_WAIT_TIME = 30 INSTANCE_DELETION_RETRY_COUNT = INSTANCE_CHECK_SHUTOFF_RETRY_COUNT = 2 INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_TIME = 10 VOLUME_CREATION_TIMEOUT =",
"= 120 INSTANCE_LAUNCH_TIMEOUT = 120 DOWNSIZE_PERIOD = 7 # Number of days before",
"\"REBOOT\" REBUILD = \"REBUILD\" RESCUE = \"RESCUE\" RESIZE = \"RESIZE\" SHUTDOWN = \"SHUTOFF\"",
"VM_MISSING = \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED,",
"= \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD = \"REBUILD\" RESCUE =",
"= \"VM_Missing\" VM_SHUTDOWN = \"VM_Shutdown\" ALL_VM_STATES = frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR,",
"= VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING = VM_RESIZING = \"VM_Waiting\" VM_OKAY =",
"days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\" BOOST_BUTTON",
"(There are more ...) NO_VM = VM_DELETED = \"No_VM\" VM_WAITING = VM_CREATING =",
"= \"VM_Okay\" VM_SUPERSIZED = \"VM_Supersized\" VM_SHELVED = \"VM_Shelved\" VM_ERROR = \"VM_Error\" VM_MISSING =",
"= nova_servers.REBOOT_SOFT REBOOT_HARD = nova_servers.REBOOT_HARD LAUNCH_WAIT_SECONDS = 300 REBOOT_WAIT_SECONDS = 180 REBOOT_CONFIRM_WAIT_SECONDS =",
"REBOOT_COMPLETE_SECONDS = 60 RESIZE_WAIT_SECONDS = 120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED",
"120 DOWNSIZE_PERIOD = 7 # Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\"",
"= \"SHUTOFF\" VERIFY_RESIZE = \"VERIFY_RESIZE\" # (There are more ...) NO_VM = VM_DELETED",
"the # python client library doesn't define constants for. ACTIVE = \"ACTIVE\" BUILD",
"constants for. ACTIVE = \"ACTIVE\" BUILD = \"BUILD\" REBOOT = \"REBOOT\" REBUILD =",
"= frozenset([NO_VM, VM_WAITING, VM_OKAY, VM_SUPERSIZED, VM_SHELVED, VM_ERROR, VM_MISSING, VM_SHUTDOWN]) REBOOT_SOFT = nova_servers.REBOOT_SOFT REBOOT_HARD",
"of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON = \"DELETE_BUTTON\"",
"# Number of days before downsizing. REBOOT_BUTTON = \"REBOOT_BUTTON\" SHELVE_BUTTON = \"SHELVE_BUTTON\" DELETE_BUTTON",
"240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\" DELETION_RETRY = 5",
"120 RESIZE_CONFIRM_WAIT_SECONDS = 240 SHELVE_WAIT_SECONDS = 180 CLOUD_INIT_FINISHED = \"finished\" CLOUD_INIT_STARTED = \"started\""
] |
[
"coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def",
"str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 :",
"加密 or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password:",
"{} dict_Result['OK'] = 0 if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error']",
"security ''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check security",
"= \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type",
"-*- import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password):",
"解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password: :return: str",
"ok ''' dict_Result = {} dict_Result['OK'] = 0 if len(username) < 6 :",
"value is all by jsondata ''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers",
"function for common @return : return value is all by jsondata ''' #-*-",
"== 1 : means checkResult ok ''' dict_Result = {} dict_Result['OK'] = 0",
"or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password: :return:",
"checkSecurityPassword(password,security_password): ''' @description: check security password :param password: :param security_password: :return: bool type",
"by jsondata ''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password from",
"''' @brief: basic function to check password and username :param username: 用户名 :param",
"method : 加密 or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security Word:",
"import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to",
"django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to check password and",
"generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password: :return: str type that has",
"Security Word: :param password: :return: str type that has make it security '''",
"django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function",
"''' def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password: :return: str type",
"authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to check password and username :param",
"str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result)",
"type that has make it security ''' security_password = make_password(password) return security_password def",
"if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True)",
"''' @description: gernerate Security Word: :param password: :return: str type that has make",
"checkResult ok ''' dict_Result = {} dict_Result['OK'] = 0 if len(username) < 6",
":param username: 用户名 :param password: 密码 :return: jsondata that whether has password or",
"< 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password)",
"if OK == 1 : means checkResult ok ''' dict_Result = {} dict_Result['OK']",
"''' dict_Result = {} dict_Result['OK'] = 0 if len(username) < 6 : str_error_type",
"dict_Result = {} dict_Result['OK'] = 0 if len(username) < 6 : str_error_type =",
"from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to check password",
"json.dumps(dict_Result) ''' password method : 加密 or 解密 ''' def generateSecurityPassword(password): ''' @description:",
"username :param username: 用户名 :param password: 密码 :return: jsondata that whether has password",
"@description: basic function for common @return : return value is all by jsondata",
"\"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type =",
"0 if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return",
"if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,)",
"def checkSecurityPassword(password,security_password): ''' @description: check security password :param password: :param security_password: :return: bool",
"checkUserLoginInfo(username,password): ''' @brief: basic function to check password and username :param username: 用户名",
"@description: gernerate Security Word: :param password: :return: str type that has make it",
"len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK']",
"= 0 if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type",
"security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check security password :param",
"it security ''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check",
":param password: 密码 :return: jsondata that whether has password or user problem if",
"jsondata that whether has password or user problem if OK == 1 :",
"username: 用户名 :param password: 密码 :return: jsondata that whether has password or user",
"= 1 return json.dumps(dict_Result) ''' password method : 加密 or 解密 ''' def",
": 加密 or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param",
"whether has password or user problem if OK == 1 : means checkResult",
"= {} dict_Result['OK'] = 0 if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\"",
"6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1",
"has password or user problem if OK == 1 : means checkResult ok",
"make it security ''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description:",
":param password: :param security_password: :return: bool type ''' b_Result = check_password(password,security_password) return b_Result",
"from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic",
":param password: :return: str type that has make it security ''' security_password =",
"password or user problem if OK == 1 : means checkResult ok '''",
": str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6",
"return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method : 加密 or",
"str type that has make it security ''' security_password = make_password(password) return security_password",
"make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to check",
"return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type",
"''' password method : 加密 or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate",
"common @return : return value is all by jsondata ''' #-*- coding:utf-8 -*-",
"''' @description: check security password :param password: :param security_password: :return: bool type '''",
"that has make it security ''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password):",
"dict_Result['OK'] = 0 if len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] =",
"密码 :return: jsondata that whether has password or user problem if OK ==",
"means checkResult ok ''' dict_Result = {} dict_Result['OK'] = 0 if len(username) <",
"user problem if OK == 1 : means checkResult ok ''' dict_Result =",
"= str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method :",
"or user problem if OK == 1 : means checkResult ok ''' dict_Result",
"problem if OK == 1 : means checkResult ok ''' dict_Result = {}",
"import authenticate def checkUserLoginInfo(username,password): ''' @brief: basic function to check password and username",
"check security password :param password: :param security_password: :return: bool type ''' b_Result =",
":return: jsondata that whether has password or user problem if OK == 1",
"6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) <",
"dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method : 加密 or 解密 '''",
"password method : 加密 or 解密 ''' def generateSecurityPassword(password): ''' @description: gernerate Security",
"Word: :param password: :return: str type that has make it security ''' security_password",
"@return : return value is all by jsondata ''' #-*- coding:utf-8 -*- import",
"json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method : 加密 or 解密",
"that whether has password or user problem if OK == 1 : means",
"jsondata ''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth",
"function to check password and username :param username: 用户名 :param password: 密码 :return:",
"security password :param password: :param security_password: :return: bool type ''' b_Result = check_password(password,security_password)",
"dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method",
"import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): '''",
"= str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error']",
"check password and username :param username: 用户名 :param password: 密码 :return: jsondata that",
"1 : means checkResult ok ''' dict_Result = {} dict_Result['OK'] = 0 if",
"\"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password",
"for common @return : return value is all by jsondata ''' #-*- coding:utf-8",
"json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate def checkUserLoginInfo(username,password): ''' @brief:",
"basic function to check password and username :param username: 用户名 :param password: 密码",
"return value is all by jsondata ''' #-*- coding:utf-8 -*- import json from",
"OK == 1 : means checkResult ok ''' dict_Result = {} dict_Result['OK'] =",
"< 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] =",
"= make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check security password :param password:",
"''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check security password",
"#-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import authenticate",
"''' @description: basic function for common @return : return value is all by",
"password: :return: str type that has make it security ''' security_password = make_password(password)",
"def checkUserLoginInfo(username,password): ''' @brief: basic function to check password and username :param username:",
": str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return",
"return security_password def checkSecurityPassword(password,security_password): ''' @description: check security password :param password: :param security_password:",
"len(username) < 6 : str_error_type = \"输入用户名过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if",
"用户名 :param password: 密码 :return: jsondata that whether has password or user problem",
"''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import",
"all by jsondata ''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import make_password,check_password",
"and username :param username: 用户名 :param password: 密码 :return: jsondata that whether has",
"security_password def checkSecurityPassword(password,security_password): ''' @description: check security password :param password: :param security_password: :return:",
":return: str type that has make it security ''' security_password = make_password(password) return",
"def generateSecurityPassword(password): ''' @description: gernerate Security Word: :param password: :return: str type that",
": means checkResult ok ''' dict_Result = {} dict_Result['OK'] = 0 if len(username)",
"1 return json.dumps(dict_Result) ''' password method : 加密 or 解密 ''' def generateSecurityPassword(password):",
"make_password(password) return security_password def checkSecurityPassword(password,security_password): ''' @description: check security password :param password: :param",
"has make it security ''' security_password = make_password(password) return security_password def checkSecurityPassword(password,security_password): '''",
"str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] =",
"is all by jsondata ''' #-*- coding:utf-8 -*- import json from django.contrib.auth.hashers import",
": return value is all by jsondata ''' #-*- coding:utf-8 -*- import json",
"password and username :param username: 用户名 :param password: 密码 :return: jsondata that whether",
"dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\"",
"basic function for common @return : return value is all by jsondata '''",
"= \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) '''",
"json.dumps(dict_Result,ensure_ascii=False,sort_keys=True) if len(password) < 6 : str_error_type = \"输入密码过短,请重新输入\" dict_Result['error'] = str_error_type return",
"@description: check security password :param password: :param security_password: :return: bool type ''' b_Result",
"to check password and username :param username: 用户名 :param password: 密码 :return: jsondata",
"str_error_type return json.dumps(dict_Result,ensure_ascii=False,sort_keys=True,) dict_Result['OK'] = 1 return json.dumps(dict_Result) ''' password method : 加密",
"password :param password: :param security_password: :return: bool type ''' b_Result = check_password(password,security_password) return",
"@brief: basic function to check password and username :param username: 用户名 :param password:",
"gernerate Security Word: :param password: :return: str type that has make it security",
"password: 密码 :return: jsondata that whether has password or user problem if OK",
"return json.dumps(dict_Result) ''' password method : 加密 or 解密 ''' def generateSecurityPassword(password): '''"
] |
[
"<reponame>PaulLafytskyi/Hackerrank-Tests<gh_stars>0 if __name__ == '__main__': start = [5, 10] end = [3, 12]",
"'__main__': start = [5, 10] end = [3, 12] #if start[- 1] >",
"if __name__ == '__main__': start = [5, 10] end = [3, 12] #if",
"__name__ == '__main__': start = [5, 10] end = [3, 12] #if start[-",
"== '__main__': start = [5, 10] end = [3, 12] #if start[- 1]"
] |
[
"https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name, ) for",
"old_instance and not getattr(obj, 'old_instance', None): # since no old version of the",
"are possible for this model (including reverse relation names). Any internal-only field names",
"field on the related model was changed for old_obj, new_obj in comparison_map: if",
"import FieldFile from itertools import chain def get_all_field_names(model): '''Return a list of all",
"isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return False,",
"old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None if not field_comparison(new_value,",
"# one of instances can be None, in this case we don't need",
"return True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related),",
"1 level return True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related =",
"ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: #",
"fields: old_instance = old_instance or obj.old_instance try: new_field = getattr(obj, f_name, None) except",
"return True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name',",
"try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case it's OneToOne",
"which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name,",
"f_name): return False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field,",
"False: error_fields.append(f_name) if error_fields: return False, error_fields return True, None def field_comparison(f1, f2):",
"need to check all fields return old_obj == new_obj field_names = get_all_field_names(old_obj) for",
"no changes return True, None for f_name in fields: old_instance = old_instance or",
"getattr(obj, field) != getattr(old_instance, field): return False, field return True, None def check_required_fields(obj,",
"not field_comparison(new_value, old_value): return False # there is no check for instance class",
"field is not None if response is False: error_fields.append(f_name) if error_fields: return False,",
"old_file = getattr(f2, 'name', None) if new_file != old_file: return False elif f1",
"object was passed in, we assume there were no changes return True, None",
"getattr(old_instance, field): return False, field return True, None def check_required_fields(obj, fields): error_fields =",
"return True, None for f_name in fields: old_instance = old_instance or obj.old_instance try:",
"check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one of",
"for field in model._meta.get_fields() if not (field.many_to_one and field.related_model is None) and not",
"list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name, ) for field in model._meta.get_fields()",
"getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value): return",
"GenericForeignKey from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import",
"field_comparison(new_field, old_field): return False, f_name return True, None def update_object(obj, kwdict): for k,",
"MyModel._meta.get_all_field_names() which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable(",
"related field, unfortunately i can't figure out a isinstance check if related: if",
"check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related",
"attribute on the object, assuming no changes return True if len(current_related) != len(old_related):",
"hasattr(new_field, 'all'): # this could be a related field, unfortunately i can't figure",
"new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one of instances",
"names that are possible for this model (including reverse relation names). Any internal-only",
"False if len(current_related) == 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id)",
"None try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case it's",
"django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import chain def",
"the object, assuming no changes return True if len(current_related) != len(old_related): return False",
"return False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field):",
"return False, field return True, None def check_required_fields(obj, fields): error_fields = [] for",
"OneToOne related field old_field = None if hasattr(new_field, 'all'): # this could be",
"field, None) except ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj, field, None)",
"check if any field on the related model was changed for old_obj, new_obj",
"error_fields = [] for f_name in fields: try: field = getattr(obj, f_name) except",
"ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import chain def get_all_field_names(model): '''Return a",
"for field in fields: old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance, field):",
"response = field is not None if response is False: error_fields.append(f_name) if error_fields:",
"new_value = None try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value =",
"None try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None if",
"object, assuming no changes return True if len(current_related) != len(old_related): return False if",
"FieldFile from itertools import chain def get_all_field_names(model): '''Return a list of all field",
"import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import chain def get_all_field_names(model):",
"reverse relation names). Any internal-only field names are not included. Replacement for MyModel._meta.get_all_field_names()",
"field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file = getattr(f2,",
"if old_related is None: # if old related was not set as an",
"field_names: try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None try:",
"related=False): if not old_instance and not getattr(obj, 'old_instance', None): # since no old",
"# in case it's OneToOne related field old_field = None if hasattr(new_field, 'all'):",
"an attribute on the object, assuming no changes return True if len(current_related) !=",
"None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance',",
"is None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj,",
"not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if",
"return True, None def update_object(obj, kwdict): for k, v in kwdict.items(): if isinstance(v,",
"in field_names: try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None",
"!= len(old_related): return False if len(current_related) == 0: return True current_related.sort(key=lambda x: x.id)",
"from django.db.models.fields.files import FieldFile from itertools import chain def get_all_field_names(model): '''Return a list",
"getattr(obj, 'old_instance', None): # since no old version of the object was passed",
"'''Return a list of all field names that are possible for this model",
"len(current_related) == 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map =",
"assuming no changes return True if len(current_related) != len(old_related): return False if len(current_related)",
"zip(current_related, old_related) # check if any field on the related model was changed",
"elif isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name",
"len(old_related): return False if len(current_related) == 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda",
"[] for f_name in fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist: return",
"check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and not getattr(obj, 'old_instance', None): #",
"if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file = getattr(f2, 'name', None)",
"'name', None) old_file = getattr(f2, 'name', None) if new_file != old_file: return False",
"of the object was passed in, we assume there were no changes return",
"the object was passed in, we assume there were no changes return True,",
"fields for field in fields: old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance,",
"def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and not getattr(obj, 'old_instance', None):",
"try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None try: old_value",
"= None try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case",
"out a isinstance check if related: if not check_rigid_related(obj, f_name): return False, f_name",
"Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name elif not",
"'{}_old'.format(related), None) if old_related is None: # if old related was not set",
"related field old_field = None if hasattr(new_field, 'all'): # this could be a",
"if error_fields: return False, error_fields return True, None def field_comparison(f1, f2): if isinstance(f1,",
"old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return False, field return",
"= None if hasattr(new_field, 'all'): # this could be a related field, unfortunately",
"not (field.many_to_one and field.related_model is None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj,",
"related: if not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model) or isinstance(new_field,",
"new_field): return False, f_name elif not field_comparison(new_field, old_field): return False, f_name return True,",
"for k, v in kwdict.items(): if isinstance(v, list): getattr(obj, k).set(v) else: setattr(obj, k,",
"isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name elif",
"None, in this case we don't need to check all fields return old_obj",
"don't go deeper than 1 level return True def check_rigid_related(obj, related): current_related =",
"obj.old_instance try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None try:",
"f_name elif not field_comparison(new_field, old_field): return False, f_name return True, None def update_object(obj,",
"old_related is None: # if old related was not set as an attribute",
"def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return False, fields for field",
"fields): error_fields = [] for f_name in fields: try: field = getattr(obj, f_name)",
"Replacement for MyModel._meta.get_all_field_names() which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api '''",
"None) old_file = getattr(f2, 'name', None) if new_file != old_file: return False elif",
"case we don't need to check all fields return old_obj == new_obj field_names",
"if related: if not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model) or",
"if len(current_related) != len(old_related): return False if len(current_related) == 0: return True current_related.sort(key=lambda",
"not included. Replacement for MyModel._meta.get_all_field_names() which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422",
"response is False: error_fields.append(f_name) if error_fields: return False, error_fields return True, None def",
"in model._meta.get_fields() if not (field.many_to_one and field.related_model is None) and not isinstance(field, GenericForeignKey)",
"return False # there is no check for instance class so we don't",
"in fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try:",
"no check for instance class so we don't go deeper than 1 level",
"old_obj == new_obj field_names = get_all_field_names(old_obj) for field in field_names: try: new_value =",
"if not old_instance and not getattr(obj, 'old_instance', None): # since no old version",
"# since no old version of the object was passed in, we assume",
"= None try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None",
"check all fields return old_obj == new_obj field_names = get_all_field_names(old_obj) for field in",
"not set as an attribute on the object, assuming no changes return True",
"True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj, Model): #",
"if len(current_related) == 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map",
"True, None def update_object(obj, kwdict): for k, v in kwdict.items(): if isinstance(v, list):",
"except ObjectDoesNotExist: # in case it's OneToOne related field old_field = None if",
"False return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and not",
"passed in, we assume there were no changes return True, None for f_name",
"!= f2: return False return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model)",
"level return True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance,",
"included. Replacement for MyModel._meta.get_all_field_names() which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api",
"a related field, unfortunately i can't figure out a isinstance check if related:",
"(field.name, ) for field in model._meta.get_fields() if not (field.many_to_one and field.related_model is None)",
"= list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: #",
"new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None try: old_field =",
"!= getattr(old_instance, field): return False, field return True, None def check_required_fields(obj, fields): error_fields",
"elif f1 != f2: return False return True def check_rigid_model_instance(old_obj, new_obj): if not",
"getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: # if old related was not",
"<filename>src/etools_validator/utils.py from django.contrib.contenttypes.fields import GenericForeignKey from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import",
"return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name, ) for field in",
"f_name in fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name",
"no old version of the object was passed in, we assume there were",
"def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if",
"not isinstance(new_obj, Model): # one of instances can be None, in this case",
"if not (field.many_to_one and field.related_model is None) and not isinstance(field, GenericForeignKey) ))) def",
"old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: # if old related",
"response = getattr(field, 'name', None) or False else: response = field is not",
"new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None try: old_value =",
"was not set as an attribute on the object, assuming no changes return",
"not check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field, old_field): return False, f_name",
"k, v in kwdict.items(): if isinstance(v, list): getattr(obj, k).set(v) else: setattr(obj, k, v)",
"unfortunately i can't figure out a isinstance check if related: if not check_rigid_related(obj,",
"there were no changes return True, None for f_name in fields: old_instance =",
"changes return True if len(current_related) != len(old_related): return False if len(current_related) == 0:",
"of instances can be None, in this case we don't need to check",
"a list of all field names that are possible for this model (including",
"or not isinstance(new_obj, Model): # one of instances can be None, in this",
"old related was not set as an attribute on the object, assuming no",
"f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file = getattr(f2, 'name',",
"x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) # check if any field",
"except AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name', None) or False else:",
"for f_name in fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist: return False,",
"except ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist:",
"f_name) except ObjectDoesNotExist: return False, f_name try: response = field.filter().count() > 0 except",
"0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related)",
"= get_all_field_names(old_obj) for field in field_names: try: new_value = getattr(old_obj, field, None) except",
"# if old related was not set as an attribute on the object,",
"isinstance check if related: if not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field,",
"return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj, Model):",
"import chain def get_all_field_names(model): '''Return a list of all field names that are",
"def check_required_fields(obj, fields): error_fields = [] for f_name in fields: try: field =",
"= field is not None if response is False: error_fields.append(f_name) if error_fields: return",
"None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file",
"ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value): return False # there is",
"False, fields for field in fields: old_instance = obj.old_instance if getattr(obj, field) !=",
"field, None) except ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value): return False",
"''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name, ) for field",
"'name', None) if new_file != old_file: return False elif f1 != f2: return",
"changed for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return",
"django.db.models.fields.files import FieldFile from itertools import chain def get_all_field_names(model): '''Return a list of",
"f_name return True, None def update_object(obj, kwdict): for k, v in kwdict.items(): if",
"try: response = field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile): response =",
"deeper than 1 level return True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter())",
"ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value",
"= getattr(f1, 'name', None) old_file = getattr(f2, 'name', None) if new_file != old_file:",
"old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return True def",
"return False elif f1 != f2: return False return True def check_rigid_model_instance(old_obj, new_obj):",
"check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not",
"if hasattr(new_field, 'all'): # this could be a related field, unfortunately i can't",
"None if response is False: error_fields.append(f_name) if error_fields: return False, error_fields return True,",
"None) except ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance, f_name, None) except",
"getattr(f1, 'name', None) old_file = getattr(f2, 'name', None) if new_file != old_file: return",
"field, unfortunately i can't figure out a isinstance check if related: if not",
"from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import chain",
"False elif f1 != f2: return False return True def check_rigid_model_instance(old_obj, new_obj): if",
"in this case we don't need to check all fields return old_obj ==",
"if getattr(obj, field) != getattr(old_instance, field): return False, field return True, None def",
"relation names). Any internal-only field names are not included. Replacement for MyModel._meta.get_all_field_names() which",
"for this model (including reverse relation names). Any internal-only field names are not",
"check_required_fields(obj, fields): error_fields = [] for f_name in fields: try: field = getattr(obj,",
"isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file = getattr(f2, 'name', None) if",
"new_obj): return False return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance",
"return True if len(current_related) != len(old_related): return False if len(current_related) == 0: return",
"f2: return False return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or",
"> 0 except AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name', None) or",
"None: # if old related was not set as an attribute on the",
"None if not field_comparison(new_value, old_value): return False # there is no check for",
"def update_object(obj, kwdict): for k, v in kwdict.items(): if isinstance(v, list): getattr(obj, k).set(v)",
"changes return True, None for f_name in fields: old_instance = old_instance or obj.old_instance",
"True if len(current_related) != len(old_related): return False if len(current_related) == 0: return True",
"= getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: # if old related was",
"FieldFile): new_file = getattr(f1, 'name', None) old_file = getattr(f2, 'name', None) if new_file",
"error_fields: return False, error_fields return True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile):",
"def get_all_field_names(model): '''Return a list of all field names that are possible for",
"class so we don't go deeper than 1 level return True def check_rigid_related(obj,",
"not isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one of instances can be",
"elif not field_comparison(new_field, old_field): return False, f_name return True, None def update_object(obj, kwdict):",
"None) or False else: response = field is not None if response is",
"set as an attribute on the object, assuming no changes return True if",
"x: x.id) comparison_map = zip(current_related, old_related) # check if any field on the",
"(field.name, field.attname) if hasattr(field, 'attname') else (field.name, ) for field in model._meta.get_fields() if",
"Model) or not isinstance(new_obj, Model): # one of instances can be None, in",
"this case we don't need to check all fields return old_obj == new_obj",
"x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) # check if any",
"field) != getattr(old_instance, field): return False, field return True, None def check_required_fields(obj, fields):",
"related was not set as an attribute on the object, assuming no changes",
"False else: response = field is not None if response is False: error_fields.append(f_name)",
"True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None)",
"return False, f_name return True, None def update_object(obj, kwdict): for k, v in",
"is not None if response is False: error_fields.append(f_name) if error_fields: return False, error_fields",
"be a related field, unfortunately i can't figure out a isinstance check if",
"django.contrib.contenttypes.fields import GenericForeignKey from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from",
"was passed in, we assume there were no changes return True, None for",
"def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one",
"if not check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field, old_field): return False,",
"or obj.old_instance try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None",
"x.id) comparison_map = zip(current_related, old_related) # check if any field on the related",
"check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return False, fields for field in",
"old_instance or obj.old_instance try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field =",
"can't figure out a isinstance check if related: if not check_rigid_related(obj, f_name): return",
"= [] for f_name in fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist:",
"old_file: return False elif f1 != f2: return False return True def check_rigid_model_instance(old_obj,",
"check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if not",
"new_obj field_names = get_all_field_names(old_obj) for field in field_names: try: new_value = getattr(old_obj, field,",
"return False return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not",
"!= old_file: return False elif f1 != f2: return False return True def",
"for field in field_names: try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value",
"model._meta.get_fields() if not (field.many_to_one and field.related_model is None) and not isinstance(field, GenericForeignKey) )))",
"GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return False, fields",
"not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if",
"is None: # if old related was not set as an attribute on",
"all fields return old_obj == new_obj field_names = get_all_field_names(old_obj) for field in field_names:",
"i can't figure out a isinstance check if related: if not check_rigid_related(obj, f_name):",
"for MyModel._meta.get_all_field_names() which does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return",
"if isinstance(field, FieldFile): response = getattr(field, 'name', None) or False else: response =",
"Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools import chain def get_all_field_names(model): '''Return",
"Any internal-only field names are not included. Replacement for MyModel._meta.get_all_field_names() which does not",
"and field.related_model is None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if",
"one of instances can be None, in this case we don't need to",
"could be a related field, unfortunately i can't figure out a isinstance check",
"field in model._meta.get_fields() if not (field.many_to_one and field.related_model is None) and not isinstance(field,",
"None def check_required_fields(obj, fields): error_fields = [] for f_name in fields: try: field",
"try: field = getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try: response =",
"False return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj, Model) or not isinstance(new_obj,",
"False, f_name try: response = field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile):",
"== 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related,",
"field_names = get_all_field_names(old_obj) for field in field_names: try: new_value = getattr(old_obj, field, None)",
"in case it's OneToOne related field old_field = None if hasattr(new_field, 'all'): #",
"figure out a isinstance check if related: if not check_rigid_related(obj, f_name): return False,",
"field = getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try: response = field.filter().count()",
"current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None:",
"== new_obj field_names = get_all_field_names(old_obj) for field in field_names: try: new_value = getattr(old_obj,",
"as an attribute on the object, assuming no changes return True if len(current_related)",
"hasattr(field, 'attname') else (field.name, ) for field in model._meta.get_fields() if not (field.many_to_one and",
"itertools import chain def get_all_field_names(model): '''Return a list of all field names that",
"getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try: response = field.filter().count() > 0",
"the related model was changed for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj,",
"a isinstance check if related: if not check_rigid_related(obj, f_name): return False, f_name elif",
"we assume there were no changes return True, None for f_name in fields:",
"from django.contrib.contenttypes.fields import GenericForeignKey from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile",
"not check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if",
"for f_name in fields: old_instance = old_instance or obj.old_instance try: new_field = getattr(obj,",
"# check if any field on the related model was changed for old_obj,",
"field old_field = None if hasattr(new_field, 'all'): # this could be a related",
"comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj, fields, old_instance=None,",
"old_value = None if not field_comparison(new_value, old_value): return False # there is no",
"new_field = None try: old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in",
"in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj, fields,",
"any field on the related model was changed for old_obj, new_obj in comparison_map:",
"= getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value):",
"and not getattr(obj, 'old_instance', None): # since no old version of the object",
"field names are not included. Replacement for MyModel._meta.get_all_field_names() which does not exist under",
"old_field = getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case it's OneToOne related",
"'old_instance', None): return False, fields for field in fields: old_instance = obj.old_instance if",
"None): # since no old version of the object was passed in, we",
"field in field_names: try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist: new_value =",
"list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: # if",
"to check all fields return old_obj == new_obj field_names = get_all_field_names(old_obj) for field",
"# there is no check for instance class so we don't go deeper",
"not None if response is False: error_fields.append(f_name) if error_fields: return False, error_fields return",
"instances can be None, in this case we don't need to check all",
"True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and not getattr(obj, 'old_instance',",
"update_object(obj, kwdict): for k, v in kwdict.items(): if isinstance(v, list): getattr(obj, k).set(v) else:",
"if old related was not set as an attribute on the object, assuming",
"ObjectDoesNotExist: # in case it's OneToOne related field old_field = None if hasattr(new_field,",
"None if hasattr(new_field, 'all'): # this could be a related field, unfortunately i",
"try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None try: old_field",
"don't need to check all fields return old_obj == new_obj field_names = get_all_field_names(old_obj)",
"old_value): return False # there is no check for instance class so we",
"fields, old_instance=None, related=False): if not old_instance and not getattr(obj, 'old_instance', None): # since",
"possible for this model (including reverse relation names). Any internal-only field names are",
"if not isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one of instances can",
"check for instance class so we don't go deeper than 1 level return",
"= None if not field_comparison(new_value, old_value): return False # there is no check",
"get_all_field_names(model): '''Return a list of all field names that are possible for this",
"field names that are possible for this model (including reverse relation names). Any",
"not old_instance and not getattr(obj, 'old_instance', None): # since no old version of",
"names). Any internal-only field names are not included. Replacement for MyModel._meta.get_all_field_names() which does",
"under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname')",
"None) except ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj, field, None) except",
"return False, error_fields return True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file",
"field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name', None)",
"None for f_name in fields: old_instance = old_instance or obj.old_instance try: new_field =",
"fields return old_obj == new_obj field_names = get_all_field_names(old_obj) for field in field_names: try:",
"False, f_name elif not field_comparison(new_field, old_field): return False, f_name return True, None def",
"is False: error_fields.append(f_name) if error_fields: return False, error_fields return True, None def field_comparison(f1,",
"except ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value): return False # there",
"not getattr(obj, 'old_instance', None): # since no old version of the object was",
"if new_file != old_file: return False elif f1 != f2: return False return",
"False # there is no check for instance class so we don't go",
"all field names that are possible for this model (including reverse relation names).",
"if not check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj, fields, old_instance=None, related=False):",
"than 1 level return True def check_rigid_related(obj, related): current_related = list(getattr(obj, related).filter()) old_related",
"f_name, None) except ObjectDoesNotExist: # in case it's OneToOne related field old_field =",
"if response is False: error_fields.append(f_name) if error_fields: return False, error_fields return True, None",
"new_file = getattr(f1, 'name', None) old_file = getattr(f2, 'name', None) if new_file !=",
"return False, f_name elif not field_comparison(new_field, old_field): return False, f_name return True, None",
"comparison_map = zip(current_related, old_related) # check if any field on the related model",
"are not included. Replacement for MyModel._meta.get_all_field_names() which does not exist under Django 1.10.",
"old_related) # check if any field on the related model was changed for",
"try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist: old_value = None if not",
"getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj, field,",
"and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None):",
"https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name, )",
"FieldFile): response = getattr(field, 'name', None) or False else: response = field is",
"f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False,",
"this could be a related field, unfortunately i can't figure out a isinstance",
"go deeper than 1 level return True def check_rigid_related(obj, related): current_related = list(getattr(obj,",
"that are possible for this model (including reverse relation names). Any internal-only field",
"field return True, None def check_required_fields(obj, fields): error_fields = [] for f_name in",
"f_name, None) except ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance, f_name, None)",
"not field_comparison(new_field, old_field): return False, f_name return True, None def update_object(obj, kwdict): for",
"(including reverse relation names). Any internal-only field names are not included. Replacement for",
"old_field = None if hasattr(new_field, 'all'): # this could be a related field,",
"not getattr(obj, 'old_instance', None): return False, fields for field in fields: old_instance =",
"ObjectDoesNotExist: return False, f_name try: response = field.filter().count() > 0 except AttributeError: if",
"False, error_fields return True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file =",
"'all'): # this could be a related field, unfortunately i can't figure out",
"False, f_name return True, None def update_object(obj, kwdict): for k, v in kwdict.items():",
"we don't go deeper than 1 level return True def check_rigid_related(obj, related): current_related",
"None): return False, fields for field in fields: old_instance = obj.old_instance if getattr(obj,",
"was changed for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False",
"0 except AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name', None) or False",
"there is no check for instance class so we don't go deeper than",
"in fields: old_instance = old_instance or obj.old_instance try: new_field = getattr(obj, f_name, None)",
"return False, fields for field in fields: old_instance = obj.old_instance if getattr(obj, field)",
"Model): # one of instances can be None, in this case we don't",
"it's OneToOne related field old_field = None if hasattr(new_field, 'all'): # this could",
"is no check for instance class so we don't go deeper than 1",
"except ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj, field, None) except ObjectDoesNotExist:",
"field_comparison(new_value, old_value): return False # there is no check for instance class so",
"error_fields return True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1,",
"field): return False, field return True, None def check_required_fields(obj, fields): error_fields = []",
"error_fields.append(f_name) if error_fields: return False, error_fields return True, None def field_comparison(f1, f2): if",
"old_field): return False, f_name return True, None def update_object(obj, kwdict): for k, v",
"response = field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile): response = getattr(field,",
"if not getattr(obj, 'old_instance', None): return False, fields for field in fields: old_instance",
"does not exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname)",
"we don't need to check all fields return old_obj == new_obj field_names =",
"or False else: response = field is not None if response is False:",
"'name', None) or False else: response = field is not None if response",
"= field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name',",
"related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is None: # if old",
"if any field on the related model was changed for old_obj, new_obj in",
"on the object, assuming no changes return True if len(current_related) != len(old_related): return",
"exist under Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field,",
"Django 1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else",
"'attname') else (field.name, ) for field in model._meta.get_fields() if not (field.many_to_one and field.related_model",
"be None, in this case we don't need to check all fields return",
"instance class so we don't go deeper than 1 level return True def",
"False, field return True, None def check_required_fields(obj, fields): error_fields = [] for f_name",
"True, None def check_required_fields(obj, fields): error_fields = [] for f_name in fields: try:",
"True, None for f_name in fields: old_instance = old_instance or obj.old_instance try: new_field",
"old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) # check if any field on",
"model was changed for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return",
"AttributeError: if isinstance(field, FieldFile): response = getattr(field, 'name', None) or False else: response",
"or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field,",
"field in fields: old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return",
"of all field names that are possible for this model (including reverse relation",
"model (including reverse relation names). Any internal-only field names are not included. Replacement",
"obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return False, field return True, None",
"None) except ObjectDoesNotExist: # in case it's OneToOne related field old_field = None",
"import GenericForeignKey from django.db.models import Model, ObjectDoesNotExist from django.db.models.fields.files import FieldFile from itertools",
"False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return",
"None def update_object(obj, kwdict): for k, v in kwdict.items(): if isinstance(v, list): getattr(obj,",
"check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field, old_field): return False, f_name return",
"= getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try: response = field.filter().count() >",
"for instance class so we don't go deeper than 1 level return True",
"version of the object was passed in, we assume there were no changes",
"old_instance = old_instance or obj.old_instance try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist:",
"def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None) old_file =",
"for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return True",
"getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance, f_name,",
"isinstance(old_obj, Model) or not isinstance(new_obj, Model): # one of instances can be None,",
"so we don't go deeper than 1 level return True def check_rigid_related(obj, related):",
"else (field.name, ) for field in model._meta.get_fields() if not (field.many_to_one and field.related_model is",
"return old_obj == new_obj field_names = get_all_field_names(old_obj) for field in field_names: try: new_value",
"new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj): return False return True def check_rigid_fields(obj,",
"check if related: if not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model)",
"return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) #",
"return True, None def check_required_fields(obj, fields): error_fields = [] for f_name in fields:",
"field.attname) if hasattr(field, 'attname') else (field.name, ) for field in model._meta.get_fields() if not",
"related model was changed for old_obj, new_obj in comparison_map: if not check_rigid_model_instance(old_obj, new_obj):",
"getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case it's OneToOne related field old_field",
"on the related model was changed for old_obj, new_obj in comparison_map: if not",
"not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return",
"Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field, old_field): return",
"= getattr(old_instance, f_name, None) except ObjectDoesNotExist: # in case it's OneToOne related field",
"f_name try: response = field.filter().count() > 0 except AttributeError: if isinstance(field, FieldFile): response",
"None) except ObjectDoesNotExist: old_value = None if not field_comparison(new_value, old_value): return False #",
"list of all field names that are possible for this model (including reverse",
"None) if old_related is None: # if old related was not set as",
"from itertools import chain def get_all_field_names(model): '''Return a list of all field names",
"))) def check_editable_fields(obj, fields): if not getattr(obj, 'old_instance', None): return False, fields for",
"no changes return True if len(current_related) != len(old_related): return False if len(current_related) ==",
"isinstance(new_obj, Model): # one of instances can be None, in this case we",
"chain def get_all_field_names(model): '''Return a list of all field names that are possible",
"getattr(f2, 'name', None) if new_file != old_file: return False elif f1 != f2:",
"assume there were no changes return True, None for f_name in fields: old_instance",
"return False, f_name try: response = field.filter().count() > 0 except AttributeError: if isinstance(field,",
"return False return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and",
"= obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return False, field return True,",
"getattr(obj, 'old_instance', None): return False, fields for field in fields: old_instance = obj.old_instance",
"None) if new_file != old_file: return False elif f1 != f2: return False",
"except ObjectDoesNotExist: return False, f_name try: response = field.filter().count() > 0 except AttributeError:",
"kwdict): for k, v in kwdict.items(): if isinstance(v, list): getattr(obj, k).set(v) else: setattr(obj,",
"= getattr(f2, 'name', None) if new_file != old_file: return False elif f1 !=",
"= getattr(obj, f_name, None) except ObjectDoesNotExist: new_field = None try: old_field = getattr(old_instance,",
"this model (including reverse relation names). Any internal-only field names are not included.",
"were no changes return True, None for f_name in fields: old_instance = old_instance",
") for field in model._meta.get_fields() if not (field.many_to_one and field.related_model is None) and",
"field.related_model is None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields): if not",
"since no old version of the object was passed in, we assume there",
"return False if len(current_related) == 0: return True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x:",
"# this could be a related field, unfortunately i can't figure out a",
"f_name in fields: old_instance = old_instance or obj.old_instance try: new_field = getattr(obj, f_name,",
"= getattr(old_obj, field, None) except ObjectDoesNotExist: new_value = None try: old_value = getattr(new_obj,",
"else: response = field is not None if response is False: error_fields.append(f_name) if",
"isinstance(new_field, Model): if not check_rigid_model_instance(old_field, new_field): return False, f_name elif not field_comparison(new_field, old_field):",
"in, we assume there were no changes return True, None for f_name in",
"getattr(field, 'name', None) or False else: response = field is not None if",
"isinstance(field, FieldFile): response = getattr(field, 'name', None) or False else: response = field",
"len(current_related) != len(old_related): return False if len(current_related) == 0: return True current_related.sort(key=lambda x:",
"old version of the object was passed in, we assume there were no",
"fields): if not getattr(obj, 'old_instance', None): return False, fields for field in fields:",
"fields: old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return False, field",
"f1 != f2: return False return True def check_rigid_model_instance(old_obj, new_obj): if not isinstance(old_obj,",
"related): current_related = list(getattr(obj, related).filter()) old_related = getattr(obj.old_instance, '{}_old'.format(related), None) if old_related is",
"= old_instance or obj.old_instance try: new_field = getattr(obj, f_name, None) except ObjectDoesNotExist: new_field",
"if hasattr(field, 'attname') else (field.name, ) for field in model._meta.get_fields() if not (field.many_to_one",
"if not check_rigid_related(obj, f_name): return False, f_name elif isinstance(old_field, Model) or isinstance(new_field, Model):",
"can be None, in this case we don't need to check all fields",
"1.10. https://github.com/django/django/blob/stable/1.7.x/django/db/models/options.py#L422 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api ''' return list(set(chain.from_iterable( (field.name, field.attname) if hasattr(field, 'attname') else (field.name,",
"in fields: old_instance = obj.old_instance if getattr(obj, field) != getattr(old_instance, field): return False,",
"fields: try: field = getattr(obj, f_name) except ObjectDoesNotExist: return False, f_name try: response",
"old_instance=None, related=False): if not old_instance and not getattr(obj, 'old_instance', None): # since no",
"= getattr(field, 'name', None) or False else: response = field is not None",
"True, None def field_comparison(f1, f2): if isinstance(f1, FieldFile): new_file = getattr(f1, 'name', None)",
"case it's OneToOne related field old_field = None if hasattr(new_field, 'all'): # this",
"True current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) # check",
"get_all_field_names(old_obj) for field in field_names: try: new_value = getattr(old_obj, field, None) except ObjectDoesNotExist:",
"return True def check_rigid_fields(obj, fields, old_instance=None, related=False): if not old_instance and not getattr(obj,",
"current_related.sort(key=lambda x: x.id) old_related.sort(key=lambda x: x.id) comparison_map = zip(current_related, old_related) # check if",
"internal-only field names are not included. Replacement for MyModel._meta.get_all_field_names() which does not exist",
"(field.many_to_one and field.related_model is None) and not isinstance(field, GenericForeignKey) ))) def check_editable_fields(obj, fields):",
"new_file != old_file: return False elif f1 != f2: return False return True",
"= zip(current_related, old_related) # check if any field on the related model was",
"names are not included. Replacement for MyModel._meta.get_all_field_names() which does not exist under Django",
"if not field_comparison(new_value, old_value): return False # there is no check for instance",
"'old_instance', None): # since no old version of the object was passed in,"
] |
[
"\"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\" ) args = parser.parse_args()",
"= argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text",
"= args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file to {}\".format(",
"if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" )",
"to be detokenized\" ) args = parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer",
"parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file",
"parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of",
"EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath ) ) tokenizer.write_detokenized_file( args.input_file, output_filepath",
"to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import",
"argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath",
"detokenized\" ) args = parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer()",
"from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(",
"__name__ == \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument(",
"import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str,",
"text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import argparse parser",
"disable=redefined-outer-name,unexpected-keyword-arg \"\"\"Script to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ ==",
") parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\" ) args",
"dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\" ) args = parser.parse_args() output_filepath",
"# pylint: disable=redefined-outer-name,unexpected-keyword-arg \"\"\"Script to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if",
"\"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\",",
"import EnAslTokenizer if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text",
"parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\" ) args =",
"lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize",
"detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import argparse",
"= parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized",
"of text to be detokenized\" ) args = parser.parse_args() output_filepath = args.input_file +",
"be detokenized\" ) args = parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer =",
"== \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\",",
"args = parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing",
"text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\"",
"files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be detokenized\" )",
"description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to be",
"help=\"filepath of text to be detokenized\" ) args = parser.parse_args() output_filepath = args.input_file",
"argparse.ArgumentParser( description=\"Detokenize text files\" ) parser.add_argument( \"--input-file\", dest=\"input_file\", type=str, help=\"filepath of text to",
") args = parser.parse_args() output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer() print(",
"= EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath ) ) tokenizer.write_detokenized_file( args.input_file,",
"+ \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath )",
"#!python # pylint: disable=redefined-outer-name,unexpected-keyword-arg \"\"\"Script to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer",
"\".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath ) )",
"print( \"Writing detokenized file to {}\".format( output_filepath ) ) tokenizer.write_detokenized_file( args.input_file, output_filepath )",
"args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath",
"file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\": import argparse parser =",
"\"\"\"Script to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__ == \"__main__\":",
"type=str, help=\"filepath of text to be detokenized\" ) args = parser.parse_args() output_filepath =",
"tokenizer = EnAslTokenizer() print( \"Writing detokenized file to {}\".format( output_filepath ) ) tokenizer.write_detokenized_file(",
"EnAslTokenizer if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser( description=\"Detokenize text files\"",
"text to be detokenized\" ) args = parser.parse_args() output_filepath = args.input_file + \".detok\"",
"pylint: disable=redefined-outer-name,unexpected-keyword-arg \"\"\"Script to detokenize text file\"\"\" from lang2sign.lang2gloss.tokenizers.en_asl import EnAslTokenizer if __name__",
"output_filepath = args.input_file + \".detok\" tokenizer = EnAslTokenizer() print( \"Writing detokenized file to"
] |
[
"return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by datetime, most recent first",
"plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots', p) for p",
"redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by datetime, most recent",
"showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots",
"os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)]",
"just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try:",
"plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output',",
"most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True)",
"ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id):",
"methods=['GET', 'POST']) def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return",
"'POST']) def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html',",
"= os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>')",
"# Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path,",
"start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results')",
"@bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from the output path\"\"\" return send_from_directory(conf.RUN['OUTPUT_PATH'],",
"index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm() if form.validate_on_submit():",
"conf from . import manager from .forms import SimulationForm bp = Blueprint('web', __name__)",
"d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing",
"render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from the output",
"[os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)] except FileNotFoundError: plots = []",
"os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def",
"SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST'])",
"recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return",
"render_template, redirect, url_for, send_from_directory import conf from . import manager from .forms import",
"def output(filename): \"\"\"serve simulation result files from the output path\"\"\" return send_from_directory(conf.RUN['OUTPUT_PATH'], filename)",
".forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start',",
"from . import manager from .forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/')",
"ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids)",
"Blueprint, render_template, redirect, url_for, send_from_directory import conf from . import manager from .forms",
"datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1],",
"import manager from .forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index():",
"def runs(): # sort by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids",
"Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form",
"results(id): # Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots =",
"sort by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda",
"import os from flask import Blueprint, render_template, redirect, url_for, send_from_directory import conf from",
"return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing top-level plots path",
"@bp.route('/results') def runs(): # sort by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH'])",
"top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots =",
"id) plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots', p) for",
"= [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files",
"plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from the output path\"\"\" return",
"render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by datetime, most recent first ids",
"def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm() if",
"url_for, send_from_directory import conf from . import manager from .forms import SimulationForm bp",
"return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from the",
"@bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index'))",
"bp = Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def",
"= Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start():",
"if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort",
"from flask import Blueprint, render_template, redirect, url_for, send_from_directory import conf from . import",
"'plots', p) for p in os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html',",
"os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots', p)",
"except FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve",
"in os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def",
"= SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs():",
"plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result",
"def results(id): # Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots",
"flask import Blueprint, render_template, redirect, url_for, send_from_directory import conf from . import manager",
"redirect, url_for, send_from_directory import conf from . import manager from .forms import SimulationForm",
"Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots')",
"return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by datetime, most",
"form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def",
"sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently",
"form=form) @bp.route('/results') def runs(): # sort by datetime, most recent first ids =",
"manager from .forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index(): return",
"def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form)",
"= os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots', p) for p in",
"[] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from",
"FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation",
"id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename): \"\"\"serve simulation result files from the output path\"\"\"",
"= os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output', id, 'plots',",
"import conf from . import manager from .forms import SimulationForm bp = Blueprint('web',",
"# sort by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids,",
"os from flask import Blueprint, render_template, redirect, url_for, send_from_directory import conf from .",
"return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data)",
"send_from_directory import conf from . import manager from .forms import SimulationForm bp =",
"= [os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)] except FileNotFoundError: plots =",
"p in os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>')",
"manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by datetime,",
"plots = [os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)] except FileNotFoundError: plots",
"import Blueprint, render_template, redirect, url_for, send_from_directory import conf from . import manager from",
"for p in os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots)",
"SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): #",
"@bp.route('/results/<string:id>') def results(id): # Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'], id)",
"form.validate_on_submit(): manager.start(**form.data) return redirect(url_for('web.index')) return render_template('start.html', form=form) @bp.route('/results') def runs(): # sort by",
"reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing top-level plots",
"@bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm()",
"render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form = SimulationForm() if form.validate_on_submit(): manager.start(**form.data) return",
"by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d:",
"runs(): # sort by datetime, most recent first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids =",
"os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html', id=id, plots=plots) @bp.route('/output/<path:filename>') def output(filename):",
"runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing top-level plots path = os.path.join(conf.RUN['OUTPUT_PATH'],",
"'plots') try: plots = [os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)] except",
"id, 'plots', p) for p in os.listdir(plots)] except FileNotFoundError: plots = [] return",
"render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing top-level plots path =",
"from .forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html')",
"d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just showing top-level",
"p) for p in os.listdir(plots)] except FileNotFoundError: plots = [] return render_template('results.html', id=id,",
"first ids = os.listdir(conf.RUN['OUTPUT_PATH']) ids = sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html',",
"= sorted(ids, key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): #",
"key=lambda d: d.split('__')[-1], reverse=True) return render_template('runs.html', runs=ids) @bp.route('/results/<string:id>') def results(id): # Currently just",
"path = os.path.join(conf.RUN['OUTPUT_PATH'], id) plots = os.path.join(path, 'plots') try: plots = [os.path.join('/output', id,",
"__name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET', 'POST']) def start(): form =",
". import manager from .forms import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def",
"import SimulationForm bp = Blueprint('web', __name__) @bp.route('/') def index(): return render_template('status.html') @bp.route('/start', methods=['GET',",
"try: plots = [os.path.join('/output', id, 'plots', p) for p in os.listdir(plots)] except FileNotFoundError:"
] |
[
"MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std =",
"= False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size,",
"default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d):",
"def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std)",
"torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self,",
"as nn import torch.nn.functional as F from torch.autograd import Variable def default_conv(in_channels, out_channels,",
"as F from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(",
"= False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True,",
"F from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels,",
"math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd",
"import math import torch import torch.nn as nn import torch.nn.functional as F from",
"torch.nn.functional as F from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return",
"class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std",
"rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3,",
"BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m =",
"1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad",
"bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ]",
"= [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if",
"kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not None:",
"torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data =",
"out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift,",
"1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean)",
"in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1):",
"False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)):",
"bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not None: m.append(act) super(BasicBlock, self).__init__(*m)",
"kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1,",
"self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad =",
"import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import",
"kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self,",
"return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean,",
"out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not",
"import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2),",
"= torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign *",
"in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size,",
"def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class",
"3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1,",
"super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1)",
"out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def",
"__init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels,",
"* rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential):",
"[nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act",
"nn import torch.nn.functional as F from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size,",
"stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias)",
"bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1)",
"3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range *",
"self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad",
"= torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data",
"= sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False",
"m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels))",
"self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels,",
"padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3,",
"import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def",
"self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign",
"from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels,",
"act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn:",
"out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2),",
"bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if",
"self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3,",
"in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is",
"sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1,",
"bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range,",
"rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def",
"self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False,",
"torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range",
"1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False",
"class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m",
"self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels,",
"std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1))",
"sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class",
"torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size,",
"nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std,",
"rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3,",
"self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self, in_channels,",
"False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, stride=1,",
"* torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class BasicBlock(nn.Sequential): def __init__(",
"kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), stride=stride,",
"kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3,",
"padding=(kernel_size//2), stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not None: m.append(act)",
"torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable",
"stride=stride, bias=bias) ] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not None: m.append(act) super(BasicBlock,",
"1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std)",
"torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def default_conv(in_channels,",
"Variable def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias)",
"__init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data",
"1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad =",
"import torch.nn.functional as F from torch.autograd import Variable def default_conv(in_channels, out_channels, kernel_size, bias=True):",
"def __init__( self, in_channels, out_channels, kernel_size, stride=1, bias=False, bn=True, act=nn.ReLU(True)): m = [nn.Conv2d(",
"rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data ="
] |
[
"tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True))",
"перечислены в соответствии с занятыми местами\") else: print(\"Команды перечислены не в соответствии с",
"tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if",
"tpl: print(\"Команды перечислены в соответствии с занятыми местами\") else: print(\"Команды перечислены не в",
"-*- coding: utf-8 -*- import sys if __name__ == '__main__': tpl = tuple(map(float,",
"if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl:",
"exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии с занятыми местами\")",
"if __name__ == '__main__': tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж",
"file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии с занятыми",
"reverse=True)) == tpl: print(\"Команды перечислены в соответствии с занятыми местами\") else: print(\"Команды перечислены",
"пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии с",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys if __name__ == '__main__':",
"if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии с занятыми местами\") else:",
"sys if __name__ == '__main__': tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный",
"utf-8 -*- import sys if __name__ == '__main__': tpl = tuple(map(float, input().split())) if",
"import sys if __name__ == '__main__': tpl = tuple(map(float, input().split())) if not tpl:",
"input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) ==",
"-*- import sys if __name__ == '__main__': tpl = tuple(map(float, input().split())) if not",
"__name__ == '__main__': tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\",",
"print(\"Команды перечислены в соответствии с занятыми местами\") else: print(\"Команды перечислены не в соответствии",
"# -*- coding: utf-8 -*- import sys if __name__ == '__main__': tpl =",
"соответствии с занятыми местами\") else: print(\"Команды перечислены не в соответствии с занятыми местами\")",
"coding: utf-8 -*- import sys if __name__ == '__main__': tpl = tuple(map(float, input().split()))",
"кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии",
"'__main__': tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1)",
"== '__main__': tpl = tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr)",
"== tpl: print(\"Команды перечислены в соответствии с занятыми местами\") else: print(\"Команды перечислены не",
"tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены",
"tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в соответствии с занятыми местами\") else: print(\"Команды",
"not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды",
"python3 # -*- coding: utf-8 -*- import sys if __name__ == '__main__': tpl",
"print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl, reverse=True)) == tpl: print(\"Команды перечислены в",
"= tuple(map(float, input().split())) if not tpl: print(\"Заданный кортеж пуст\", file=sys.stderr) exit(1) if tuple(sorted(tpl,",
"в соответствии с занятыми местами\") else: print(\"Команды перечислены не в соответствии с занятыми"
] |
[
"[ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={",
"Generated by Django 2.2.7 on 2020-01-08 09:40 from django.db import migrations, models import",
"bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x',",
"= [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ],",
"Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[",
"to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"<filename>getchapp/migrations/0003_post_tag.py # Generated by Django 2.2.7 on 2020-01-08 09:40 from django.db import migrations,",
"parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag',",
"on 2020-01-08 09:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[",
"name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)),",
"False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False,",
"operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')),",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'),",
"}, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')),",
"fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target',",
"primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')),",
"models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ],",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel(",
"dependencies = [ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr',",
"'0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True,",
"2020-01-08 09:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"by Django 2.2.7 on 2020-01-08 09:40 from django.db import migrations, models import django.db.models.deletion",
"models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')),",
"('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ),",
"('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True,",
"Django 2.2.7 on 2020-01-08 09:40 from django.db import migrations, models import django.db.models.deletion class",
"on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand',",
"('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={",
"on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel(",
"('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"= [ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True,",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), ]",
"options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True,",
"('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract': False,",
"# Generated by Django 2.2.7 on 2020-01-08 09:40 from django.db import migrations, models",
"to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True,",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ]",
"name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False,",
"serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr',",
"('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')),",
"to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract': False, }, bases=('getchapp.channel',),",
"class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations",
"] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False,",
"fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, },",
"], options={ 'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE,",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp',",
"'abstract': False, }, bases=('getchapp.channel',), ), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True,",
"09:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"[ ('getchapp', '0002_brand_item'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE,",
"parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y', models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item',",
"migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)), ('y',",
"models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',), ),",
"2.2.7 on 2020-01-08 09:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations = [",
"('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract': False, }, bases=('getchapp.channel',),",
"models.FloatField(default=0)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract':",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Pix')), ('with_brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Brand')), ('with_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='getchapp.Item')), ], options={ 'abstract': False, },",
"migrations.CreateModel( name='Post', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ], options={ 'abstract':",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('getchapp', '0002_brand_item'), ] operations =",
"), migrations.CreateModel( name='Tag', fields=[ ('channel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='getchapp.Channel')), ('x', models.FloatField(default=0)),"
] |
[
"collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None,",
"+ params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr",
"dw list \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None,",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout)",
"__MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group,",
"no_wait=None): params = get_params(locals()) command = \"az sql dw create \" + params",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group,",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group): params",
"\"az sql dw show \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"__TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals()) command = \"az sql dw",
"command = \"az sql dw resume \" + params print(command) output = subprocess.run(command,",
"update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals())",
"= get_params(locals()) command = \"az sql dw update \" + params print(command) output",
"backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals())",
"pause \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"list(server, resource_group): params = get_params(locals()) command = \"az sql dw list \" +",
"= \"az sql dw delete \" + params print(command) output = subprocess.run(command, shell=True,",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server, name): params",
"command = \"az sql dw list \" + params print(command) output = subprocess.run(command,",
"tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None,",
"print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params = get_params(locals()) command",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None,",
"name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command =",
"params = get_params(locals()) command = \"az sql dw create \" + params print(command)",
"params = get_params(locals()) command = \"az sql dw show \" + params print(command)",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None):",
"add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command = \"az sql dw update",
"pause(name, server, resource_group): params = get_params(locals()) command = \"az sql dw pause \"",
"print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params =",
"update \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"show \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"__AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server,",
"\"az sql dw delete \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals())",
"get_params(locals()) command = \"az sql dw resume \" + params print(command) output =",
"dw resume \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"else: raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None,",
"server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command",
"get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None,",
"params = get_params(locals()) command = \"az sql dw update \" + params print(command)",
"print(stderr) def resume(name, server, resource_group): params = get_params(locals()) command = \"az sql dw",
"get_params(locals()) command = \"az sql dw pause \" + params print(command) output =",
"get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None,",
"\" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\")",
"show(resource_group, server, name): params = get_params(locals()) command = \"az sql dw show \"",
"= subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout:",
"json, subprocess from ... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None,",
"Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals()) command = \"az sql dw",
"server, name, yes=None, no_wait=None): params = get_params(locals()) command = \"az sql dw delete",
"print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals()) command =",
"shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout)",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None,",
"raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals()) command",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server, name,",
"__MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals()) command",
"yes=None, no_wait=None): params = get_params(locals()) command = \"az sql dw delete \" +",
"else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params = get_params(locals()) command =",
"stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group,",
"dw delete \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"name): params = get_params(locals()) command = \"az sql dw show \" + params",
"resource_group): params = get_params(locals()) command = \"az sql dw list \" + params",
"sql dw create \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr =",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server,",
"import json, subprocess from ... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None,",
"__READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params",
"remove=None, force_string=None, no_wait=None): params = get_params(locals()) command = \"az sql dw update \"",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group): params =",
"print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params = get_params(locals()) command",
"sql dw pause \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group,",
"= get_params(locals()) command = \"az sql dw resume \" + params print(command) output",
"resource_group): params = get_params(locals()) command = \"az sql dw resume \" + params",
"__CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals()) command = \"az",
"def resume(name, server, resource_group): params = get_params(locals()) command = \"az sql dw resume",
"print(stderr) def pause(name, server, resource_group): params = get_params(locals()) command = \"az sql dw",
"sql dw resume \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params",
"get_params(locals()) command = \"az sql dw delete \" + params print(command) output =",
"max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None,",
"def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None,",
"params = get_params(locals()) command = \"az sql dw pause \" + params print(command)",
"resource_group, no_wait=None): params = get_params(locals()) command = \"az sql dw create \" +",
"resource_group): params = get_params(locals()) command = \"az sql dw pause \" + params",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params",
"= get_params(locals()) command = \"az sql dw create \" + params print(command) output",
"force_string=None, no_wait=None): params = get_params(locals()) command = \"az sql dw update \" +",
"<filename>test/pyaz/sql/dw/__init__.py import json, subprocess from ... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None,",
"else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals())",
"Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None):",
"print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals()) command = \"az",
"no_wait=None): params = get_params(locals()) command = \"az sql dw delete \" + params",
"subprocess from ... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None,",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params",
"= \"az sql dw pause \" + params print(command) output = subprocess.run(command, shell=True,",
"print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None,",
"create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None,",
"else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params = get_params(locals()) command =",
"params = get_params(locals()) command = \"az sql dw resume \" + params print(command)",
"= \"az sql dw resume \" + params print(command) output = subprocess.run(command, shell=True,",
"name, yes=None, no_wait=None): params = get_params(locals()) command = \"az sql dw delete \"",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server, name):",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server, name): params =",
"\"az sql dw create \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None,",
"params = get_params(locals()) command = \"az sql dw list \" + params print(command)",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params = get_params(locals())",
"else: raise Exception(stderr) print(stderr) def show(resource_group, server, name): params = get_params(locals()) command =",
"= \"az sql dw list \" + params print(command) output = subprocess.run(command, shell=True,",
"create \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"else: raise Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals()) command = \"az",
"def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params =",
"delete \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"command = \"az sql dw delete \" + params print(command) output = subprocess.run(command,",
"import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None,",
"= output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr)",
"get_params(locals()) command = \"az sql dw show \" + params print(command) output =",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group):",
"pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None,",
"delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals()) command = \"az sql dw",
"= \"az sql dw show \" + params print(command) output = subprocess.run(command, shell=True,",
"print(stderr) def list(server, resource_group): params = get_params(locals()) command = \"az sql dw list",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params",
"name, server, resource_group, no_wait=None): params = get_params(locals()) command = \"az sql dw create",
"get_params(locals()) command = \"az sql dw update \" + params print(command) output =",
"sql dw list \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"__FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals()) command = \"az sql",
"= get_params(locals()) command = \"az sql dw pause \" + params print(command) output",
"Exception(stderr) print(stderr) def show(resource_group, server, name): params = get_params(locals()) command = \"az sql",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params = get_params(locals())",
"print(stderr) def show(resource_group, server, name): params = get_params(locals()) command = \"az sql dw",
"= \"az sql dw create \" + params print(command) output = subprocess.run(command, shell=True,",
"= get_params(locals()) command = \"az sql dw show \" + params print(command) output",
"stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def",
"= \"az sql dw update \" + params print(command) output = subprocess.run(command, shell=True,",
"list \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group):",
"raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params = get_params(locals()) command = \"az",
"__IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params = get_params(locals()) command =",
"__SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None,",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name,",
"get_params(locals()) command = \"az sql dw create \" + params print(command) output =",
"subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return",
"Exception(stderr) print(stderr) def pause(name, server, resource_group): params = get_params(locals()) command = \"az sql",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server,",
"command = \"az sql dw create \" + params print(command) output = subprocess.run(command,",
"server, resource_group): params = get_params(locals()) command = \"az sql dw pause \" +",
"command = \"az sql dw show \" + params print(command) output = subprocess.run(command,",
"\"az sql dw update \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server,",
"sql dw delete \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server, name,",
"__RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None,",
"__SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None,",
"stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else:",
"get_params(locals()) command = \"az sql dw list \" + params print(command) output =",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server,",
"Exception(stderr) print(stderr) def delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals()) command =",
"raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params = get_params(locals()) command = \"az",
"__SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None,",
"__HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None): params =",
"if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group):",
"def pause(name, server, resource_group): params = get_params(locals()) command = \"az sql dw pause",
"__COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name, server, resource_group, no_wait=None):",
"zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None, __HIGH_AVAILABILITY_REPLICA_COUNT=None, backup_storage_redundancy=None, __MAINTENANCE_CONFIGURATION_ID=None, __IS_LEDGER_ON=None, __CAPACITY=None, __FAMILY=None, __TIER=None, name,",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name, server, resource_group): params =",
"\"az sql dw resume \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server,",
"sql dw show \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"resume \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout =",
"= get_params(locals()) command = \"az sql dw delete \" + params print(command) output",
"no_wait=None): params = get_params(locals()) command = \"az sql dw update \" + params",
"resume(name, server, resource_group): params = get_params(locals()) command = \"az sql dw resume \"",
"raise Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals()) command = \"az sql",
"def list(server, resource_group): params = get_params(locals()) command = \"az sql dw list \"",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def pause(name,",
"server, name): params = get_params(locals()) command = \"az sql dw show \" +",
"dw show \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"dw create \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\")",
"__LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None, __READ_SCALE=None,",
"raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None,",
"command = \"az sql dw pause \" + params print(command) output = subprocess.run(command,",
"def show(resource_group, server, name): params = get_params(locals()) command = \"az sql dw show",
"command = \"az sql dw update \" + params print(command) output = subprocess.run(command,",
"service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command = \"az sql",
"max_size=None, service_objective=None, set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command = \"az",
"sql dw update \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server, name): params = get_params(locals())",
"json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server, resource_group): params = get_params(locals()) command",
"stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None,",
"params = get_params(locals()) command = \"az sql dw delete \" + params print(command)",
"dw update \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"= output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(server,",
"= get_params(locals()) command = \"az sql dw list \" + params print(command) output",
"server, resource_group, no_wait=None): params = get_params(locals()) command = \"az sql dw create \"",
"dw pause \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout",
"print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server, name): params = get_params(locals()) command",
"Exception(stderr) print(stderr) def resume(name, server, resource_group): params = get_params(locals()) command = \"az sql",
"def delete(resource_group, server, name, yes=None, no_wait=None): params = get_params(locals()) command = \"az sql",
"from ... pyaz_utils import get_cli_name, get_params def create(__CATALOG_COLLATION=None, collation=None, __ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None,",
"output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server, name, max_size=None, service_objective=None,",
"\"az sql dw pause \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def resume(name, server, resource_group): params =",
"\"az sql dw list \" + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,",
"server, resource_group): params = get_params(locals()) command = \"az sql dw resume \" +",
"set=None, add=None, remove=None, force_string=None, no_wait=None): params = get_params(locals()) command = \"az sql dw",
"output.stdout.decode(\"utf-8\") stderr = output.stderr.decode(\"utf-8\") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr)",
"raise Exception(stderr) print(stderr) def show(resource_group, server, name): params = get_params(locals()) command = \"az",
"__ELASTIC_POOL_ID=None, __LICENSE_TYPE=None, max_size=None, service_objective=None, __RESTORE_POINT_IN_TIME=None, __SAMPLE_NAME=None, __SKU=None, __SOURCE_DATABASE_DELETION_DATE=None, tags=None, zone_redundant=None, __AUTO_PAUSE_DELAY=None, __MIN_CAPACITY=None, __COMPUTE_MODEL=None,"
] |
[
"VALUES (%d, %d, %d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id) #print \">\",",
"range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO `show`",
"price, theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print",
"\">\", query cur.execute(query) show_real_id = db.insert_id() # craete ticket for seat_col in range(0,",
"seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\" % (price, seat_id,",
"= \"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\"",
"range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) # get seat_id",
"theater_id) VALUES (%d, %d, %d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id) #print",
"\"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id,",
"\"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\");",
"in range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) # get",
"cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id",
"%d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id() #",
"('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id =",
"MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" # truncate old data",
"1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema',",
"film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id() # craete ticket for seat_col",
"%H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" #",
"\"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1,",
"= \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d,",
"db.cursor() print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\");",
"for show_id in range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185); query =",
"cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print",
"= MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" # truncate old",
"seat_row in range(0, 10): price = random.randint(18,25) # get seat_id seat_id += 1",
"data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\");",
"for theater for seat_col in range(0, 10): for seat_row in range(0, 10): price",
"theater for seat_col in range(0, 10): for seat_row in range(0, 10): price =",
"in range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) query =",
"#print \">\", query cur.execute(query) # create shows now = dt.now() + timedelta(days=1) for",
"in range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO",
"theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1 query = \"INSERT",
"`theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema`",
"# truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE",
"`show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create",
"1001): #is_3D = random.randint(0,1) is_3D = 1 query = \"INSERT INTO `theater` (theater_id,",
"\">\", query cur.execute(query) # create shows now = dt.now() + timedelta(days=1) for show_id",
"passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS",
"query cur.execute(query) # create shows now = dt.now() + timedelta(days=1) for show_id in",
"FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\");",
"\"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\" %",
"DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor()",
"in range(0, 10): price = random.randint(18,25) query = \"INSERT INTO `seat` (row, col,",
"seat_id += 1 query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id)",
"`cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id in range(1,",
"is_3D = 1 query = \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES",
"VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id",
"= \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\"",
"'%d', '1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() #",
"price = random.randint(18,25) query = \"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES",
"(now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id() # craete ticket",
"db.insert_id() # craete ticket for seat_col in range(0, 10): for seat_row in range(0,",
"INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\"",
"user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" # truncate old data cur.execute(\"SET",
"for seat_row in range(0, 10): price = random.randint(18,25) # get seat_id seat_id +=",
"address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id in range(1, 1001): #is_3D",
"show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\" % (price, seat_id, show_real_id,",
"= '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print",
"(start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\",",
"for seat_row in range(0, 10): price = random.randint(18,25) query = \"INSERT INTO `seat`",
"# MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\")",
"%d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query) # create",
"'%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\"",
"cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE",
"`cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT",
"import random from datetime import datetime as dt, timedelta # MySQL format DATE_FORMAT",
"0 for theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1 query",
"query = \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d',",
"10): for seat_row in range(0, 10): price = random.randint(18,25) # get seat_id seat_id",
"create shows now = dt.now() + timedelta(days=1) for show_id in range(0, 1): film_id",
"\"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id",
"= 1 query = \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d',",
"VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id",
"# create shows now = dt.now() + timedelta(days=1) for show_id in range(0, 1):",
"range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1 query = \"INSERT INTO `theater`",
"= random.randint(0,1) is_3D = 1 query = \"INSERT INTO `theater` (theater_id, name, is_3D,",
"VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id in range(1, 1001): #is_3D =",
"timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\"",
"cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query)",
"(theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() # create seats for",
"= db.insert_id() # create seats for theater for seat_col in range(0, 10): for",
"theater_real_id) #print \">\", query cur.execute(query) # create shows now = dt.now() + timedelta(days=1)",
"cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id)",
"= 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET",
"seat_id = 0 for theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D =",
"now = dt.now() + timedelta(days=1) for show_id in range(0, 1): film_id = random.randint(1,999)",
"film_id = random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id,",
"+= timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d,",
"random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES",
"cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name,",
"ticket for seat_col in range(0, 10): for seat_row in range(0, 10): price =",
"truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\");",
"as dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\",",
"datetime import datetime as dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S'",
"db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur = db.cursor() print \"connected\" # truncate",
"create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0",
"seats for theater for seat_col in range(0, 10): for seat_row in range(0, 10):",
"(theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,)",
"= 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES",
"theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\",",
"VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\", query",
"%d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query) # create shows",
"format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur =",
"#print \">\", query cur.execute(query) show_real_id = db.insert_id() # craete ticket for seat_col in",
"cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for",
"film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query)",
"price, theater_real_id) #print \">\", query cur.execute(query) # create shows now = dt.now() +",
"cur = db.cursor() print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\");",
"(name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id in range(1, 1001):",
"random.randint(0,1) is_3D = 1 query = \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id)",
"range(0, 10): price = random.randint(18,25) query = \"INSERT INTO `seat` (row, col, price,",
"dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\",",
"= \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT),",
"MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"sakila\") cur",
"(%d, %d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query)",
"query cur.execute(query) theater_real_id = db.insert_id() # create seats for theater for seat_col in",
"0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS",
"INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id = 0 for theater_id in",
"`ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\" %",
"INTO `seat` (row, col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row,",
"1): film_id = random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO `show` (start_date,",
"= 0 for theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1",
"query = \"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES (%d, %d, %d,",
"cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS =",
"get seat_id seat_id += 1 query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id,",
"# create seats for theater for seat_col in range(0, 10): for seat_row in",
"10): price = random.randint(18,25) query = \"INSERT INTO `seat` (row, col, price, theater_theater_id)",
"`theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id,",
"(seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query) # create shows now =",
"db.insert_id() # create seats for theater for seat_col in range(0, 10): for seat_row",
"cur.execute(query) # create shows now = dt.now() + timedelta(days=1) for show_id in range(0,",
"query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" %",
"cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO",
"print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\")",
"10): price = random.randint(18,25) # get seat_id seat_id += 1 query = \"INSERT",
"import MySQLdb import random from datetime import datetime as dt, timedelta # MySQL",
"range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) query = \"INSERT",
"`seat` (row, col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col,",
"= dt.now() + timedelta(days=1) for show_id in range(0, 1): film_id = random.randint(1,999) now",
"theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() # create seats for theater",
"= random.randint(18,25) # get seat_id seat_id += 1 query = \"INSERT INTO `ticket`",
"1 query = \"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d',",
"# get seat_id seat_id += 1 query = \"INSERT INTO `ticket` (price, seat_seat_id,",
"cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" #",
"`ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\");",
"%d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id) #print \">\", query cur.execute(query) db.commit()",
"#!/usr/bin/python import MySQLdb import random from datetime import datetime as dt, timedelta #",
"MySQLdb import random from datetime import datetime as dt, timedelta # MySQL format",
"(%d, %d, %d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id) #print \">\", query",
"dt.now() + timedelta(days=1) for show_id in range(0, 1): film_id = random.randint(1,999) now +=",
"theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id() # craete ticket for",
"shows now = dt.now() + timedelta(days=1) for show_id in range(0, 1): film_id =",
"random from datetime import datetime as dt, timedelta # MySQL format DATE_FORMAT =",
"= random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id)",
"in range(0, 10): price = random.randint(18,25) # get seat_id seat_id += 1 query",
"seat_col in range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) query",
"# craete ticket for seat_col in range(0, 10): for seat_row in range(0, 10):",
"for seat_col in range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25)",
"range(0, 10): price = random.randint(18,25) # get seat_id seat_id += 1 query =",
"10): for seat_row in range(0, 10): price = random.randint(18,25) query = \"INSERT INTO",
"timedelta(days=1) for show_id in range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185); query",
"% (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() # create seats",
"%d, %d, 1, %d);\" % (price, seat_id, show_real_id, theater_real_id) #print \">\", query cur.execute(query)",
"seat_id seat_id += 1 query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id,",
"theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query",
"cur.execute(query) theater_real_id = db.insert_id() # create seats for theater for seat_col in range(0,",
"# create cinema cur.execute(\"INSERT INTO `cinema` (name, address) VALUES ('cinema', 'wroclaw');\") seat_id =",
"is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() # create seats for theater for",
"print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE",
"INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id)",
"create seats for theater for seat_col in range(0, 10): for seat_row in range(0,",
"\"INSERT INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" %",
"`show` (start_date, theater_theater_id, film_film_id) VALUES ('%s', %d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print",
"seat_col in range(0, 10): for seat_row in range(0, 10): price = random.randint(18,25) #",
"('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id =",
"1 query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d,",
"query cur.execute(query) show_real_id = db.insert_id() # craete ticket for seat_col in range(0, 10):",
"import datetime as dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db",
"in range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1 query = \"INSERT INTO",
"#is_3D = random.randint(0,1) is_3D = 1 query = \"INSERT INTO `theater` (theater_id, name,",
"`seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\"",
"(row, col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col, price,",
"cur.execute(query) show_real_id = db.insert_id() # craete ticket for seat_col in range(0, 10): for",
"show_real_id = db.insert_id() # craete ticket for seat_col in range(0, 10): for seat_row",
"'1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id() # create",
"+ timedelta(days=1) for show_id in range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185);",
"craete ticket for seat_col in range(0, 10): for seat_row in range(0, 10): price",
"price = random.randint(18,25) # get seat_id seat_id += 1 query = \"INSERT INTO",
"is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print query",
"'wroclaw');\") seat_id = 0 for theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D",
"datetime as dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db =",
"old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE `ticket`;\"); cur.execute(\"TRUNCATE `seat`;\"); cur.execute(\"TRUNCATE `show`;\"); cur.execute(\"TRUNCATE",
"%d, %d);\" % (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id()",
"INTO `theater` (theater_id, name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id,",
"now += timedelta(minutes=185); query = \"INSERT INTO `show` (start_date, theater_theater_id, film_film_id) VALUES ('%s',",
"query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d,",
"% (now.strftime(DATE_FORMAT), theater_real_id, film_id) #print \">\", query cur.execute(query) show_real_id = db.insert_id() # craete",
"random.randint(18,25) query = \"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES (%d, %d,",
"= db.insert_id() # craete ticket for seat_col in range(0, 10): for seat_row in",
"seat_row in range(0, 10): price = random.randint(18,25) query = \"INSERT INTO `seat` (row,",
"db=\"sakila\") cur = db.cursor() print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS =",
"#print query cur.execute(query) theater_real_id = db.insert_id() # create seats for theater for seat_col",
"theater_real_id = db.insert_id() # create seats for theater for seat_col in range(0, 10):",
"'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print query cur.execute(query) theater_real_id = db.insert_id()",
"('cinema', 'wroclaw');\") seat_id = 0 for theater_id in range(1, 1001): #is_3D = random.randint(0,1)",
"name, is_3D, cinema_cinema_id) VALUES ('%d', 'theater%d', '%d', '1');\" % (theater_id, theater_id, is_3D,) #print",
"%d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query) #",
"for theater_id in range(1, 1001): #is_3D = random.randint(0,1) is_3D = 1 query =",
"% (seat_row, seat_col, price, theater_real_id) #print \">\", query cur.execute(query) # create shows now",
"random.randint(18,25) # get seat_id seat_id += 1 query = \"INSERT INTO `ticket` (price,",
"timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d %H:%M:%S' db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\",",
"col, price, theater_theater_id) VALUES (%d, %d, %d, %d);\" % (seat_row, seat_col, price, theater_real_id)",
"= random.randint(18,25) query = \"INSERT INTO `seat` (row, col, price, theater_theater_id) VALUES (%d,",
"show_id in range(0, 1): film_id = random.randint(1,999) now += timedelta(minutes=185); query = \"INSERT",
"= db.cursor() print \"connected\" # truncate old data cur.execute(\"SET FOREIGN_KEY_CHECKS = 0;\"); cur.execute(\"TRUNCATE",
"FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema cur.execute(\"INSERT INTO `cinema` (name, address)",
"cur.execute(\"TRUNCATE `cinema`;\"); cur.execute(\"TRUNCATE `theater`;\"); cur.execute(\"SET FOREIGN_KEY_CHECKS = 1;\"); print \"cleaned\" # create cinema",
"from datetime import datetime as dt, timedelta # MySQL format DATE_FORMAT = '%Y-%m-%d",
"seat_col, price, theater_real_id) #print \">\", query cur.execute(query) # create shows now = dt.now()",
"(price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES (%d, %d, %d, 1, %d);\" % (price,",
"+= 1 query = \"INSERT INTO `ticket` (price, seat_seat_id, show_show_id, cinema_cinema_id, theater_id) VALUES"
] |
[
"cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf",
"wiht every properties as keys ndarray or list can be given for Vector",
"material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter",
"not None: self._mat_type.parent = self # The Magnet material # Type : Material",
"check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import",
"default value with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if",
"fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization",
"if self._mat_type is not None: self._mat_type.parent = self # The Magnet material #",
"Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] =",
"in all object save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor",
"== -1: mat_type = Material() if init_dict is not None: # Initialisation by",
"self._type_magnetization = value # Permanent magnet magnetization type: 0 for radial, 1 for",
"if init_dict is not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"])",
"material # Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\"",
"import Material class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening",
"property with an empty Matrix for pyleecan type, None will call the default",
"if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization",
"(arg1 = 1, arg3 = 5) every parameters have name and default values",
"self._mat_type = value if self._mat_type is not None: self._mat_type.parent = self # The",
"isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag",
"= init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()):",
"new properties self._freeze() def __str__(self): \"\"\"Convert this objet in a readeable string (for",
"if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag =",
"(except pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag",
"save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class.",
"can be given for pyleecan Object\"\"\" if mat_type == -1: mat_type = Material()",
"dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization =",
"def __str__(self): \"\"\"Convert this objet in a readeable string (for print)\"\"\" Magnet_str =",
"linesep Magnet_str += \"Lmag = \" + str(self.Lmag) return Magnet_str def __eq__(self, other):",
"linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag",
"Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0)",
"\"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent = None",
") def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of",
"# Type : int, min = 0, max = 5 type_magnetization = property(",
"= save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can",
"Magnet_str += \"parent = \" + str(type(self.parent)) + \" object\" + linesep Magnet_str",
"-*- coding: utf-8 -*- \"\"\"Warning : this file has been generated, you shouldn't",
"for Matrix, None will initialise the property with an empty Matrix for pyleecan",
"1 for parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\"",
"comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume",
"(skip parent)\"\"\" if type(other) != type(self): return False if other.mat_type != self.mat_type: return",
"# save method is available in all object save = save def __init__(self,",
"for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self,",
"radial, 1 for parallel, 2 for HallBach [] # Type : int, min",
"import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1 # cf",
"Lmag # The class is frozen, for now it's impossible to add new",
"object\" + linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) + linesep +",
"Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name",
"# -*- coding: utf-8 -*- \"\"\"Warning : this file has been generated, you",
"__init__ (arg1 = 1, arg3 = 5) every parameters have name and default",
"from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening",
"from os import linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save",
"d must be a dictionnary wiht every properties as keys ndarray or list",
"init_dict=None): \"\"\"Constructor of the class. Can be use in two ways : -",
"Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other) != type(self):",
"type: 0 for radial, 1 for parallel, 2 for HallBach [] # Type",
"\"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value,",
"\"\"\"Convert this objet in a readeable string (for print)\"\"\" Magnet_str = \"\" if",
"5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial,",
"_set_None(self): \"\"\"Set all the properties to None (except pyleecan object)\"\"\" if self.mat_type is",
"plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION =",
"\"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the properties to None (except pyleecan",
"None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of",
"the class. Can be use in two ways : - __init__ (arg1 =",
"default constructor - __init__ (init_dict = d) d must be a dictionnary wiht",
"- __init__ (init_dict = d) d must be a dictionnary wiht every properties",
"from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from",
"_get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\",",
"str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other)",
"is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def _get_mat_type(self): \"\"\"getter",
"from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from",
"comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening",
"def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if",
"Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume",
"The class name is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\"",
": Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self):",
"init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag",
"the properties to None (except pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None()",
"a dictionnary wiht every properties as keys ndarray or list can be given",
"self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value",
"self._freeze() def __str__(self): \"\"\"Convert this objet in a readeable string (for print)\"\"\" Magnet_str",
"1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height",
"Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict",
"= type_magnetization self.Lmag = Lmag # The class is frozen, for now it's",
"# cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume #",
"value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type is",
"from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from",
"name is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict",
"been generated, you shouldn't edit it\"\"\" from os import linesep from pyleecan.Classes.check import",
"self.mat_type: return False if other.type_magnetization != self.type_magnetization: return False if other.Lmag != self.Lmag:",
"Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag",
"property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return",
"objects (skip parent)\"\"\" if type(other) != type(self): return False if other.mat_type != self.mat_type:",
"# Magnet axial length # Type : float, min = 0 Lmag =",
"= value # Permanent magnet magnetization type: 0 for radial, 1 for parallel,",
"type_magnetization self.Lmag = Lmag # The class is frozen, for now it's impossible",
"Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards",
"is available in all object save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95,",
"= comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface =",
"magnetization type: 0 for radial, 1 for parallel, 2 for HallBach []\"\"\", )",
"in two ways : - __init__ (arg1 = 1, arg3 = 5) every",
"object save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the",
"comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot",
"value # Magnet axial length # Type : float, min = 0 Lmag",
"value with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\"",
"of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value # Magnet axial length",
"pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot",
"self.Lmag: return False return True def as_dict(self): \"\"\"Convert this objet in a json",
"length # Type : float, min = 0 Lmag = property(fget=_get_Lmag, fset=_set_Lmag, doc=u\"\"\"Magnet",
"pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface",
"return False if other.type_magnetization != self.type_magnetization: return False if other.Lmag != self.Lmag: return",
"type(self): return False if other.mat_type != self.mat_type: return False if other.type_magnetization != self.type_magnetization:",
"!= self.mat_type: return False if other.type_magnetization != self.type_magnetization: return False if other.Lmag !=",
"FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass",
"\"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict content if \"mat_type\" in list(init_dict.keys()):",
"\"\"\"Compare two objects (skip parent)\"\"\" if type(other) != type(self): return False if other.mat_type",
"is not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite",
"Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be use in two ways :",
"a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization",
"self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name is added",
"method is available in all object save = save def __init__(self, mat_type=-1, type_magnetization=0,",
"json seriable dict (can be use in __init__) \"\"\" Magnet_dict = dict() if",
"for parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return",
"a Material object or a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else:",
"value if self._mat_type is not None: self._mat_type.parent = self # The Magnet material",
"value # Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2",
"all the properties to None (except pyleecan object)\"\"\" if self.mat_type is not None:",
"comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume",
"not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def _get_mat_type(self): \"\"\"getter of",
"\" + str(type(self.parent)) + \" object\" + linesep Magnet_str += \"mat_type = \"",
"value, \"Material\") self._mat_type = value if self._mat_type is not None: self._mat_type.parent = self",
"of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\",",
"Material class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening #",
"return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag",
"class is frozen, for now it's impossible to add new properties self._freeze() def",
"= 5) every parameters have name and default values for Matrix, None will",
"list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\"",
"d) d must be a dictionnary wiht every properties as keys ndarray or",
"1 for parallel, 2 for HallBach [] # Type : int, min =",
"object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None",
"Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot",
"every properties as keys ndarray or list can be given for Vector and",
"it\"\"\" from os import linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import",
"ways : - __init__ (arg1 = 1, arg3 = 5) every parameters have",
"be a dictionnary wiht every properties as keys ndarray or list can be",
"= value if self._mat_type is not None: self._mat_type.parent = self # The Magnet",
"doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self,",
"self.parent = None # mat_type can be None, a Material object or a",
"is None: Magnet_str += \"parent = None \" + linesep else: Magnet_str +=",
"is frozen, for now it's impossible to add new properties self._freeze() def __str__(self):",
"of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type is not None:",
"True def as_dict(self): \"\"\"Convert this objet in a json seriable dict (can be",
"is not None: self._mat_type.parent = self # The Magnet material # Type :",
"0 for radial, 1 for parallel, 2 for HallBach [] # Type :",
"readeable string (for print)\"\"\" Magnet_str = \"\" if self.parent is None: Magnet_str +=",
"comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume",
"other.Lmag != self.Lmag: return False return True def as_dict(self): \"\"\"Convert this objet in",
"type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet magnetization",
"None will call the default constructor - __init__ (init_dict = d) d must",
"if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent =",
"magnetization type: 0 for radial, 1 for parallel, 2 for HallBach [] #",
"is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material",
"int, min = 0, max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent",
"cf Methods.Machine.Magnet.plot plot = plot # save method is available in all object",
"to add new properties self._freeze() def __str__(self): \"\"\"Convert this objet in a readeable",
"5) every parameters have name and default values for Matrix, None will initialise",
"Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height",
"[] # Type : int, min = 0, max = 5 type_magnetization =",
"with an empty Matrix for pyleecan type, None will call the default constructor",
"import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import",
"cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf",
"The class is frozen, for now it's impossible to add new properties self._freeze()",
"!= self.Lmag: return False return True def as_dict(self): \"\"\"Convert this objet in a",
"Matrix, None will initialise the property with an empty Matrix for pyleecan type,",
"this objet in a json seriable dict (can be use in __init__) \"\"\"",
"# Initialisation by argument self.parent = None # mat_type can be None, a",
"keys ndarray or list can be given for Vector and Matrix object or",
"from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from",
"self.type_magnetization: return False if other.Lmag != self.Lmag: return False return True def as_dict(self):",
"other.mat_type != self.mat_type: return False if other.type_magnetization != self.type_magnetization: return False if other.Lmag",
"else: Magnet_str += \"parent = \" + str(type(self.parent)) + \" object\" + linesep",
"= Material() if init_dict is not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\",",
"+ linesep else: Magnet_str += \"parent = \" + str(type(self.parent)) + \" object\"",
"def _set_None(self): \"\"\"Set all the properties to None (except pyleecan object)\"\"\" if self.mat_type",
"dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict content if",
"class. Can be use in two ways : - __init__ (arg1 = 1,",
"parent)\"\"\" if type(other) != type(self): return False if other.mat_type != self.mat_type: return False",
"import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import",
"comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards",
"self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag",
"+ linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str +=",
"def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\"",
"pyleecan Object\"\"\" if mat_type == -1: mat_type = Material() if init_dict is not",
"import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import",
"self.type_magnetization = None self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type",
"0 for radial, 1 for parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self):",
"property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1 for parallel,",
"and Matrix object or dict can be given for pyleecan Object\"\"\" if mat_type",
"type(other) != type(self): return False if other.mat_type != self.mat_type: return False if other.type_magnetization",
"to None (except pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization =",
"comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards",
"= None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter",
"[]\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter",
"the default constructor - __init__ (init_dict = d) d must be a dictionnary",
"= init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument",
"else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class",
"and default values for Matrix, None will initialise the property with an empty",
"# Overwrite default value with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type =",
"type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1",
"for pyleecan type, None will call the default constructor - __init__ (init_dict =",
"\"\" if self.parent is None: Magnet_str += \"parent = None \" + linesep",
"as keys ndarray or list can be given for Vector and Matrix object",
"be given for Vector and Matrix object or dict can be given for",
"from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass",
"list can be given for Vector and Matrix object or dict can be",
"self._mat_type.parent = self # The Magnet material # Type : Material mat_type =",
"mat_type == -1: mat_type = Material() if init_dict is not None: # Initialisation",
"from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class",
"argument self.parent = None # mat_type can be None, a Material object or",
"\"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet magnetization type: 0 for",
"+= \"Lmag = \" + str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two",
"if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def",
"type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0,",
"cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf",
"(for print)\"\"\" Magnet_str = \"\" if self.parent is None: Magnet_str += \"parent =",
"init_dict is not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) #",
"return False return True def as_dict(self): \"\"\"Convert this objet in a json seriable",
"from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from",
"use in two ways : - __init__ (arg1 = 1, arg3 = 5)",
"False return True def as_dict(self): \"\"\"Convert this objet in a json seriable dict",
"\"\"\"Constructor of the class. Can be use in two ways : - __init__",
"type, None will call the default constructor - __init__ (init_dict = d) d",
"= None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag #",
"for Vector and Matrix object or dict can be given for pyleecan Object\"\"\"",
"Magnet_dict def _set_None(self): \"\"\"Set all the properties to None (except pyleecan object)\"\"\" if",
"# mat_type can be None, a Material object or a dict if isinstance(mat_type,",
"def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization =",
"Material() if init_dict is not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\",",
"\"parent = None \" + linesep else: Magnet_str += \"parent = \" +",
"linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import",
"__init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be use in",
"all object save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of",
"self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value):",
"be use in __init__) \"\"\" Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"]",
"given for Vector and Matrix object or dict can be given for pyleecan",
"pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag =",
"for HallBach [] # Type : int, min = 0, max = 5",
"2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def",
"Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter",
"None (except pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None",
"from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from",
"for now it's impossible to add new properties self._freeze() def __str__(self): \"\"\"Convert this",
"dict (can be use in __init__) \"\"\" Magnet_dict = dict() if self.mat_type is",
"\" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \" + str(self.Lmag) return",
"= None \" + linesep else: Magnet_str += \"parent = \" + str(type(self.parent))",
"mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type is not None: self._mat_type.parent",
"1, arg3 = 5) every parameters have name and default values for Matrix,",
"every parameters have name and default values for Matrix, None will initialise the",
"# Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2 for",
"constructor - __init__ (init_dict = d) d must be a dictionnary wiht every",
"if other.type_magnetization != self.type_magnetization: return False if other.Lmag != self.Lmag: return False return",
"str(type(self.parent)) + \" object\" + linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict())",
"= \"\" if self.parent is None: Magnet_str += \"parent = None \" +",
"pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass",
"self.parent is None: Magnet_str += \"parent = None \" + linesep else: Magnet_str",
"pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards",
"= \" + str(type(self.parent)) + \" object\" + linesep Magnet_str += \"mat_type =",
"comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface",
"edit it\"\"\" from os import linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save",
"= 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height =",
"# cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass #",
"cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf",
"Matrix object or dict can be given for pyleecan Object\"\"\" if mat_type ==",
"# Type : float, min = 0 Lmag = property(fget=_get_Lmag, fset=_set_Lmag, doc=u\"\"\"Magnet axial",
"= \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the properties to None (except",
"import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import",
"plot # save method is available in all object save = save def",
"arg3 = 5) every parameters have name and default values for Matrix, None",
"import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import",
"if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] =",
"dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"]",
"parameters have name and default values for Matrix, None will initialise the property",
"Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value):",
"pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening =",
"None \" + linesep else: Magnet_str += \"parent = \" + str(type(self.parent)) +",
"the property with an empty Matrix for pyleecan type, None will call the",
"= comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume =",
"= 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for",
"list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation",
"False if other.type_magnetization != self.type_magnetization: return False if other.Lmag != self.Lmag: return False",
"type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be use in two ways",
"Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name is added to",
"self._Lmag = value # Magnet axial length # Type : float, min =",
"= d) d must be a dictionnary wiht every properties as keys ndarray",
"default values for Matrix, None will initialise the property with an empty Matrix",
"add new properties self._freeze() def __str__(self): \"\"\"Convert this objet in a readeable string",
"Magnet_dict[\"Lmag\"] = self.Lmag # The class name is added to the dict fordeserialisation",
"+ linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) + linesep + linesep",
"is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def",
"fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def",
"Magnet_str += \"parent = None \" + linesep else: Magnet_str += \"parent =",
"import check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening",
"objet in a json seriable dict (can be use in __init__) \"\"\" Magnet_dict",
"will call the default constructor - __init__ (init_dict = d) d must be",
"Vmax=5) self._type_magnetization = value # Permanent magnet magnetization type: 0 for radial, 1",
"linesep + linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str",
"Magnet_str += \"Lmag = \" + str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare",
"self.Lmag # The class name is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"]",
"= \" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization = \"",
"in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent = None #",
"None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The",
"added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self):",
"self.Lmag = Lmag # The class is frozen, for now it's impossible to",
"Magnet material # Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet",
"type: 0 for radial, 1 for parallel, 2 for HallBach []\"\"\", ) def",
"linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str",
"if type(other) != type(self): return False if other.mat_type != self.mat_type: return False if",
"string (for print)\"\"\" Magnet_str = \"\" if self.parent is None: Magnet_str += \"parent",
") def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of",
"by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict content",
"impossible to add new properties self._freeze() def __str__(self): \"\"\"Convert this objet in a",
"+= \"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \"",
"return Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other) !=",
"def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be use",
"of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\")",
"# cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening #",
"= \" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \" + str(self.Lmag)",
"of the class. Can be use in two ways : - __init__ (arg1",
"other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other) != type(self): return False if",
"\"Lmag = \" + str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two objects",
"magnet magnetization type: 0 for radial, 1 for parallel, 2 for HallBach []\"\"\",",
"in a readeable string (for print)\"\"\" Magnet_str = \"\" if self.parent is None:",
"str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \" + str(self.Lmag) return Magnet_str def",
"fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the properties",
"max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0",
"properties as keys ndarray or list can be given for Vector and Matrix",
"save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be",
"\"mat_type = \" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization =",
"available in all object save = save def __init__(self, mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None):",
"def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other) != type(self): return",
"# The class is frozen, for now it's impossible to add new properties",
"Type : int, min = 0, max = 5 type_magnetization = property( fget=_get_type_magnetization,",
"None, a Material object or a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type)",
"_set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value #",
"None will initialise the property with an empty Matrix for pyleecan type, None",
"Initialisation by argument self.parent = None # mat_type can be None, a Material",
"pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from",
"pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check",
"= 1, arg3 = 5) every parameters have name and default values for",
"has been generated, you shouldn't edit it\"\"\" from os import linesep from pyleecan.Classes.check",
"Type : float, min = 0 Lmag = property(fget=_get_Lmag, fset=_set_Lmag, doc=u\"\"\"Magnet axial length\"\"\")",
"as_dict(self): \"\"\"Convert this objet in a json seriable dict (can be use in",
"(can be use in __init__) \"\"\" Magnet_dict = dict() if self.mat_type is None:",
"self.mat_type is not None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def _get_mat_type(self):",
"not None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default",
"__init__) \"\"\" Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else:",
"the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all",
"if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization =",
"given for pyleecan Object\"\"\" if mat_type == -1: mat_type = Material() if init_dict",
"use in __init__) \"\"\" Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] =",
"ndarray or list can be given for Vector and Matrix object or dict",
"[\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict content if \"mat_type\" in",
"_get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\",",
"list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent = None # mat_type",
"__init__ (init_dict = d) d must be a dictionnary wiht every properties as",
"now it's impossible to add new properties self._freeze() def __str__(self): \"\"\"Convert this objet",
"be given for pyleecan Object\"\"\" if mat_type == -1: mat_type = Material() if",
"\"\"\" Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"]",
"coding: utf-8 -*- \"\"\"Warning : this file has been generated, you shouldn't edit",
"comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface",
"seriable dict (can be use in __init__) \"\"\" Magnet_dict = dict() if self.mat_type",
"from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from",
"check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening",
"self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name is added to the dict",
"class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf",
"+ linesep + linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) + linesep",
"it's impossible to add new properties self._freeze() def __str__(self): \"\"\"Convert this objet in",
"pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material",
"None: Magnet_str += \"parent = None \" + linesep else: Magnet_str += \"parent",
"0, max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type:",
"if mat_type == -1: mat_type = Material() if init_dict is not None: #",
"Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface",
"values for Matrix, None will initialise the property with an empty Matrix for",
"return False if other.Lmag != self.Lmag: return False return True def as_dict(self): \"\"\"Convert",
": - __init__ (arg1 = 1, arg3 = 5) every parameters have name",
"= dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict()",
"Vector and Matrix object or dict can be given for pyleecan Object\"\"\" if",
"Object\"\"\" if mat_type == -1: mat_type = Material() if init_dict is not None:",
"(init_dict = d) d must be a dictionnary wiht every properties as keys",
"# The Magnet material # Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type,",
"\"\"\"Warning : this file has been generated, you shouldn't edit it\"\"\" from os",
"parallel, 2 for HallBach [] # Type : int, min = 0, max",
"# cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards #",
"is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"]",
"return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type =",
"\"Material\") self._mat_type = value if self._mat_type is not None: self._mat_type.parent = self #",
"can be given for Vector and Matrix object or dict can be given",
"Magnet_str = \"\" if self.parent is None: Magnet_str += \"parent = None \"",
"cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface # cf",
"comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface",
"mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in",
"HallBach [] # Type : int, min = 0, max = 5 type_magnetization",
"from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1",
"+ str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if",
"for parallel, 2 for HallBach [] # Type : int, min = 0,",
"= comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards =",
"_set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value",
"content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization",
"utf-8 -*- \"\"\"Warning : this file has been generated, you shouldn't edit it\"\"\"",
"2 for HallBach [] # Type : int, min = 0, max =",
"-*- \"\"\"Warning : this file has been generated, you shouldn't edit it\"\"\" from",
"Vmin=0) self._Lmag = value # Magnet axial length # Type : float, min",
"initialise the property with an empty Matrix for pyleecan type, None will call",
"\" + str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\"",
"import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import",
"for radial, 1 for parallel, 2 for HallBach [] # Type : int,",
"!= self.type_magnetization: return False if other.Lmag != self.Lmag: return False return True def",
"- __init__ (arg1 = 1, arg3 = 5) every parameters have name and",
"if other.Lmag != self.Lmag: return False return True def as_dict(self): \"\"\"Convert this objet",
"+= \"parent = \" + str(type(self.parent)) + \" object\" + linesep Magnet_str +=",
"be use in two ways : - __init__ (arg1 = 1, arg3 =",
"= None self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def",
"= value # Magnet axial length # Type : float, min = 0",
"is_outwards # cf Methods.Machine.Magnet.plot plot = plot # save method is available in",
"have name and default values for Matrix, None will initialise the property with",
"else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag # The class",
"save method is available in all object save = save def __init__(self, mat_type=-1,",
"+ str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \" + str(self.Lmag) return Magnet_str",
"object or a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type =",
"value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet magnetization type: 0",
"mat_type = Material() if init_dict is not None: # Initialisation by dict check_init_dict(init_dict,",
"purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the properties to",
"or a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type",
"The Magnet material # Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The",
"check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet magnetization type:",
"comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError",
"= property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1 for",
"+= \"parent = None \" + linesep else: Magnet_str += \"parent = \"",
"mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of",
"self._mat_type is not None: self._mat_type.parent = self # The Magnet material # Type",
"+ linesep Magnet_str += \"Lmag = \" + str(self.Lmag) return Magnet_str def __eq__(self,",
"Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str +=",
"Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag =",
"if self.parent is None: Magnet_str += \"parent = None \" + linesep else:",
"= self # The Magnet material # Type : Material mat_type = property(",
"+ str(type(self.parent)) + \" object\" + linesep Magnet_str += \"mat_type = \" +",
"\"float\", Vmin=0) self._Lmag = value # Magnet axial length # Type : float,",
"pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume",
"from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from",
"two ways : - __init__ (arg1 = 1, arg3 = 5) every parameters",
"\" + linesep else: Magnet_str += \"parent = \" + str(type(self.parent)) + \"",
"\"\"\"Set all the properties to None (except pyleecan object)\"\"\" if self.mat_type is not",
"HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value):",
"self # The Magnet material # Type : Material mat_type = property( fget=_get_mat_type,",
"= mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag # The class is frozen,",
"Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot = plot # save method",
"None self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self,",
"comp_surface = comp_surface # cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards",
"dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the",
"\"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type is not",
"= is_outwards # cf Methods.Machine.Magnet.plot plot = plot # save method is available",
"None: self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\"",
"for radial, 1 for parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter",
"\"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value # Magnet axial",
"fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2 for",
"Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening",
"for pyleecan Object\"\"\" if mat_type == -1: mat_type = Material() if init_dict is",
"comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot",
"Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent = None # mat_type can",
"Magnet axial length # Type : float, min = 0 Lmag = property(fget=_get_Lmag,",
"mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag # The class is frozen, for",
"Material object or a dict if isinstance(mat_type, dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type",
"def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value",
"this objet in a readeable string (for print)\"\"\" Magnet_str = \"\" if self.parent",
"in a json seriable dict (can be use in __init__) \"\"\" Magnet_dict =",
"None: # Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value",
"value, \"float\", Vmin=0) self._Lmag = value # Magnet axial length # Type :",
"# cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height #",
"dict can be given for pyleecan Object\"\"\" if mat_type == -1: mat_type =",
"Overwrite default value with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"]",
"can be None, a Material object or a dict if isinstance(mat_type, dict): self.mat_type",
"= init_dict[\"Lmag\"] # Initialisation by argument self.parent = None # mat_type can be",
"# Initialisation by dict check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with",
"mat_type can be None, a Material object or a dict if isinstance(mat_type, dict):",
"= Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag #",
"cf Methods.Machine.Magnet.comp_volume comp_volume = comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf",
"check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value # Magnet axial length # Type",
"\"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"]",
"value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value #",
"pyleecan.Functions.save import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height",
"to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set",
"\"Lmag\"]) # Overwrite default value with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type",
"os import linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save from",
"min = 0, max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet",
"of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet",
"dictionnary wiht every properties as keys ndarray or list can be given for",
"return False if other.mat_type != self.mat_type: return False if other.type_magnetization != self.type_magnetization: return",
"None # mat_type can be None, a Material object or a dict if",
"self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag # The class is",
"other.type_magnetization != self.type_magnetization: return False if other.Lmag != self.Lmag: return False return True",
"comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening",
"\"parent = \" + str(type(self.parent)) + \" object\" + linesep Magnet_str += \"mat_type",
"def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\"",
"self.type_magnetization = type_magnetization self.Lmag = Lmag # The class is frozen, for now",
"name and default values for Matrix, None will initialise the property with an",
"\"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value,",
"import linesep from pyleecan.Classes.check import check_init_dict, check_var from pyleecan.Functions.save import save from pyleecan.Classes.frozen",
"= Lmag # The class is frozen, for now it's impossible to add",
": int, min = 0, max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization,",
"False if other.Lmag != self.Lmag: return False return True def as_dict(self): \"\"\"Convert this",
"= self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name is",
"return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5)",
"properties to None (except pyleecan object)\"\"\" if self.mat_type is not None: self.mat_type._set_None() self.type_magnetization",
"str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization) +",
"Matrix for pyleecan type, None will call the default constructor - __init__ (init_dict",
"Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag = Lmag # The",
"# Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" )",
"\" object\" + linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) + linesep",
"linesep else: Magnet_str += \"parent = \" + str(type(self.parent)) + \" object\" +",
"__eq__(self, other): \"\"\"Compare two objects (skip parent)\"\"\" if type(other) != type(self): return False",
"# The class name is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] =",
"# cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot = plot #",
"is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot = plot # save method is",
"in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] #",
"two objects (skip parent)\"\"\" if type(other) != type(self): return False if other.mat_type !=",
"Type : Material mat_type = property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def",
"Vmin=0, Vmax=5) self._type_magnetization = value # Permanent magnet magnetization type: 0 for radial,",
"import save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import",
"\"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization = value # Permanent",
"doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2 for HallBach",
"objet in a readeable string (for print)\"\"\" Magnet_str = \"\" if self.parent is",
"_set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type",
"False if other.mat_type != self.mat_type: return False if other.type_magnetization != self.type_magnetization: return False",
"# cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening = comp_ratio_opening # cf Methods.Machine.Magnet.comp_surface comp_surface = comp_surface #",
"None: self._mat_type.parent = self # The Magnet material # Type : Material mat_type",
": this file has been generated, you shouldn't edit it\"\"\" from os import",
"in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"] if",
"shouldn't edit it\"\"\" from os import linesep from pyleecan.Classes.check import check_init_dict, check_var from",
"generated, you shouldn't edit it\"\"\" from os import linesep from pyleecan.Classes.check import check_init_dict,",
"Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass",
"pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening",
"a json seriable dict (can be use in __init__) \"\"\" Magnet_dict = dict()",
"__str__(self): \"\"\"Convert this objet in a readeable string (for print)\"\"\" Magnet_str = \"\"",
"file has been generated, you shouldn't edit it\"\"\" from os import linesep from",
"comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass",
"comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass",
"pyleecan type, None will call the default constructor - __init__ (init_dict = d)",
"of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\",",
"-1: mat_type = Material() if init_dict is not None: # Initialisation by dict",
"from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import plot from",
"self.mat_type._set_None() self.type_magnetization = None self.Lmag = None def _get_mat_type(self): \"\"\"getter of mat_type\"\"\" return",
"if other.mat_type != self.mat_type: return False if other.type_magnetization != self.type_magnetization: return False if",
"return Magnet_dict def _set_None(self): \"\"\"Set all the properties to None (except pyleecan object)\"\"\"",
"comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import comp_ratio_opening",
"def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\" return self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\"",
"or list can be given for Vector and Matrix object or dict can",
"# cf Methods.Machine.Magnet.plot plot = plot # save method is available in all",
"init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by argument self.parent",
"this file has been generated, you shouldn't edit it\"\"\" from os import linesep",
"comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot = plot",
"\"\"\"getter of mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value,",
"a readeable string (for print)\"\"\" Magnet_str = \"\" if self.parent is None: Magnet_str",
"None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization Magnet_dict[\"Lmag\"] =",
"or dict can be given for pyleecan Object\"\"\" if mat_type == -1: mat_type",
"import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height from pyleecan.Methods.Machine.Magnet.comp_mass import comp_mass from pyleecan.Methods.Machine.Magnet.comp_ratio_opening import",
"Magnet_dict[\"__class__\"] = \"Magnet\" return Magnet_dict def _set_None(self): \"\"\"Set all the properties to None",
"must be a dictionnary wiht every properties as keys ndarray or list can",
"\"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()): type_magnetization = init_dict[\"type_magnetization\"]",
"mat_type\"\"\" return self._mat_type def _set_mat_type(self, value): \"\"\"setter of mat_type\"\"\" check_var(\"mat_type\", value, \"Material\") self._mat_type",
"pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1 #",
"in __init__) \"\"\" Magnet_dict = dict() if self.mat_type is None: Magnet_dict[\"mat_type\"] = None",
"= plot # save method is available in all object save = save",
"\" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization = \" +",
"Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value # Magnet axial length #",
"= property( fget=_get_mat_type, fset=_set_mat_type, doc=u\"\"\"The Magnet material\"\"\" ) def _get_type_magnetization(self): \"\"\"getter of type_magnetization\"\"\"",
"= comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height = comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass =",
"fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2",
"mat_type=-1, type_magnetization=0, Lmag=0.95, init_dict=None): \"\"\"Constructor of the class. Can be use in two",
"pyleecan.Methods.Machine.Magnet.plot import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass):",
"Permanent magnet magnetization type: 0 for radial, 1 for parallel, 2 for HallBach",
"cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot = plot # save",
"with init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in",
"properties self._freeze() def __str__(self): \"\"\"Convert this objet in a readeable string (for print)\"\"\"",
"be None, a Material object or a dict if isinstance(mat_type, dict): self.mat_type =",
"Can be use in two ways : - __init__ (arg1 = 1, arg3",
"axial length # Type : float, min = 0 Lmag = property(fget=_get_Lmag, fset=_set_Lmag,",
"import comp_surface from pyleecan.Methods.Machine.Magnet.comp_volume import comp_volume from pyleecan.Methods.Machine.Magnet.is_outwards import is_outwards from pyleecan.Methods.Machine.Magnet.plot import",
"frozen, for now it's impossible to add new properties self._freeze() def __str__(self): \"\"\"Convert",
"InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening",
"import plot from pyleecan.Classes.check import InitUnKnowClassError from pyleecan.Classes.Material import Material class Magnet(FrozenClass): VERSION",
"\"\"\"Convert this objet in a json seriable dict (can be use in __init__)",
"will initialise the property with an empty Matrix for pyleecan type, None will",
"= self.Lmag # The class name is added to the dict fordeserialisation purpose",
"you shouldn't edit it\"\"\" from os import linesep from pyleecan.Classes.check import check_init_dict, check_var",
"plot = plot # save method is available in all object save =",
"self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag =",
"radial, 1 for parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of",
"_get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag def _set_Lmag(self, value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\",",
"call the default constructor - __init__ (init_dict = d) d must be a",
"empty Matrix for pyleecan type, None will call the default constructor - __init__",
"an empty Matrix for pyleecan type, None will call the default constructor -",
"self.mat_type is None: Magnet_dict[\"mat_type\"] = None else: Magnet_dict[\"mat_type\"] = self.mat_type.as_dict() Magnet_dict[\"type_magnetization\"] = self.type_magnetization",
"class name is added to the dict fordeserialisation purpose Magnet_dict[\"__class__\"] = \"Magnet\" return",
"def as_dict(self): \"\"\"Convert this objet in a json seriable dict (can be use",
"by argument self.parent = None # mat_type can be None, a Material object",
"+ \" object\" + linesep Magnet_str += \"mat_type = \" + str(self.mat_type.as_dict()) +",
"magnet magnetization type: 0 for radial, 1 for parallel, 2 for HallBach []",
"+= \"mat_type = \" + str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization",
"dict): self.mat_type = Material(init_dict=mat_type) else: self.mat_type = mat_type self.type_magnetization = type_magnetization self.Lmag =",
"self._type_magnetization def _set_type_magnetization(self, value): \"\"\"setter of type_magnetization\"\"\" check_var(\"type_magnetization\", value, \"int\", Vmin=0, Vmax=5) self._type_magnetization",
"value): \"\"\"setter of Lmag\"\"\" check_var(\"Lmag\", value, \"float\", Vmin=0) self._Lmag = value # Magnet",
"print)\"\"\" Magnet_str = \"\" if self.parent is None: Magnet_str += \"parent = None",
"save from pyleecan.Classes.frozen import FrozenClass from pyleecan.Methods.Machine.Magnet.comp_angle_opening import comp_angle_opening from pyleecan.Methods.Machine.Magnet.comp_height import comp_height",
"init_dict[\"Lmag\"] # Initialisation by argument self.parent = None # mat_type can be None,",
"check_var(\"mat_type\", value, \"Material\") self._mat_type = value if self._mat_type is not None: self._mat_type.parent =",
"= comp_height # cf Methods.Machine.Magnet.comp_mass comp_mass = comp_mass # cf Methods.Machine.Magnet.comp_ratio_opening comp_ratio_opening =",
"type_magnetization = init_dict[\"type_magnetization\"] if \"Lmag\" in list(init_dict.keys()): Lmag = init_dict[\"Lmag\"] # Initialisation by",
"init_dict content if \"mat_type\" in list(init_dict.keys()): mat_type = init_dict[\"mat_type\"] if \"type_magnetization\" in list(init_dict.keys()):",
"\"type_magnetization = \" + str(self.type_magnetization) + linesep Magnet_str += \"Lmag = \" +",
"= comp_volume # cf Methods.Machine.Magnet.is_outwards is_outwards = is_outwards # cf Methods.Machine.Magnet.plot plot =",
"object or dict can be given for pyleecan Object\"\"\" if mat_type == -1:",
"+ str(self.mat_type.as_dict()) + linesep + linesep Magnet_str += \"type_magnetization = \" + str(self.type_magnetization)",
"!= type(self): return False if other.mat_type != self.mat_type: return False if other.type_magnetization !=",
"= 0, max = 5 type_magnetization = property( fget=_get_type_magnetization, fset=_set_type_magnetization, doc=u\"\"\"Permanent magnet magnetization",
"VERSION = 1 # cf Methods.Machine.Magnet.comp_angle_opening comp_angle_opening = comp_angle_opening # cf Methods.Machine.Magnet.comp_height comp_height",
"parallel, 2 for HallBach []\"\"\", ) def _get_Lmag(self): \"\"\"getter of Lmag\"\"\" return self._Lmag",
"= \" + str(self.Lmag) return Magnet_str def __eq__(self, other): \"\"\"Compare two objects (skip",
"check_init_dict(init_dict, [\"mat_type\", \"type_magnetization\", \"Lmag\"]) # Overwrite default value with init_dict content if \"mat_type\"",
"Methods.Machine.Magnet.plot plot = plot # save method is available in all object save",
"= None # mat_type can be None, a Material object or a dict",
"return True def as_dict(self): \"\"\"Convert this objet in a json seriable dict (can",
"= self.type_magnetization Magnet_dict[\"Lmag\"] = self.Lmag # The class name is added to the"
] |
[
"= MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return",
"from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore(",
"def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return",
"tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir):",
"from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder",
") @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder(",
"def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store",
"builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture",
"JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs",
"\"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store)",
"test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder =",
"key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run()",
"MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir) / \"test.json\") loadfn(Path(tmpdir) / \"test.json\")",
"/ \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\"",
"@pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store,",
"pathlib import Path import pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization import",
"return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\")",
"loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return",
"@pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\",",
"materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs,",
"tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store =",
"builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() ==",
"from pathlib import Path import pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization",
"dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir):",
"electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" )",
"= MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def",
"MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def",
"assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(),",
"def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir)",
"@pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir):",
"MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir):",
"= ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3",
") @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return",
"from maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import",
"def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store,",
"): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count()",
"dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert",
"/ \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store,",
"electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, )",
"bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder(",
"builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir) / \"test.json\")",
"import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from",
"return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs,",
"test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\",",
"MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def",
"maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder",
"= ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir) / \"test.json\") loadfn(Path(tmpdir)",
"import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def",
"test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ):",
"materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store():",
"pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure",
"ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir) / \"test.json\") loadfn(Path(tmpdir) /",
"bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run()",
"== 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() )",
"electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder =",
"MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import",
"\"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder =",
"monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\")",
"materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder",
"bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore(",
"@pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store",
"3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(),",
"Path import pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn",
"JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir /",
"materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir /",
"emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" )",
"import pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from",
"\"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" )",
") builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(),",
"tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs,",
"def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store,",
"def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\"",
"emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir",
"def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture",
"@pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store):",
"MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\")",
"/ \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder",
"JSONStore, MemoryStore from monty.serialization import dumpfn, loadfn from emmet.builders.materials.electronic_structure import ElectronicStructureBuilder from emmet.builders.vasp.materials",
"key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def",
"return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir",
") def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store,",
"builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(),",
"dos_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_dos_objs.json.gz\", key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store,",
"import ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir /",
"return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture def dos_fs(test_dir): return JSONStore( test_dir",
"JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\") def materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder",
"key=\"task_id\" ) def test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder(",
"materials_store(tasks_store): materials_store = MemoryStore(key=\"material_id\") builder = MaterialsBuilder(tasks=tasks_store, materials=materials_store) builder.run() return materials_store @pytest.fixture def",
"builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore(",
"import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\" ) @pytest.fixture(scope=\"session\")",
"materials=materials_store) builder.run() return materials_store @pytest.fixture def electronic_structure_store(): return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return",
"test_electronic_structure_builder( tasks_store, materials_store, electronic_structure_store, bandstructure_fs, dos_fs ): builder = ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store,",
"import Path import pytest from maggma.stores import JSONStore, MemoryStore from monty.serialization import dumpfn,",
"electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore()",
"ElectronicStructureBuilder from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\",",
"dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(),",
"test_serialization(tmpdir): builder = ElectronicStructureBuilder( MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore(), MemoryStore() ) dumpfn(builder.as_dict(), Path(tmpdir) /",
"from emmet.builders.vasp.materials import MaterialsBuilder @pytest.fixture(scope=\"session\") def tasks_store(test_dir): return JSONStore( test_dir / \"electronic_structure/es_task_docs.json.gz\", key=\"task_id\"",
"return MemoryStore(key=\"material_id\") @pytest.fixture def bandstructure_fs(test_dir): return JSONStore( test_dir / \"electronic_structure/es_bs_objs.json.gz\", key=\"task_id\" ) @pytest.fixture",
"ElectronicStructureBuilder( tasks=tasks_store, materials=materials_store, electronic_structure=electronic_structure_store, bandstructure_fs=bandstructure_fs, dos_fs=dos_fs, ) builder.run() assert electronic_structure_store.count() == 3 def"
] |
[
"a, b = 0, 0 for i in range(T): n, c = map(int,",
"= map(int, input().split(' ')) a += n * c b += c *",
"input().split(' ')) a += n * c b += c * 100 print(\"{:.4f}\".format(a",
"= int(input()) except EOFError: break a, b = 0, 0 for i in",
"c = map(int, input().split(' ')) a += n * c b += c",
"True: try: T = int(input()) except EOFError: break a, b = 0, 0",
"try: T = int(input()) except EOFError: break a, b = 0, 0 for",
"0 for i in range(T): n, c = map(int, input().split(' ')) a +=",
"except EOFError: break a, b = 0, 0 for i in range(T): n,",
"a += n * c b += c * 100 print(\"{:.4f}\".format(a / b))",
"b = 0, 0 for i in range(T): n, c = map(int, input().split('",
"for i in range(T): n, c = map(int, input().split(' ')) a += n",
"EOFError: break a, b = 0, 0 for i in range(T): n, c",
"range(T): n, c = map(int, input().split(' ')) a += n * c b",
"map(int, input().split(' ')) a += n * c b += c * 100",
"= 0, 0 for i in range(T): n, c = map(int, input().split(' '))",
"int(input()) except EOFError: break a, b = 0, 0 for i in range(T):",
"i in range(T): n, c = map(int, input().split(' ')) a += n *",
"break a, b = 0, 0 for i in range(T): n, c =",
"')) a += n * c b += c * 100 print(\"{:.4f}\".format(a /",
"n, c = map(int, input().split(' ')) a += n * c b +=",
"T = int(input()) except EOFError: break a, b = 0, 0 for i",
"in range(T): n, c = map(int, input().split(' ')) a += n * c",
"<filename>uri/2533.py<gh_stars>0 while True: try: T = int(input()) except EOFError: break a, b =",
"0, 0 for i in range(T): n, c = map(int, input().split(' ')) a",
"while True: try: T = int(input()) except EOFError: break a, b = 0,"
] |
[
"URL: {url}', file=sys.stderr) if response is None or response.status_code != 200: print(f'Error {response.status_code}',",
"args = parse_io() source_url = args.input output_file = args.output output_dir, file_name = os.path.split(output_file)",
"print(f'ERROR, something went wrong while downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip')",
"#!/usr/bin/env python \"\"\" Download needed raw data Author: <NAME> Copyright (c) 2021 -",
"target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def",
"- <NAME> License: See the LICENSE file. Date: 2021-02-05 \"\"\" import os import",
"file from URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length',",
"URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with",
"f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong",
"shutil import tarfile from tqdm import tqdm from parse_args import parse_io def download_url(url,",
"response = None try: response = requests.get(url, stream=True) except: print(f'Connection error occurred trying",
"tqdm from parse_args import parse_io def download_url(url, output_dir, file_name): response = None try:",
"zipfile import shutil import tarfile from tqdm import tqdm from parse_args import parse_io",
"if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 #",
"response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file from URL: {url}') return None",
"def download_url(url, output_dir, file_name): response = None try: response = requests.get(url, stream=True) except:",
"int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar:",
"print(f'Error {response.status_code}', f'while downloading file from URL: {url}') return None tmp_fd, tmp_fn =",
"(c) 2021 - <NAME> License: See the LICENSE file. Date: 2021-02-05 \"\"\" import",
"any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target)",
"import tarfile from tqdm import tqdm from parse_args import parse_io def download_url(url, output_dir,",
"Copyright (c) 2021 - <NAME> License: See the LICENSE file. Date: 2021-02-05 \"\"\"",
"python \"\"\" Download needed raw data Author: <NAME> Copyright (c) 2021 - <NAME>",
"See the LICENSE file. Date: 2021-02-05 \"\"\" import os import time import random",
"went wrong while downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not",
"the LICENSE file. Date: 2021-02-05 \"\"\" import os import time import random import",
"Author: <NAME> Copyright (c) 2021 - <NAME> License: See the LICENSE file. Date:",
"stream=True) except: print(f'Connection error occurred trying to get URL: {url}', file=sys.stderr) if response",
"= 1024 # 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes",
"total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}') target = os.path.join(output_dir, file_name) if",
"data Author: <NAME> Copyright (c) 2021 - <NAME> License: See the LICENSE file.",
"os.remove(target) else: shutil.move(tmp_fn, target) return target def main(): args = parse_io() source_url =",
"f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target)",
"import tempfile import sys import zipfile import shutil import tarfile from tqdm import",
"from tqdm import tqdm from parse_args import parse_io def download_url(url, output_dir, file_name): response",
"os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar:",
"None or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file from URL: {url}')",
"total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)",
"shutil.move(tmp_fn, target) return target def main(): args = parse_io() source_url = args.input output_file",
"downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target,",
"file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn)",
"url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return",
"with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def main():",
"args.input output_file = args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url,",
"and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar')",
"import tqdm from parse_args import parse_io def download_url(url, output_dir, file_name): response = None",
"parse_args import parse_io def download_url(url, output_dir, file_name): response = None try: response =",
"= requests.get(url, stream=True) except: print(f'Connection error occurred trying to get URL: {url}', file=sys.stderr)",
"'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None:",
"block_size = 1024 # 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if",
"total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while downloading",
"random import requests import tempfile import sys import zipfile import shutil import tarfile",
"else: shutil.move(tmp_fn, target) return target def main(): args = parse_io() source_url = args.input",
"needed raw data Author: <NAME> Copyright (c) 2021 - <NAME> License: See the",
"parse_io def download_url(url, output_dir, file_name): response = None try: response = requests.get(url, stream=True)",
"None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as",
"not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for",
"parse_io() source_url = args.input output_file = args.output output_dir, file_name = os.path.split(output_file) if not",
"= os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5) if __name__ ==",
"trying to get URL: {url}', file=sys.stderr) if response is None or response.status_code !=",
"for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else:",
"except: print(f'Connection error occurred trying to get URL: {url}', file=sys.stderr) if response is",
"f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else:",
"= args.input output_file = args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir)",
"= os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as",
"tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out,",
"tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def main(): args",
"downloading file from URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes =",
"as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def main(): args =",
"return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb')",
"with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes",
"response is None or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file from",
"int(total_size_in_bytes) block_size = 1024 # 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data)",
"import shutil import tarfile from tqdm import tqdm from parse_args import parse_io def",
"elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir)",
"raw data Author: <NAME> Copyright (c) 2021 - <NAME> License: See the LICENSE",
"download_url(url, output_dir, file_name): response = None try: response = requests.get(url, stream=True) except: print(f'Connection",
"with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in",
"f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def main(): args = parse_io() source_url",
"zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]):",
"total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1 KB for data in response.iter_content(block_size):",
"tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes =",
"file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5) if __name__",
"def main(): args = parse_io() source_url = args.input output_file = args.output output_dir, file_name",
"or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file from URL: {url}') return",
"file=sys.stderr) if response is None or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading",
"zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el",
"2021 - <NAME> License: See the LICENSE file. Date: 2021-02-05 \"\"\" import os",
"tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB',",
"unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size",
"total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1",
"import random import requests import tempfile import sys import zipfile import shutil import",
"f'while downloading file from URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes",
"None try: response = requests.get(url, stream=True) except: print(f'Connection error occurred trying to get",
"unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes)",
"{response.status_code}', f'while downloading file from URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp()",
"{url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w',",
"License: See the LICENSE file. Date: 2021-02-05 \"\"\" import os import time import",
"import parse_io def download_url(url, output_dir, file_name): response = None try: response = requests.get(url,",
"and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}') target =",
"if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5) if __name__ == '__main__': main()",
"progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}') target = os.path.join(output_dir,",
"target def main(): args = parse_io() source_url = args.input output_file = args.output output_dir,",
"if response is None or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file",
"wrong while downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn):",
"time import random import requests import tempfile import sys import zipfile import shutil",
"import zipfile import shutil import tarfile from tqdm import tqdm from parse_args import",
"error occurred trying to get URL: {url}', file=sys.stderr) if response is None or",
"while downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with",
"if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while",
"response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something",
"progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went",
"0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}') target",
"from parse_args import parse_io def download_url(url, output_dir, file_name): response = None try: response",
"target) return target def main(): args = parse_io() source_url = args.input output_file =",
"as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size =",
"import sys import zipfile import shutil import tarfile from tqdm import tqdm from",
"2021-02-05 \"\"\" import os import time import random import requests import tempfile import",
"for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n !=",
"f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as",
"os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is",
"requests import tempfile import sys import zipfile import shutil import tarfile from tqdm",
"args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5)",
"in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR,",
"in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target)",
"file. Date: 2021-02-05 \"\"\" import os import time import random import requests import",
"file_name): response = None try: response = requests.get(url, stream=True) except: print(f'Connection error occurred",
"requests.get(url, stream=True) except: print(f'Connection error occurred trying to get URL: {url}', file=sys.stderr) if",
"progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024",
"el in url.split('?')]): shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn,",
"print(f'Connection error occurred trying to get URL: {url}', file=sys.stderr) if response is None",
"else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1 KB for data in",
"something went wrong while downloading {url}') target = os.path.join(output_dir, file_name) if target.endswith('.zip') and",
"return target def main(): args = parse_io() source_url = args.input output_file = args.output",
"= int(total_size_in_bytes) block_size = 1024 # 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data))",
"to get URL: {url}', file=sys.stderr) if response is None or response.status_code != 200:",
"tqdm import tqdm from parse_args import parse_io def download_url(url, output_dir, file_name): response =",
"data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:",
"output_dir, file_name): response = None try: response = requests.get(url, stream=True) except: print(f'Connection error",
"\\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content) else: total_size_in_bytes",
"shutil.move(tmp_fn, target) with tarfile.open(target) as f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target",
"Download needed raw data Author: <NAME> Copyright (c) 2021 - <NAME> License: See",
"source_url = args.input output_file = args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir):",
"zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target)",
"f_tar: f_tar.extractall(output_dir) os.remove(target) else: shutil.move(tmp_fn, target) return target def main(): args = parse_io()",
"output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5) if",
"<NAME> Copyright (c) 2021 - <NAME> License: See the LICENSE file. Date: 2021-02-05",
"# 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0",
"import os import time import random import requests import tempfile import sys import",
"target = os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)",
"import time import random import requests import tempfile import sys import zipfile import",
"\"\"\" import os import time import random import requests import tempfile import sys",
"= parse_io() source_url = args.input output_file = args.output output_dir, file_name = os.path.split(output_file) if",
"import requests import tempfile import sys import zipfile import shutil import tarfile from",
"os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name) time.sleep(random.random()*5) if __name__ == '__main__':",
"if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn)",
"LICENSE file. Date: 2021-02-05 \"\"\" import os import time import random import requests",
"occurred trying to get URL: {url}', file=sys.stderr) if response is None or response.status_code",
"1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and",
"try: response = requests.get(url, stream=True) except: print(f'Connection error occurred trying to get URL:",
"as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if total_size_in_bytes is None: f_out.write(response.content)",
"200: print(f'Error {response.status_code}', f'while downloading file from URL: {url}') return None tmp_fd, tmp_fn",
"response = requests.get(url, stream=True) except: print(f'Connection error occurred trying to get URL: {url}',",
"!= 200: print(f'Error {response.status_code}', f'while downloading file from URL: {url}') return None tmp_fd,",
"\"\"\" Download needed raw data Author: <NAME> Copyright (c) 2021 - <NAME> License:",
"tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\",
"= int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as",
"None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1 KB for",
"target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif",
"tarfile from tqdm import tqdm from parse_args import parse_io def download_url(url, output_dir, file_name):",
"is None: f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1 KB",
"from URL: {url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0))",
"main(): args = parse_io() source_url = args.input output_file = args.output output_dir, file_name =",
"1024 # 1 KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes !=",
"as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn, target) with",
"<NAME> License: See the LICENSE file. Date: 2021-02-05 \"\"\" import os import time",
"sys import zipfile import shutil import tarfile from tqdm import tqdm from parse_args",
"'w', zipfile.ZIP_DEFLATED) as f_zip: f_zip.write(tmp_fn) os.unlink(tmp_fn) elif any([el.endswith('.tar') for el in url.split('?')]): shutil.move(tmp_fn,",
"f_out.write(response.content) else: total_size_in_bytes = int(total_size_in_bytes) block_size = 1024 # 1 KB for data",
"is None or response.status_code != 200: print(f'Error {response.status_code}', f'while downloading file from URL:",
"{url}') return None tmp_fd, tmp_fn = tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd,",
"!= total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}') target = os.path.join(output_dir, file_name)",
"0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) as progress_bar: if",
"os.path.join(output_dir, file_name) if target.endswith('.zip') and not zipfile.is_zipfile(tmp_fn): with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as f_zip:",
"os import time import random import requests import tempfile import sys import zipfile",
"= None try: response = requests.get(url, stream=True) except: print(f'Connection error occurred trying to",
"= tempfile.mkstemp() total_size_in_bytes = int(response.headers.get('content-length', 0)) with os.fdopen(tmp_fd, 'wb') as f_out, \\ tqdm(total=total_size_in_bytes,",
"get URL: {url}', file=sys.stderr) if response is None or response.status_code != 200: print(f'Error",
"Date: 2021-02-05 \"\"\" import os import time import random import requests import tempfile",
"{url}', file=sys.stderr) if response is None or response.status_code != 200: print(f'Error {response.status_code}', f'while",
"!= 0 and progress_bar.n != total_size_in_bytes: print(f'ERROR, something went wrong while downloading {url}')",
"output_file = args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir,",
"= args.output output_dir, file_name = os.path.split(output_file) if not os.path.exists(output_dir): os.makedirs(output_dir) download_url(source_url, output_dir, file_name)",
"KB for data in response.iter_content(block_size): progress_bar.update(len(data)) f_out.write(data) if total_size_in_bytes != 0 and progress_bar.n",
"tempfile import sys import zipfile import shutil import tarfile from tqdm import tqdm"
] |
[
"delphifmx import * class Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading =",
"Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading = None self.result_text_label = None",
"def __init__(self, owner): self.child_heading = None self.result_text_heading = None self.result_text_label = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)),",
"import * class Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading = None",
"from delphifmx import * class Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading",
"* class Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading = None self.result_text_label",
"class Child_Form(Form): def __init__(self, owner): self.child_heading = None self.result_text_heading = None self.result_text_label =",
"import os from delphifmx import * class Child_Form(Form): def __init__(self, owner): self.child_heading =",
"__init__(self, owner): self.child_heading = None self.result_text_heading = None self.result_text_label = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"child_window.pyfmx\"))",
"os from delphifmx import * class Child_Form(Form): def __init__(self, owner): self.child_heading = None"
] |
[
"build system yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), #",
"supported in this build system yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup(",
"'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy mcell library to the current",
"else: sys.exit(\"Operating system '\" + platform.system() + \"' is not supported in this",
"'3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically - has to be number",
"+ \"' is not supported in this build system yet.\") def get_mcell_version(): #",
"== 'Darwin': # pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\"",
"automatically - has to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\",",
"# TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically - has",
"in this build system yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell',",
"long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\", \"License",
"pass elif platform.system() == 'Darwin': # pass elif 'Windows' in platform.system(): pass else:",
"set automatically - has to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\",",
"sys.exit(\"Operating system '\" + platform.system() + \"' is not supported in this build",
"\"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\" ], zip_safe=True",
"platform.system() == 'Darwin': # pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system",
"get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically -",
"Beta\", \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\" ],",
"platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system() + \"' is not supported",
"- has to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\",",
"'\" + platform.system() + \"' is not supported in this build system yet.\")",
"version=get_mcell_version(), # todo: set automatically - has to be number py_modules=['lib/mcell'], author=\"Salk Institute",
"'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system() + \"' is",
"# todo: set automatically - has to be number py_modules=['lib/mcell'], author=\"Salk Institute for",
"system '\" + platform.system() + \"' is not supported in this build system",
"for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status",
"in platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system() + \"' is not",
"+ platform.system() + \"' is not supported in this build system yet.\") def",
"to the current directory pass elif platform.system() == 'Darwin': # pass elif 'Windows'",
"sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux':",
"os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO:",
"url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\", \"License :: OSI",
"TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically - has to",
"TODO: copy mcell library to the current directory pass elif platform.system() == 'Darwin':",
"author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 -",
"# TODO: copy mcell library to the current directory pass elif platform.system() ==",
"copy mcell library to the current directory pass elif platform.system() == 'Darwin': #",
"THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy",
":: 4 - Beta\", \"License :: OSI Approved :: GNU General Public License",
"\"' is not supported in this build system yet.\") def get_mcell_version(): # TODO",
"number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\",",
"4 - Beta\", \"License :: OSI Approved :: GNU General Public License v2",
"yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set",
"Status :: 4 - Beta\", \"License :: OSI Approved :: GNU General Public",
"\"Development Status :: 4 - Beta\", \"License :: OSI Approved :: GNU General",
"Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status ::",
"todo: set automatically - has to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal",
"has to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\",",
"classifiers=[ \"Development Status :: 4 - Beta\", \"License :: OSI Approved :: GNU",
"Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development",
"if platform.system() == 'Linux': # TODO: copy mcell library to the current directory",
"import platform import sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if",
"setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically - has to be number py_modules=['lib/mcell'],",
"- Beta\", \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\"",
"pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system() +",
"py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8',",
"is not supported in this build system yet.\") def get_mcell_version(): # TODO return",
"setuptools import platform import sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/'",
"= 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy mcell library to the",
"import setuptools import platform import sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR =",
"Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4",
"this build system yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(),",
"== 'Linux': # TODO: copy mcell library to the current directory pass elif",
"'Darwin': # pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\" +",
"import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': #",
"author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[",
"be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\",",
"'Linux': # TODO: copy mcell library to the current directory pass elif platform.system()",
"platform.system() == 'Linux': # TODO: copy mcell library to the current directory pass",
"platform.system() + \"' is not supported in this build system yet.\") def get_mcell_version():",
"import sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() ==",
"# pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system()",
"python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\", \"License :: OSI Approved ::",
"os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy mcell library",
"platform import sys import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system()",
"elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating system '\" + platform.system() + \"'",
"to be number py_modules=['lib/mcell'], author=\"Salk Institute for Biologocal Studies\", author_email=\"<EMAIL>\", description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\",",
"not supported in this build system yet.\") def get_mcell_version(): # TODO return '3.99.0'",
"def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically",
"current directory pass elif platform.system() == 'Darwin': # pass elif 'Windows' in platform.system():",
"library to the current directory pass elif platform.system() == 'Darwin': # pass elif",
"description=\"MCell4\", long_description=\"MCell4\", long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\",",
"= os.path.dirname(os.path.abspath(__file__)) BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy mcell",
"name='mcell', version=get_mcell_version(), # todo: set automatically - has to be number py_modules=['lib/mcell'], author=\"Salk",
"directory pass elif platform.system() == 'Darwin': # pass elif 'Windows' in platform.system(): pass",
"download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\", \"License :: OSI Approved",
"return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo: set automatically - has to be",
"mcell library to the current directory pass elif platform.system() == 'Darwin': # pass",
"the current directory pass elif platform.system() == 'Darwin': # pass elif 'Windows' in",
"elif platform.system() == 'Darwin': # pass elif 'Windows' in platform.system(): pass else: sys.exit(\"Operating",
"long_description_content_type=\"text/markdown\", url=\"https://www.mcell.org\", download_url=\"https://mcell.org/download.html\", python_requires='>=3.8', classifiers=[ \"Development Status :: 4 - Beta\", \"License ::",
"system yet.\") def get_mcell_version(): # TODO return '3.99.0' setuptools.setup( name='mcell', version=get_mcell_version(), # todo:",
"pass else: sys.exit(\"Operating system '\" + platform.system() + \"' is not supported in",
":: OSI Approved :: GNU General Public License v2 (GPLv2)\" ], zip_safe=True )",
"BUILD_DIR = 'mcell/utils/pybind11_test/build/' if platform.system() == 'Linux': # TODO: copy mcell library to"
] |
[
"= etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title':",
"import AbstractJob from lxml import etree class Plex(AbstractJob): def __init__(self, conf): self.interval =",
"tree = etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'),",
"= conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree =",
"try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows =",
"import requests from jobs import AbstractJob from lxml import etree class Plex(AbstractJob): def",
"= etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year':",
"movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows = [] for show in",
"etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year')",
"show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout)",
"from lxml import etree class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies",
"AbstractJob from lxml import etree class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval']",
"show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try:",
"movies = self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows':",
"xml): tree = etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name':",
"conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies = []",
"movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self, xml): tree =",
"self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies",
"__init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout =",
"python import requests from jobs import AbstractJob from lxml import etree class Plex(AbstractJob):",
"conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml)",
"def _parse_movies(self, xml): tree = etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'):",
"'title': movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self, xml): tree = etree.fromstring(xml)",
"r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows': shows} except requests.exceptions.ConnectionError:",
"_parse_shows(self, xml): tree = etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({",
"class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows =",
"tree = etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'),",
"def _parse_shows(self, xml): tree = etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'):",
"= [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2),",
"from jobs import AbstractJob from lxml import etree class Plex(AbstractJob): def __init__(self, conf):",
"requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows': shows} except requests.exceptions.ConnectionError: return {}",
"for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2)",
"_parse_movies(self, xml): tree = etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({",
"'year': movie.get('year') }) return movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows =",
"}) return shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content)",
"self.movies = conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree",
"movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self,",
"shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r =",
"conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml):",
"def __init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout",
"'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self):",
"timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies,",
"}) return movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows = [] for",
"etree.fromstring(xml) shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'),",
"movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows",
"show.get('parentIndex').zfill(2) }) return shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies =",
"requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies':",
"= [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return",
"show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) })",
"tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self, xml): tree",
"'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try: r = requests.get(self.movies,",
"tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows",
"def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows)",
"in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies def _parse_shows(self, xml):",
"= requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return",
"= conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies = [] for movie",
"import etree class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies']",
"xml): tree = etree.fromstring(xml) movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title':",
"return shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r",
"conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout')",
"r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content)",
"'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try: r",
"= self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows': shows}",
"show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try: r =",
"lxml import etree class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies =",
"[] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies",
"Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows = conf['shows']",
"movie.get('year') }) return movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows = []",
"in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return",
"movies = [] for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') })",
"self.interval = conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def",
"etree class Plex(AbstractJob): def __init__(self, conf): self.interval = conf['interval'] self.movies = conf['movies'] self.shows",
"= requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows': shows} except requests.exceptions.ConnectionError: return",
"requests from jobs import AbstractJob from lxml import etree class Plex(AbstractJob): def __init__(self,",
"shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season': show.get('parentIndex').zfill(2) }) return shows def",
"return movies def _parse_shows(self, xml): tree = etree.fromstring(xml) shows = [] for show",
"shows = [] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode':",
"conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies = [] for movie in",
"get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies = self._parse_movies(r.content) r = requests.get(self.shows) shows",
"for movie in tree.xpath('/MediaContainer/Video'): movies.append({ 'title': movie.get('title'), 'year': movie.get('year') }) return movies def",
"jobs import AbstractJob from lxml import etree class Plex(AbstractJob): def __init__(self, conf): self.interval",
"[] for show in tree.xpath('/MediaContainer/Video'): shows.append({ 'name': show.get('grandparentTitle'), 'title': show.get('title'), 'episode': show.get('index').zfill(2), 'season':",
"#!/usr/bin/env python import requests from jobs import AbstractJob from lxml import etree class",
"self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies = [] for",
"'season': show.get('parentIndex').zfill(2) }) return shows def get(self): try: r = requests.get(self.movies, timeout=self.timeout) movies",
"self._parse_movies(r.content) r = requests.get(self.shows) shows = self._parse_shows(r.content) return {'movies': movies, 'shows': shows} except",
"= conf['interval'] self.movies = conf['movies'] self.shows = conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self,",
"= conf['shows'] self.timeout = conf.get('timeout') def _parse_movies(self, xml): tree = etree.fromstring(xml) movies ="
] |
[] |
[
"Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton Marker Application') set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')],",
"username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password, urladmin) edit()",
"port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton",
"def run(cfg): \"\"\"OSB Fix to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port')",
"with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username,",
"urladmin=admin + \":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker",
"password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain",
"to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" +",
"urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton",
"cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton Marker Application')",
"connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB",
"+ \":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application')",
"Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton Marker Application') set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName))",
"run(cfg): \"\"\"OSB Fix to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin",
"\"\"\"OSB Fix to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin +",
"admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster",
"requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password, urladmin)",
"Fix to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\"",
"+ port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')],",
"port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName))",
"deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port",
"Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton Marker Application') set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) activate()",
"password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB",
"\":\" + port connect(username, password, urladmin) edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit()",
"11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host') port=cfg.getProperty('wls.admin.listener.port') urladmin=admin + \":\" + port connect(username, password,",
"edit() cd('/AppDeployments/ALSB Cluster Singleton Marker Application') startEdit() set('Targets',jarray.array([ObjectName('com.bea:Name=osb_cluster,Type=Cluster')], ObjectName)) cd('/AppDeployments/ALSB Domain Singleton Marker",
"<gh_stars>1-10 def run(cfg): \"\"\"OSB Fix to deal with 11.1.1.5+ requirements\"\"\" username=cfg.getProperty('wls.admin.username') password=cfg.getProperty('wls.admin.password') admin=cfg.getProperty('osb.as.host')"
] |
[
"Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for",
"in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier +",
"df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for",
"',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df",
"nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df =",
"for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' +",
"if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\":",
"= pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left',",
"print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning':",
"as sp import numpy as np import pandas as pd import glob def",
"= read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test:",
"+ classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test:",
"friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe)",
"models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier,",
"+ 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']:",
"pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning'",
"list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in list_classifiers: for",
"list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0])",
"pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']:",
"experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df",
"+ '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH +",
"import pandas as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row",
"np import pandas as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index,",
"df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for",
"'*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' +",
"models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier +",
"+ '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH +",
"df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models",
"list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric))",
"df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding',",
"print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if",
"sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics =",
"for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col",
"in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier,",
"df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in",
"classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH",
"def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning'",
"list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1]",
"print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in",
"how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in list_models:",
"for models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier",
"as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()])",
"skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics",
"how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], #",
"classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH",
"index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in",
"models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier",
"+ '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier,",
"how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) print()",
"= sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return",
"print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df =",
"'*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier,",
"print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None",
"in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left',",
"from scipy import stats import scikit_posthocs as sp import numpy as np import",
"+'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df",
"pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def",
"Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in",
"experiment in list_experiment: for classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if",
"df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k",
"models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df =",
"= df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for",
"= df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt']",
"PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment",
"for experiment in list_experiment: for classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric))",
"= df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k)))",
"nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH",
"pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in",
"'*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric))",
"df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_'",
"models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600']",
"pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding')",
"read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers",
"experiment=='Fine_tuning': for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_'",
"if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_'",
"'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df",
"+ k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] =",
"def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index)",
"df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2)",
"in list_experiment: for classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static':",
"in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0])",
"sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path,",
"classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df",
"+'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original =",
"print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for",
"list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for",
"+ models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original']",
"nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path):",
"df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt']",
"in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.')",
"#df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models:",
"import stats import scikit_posthocs as sp import numpy as np import pandas as",
"#df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df =",
"pandas as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in",
"dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return",
"+ classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df =",
"print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in list_models: print(models) df",
"skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if",
"+ '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_'",
"Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet']",
"= ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in list_classifiers: for metric",
"'*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k",
"import numpy as np import pandas as pd import glob def friedman_test(dataframe): return",
"col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment",
"df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0])",
"import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe):",
"nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/'",
"pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica']",
"classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier",
"['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding',",
"sp import numpy as np import pandas as pd import glob def friedman_test(dataframe):",
"classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models +",
"list_experiment: for classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\")",
"row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns:",
"for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:]))",
"for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.')",
"PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro']",
"for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier +",
"metric)) if experiment=='Fine_tuning': for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models",
"scipy import stats import scikit_posthocs as sp import numpy as np import pandas",
"classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df =",
"list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if",
"on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.')",
"+ '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier +",
"return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/' #list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers =",
"list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment",
"print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] =",
"+ classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models",
"read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models",
"df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding')",
"# skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric))",
"for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier",
"= pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in",
"= read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for",
"+ '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment,",
"+ classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test: ',friedman_test(df.iloc[:,1:]))",
"df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original",
"'*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0],",
"for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment,",
"+ '-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH",
"return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments Results/' PATH_OUT='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Statistical_Reslts/'",
"= round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' +",
"as np import pandas as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for",
"'-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_'",
"on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in",
"',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in list_models: print(models) df =",
"#df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning':",
"k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'),",
"experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' +",
"numpy as np import pandas as pd import glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row",
"'-1-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]) for k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+",
"models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH",
"in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)])",
"+'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test:",
"list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2],",
"= ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in",
"['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in list_classifiers: for metric in",
"= pd.read_csv(glob.glob(PATH + 'InData/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.') df.iloc[:,1] = round(df.iloc[:,1]*100,2) for k",
"#list_experiment=['Static','Transformers','Fine_tuning','Task_Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_experiment=['Fine_tuning']#'Static','Transformers','Fine_tuning','Task_Fine_tuning' list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment:",
"metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models) df=None df = pd.read_csv(glob.glob(PATH +",
"= df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models",
"stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for",
"list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test:",
"metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df =",
"for classifier in list_classifiers: for metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df",
"def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi =",
"if experiment=='Fine_tuning': for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models +",
"nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models)",
"['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in list_classifiers:",
"round(df.iloc[:,1]*100,2) for k in ['LOO','22Dt']: df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier",
"stats import scikit_posthocs as sp import numpy as np import pandas as pd",
"return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[]",
"['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]), how='left',",
"nemenyi_test(dataframe): nemenyi = sp.posthoc_nemenyi_friedman(dataframe) list_index=[] for col in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def",
"classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment,",
"classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df = df.merge(df_original,how='left', on='Embedding') #df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600','original'] df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:]))",
"on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment=='Fine_tuning': for models in list_models: print(models)",
"classifier, metric)) if experiment=='Fine_tuning': for models in list_models: print(models) df = pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+",
"k in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier +",
"list_classifiers = ['MLPClassifier','Random_Forest','SVM','XGboost','Reg_Logistica'] list_metrics = ['accuracy','f1_macro'] list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier",
"in nemenyi.columns: list_index.append([col,list(nemenyi[nemenyi[col]<0.05].index),list(nemenyi[nemenyi[col]<0.05][col].values)]) return pd.DataFrame(list_index) def read_dataset(dataframe_path): return pd.read_csv(dataframe_path, skiprows=[0,2], sep=\",\",decimal='.') PATH='/Users/sergiojunior/sentiment-embeddings-final/Experiment Results/Experiments",
"if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]),",
"df = df.merge(pd.read_csv(glob.glob(PATH + k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k)))",
"metric in list_metrics: print(\"{}_{}_{}\".format(experiment,classifier,metric)) if experiment=='Static': print(\"Static_embedding\") df = read_dataset(glob.glob(PATH+experiment+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment,",
"k +'/'+models+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0],sep=\",\",decimal='.'), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) df.columns=['Embedding','InData','LOO','22Dt'] df['22Dt'] = round(df['22Dt']*100,2)",
"in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric))",
"list_models=['BERT',\"RoBERTa\",'BERTweet'] for experiment in list_experiment: for classifier in list_classifiers: for metric in list_metrics:",
"read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left', on='Embedding') print('friedman_test: ',friedman_test(df.iloc[:,1:]))",
"in ['5','05','10','25','50','250','500','1500','6600']: df = df.merge(pd.read_csv(glob.glob(PATH +'Fine_tuning_Generic_tweets/'+ models + '-'+k+'-LM/pivot_' + classifier + '*'+metric+'*.csv')[0]),",
"+ classifier + '*'+metric+'*.csv')[0]), how='left', on='Embedding', suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' +",
"scikit_posthocs as sp import numpy as np import pandas as pd import glob",
"df.columns=['Embedding','1','5','05','10','25','50','250','500','1500','6600'] print('friedman_test: ',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}_{}.csv\".format(models,experiment, classifier, metric)) if experiment=='Task_Fine_tuning': for models in list_models: print(models)",
"suffixes=(\"\",\"_\"+str(k))) #df_original = pd.read_csv(glob.glob(PATH + models+'/Pivot_tables/pivot_' + classifier + '*'+metric+'*.csv')[0], # skiprows=[0,2],sep=\",\",decimal='.') #df",
"import scikit_posthocs as sp import numpy as np import pandas as pd import",
"',friedman_test(df.iloc[:,1:])) nemenyi_test(df.iloc[:,1:]).to_csv(PATH_OUT+\"nemenyi_{}_{}_{}.csv\".format(experiment, classifier, metric)) if experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]:",
"glob def friedman_test(dataframe): return stats.friedmanchisquare(*[row for index, row in dataframe.T.iterrows()]) def nemenyi_test(dataframe): nemenyi",
"experiment==\"Transformers\": df = read_dataset(glob.glob(PATH+list_models[0]+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]) for models in list_models[1:]: print(models) df = df.merge(read_dataset(glob.glob(PATH+models+'/Pivot_tables/pivot_'+classifier+'*'+metric+'*.csv')[0]), how='left',"
] |
[
"import SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response = client.call_action('example',",
"Client from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS})",
"== '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response = client.call_action('example', 'square', {'number': 42}) print(action_response)",
"settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response =",
"SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response = client.call_action('example', 'square',",
"from pysoa.client import Client from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client",
"__name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response = client.call_action('example', 'square', {'number': 42})",
"from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response",
"import Client from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client = Client({'example':",
"<filename>client.py from pysoa.client import Client from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__':",
"pysoa.client import Client from settings import SOA_CLIENT_SETTINGS if __name__ == '__main__': client =",
"if __name__ == '__main__': client = Client({'example': SOA_CLIENT_SETTINGS}) action_response = client.call_action('example', 'square', {'number':"
] |
[] |
[
"Unless required by applicable law or agreed to in writing, software # distributed",
"ValueError( \"Expected argument starting point to be a vector with at least one",
"= np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function,",
"positive integer, instead it is \" f\"{max_iterations}.\" ) if verbosity is None: verbosity",
"bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float,",
"= False, epsilon: float = 1e-6, max_iterations: int = 100000, verbosity: Optional[str] =",
"of the output during algorithm execution. decimal_precision (int): An int representing the number",
"to be a str, instead it is {type(verbosity)}.\" ) if verbosity not in",
"a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise",
"number. TypeError: Raised if argument verbosity is not a str. KeyError: Raised if",
"round numbers outputted during algorithm execution. \"\"\" if verbosity == 1: print(f\"c =",
"float. TypeError: Raised if argument use_jakobovic_expand is not a bool. TypeError: Raised if",
"= np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity:",
"\"The available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]])",
"A float representing the error threshold. max_iterations (int): An int representing the maximum",
"= np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision,",
"a simplex. beta (float): A float representing the amount a point will be",
"representing the stride for simplex generation. Defaults to 1. alpha (float, optional): A",
"gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision:",
"float. TypeError: Raised if argument beta is not a float. TypeError: Raised if",
"point contraction. Defaults to 0.5. gamma (float, optional): A float used in point",
"\"Expected argument use_jakobovic_expand to be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" )",
"A float used in point contraction. Defaults to 0.5. gamma (float, optional): A",
"verbosity: Optional[str] = None, decimal_precision: int = 3, ) -> np.ndarray: \"\"\" Uses",
"do this since the maximum value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point",
"A numpy.ndarray representing the vector of simplex values. centroid_value (float): A float representing",
"maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid",
"only available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available",
"algorithm execution. decimal_precision (int): An int representing the number of decimal digits to",
"digits to round numbers outputted during algorithm execution. \"\"\" if verbosity == 1:",
"numpy as np from . import constants from .function import Function def clean_nelder_mead_simplex_search_arguments(",
"np.ndarray: A numpy.ndarray representing the expanded point. \"\"\" return (1 - gamma) *",
"is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta) if not isinstance(beta,",
"np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid:",
"argument start is not a numpy.ndarray. ValueError: Raised if argument start is a",
"if isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"-> np.ndarray: \"\"\" Generates simplex points for a starting point. Args: start (np.ndarray):",
"\"\"\" Reflects argument maximum_points wrt centroid by argument alpha. Args: centroid (np.ndarray): A",
"f\"Expected argument verbosity to be a str, instead it is {type(verbosity)}.\" ) if",
"need to do this since the maximum value has potentially changed maximum_value =",
"-> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and returns them prepared for",
"): \"\"\" Prints the Nelder Mead Simplex Search values. Args: function (Function): A",
"def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma: float, sigma: float, use_jakobovic_expand:",
"Do this to get a more precise result maximum_index = np.argmax(simplex_values) centroid =",
"the specific language governing permissions and # limitations under the License. import sys",
"timed_out = False break if timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed",
"if argument epsilon is a negative number. TypeError: Raised if argument max_iterations is",
"ValueError( \"Expected argument epsilon to be a positive float, instead it is \"",
"__expand_jakobovic if use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index",
"(float): A float used in point reflection. beta (float): A float used in",
"use_jakobovic_expand: bool = False, epsilon: float = 1e-6, max_iterations: int = 100000, verbosity:",
"A numpy.ndarray representing the reflected point. \"\"\" return (1 + alpha) * centroid",
"(int): An int representing the level of verbosity of the output during algorithm",
"to False. epsilon (float): A float representing the error threshold. max_iterations (int): An",
"False. epsilon (float, optional): A float representing the error threshold. Defaults to 1e-6.",
"max_iterations < 1: raise ValueError( \"Expected argument max_interations to be a positive integer,",
"(Optional[str], optional): A str representing the verbosity of the output during algorithm execution.",
"float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start",
"float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"\"Expected argument decimal_precision to be a positive int, instead it is\" f\"{decimal_precision}.\" )",
"str. KeyError: Raised if argument verbosity is an invalid key. TypeError: Raised if",
"to round numbers outputted during algorithm execution. Defaults to 3. Returns: np.ndarray: A",
"instead it is \" f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError( \"Expected",
"verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray,",
"wrt centroid by argument alpha. This is a modified version which is supposedly",
"invalid key. TypeError: Raised if argument decimal_precision is not an int. ValueError: Raised",
") return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision,",
"bool, float, int, int, int]: Cleaned arguments. \"\"\" if not isinstance(function, Function): raise",
"if argument alpha is not a float. TypeError: Raised if argument beta is",
"start to be a numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start =",
"if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to be a numpy.ndarray,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False",
"point expansion. sigma (float): A float used when moving points to the optimum.",
"to be a vector with at least one \" \"element, instead it is",
"Simplex Search to find an n-D optimum of a function. Args: function (Function):",
"Returns: np.ndarray: A numpy.ndarray representing the reflected point. \"\"\" return (1 + alpha)",
"isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to be an int, instead it",
"simplex. beta (float): A float representing the amount a point will be contracted.",
"argument maximum_points wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing",
"import constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta:",
"it's time to stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray",
"to the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A bool determining whether",
"< 0: raise ValueError( \"Expected argument epsilon to be a positive float, instead",
"= expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index]",
"a vector with at least one \" \"element, instead it is empty.\" )",
"used in point expansion. sigma (float): A float used when moving points to",
"decimal_precision: int = 3, ) -> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search",
") * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value",
"if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point",
"np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects argument maximum_points wrt",
"reflected point. \"\"\" return (1 + alpha) * centroid - alpha * maximum_point",
"if not isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride to be a",
"\"\"\" if not isinstance(function, Function): raise TypeError( \"Expected argument function to be a",
"A numpy.ndarray representing the starting point for simplex generation. stride (Union[float, int]): A",
"+ alpha) * centroid - alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point:",
"an int, instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise",
"modified version which is supposedly the correct one, as said by prof. Jakobović.",
"Raised if argument gamma is not a float. TypeError: Raised if argument sigma",
"negative number. TypeError: Raised if argument max_iterations is not an int. ValueError: Raised",
"Raised if argument start is a zero-length vector. TypeError: Raised if argument stride",
"numpy.ndarray representing the starting point for simplex generation. stride (Union[float, int]): A float",
"generation. stride (Union[float, int]): A float or int representing the stride. Raises: TypeError:",
"since the maximum value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract(",
"raise TypeError( \"Expected argument max_interations to be an int, instead it is \"",
"decimal_precision (int): An int representing the number of decimal digits to round numbers",
"if not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to be a float,",
"stride for simplex generation. Defaults to 1. alpha (float, optional): A float used",
"simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value",
"representing the expanded point. \"\"\" return (1 - gamma) * centroid - gamma",
"decimal_precision is a negative number. Returns: Tuple[Function, float, float, float, float, bool, float,",
"* sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if",
"arguments and returns them prepared for work. Args: function (Function): A Function representing",
"use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int]",
"raise TypeError( \"Expected argument beta to be a float, instead it is \"",
"max_iterations is not an int. ValueError: Raised if argument max_iterations is a negative",
"by argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point",
"use_jakobovic_expand (float, optional): A bool determining whether or not to use the __expand_jakobovic",
"\"Expected argument gamma to be a float, instead it is \" f\"{type(gamma)}.\" )",
"clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the",
"value of the simplex centroid. epsilon (float): A float representing the error threshold.",
"\" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to",
"a float, instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta =",
"TypeError( \"Expected argument gamma to be a float, instead it is \" f\"{type(gamma)}.\"",
"float ) -> bool: \"\"\" Checks if it's time to stop Nelder Mead",
"potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value",
"Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise",
"int, int, int]: \"\"\" Checks the Nelder Mead Simplex Search arguments and returns",
"function. start (np.ndarray): A numpy.ndarray representing the starting point of the search. stride",
"is None: verbosity = \"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected argument",
"not use this file except in compliance with the License. # You may",
"centroid by argument alpha. This is a modified version which is supposedly the",
"whether or not to use the __expand_jakobovic method instead of the __expand method",
"verbosity_dict_length == 0: verbosity_string = \"There are no keys available.\" elif verbosity_dict_length ==",
"optimum of a function. Args: function (Function): A Function representing the loss function.",
"function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints the Nelder",
"reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point",
"all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index]",
"is empty.\" ) if not isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride",
"int): raise TypeError( \"Expected argument decimal_precision to be an int, instead it is",
"minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma",
"isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to be a numpy.ndarray, instead it",
"execution). decimal_precision (int, optional): An int representing the number of decimal digits to",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
") def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\"",
"A numpy.ndarray representing the contracted point. \"\"\" return (1 - beta) * centroid",
"point of a simplex. alpha (float): A float representing the amount a point",
"beta: float ) -> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by argument",
"numpy.ndarray representing the contracted point. \"\"\" return (1 - beta) * centroid +",
"Raised if argument function is not a Function. TypeError: Raised if argument alpha",
"float. ValueError: Raised if argument epsilon is a negative number. TypeError: Raised if",
"_keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \" verbosity_string += \",",
"one, as said by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the",
"agreed to in writing, software # distributed under the License is distributed on",
"difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values)",
"TypeError: Raised if argument beta is not a float. TypeError: Raised if argument",
"A Function representing the loss function. centroid (np.ndarray): A numpy.ndarray representing the simplex",
"if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result",
"None: verbosity = \"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity",
"(Union[float, int]): A float or int representing the stride. Raises: TypeError: Raised if",
"raise KeyError( f'Verbosity key \"{verbosity}\" is not in the Nelder Mead Simplex Verbosity",
"numpy.ndarray. ValueError: Raised if argument start is a zero-length vector. TypeError: Raised if",
"Raised if argument verbosity is an invalid key. TypeError: Raised if argument decimal_precision",
"Function, start: np.ndarray, stride: Union[float, int] = 1, alpha: float = 1.0, beta:",
"_key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is \"{_key}\".' else: _keys",
"simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in simplex_points]) timed_out =",
") reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point =",
"# We need to do this since the maximum value has potentially changed",
"used when moving points to the optimum. use_jakobovic_expand (bool): A bool determining whether",
"in simplex_points]) timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for",
"be a positive integer, instead it is \" f\"{max_iterations}.\" ) if verbosity is",
"worst point of a simplex. alpha (float): A float representing the amount a",
"to be a numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start = np.reshape(start,",
"Nelder Mead Simplex Search has been met, False otherwise. \"\"\" difference_in_values = simplex_values",
"verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float, float, float, bool, float,",
"Tuple, Union import numpy as np from . import constants from .function import",
") -> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to find an n-D",
"specific language governing permissions and # limitations under the License. import sys from",
"print( f\"WARNING: Nelder Mead Simplex Search timed out after {max_iterations} \" \"iterations -",
"Mead Simplex Search arguments and returns them prepared for work. Args: function (Function):",
"error threshold. max_iterations (int): An int representing the maximum number of iterations before",
"Function representing the loss function. centroid (np.ndarray): A numpy.ndarray representing the simplex centroid.",
"is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand",
"\"\"\" Checks the __get_simplex_points arguments and returns them prepared for work. Args: start",
"(float): A float used when moving points to the optimum. use_jakobovic_expand (bool): A",
"< reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value #",
"to in writing, software # distributed under the License is distributed on an",
"to 1. alpha (float, optional): A float used in point reflection. Defaults to",
"implied. # See the License for the specific language governing permissions and #",
"np.ndarray): raise TypeError( \"Expected argument start to be a numpy.ndarray, instead it is",
"representing a point of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points",
"language governing permissions and # limitations under the License. import sys from typing",
"a float. TypeError: Raised if argument gamma is not a float. TypeError: Raised",
"been met, False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values)",
"- centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def",
"\"\"\" return (1 - gamma) * centroid + gamma * reflected_point def __expand_jakobovic(",
"alpha (float): A float used in point reflection. beta (float): A float used",
"if not isinstance(function, Function): raise TypeError( \"Expected argument function to be a Function,",
"number. TypeError: Raised if argument max_iterations is not an int. ValueError: Raised if",
"clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool,",
"function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments(",
"1)) points = points + stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect(",
"function(centroid, dont_count=True) result = ( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" )",
"import Optional, Tuple, Union import numpy as np from . import constants from",
"verbosity: int, decimal_precision: int, ): \"\"\" Prints the Nelder Mead Simplex Search values.",
"np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int,",
"prepared for work. Args: start (np.ndarray): A numpy.ndarray representing the starting point for",
"= 1e-6, max_iterations: int = 100000, verbosity: Optional[str] = None, decimal_precision: int =",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"= np.argmax(simplex_values) # We need to do this since the maximum value has",
"np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. Args: centroid (np.ndarray):",
"argument function to be a Function, instead it is \" f\"{type(function)}.\" ) if",
"A str representing the verbosity of the output during algorithm execution. decimal_precision (int):",
"is not a bool. TypeError: Raised if argument epsilon is not a float.",
"reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index]",
"used in point reflection. Defaults to 1.0. beta (float, optional): A float used",
"stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and",
"function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride",
"timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed out after {max_iterations} \" \"iterations",
"verbosity (int): An int representing the level of verbosity of the output during",
"execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing the last found optimum.",
"(float): A float representing the error threshold. Returns: bool: True if the stopping",
"Search values. Args: function (Function): A Function representing the loss function. centroid (np.ndarray):",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to be a numpy.ndarray, instead",
"if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def",
"not isinstance(sigma, float): raise TypeError( \"Expected argument sigma to be a float, instead",
"representing the loss function. centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity",
"beta. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A",
"alpha: float ) -> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by argument",
"= function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid,",
"governing permissions and # limitations under the License. import sys from typing import",
"Search has been met, False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values",
"(np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity (int): An int representing the",
"axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index],",
"decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int] =",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"int, instead it is \" f\"{type(stride)}.\" ) stride = float(stride) return start, stride",
"you may not use this file except in compliance with the License. #",
"are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f'",
"maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. beta (float):",
"is a negative number. Returns: Tuple[Function, float, float, float, float, bool, float, int,",
"raise ValueError( \"Expected argument max_interations to be a positive integer, instead it is",
"Expands argument reflected_point wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray",
"beta=beta, ) contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index]",
"= reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out =",
"f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to be",
"the amount a point will be contracted. Returns: np.ndarray: A numpy.ndarray representing the",
"\"\"\" return (1 + alpha) * centroid - alpha * maximum_point def __contract(",
"are no keys available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string =",
"the stride for simplex generation. Defaults to 1. alpha (float, optional): A float",
"bool = False, epsilon: float = 1e-6, max_iterations: int = 100000, verbosity: Optional[str]",
"argument epsilon is not a float. ValueError: Raised if argument epsilon is a",
"# Copyright 2020 Yalfoosh # # Licensed under the Apache License, Version 2.0",
"has been met, False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values =",
"not an int. ValueError: Raised if argument max_iterations is a negative number. TypeError:",
") if epsilon < 0: raise ValueError( \"Expected argument epsilon to be a",
") print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray,",
"verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point",
"argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray):",
"TypeError( \"Expected argument decimal_precision to be an int, instead it is \" f\"{type(decimal_precision)}.\"",
"if isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected",
"instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma) if",
"0: raise ValueError( \"Expected argument starting point to be a vector with at",
"level of verbosity of the output during algorithm execution. decimal_precision (int): An int",
"is not an int. ValueError: Raised if argument max_iterations is a negative number.",
"in point reflection. Defaults to 1.0. beta (float, optional): A float used in",
"point will be contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted point. \"\"\"",
"an n-D optimum of a function. Args: function (Function): A Function representing the",
"int, int]: \"\"\" Checks the Nelder Mead Simplex Search arguments and returns them",
"= f'The only available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string =",
"centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] =",
"generation. Defaults to 1. alpha (float, optional): A float used in point reflection.",
"not a bool. TypeError: Raised if argument epsilon is not a float. ValueError:",
"the __expand method for point expansion. Defaults to False. epsilon (float): A float",
"values. centroid_value (float): A float representing the value of the simplex centroid. epsilon",
"numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0]",
"during algorithm execution. \"\"\" if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif",
"instead it is \" f\"{max_iterations}.\" ) if verbosity is None: verbosity = \"none\"",
"not a float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not",
"centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects argument maximum_points",
"might not be a minimum.\", file=sys.stderr, ) # Do this to get a",
"Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector of simplex values. centroid_value",
"if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value =",
"for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points,",
"expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index]",
"algorithm execution. Defaults to None (no output during algorithm execution). decimal_precision (int, optional):",
"float or int representing the stride. Raises: TypeError: Raised if argument start is",
"be a float or int, instead it is \" f\"{type(stride)}.\" ) stride =",
"a point of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points =",
"int representing the maximum number of iterations before the algorithm times out and",
"use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values)",
"argument decimal_precision to be a positive int, instead it is\" f\"{decimal_precision}.\" ) return",
"gamma: float ) -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument",
"to be a float, instead it is \" f\"{type(epsilon)}.\" ) if epsilon <",
"* np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float",
"* centroid - alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta:",
"numpy.ndarray representing the vector of simplex values. centroid_value (float): A float representing the",
"a point will be contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted point.",
"= simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if",
"\"\"\" Checks the Nelder Mead Simplex Search arguments and returns them prepared for",
"Copyright 2020 Yalfoosh # # Licensed under the Apache License, Version 2.0 (the",
"get a more precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0),",
"a float, instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma =",
"representing the error threshold. Defaults to 1e-6. max_iterations (int, optional): An int representing",
"beta: float = 0.5, gamma: float = 2.0, sigma: float = 0.5, use_jakobovic_expand:",
"= __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if",
"sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma,",
"\"There are no keys available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string",
"Defaults to None (no output during algorithm execution). decimal_precision (int, optional): An int",
"np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function:",
"Checks the Nelder Mead Simplex Search arguments and returns them prepared for work.",
"\"element, instead it is empty.\" ) if not isinstance(stride, (float, int)): raise TypeError(",
"A float representing the amount a point will be reflected. Returns: np.ndarray: A",
"a new point and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We",
"the stopping condition of Nelder Mead Simplex Search has been met, False otherwise.",
"alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride =",
"instead it is \" f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0] ==",
"float used when moving points to the optimum. Defaults to 0.5. use_jakobovic_expand (float,",
"print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result = function(centroid, dont_count=True) result",
"alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point",
"least one \" \"element, instead it is empty.\" ) if not isinstance(stride, (float,",
".function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma: float,",
"float, float, float, bool, float, int, int, int]: \"\"\" Checks the Nelder Mead",
"= float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected argument gamma to be",
"is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations",
"representing the stride. Returns: np.ndarray: A matrix with each row representing a point",
"(np.ndarray): A numpy.ndarray representing the worst point of a simplex. beta (float): A",
"amount a point will be expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded",
"not be a minimum.\", file=sys.stderr, ) # Do this to get a more",
"starting point for simplex generation. stride (float): A float representing the stride. Returns:",
"optional): A float representing the error threshold. Defaults to 1e-6. max_iterations (int, optional):",
"simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points = points + stride *",
"error threshold. Returns: bool: True if the stopping condition of Nelder Mead Simplex",
"it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError( \"Expected argument",
"= 0.5, gamma: float = 2.0, sigma: float = 0.5, use_jakobovic_expand: bool =",
"maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity,",
"the number of decimal digits to round numbers outputted during algorithm execution. \"\"\"",
"function: Function, alpha: float, beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon:",
"a more precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0)",
"negative number. TypeError: Raised if argument verbosity is not a str. KeyError: Raised",
"Raised if argument decimal_precision is not an int. ValueError: Raised if argument decimal_precision",
"to be an int, instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations <",
"numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point",
"point. \"\"\" return (1 + alpha) * centroid - alpha * maximum_point def",
"argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray):",
"__time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if timed_out: print( f\"WARNING:",
"the loss function. start (np.ndarray): A numpy.ndarray representing the starting point of the",
"it is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if",
"stride: float) -> np.ndarray: \"\"\" Generates simplex points for a starting point. Args:",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"TypeError: Raised if argument epsilon is not a float. ValueError: Raised if argument",
"function to be a Function, instead it is \" f\"{type(function)}.\" ) if isinstance(alpha,",
"TypeError: Raised if argument gamma is not a float. TypeError: Raised if argument",
"argument beta is not a float. TypeError: Raised if argument gamma is not",
"it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma) if not",
"f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta) if not isinstance(beta, float): raise",
"optional): A float used in point reflection. Defaults to 1.0. beta (float, optional):",
"f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity,",
"if timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed out after {max_iterations} \"",
"reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) <",
"it is \" f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0] == 0:",
"raise ValueError( \"Expected argument starting point to be a vector with at least",
"a modified version which is supposedly the correct one, as said by prof.",
"int]: Cleaned arguments. \"\"\" if not isinstance(function, Function): raise TypeError( \"Expected argument function",
"the level of verbosity of the output during algorithm execution. decimal_precision (int): An",
"= list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"')",
"_ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index,",
"Nelder Mead Simplex Search arguments and returns them prepared for work. Args: function",
"timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for _ in",
"Raised if argument epsilon is a negative number. TypeError: Raised if argument max_iterations",
"gamma=gamma ) expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index]",
"isinstance(sigma, float): raise TypeError( \"Expected argument sigma to be a float, instead it",
"starting point for simplex generation. stride (Union[float, int]): A float or int representing",
"\"Expected argument starting point to be a vector with at least one \"",
"contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value <",
"See the License for the specific language governing permissions and # limitations under",
"maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. alpha (float):",
"centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] =",
"< 1: raise ValueError( \"Expected argument max_interations to be a positive integer, instead",
"f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not in the Nelder",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"worst point of a simplex. beta (float): A float representing the amount a",
"stride=stride) simplex_values = np.array([function(x) for x in simplex_points]) timed_out = True expansion_method =",
"+ beta * maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float )",
"verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string =",
"the stride. Returns: np.ndarray: A matrix with each row representing a point of",
"+ gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float )",
"and returns them prepared for work. Args: function (Function): A Function representing the",
"\"Expected argument beta to be a float, instead it is \" f\"{type(beta)}.\" )",
"Returns: Tuple[Function, float, float, float, float, bool, float, int, int, int]: Cleaned arguments.",
"TypeError( \"Expected argument sigma to be a float, instead it is \" f\"{type(sigma)}.\"",
"function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points(",
"be an int, instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1:",
"a negative number. Returns: Tuple[Function, float, float, float, float, bool, float, int, int,",
"A float used in point reflection. Defaults to 1.0. beta (float, optional): A",
"\"Expected argument function to be a Function, instead it is \" f\"{type(function)}.\" )",
"expanded point. \"\"\" return (1 - gamma) * centroid + gamma * reflected_point",
"float, int, int, int]: \"\"\" Checks the Nelder Mead Simplex Search arguments and",
"simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon",
"simplex_values[maximum_index] = contracted_value else: for i, simplex_point in enumerate(simplex_points): if i == minimum_index:",
"\" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to",
"verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values",
"if the stopping condition of Nelder Mead Simplex Search has been met, False",
"1.0. beta (float, optional): A float used in point contraction. Defaults to 0.5.",
"decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values =",
"Defaults to 1.0. beta (float, optional): A float used in point contraction. Defaults",
"np.ndarray: A matrix with each row representing a point of the simplex. \"\"\"",
"sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, )",
"A matrix with each row representing a point of the simplex. \"\"\" points",
"np.ndarray: A numpy.ndarray representing the reflected point. \"\"\" return (1 + alpha) *",
"to stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the",
"execution. \"\"\" if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity >",
"f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision to be",
"np.tile(start, reps=(start.shape[0], 1)) points = points + stride * np.eye(points.shape[0]) return np.vstack([start, points])",
"TypeError( \"Expected argument start to be a numpy.ndarray, instead it is \" f\"{type(start)}.\"",
"the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points = points + stride",
") if isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma, float): raise TypeError(",
"alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function,",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\"",
"Args: start (np.ndarray): A numpy.ndarray representing the starting point for simplex generation. stride",
"centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point",
"the verbosity of the output during algorithm execution. Defaults to None (no output",
"Union[float, int] = 1, alpha: float = 1.0, beta: float = 0.5, gamma:",
"100000, verbosity: Optional[str] = None, decimal_precision: int = 3, ) -> np.ndarray: \"\"\"",
"of verbosity of the output during algorithm execution. decimal_precision (int): An int representing",
"to 1.0. beta (float, optional): A float used in point contraction. Defaults to",
") -> Tuple[Function, float, float, float, float, bool, float, int, int, int]: \"\"\"",
") reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value =",
"function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value",
"will be reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected point. \"\"\" return",
"a positive integer, instead it is \" f\"{max_iterations}.\" ) if verbosity is None:",
"to use the __expand_jakobovic method instead of the __expand method for point expansion.",
"gamma) * centroid + gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray,",
"optional): An int representing the maximum number of iterations before the algorithm times",
"= expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else:",
"__contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts argument",
"range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0)",
"expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded point. \"\"\" return (1 -",
"* maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray:",
"Tuple[Function, float, float, float, float, bool, float, int, int, int]: \"\"\" Checks the",
"starting point. Args: start (np.ndarray): A numpy.ndarray representing the starting point for simplex",
"__time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float ) -> bool: \"\"\" Checks if",
"version which is supposedly the correct one, as said by prof. Jakobović. Args:",
"reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected point. \"\"\" return (1 +",
"float, instead it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError(",
"an int, instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise",
"epsilon to be a positive float, instead it is \" f\"{epsilon}.\" ) if",
"is not a float. ValueError: Raised if argument epsilon is a negative number.",
"= \"There are no keys available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0]",
"is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \"",
"float used when moving points to the optimum. use_jakobovic_expand (bool): A bool determining",
"the amount a point will be reflected. Returns: np.ndarray: A numpy.ndarray representing the",
"reflected_point wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the",
"- result might not be a minimum.\", file=sys.stderr, ) # Do this to",
"clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start,",
"if start.shape[0] == 0: raise ValueError( \"Expected argument starting point to be a",
"float): raise TypeError( \"Expected argument beta to be a float, instead it is",
"point expansion. Defaults to False. epsilon (float): A float representing the error threshold.",
"maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\"",
"np.reshape(start, -1) if start.shape[0] == 0: raise ValueError( \"Expected argument starting point to",
"epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] )",
"a str, instead it is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length",
"= float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\"",
"use_jakobovic_expand to be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not",
"+= \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise",
"__expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument",
"np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect(",
"key \"{verbosity}\" is not in the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\"",
"minimum.\", file=sys.stderr, ) # Do this to get a more precise result maximum_index",
"KIND, either express or implied. # See the License for the specific language",
"file=sys.stderr, ) # Do this to get a more precise result maximum_index =",
"sigma = float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected argument sigma to",
"-> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to find an n-D optimum",
"start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for",
"= clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, )",
"argument stride is not a float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments.",
"Nelder Mead Simplex Search to find an n-D optimum of a function. Args:",
"stride: Union[float, int] = 1, alpha: float = 1.0, beta: float = 0.5,",
"maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point)",
"if argument decimal_precision is a negative number. Returns: Tuple[Function, float, float, float, float,",
"if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for i,",
"epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float,",
"__reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects argument",
"is not a float. TypeError: Raised if argument beta is not a float.",
"reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float ) -> bool: \"\"\"",
"numpy.ndarray representing the simplex centroid. verbosity (int): An int representing the level of",
"ANY KIND, either express or implied. # See the License for the specific",
"the error threshold. Returns: bool: True if the stopping condition of Nelder Mead",
"simplex_values = np.array([function(x) for x in simplex_points]) timed_out = True expansion_method = __expand_jakobovic",
"gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta,",
"Function, instead it is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha)",
"simplex values. centroid_value (float): A float representing the value of the simplex centroid.",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"raise TypeError( f\"Expected argument verbosity to be a str, instead it is {type(verbosity)}.\"",
"stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x",
"supposedly the correct one, as said by prof. Jakobović. Args: centroid (np.ndarray): A",
"centroid_value (float): A float representing the value of the simplex centroid. epsilon (float):",
"if argument use_jakobovic_expand is not a bool. TypeError: Raised if argument epsilon is",
"points + stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point:",
"(1 + alpha) * centroid - alpha * maximum_point def __contract( centroid: np.ndarray,",
"alpha to be a float, instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta,",
"- gamma) * centroid - gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value:",
") -> bool: \"\"\" Checks if it's time to stop Nelder Mead Simplex",
") -> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by argument beta. Args:",
"epsilon (float, optional): A float representing the error threshold. Defaults to 1e-6. max_iterations",
"Returns: np.ndarray: A numpy.ndarray representing the last found optimum. \"\"\" ( function, alpha,",
"simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if timed_out: print( f\"WARNING: Nelder",
"centroid - gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float",
"= reflected_value # We need this here since we're introducing a new point",
"float, float, float, bool, float, int, int, int]: Cleaned arguments. \"\"\" if not",
"the last found optimum. verbosity (Optional[str]): A str representing the verbosity of the",
"Search arguments and returns them prepared for work. Args: function (Function): A Function",
"the search. stride (Union[float, int], optional): A float or int representing the stride",
"TypeError( f\"Expected argument verbosity to be a str, instead it is {type(verbosity)}.\" )",
"\" f\"{max_iterations}.\" ) if verbosity is None: verbosity = \"none\" if not isinstance(verbosity,",
"wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex",
"verbosity = \"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to",
"float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float, float,",
"instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta) if",
"* reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float ) -> bool:",
"bool. TypeError: Raised if argument epsilon is not a float. ValueError: Raised if",
"of the search. stride (Union[float, int], optional): A float or int representing the",
"epsilon=epsilon, ): timed_out = False break if timed_out: print( f\"WARNING: Nelder Mead Simplex",
"if not isinstance(gamma, float): raise TypeError( \"Expected argument gamma to be a float,",
"simplex. alpha (float): A float representing the amount a point will be reflected.",
"for simplex generation. Defaults to 1. alpha (float, optional): A float used in",
"np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments",
"from typing import Optional, Tuple, Union import numpy as np from . import",
"before the algorithm times out and returns the last found optimum. Defaults to",
"found optimum. verbosity (Optional[str]): A str representing the verbosity of the output during",
"numbers outputted during algorithm execution. Raises: TypeError: Raised if argument function is not",
"a function. Args: function (Function): A Function representing the loss function. start (np.ndarray):",
"-> Tuple[Function, float, float, float, float, bool, float, int, int, int]: \"\"\" Checks",
"output during algorithm execution. decimal_precision (int): An int representing the number of decimal",
"work. Args: start (np.ndarray): A numpy.ndarray representing the starting point for simplex generation.",
"start, stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex points",
"the output during algorithm execution. Defaults to None (no output during algorithm execution).",
"by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point",
"= 100000, verbosity: Optional[str] = None, decimal_precision: int = 3, ) -> np.ndarray:",
"numpy.ndarray representing the reflected point. \"\"\" return (1 + alpha) * centroid -",
"float, bool, float, int, int, int]: \"\"\" Checks the Nelder Mead Simplex Search",
"np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) =",
"expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value",
"argument function is not a Function. TypeError: Raised if argument alpha is not",
"__reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value",
"optimum. \"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision,",
"return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision:",
"representing the loss function. alpha (float): A float used in point reflection. beta",
") -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. Args:",
"verbosity (Optional[str], optional): A str representing the verbosity of the output during algorithm",
"iterations before the algorithm times out and returns the last found optimum. Defaults",
"np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to do this since the maximum",
"epsilon is not a float. ValueError: Raised if argument epsilon is a negative",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations,",
"else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function,",
"the correct one, as said by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray",
"the last found optimum. \"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon,",
"to False. epsilon (float, optional): A float representing the error threshold. Defaults to",
"representing the stride. Raises: TypeError: Raised if argument start is not a numpy.ndarray.",
"found optimum. Defaults to 100000. verbosity (Optional[str], optional): A str representing the verbosity",
"= clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in",
"(Optional[str]): A str representing the verbosity of the output during algorithm execution. decimal_precision",
"of decimal digits to round numbers outputted during algorithm execution. Defaults to 3.",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"max_interations to be a positive integer, instead it is \" f\"{max_iterations}.\" ) if",
"argument maximum_points wrt centroid by argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing",
"\".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity",
"is not an int. ValueError: Raised if argument decimal_precision is a negative number.",
"beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start,",
"or not to use the __expand_jakobovic method instead of the __expand method for",
"= __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value < maximum_value:",
"applicable law or agreed to in writing, software # distributed under the License",
"float representing the amount a point will be expanded. Returns: np.ndarray: A numpy.ndarray",
"is not in the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity",
"False, epsilon: float = 1e-6, max_iterations: int = 100000, verbosity: Optional[str] = None,",
"argument alpha is not a float. TypeError: Raised if argument beta is not",
"in the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity]",
"= ( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid,",
"execution. Defaults to None (no output during algorithm execution). decimal_precision (int, optional): An",
"after {max_iterations} \" \"iterations - result might not be a minimum.\", file=sys.stderr, )",
"to be a positive integer, instead it is \" f\"{max_iterations}.\" ) if verbosity",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"\"Expected argument max_interations to be an int, instead it is \" f\"{type(max_iterations)}.\" )",
"A float used when moving points to the optimum. Defaults to 0.5. use_jakobovic_expand",
"with at least one \" \"element, instead it is empty.\" ) if not",
"of decimal digits to round numbers outputted during algorithm execution. \"\"\" if verbosity",
"== 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result = function(centroid,",
"float or int representing the stride for simplex generation. Defaults to 1. alpha",
"it is \" f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError( \"Expected argument",
"the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if",
"is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon",
"{np.around(centroid, decimal_precision)}\") elif verbosity > 1: result = function(centroid, dont_count=True) result = (",
"a positive float, instead it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int):",
"integer, instead it is \" f\"{max_iterations}.\" ) if verbosity is None: verbosity =",
"1, alpha: float = 1.0, beta: float = 0.5, gamma: float = 2.0,",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"A Function representing the loss function. start (np.ndarray): A numpy.ndarray representing the starting",
"bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError(",
"(float, optional): A float used when moving points to the optimum. Defaults to",
"is supposedly the correct one, as said by prof. Jakobović. Args: centroid (np.ndarray):",
"argument alpha. This is a modified version which is supposedly the correct one,",
"compliance with the License. # You may obtain a copy of the License",
"out after {max_iterations} \" \"iterations - result might not be a minimum.\", file=sys.stderr,",
"maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value:",
"(float): A float representing the stride. Returns: np.ndarray: A matrix with each row",
"epsilon: float ) -> bool: \"\"\" Checks if it's time to stop Nelder",
"float ) -> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by argument beta.",
"3, ) -> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to find an",
"np.ndarray: \"\"\" Generates simplex points for a starting point. Args: start (np.ndarray): A",
"for the specific language governing permissions and # limitations under the License. import",
"alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start:",
"float. TypeError: Raised if argument gamma is not a float. TypeError: Raised if",
"Reflects argument maximum_points wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray",
"gamma (float): A float representing the amount a point will be expanded. Returns:",
"clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in simplex_points])",
"2020 Yalfoosh # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"__expand method for point expansion. Defaults to False. epsilon (float, optional): A float",
"vector with at least one \" \"element, instead it is empty.\" ) if",
"optional): A float used in point expansion. Defaults to 2.0. sigma (float, optional):",
"= 3, ) -> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to find",
"simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point in enumerate(simplex_points): if",
"= np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to do this since the",
"and # limitations under the License. import sys from typing import Optional, Tuple,",
"\"\"\" Expands argument reflected_point wrt centroid by argument alpha. This is a modified",
"maximum number of iterations before the algorithm times out and returns the last",
"digits to round numbers outputted during algorithm execution. Defaults to 3. Returns: np.ndarray:",
"An int representing the maximum number of iterations before the algorithm times out",
"= reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0)",
"beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha,",
"numpy.ndarray representing the expanded point. \"\"\" return (1 - gamma) * centroid +",
"(float): A float representing the value of the simplex centroid. epsilon (float): A",
"decimal_precision)}\") elif verbosity > 1: result = function(centroid, dont_count=True) result = ( np.around(result,",
"A str representing the verbosity of the output during algorithm execution. Defaults to",
"epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start,",
"in point contraction. Defaults to 0.5. gamma (float, optional): A float used in",
"else: for i, simplex_point in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] +=",
"int, int, int]: Cleaned arguments. \"\"\" if not isinstance(function, Function): raise TypeError( \"Expected",
"if argument epsilon is not a float. ValueError: Raised if argument epsilon is",
"during algorithm execution. decimal_precision (int): An int representing the number of decimal digits",
"< maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We need this here",
"the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A bool determining whether or",
"verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".'",
"return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) ->",
"representing the vector of simplex values. centroid_value (float): A float representing the value",
"bool, float, int, int, int]: \"\"\" Checks the Nelder Mead Simplex Search arguments",
"Nelder Mead Simplex Search timed out after {max_iterations} \" \"iterations - result might",
"int): alpha = float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected argument alpha",
"gamma (float, optional): A float used in point expansion. Defaults to 2.0. sigma",
"(np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the",
"is \" f\"{max_iterations}.\" ) if verbosity is None: verbosity = \"none\" if not",
"np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int,",
"Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not",
"them prepared for work. Args: start (np.ndarray): A numpy.ndarray representing the starting point",
"f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to be",
"the error threshold. Defaults to 1e-6. max_iterations (int, optional): An int representing the",
"is not a float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if",
"(the \"License\"); # you may not use this file except in compliance with",
"is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma,",
"Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float, float, float, bool, float, int,",
"simplex points for a starting point. Args: start (np.ndarray): A numpy.ndarray representing the",
"< minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if",
"stride. Returns: np.ndarray: A matrix with each row representing a point of the",
"reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid",
"# Unless required by applicable law or agreed to in writing, software #",
"Generates simplex points for a starting point. Args: start (np.ndarray): A numpy.ndarray representing",
"of a function. Args: function (Function): A Function representing the loss function. start",
"by applicable law or agreed to in writing, software # distributed under the",
"value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to do this",
"-> bool: \"\"\" Checks if it's time to stop Nelder Mead Simplex Search.",
"iterations before the algorithm times out and returns the last found optimum. verbosity",
") if isinstance(beta, int): beta = float(beta) if not isinstance(beta, float): raise TypeError(",
"simplex centroid. verbosity (int): An int representing the level of verbosity of the",
"point of a simplex. gamma (float): A float representing the amount a point",
"if decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision to be a positive",
"Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector of simplex",
") if isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma, float): raise TypeError(",
"wrt centroid by argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex",
"file except in compliance with the License. # You may obtain a copy",
"centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid.",
"if argument verbosity is an invalid key. TypeError: Raised if argument decimal_precision is",
"ValueError: Raised if argument decimal_precision is a negative number. Returns: Tuple[Function, float, float,",
"a point will be expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded point.",
"<= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ):",
"search. stride (Union[float, int], optional): A float or int representing the stride for",
"to 0.5. use_jakobovic_expand (float, optional): A bool determining whether or not to use",
"of decimal digits to round numbers outputted during algorithm execution. Raises: TypeError: Raised",
"np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex points for a starting point.",
"__get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex points for a starting",
"to do this since the maximum value has potentially changed maximum_value = simplex_values[maximum_index]",
"for work. Args: function (Function): A Function representing the loss function. alpha (float):",
"sigma (float, optional): A float used when moving points to the optimum. Defaults",
"used when moving points to the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional):",
") = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision,",
"np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by argument beta. Args: centroid (np.ndarray):",
"a float. ValueError: Raised if argument epsilon is a negative number. TypeError: Raised",
"\" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma, float):",
"= simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma )",
"else __expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid",
"A float representing the amount a point will be expanded. Returns: np.ndarray: A",
"-> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by argument alpha. Args: centroid",
"gamma) * centroid - gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float,",
"beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray,",
") start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x)",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to be a float, instead it",
"3. Returns: np.ndarray: A numpy.ndarray representing the last found optimum. \"\"\" ( function,",
"(bool): A bool determining whether or not to use the __expand_jakobovic method instead",
"def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects",
"minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value",
"ValueError( \"Expected argument decimal_precision to be a positive int, instead it is\" f\"{decimal_precision}.\"",
"= False break if timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed out",
"def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks",
"print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride:",
"not isinstance(gamma, float): raise TypeError( \"Expected argument gamma to be a float, instead",
"int, instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError(",
"will be contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted point. \"\"\" return",
"representing the starting point for simplex generation. stride (Union[float, int]): A float or",
"said by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid.",
"minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] =",
"( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] =",
"dont_count=True) result = ( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c",
"decimal_precision: int, ) -> Tuple[Function, float, float, float, float, bool, float, int, int,",
") contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] =",
"Defaults to 1. alpha (float, optional): A float used in point reflection. Defaults",
") expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] =",
"(float, optional): A float representing the error threshold. Defaults to 1e-6. max_iterations (int,",
"\"Expected argument alpha to be a float, instead it is \" f\"{type(alpha)}.\" )",
"is not a Function. TypeError: Raised if argument alpha is not a float.",
"A numpy.ndarray representing the worst point of a simplex. alpha (float): A float",
"numbers outputted during algorithm execution. \"\"\" if verbosity == 1: print(f\"c = {np.around(centroid,",
"the vector of simplex values. centroid_value (float): A float representing the value of",
"2.0. sigma (float, optional): A float used when moving points to the optimum.",
"isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to be an int, instead it",
"the Nelder Mead Simplex Search values. Args: function (Function): A Function representing the",
"> 1: result = function(centroid, dont_count=True) result = ( np.around(result, 3) if isinstance(result,",
"Returns: np.ndarray: A numpy.ndarray representing the contracted point. \"\"\" return (1 - beta)",
"is not a float. TypeError: Raised if argument gamma is not a float.",
"f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected",
"argument stride to be a float or int, instead it is \" f\"{type(stride)}.\"",
"len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There are no keys available.\" elif",
"float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected argument sigma to be a",
"starting point to be a vector with at least one \" \"element, instead",
"of a simplex. gamma (float): A float representing the amount a point will",
"instead of the __expand method for point expansion. Defaults to False. epsilon (float):",
"elif verbosity > 1: result = function(centroid, dont_count=True) result = ( np.around(result, 3)",
"== minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i]",
"if use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index =",
"TypeError( \"Expected argument use_jakobovic_expand to be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\"",
"A Function representing the loss function. alpha (float): A float used in point",
"__expand method for point expansion. Defaults to False. epsilon (float): A float representing",
"ValueError: Raised if argument start is a zero-length vector. TypeError: Raised if argument",
"row representing a point of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1))",
"point expansion. Defaults to 2.0. sigma (float, optional): A float used when moving",
"raise TypeError( \"Expected argument stride to be a float or int, instead it",
"points for a starting point. Args: start (np.ndarray): A numpy.ndarray representing the starting",
"under the License. import sys from typing import Optional, Tuple, Union import numpy",
"\" \"element, instead it is empty.\" ) if not isinstance(stride, (float, int)): raise",
"max_iterations: int = 100000, verbosity: Optional[str] = None, decimal_precision: int = 3, )",
"decimal_precision (int, optional): An int representing the number of decimal digits to round",
"not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to be a float, instead",
"(float): A float representing the error threshold. max_iterations (int): An int representing the",
"point. Args: start (np.ndarray): A numpy.ndarray representing the starting point for simplex generation.",
"numpy.ndarray representing the starting point of the search. stride (Union[float, int], optional): A",
"it is \" f\"{max_iterations}.\" ) if verbosity is None: verbosity = \"none\" if",
"__get_simplex_points arguments and returns them prepared for work. Args: start (np.ndarray): A numpy.ndarray",
"(np.ndarray): A numpy.ndarray representing the vector of simplex values. centroid_value (float): A float",
"epsilon: float = 1e-6, max_iterations: int = 100000, verbosity: Optional[str] = None, decimal_precision:",
"instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError( \"Expected",
"the __expand method for point expansion. Defaults to False. epsilon (float, optional): A",
"1: result = function(centroid, dont_count=True) result = ( np.around(result, 3) if isinstance(result, np.ndarray)",
"= simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index]",
"\"\"\" Expands argument reflected_point wrt centroid by argument alpha. Args: centroid (np.ndarray): A",
"representing the error threshold. max_iterations (int): An int representing the maximum number of",
"it is empty.\" ) if not isinstance(stride, (float, int)): raise TypeError( \"Expected argument",
"= function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else:",
"sigma (float): A float used when moving points to the optimum. use_jakobovic_expand (bool):",
"argument verbosity is an invalid key. TypeError: Raised if argument decimal_precision is not",
"the number of decimal digits to round numbers outputted during algorithm execution. Defaults",
"maximum_index = np.argmax(simplex_values) # We need to do this since the maximum value",
"simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value",
"= None, decimal_precision: int = 3, ) -> np.ndarray: \"\"\" Uses Nelder Mead",
"threshold. Defaults to 1e-6. max_iterations (int, optional): An int representing the maximum number",
") if isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha, float): raise TypeError(",
"Raised if argument decimal_precision is a negative number. Returns: Tuple[Function, float, float, float,",
"the amount a point will be expanded. Returns: np.ndarray: A numpy.ndarray representing the",
") if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to be a",
"isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to be a str, instead it",
"float, instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma)",
"not isinstance(beta, float): raise TypeError( \"Expected argument beta to be a float, instead",
"is not a float. TypeError: Raised if argument use_jakobovic_expand is not a bool.",
"representing the maximum number of iterations before the algorithm times out and returns",
"for x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key",
"def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands",
"return (1 - gamma) * centroid - gamma * reflected_point def __time_to_stop( simplex_values:",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"beta to be a float, instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma,",
"if argument max_iterations is a negative number. TypeError: Raised if argument verbosity is",
"centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument reflected_point",
"timed out after {max_iterations} \" \"iterations - result might not be a minimum.\",",
"\"Expected argument epsilon to be a positive float, instead it is \" f\"{epsilon}.\"",
"float, instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma)",
"stride is not a float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\"",
"if argument verbosity is not a str. KeyError: Raised if argument verbosity is",
"2.0, sigma: float = 0.5, use_jakobovic_expand: bool = False, epsilon: float = 1e-6,",
"maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point",
"start (np.ndarray): A numpy.ndarray representing the starting point for simplex generation. stride (Union[float,",
"stride (Union[float, int], optional): A float or int representing the stride for simplex",
"max_iterations (int, optional): An int representing the maximum number of iterations before the",
"simplex_values[maximum_index] = reflected_value # We need this here since we're introducing a new",
"\"Expected argument sigma to be a float, instead it is \" f\"{type(sigma)}.\" )",
"reflection. Defaults to 1.0. beta (float, optional): A float used in point contraction.",
"float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str],",
"= \"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to be",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"float used in point contraction. Defaults to 0.5. gamma (float, optional): A float",
"float representing the stride. Returns: np.ndarray: A matrix with each row representing a",
"it is \" f\"{type(stride)}.\" ) stride = float(stride) return start, stride def __get_simplex_points(start:",
"the License. import sys from typing import Optional, Tuple, Union import numpy as",
"optional): A str representing the verbosity of the output during algorithm execution. Defaults",
"a float. TypeError: Raised if argument beta is not a float. TypeError: Raised",
"optional): A float or int representing the stride for simplex generation. Defaults to",
"if argument sigma is not a float. TypeError: Raised if argument use_jakobovic_expand is",
"(np.ndarray): A numpy.ndarray representing the worst point of a simplex. gamma (float): A",
"max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride)",
"= __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in simplex_points]) timed_out = True",
"\"{verbosity}\" is not in the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" )",
"max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon,",
"i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) * sigma",
"simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex.",
"instead it is \" f\"{type(stride)}.\" ) stride = float(stride) return start, stride def",
"A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst",
"Defaults to 1e-6. max_iterations (int, optional): An int representing the maximum number of",
"verbosity_string = \"The available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x",
"float, float, bool, float, int, int, int]: \"\"\" Checks the Nelder Mead Simplex",
"during algorithm execution). decimal_precision (int, optional): An int representing the number of decimal",
"__expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument",
"used in point expansion. Defaults to 2.0. sigma (float, optional): A float used",
"algorithm execution. \"\"\" if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity",
"epsilon def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\"",
"np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid,",
"optional): A bool determining whether or not to use the __expand_jakobovic method instead",
"gamma is not a float. TypeError: Raised if argument sigma is not a",
"is \" f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0] == 0: raise",
"optimum. Defaults to 100000. verbosity (Optional[str], optional): A str representing the verbosity of",
"the License for the specific language governing permissions and # limitations under the",
"to be a positive int, instead it is\" f\"{decimal_precision}.\" ) return ( function,",
"argument start to be a numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start",
"representing the amount a point will be reflected. Returns: np.ndarray: A numpy.ndarray representing",
"a float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start,",
"bool: True if the stopping condition of Nelder Mead Simplex Search has been",
"the maximum value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid,",
"float = 0.5, gamma: float = 2.0, sigma: float = 0.5, use_jakobovic_expand: bool",
"centroid_value: float, epsilon: float ) -> bool: \"\"\" Checks if it's time to",
"numpy.ndarray representing the starting point for simplex generation. stride (float): A float representing",
"- alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float )",
"TypeError( \"Expected argument stride to be a float or int, instead it is",
"argument beta to be a float, instead it is \" f\"{type(beta)}.\" ) if",
"result = ( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c =",
"will be expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded point. \"\"\" return",
"function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon,",
"{type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length ==",
"if epsilon < 0: raise ValueError( \"Expected argument epsilon to be a positive",
"= True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for _ in range(max_iterations):",
"simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point",
"if argument beta is not a float. TypeError: Raised if argument gamma is",
"(Function): A Function representing the loss function. start (np.ndarray): A numpy.ndarray representing the",
". import constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float,",
"simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break",
"it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta) if not",
"float used in point expansion. Defaults to 2.0. sigma (float, optional): A float",
"float used in point reflection. beta (float): A float used in point contraction.",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"not isinstance(function, Function): raise TypeError( \"Expected argument function to be a Function, instead",
"to find an n-D optimum of a function. Args: function (Function): A Function",
"{result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int] = 1, alpha:",
"\"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points = points + stride * np.eye(points.shape[0])",
"the number of decimal digits to round numbers outputted during algorithm execution. Raises:",
"decimal_precision to be a positive int, instead it is\" f\"{decimal_precision}.\" ) return (",
"of a simplex. beta (float): A float representing the amount a point will",
"in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i]",
"the contracted point. \"\"\" return (1 - beta) * centroid + beta *",
"by argument alpha. This is a modified version which is supposedly the correct",
"no keys available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The",
"be a Function, instead it is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha",
"__expand_jakobovic method instead of the __expand method for point expansion. Defaults to False.",
"expansion. Defaults to 2.0. sigma (float, optional): A float used when moving points",
"License. import sys from typing import Optional, Tuple, Union import numpy as np",
"the stride. Raises: TypeError: Raised if argument start is not a numpy.ndarray. ValueError:",
"Raised if argument alpha is not a float. TypeError: Raised if argument beta",
"alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) ->",
"return (1 - beta) * centroid + beta * maximum_point def __expand( centroid:",
"\"\"\" Prints the Nelder Mead Simplex Search values. Args: function (Function): A Function",
"not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to be an int, instead",
"or int representing the stride. Raises: TypeError: Raised if argument start is not",
"Defaults to 2.0. sigma (float, optional): A float used when moving points to",
"maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid,",
"we're introducing a new point and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values)",
"np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by",
"maximum_points wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the",
"alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A",
"execution. decimal_precision (int): An int representing the number of decimal digits to round",
"last found optimum. \"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations,",
"use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points =",
"i, simplex_point in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index]",
") if not isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride to be",
"condition of Nelder Mead Simplex Search has been met, False otherwise. \"\"\" difference_in_values",
"of the __expand method for point expansion. Defaults to False. epsilon (float, optional):",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"is a negative number. TypeError: Raised if argument max_iterations is not an int.",
"(float, optional): A float used in point reflection. Defaults to 1.0. beta (float,",
"positive int, instead it is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma,",
"a minimum.\", file=sys.stderr, ) # Do this to get a more precise result",
"alpha (float, optional): A float used in point reflection. Defaults to 1.0. beta",
"of the simplex centroid. epsilon (float): A float representing the error threshold. Returns:",
"it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError( \"Expected argument",
"if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We need",
"more precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) return",
"contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted point. \"\"\" return (1 -",
"{np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int]",
"for x in simplex_points]) timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand else",
"centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. alpha",
"f'The only available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The",
"TypeError( \"Expected argument epsilon to be a float, instead it is \" f\"{type(epsilon)}.\"",
"We need to do this since the maximum value has potentially changed maximum_value",
"float used in point reflection. Defaults to 1.0. beta (float, optional): A float",
"before the algorithm times out and returns the last found optimum. verbosity (Optional[str]):",
"np.ndarray, stride: Union[float, int] = 1, alpha: float = 1.0, beta: float =",
"alpha = float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected argument alpha to",
"A float used in point expansion. Defaults to 2.0. sigma (float, optional): A",
"\"\"\" return (1 - beta) * centroid + beta * maximum_point def __expand(",
") if not isinstance(epsilon, float): raise TypeError( \"Expected argument epsilon to be a",
"\"\"\" Checks if it's time to stop Nelder Mead Simplex Search. Args: simplex_values",
"import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma: float, sigma:",
"a float, instead it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise",
"to get a more precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index,",
"an int. ValueError: Raised if argument max_iterations is a negative number. TypeError: Raised",
"beta (float): A float representing the amount a point will be contracted. Returns:",
"argument max_interations to be an int, instead it is \" f\"{type(max_iterations)}.\" ) if",
"isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to be a bool, instead it",
"isinstance(beta, float): raise TypeError( \"Expected argument beta to be a float, instead it",
"a bool. TypeError: Raised if argument epsilon is not a float. ValueError: Raised",
"1. alpha (float, optional): A float used in point reflection. Defaults to 1.0.",
"is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision",
"contracted_value else: for i, simplex_point in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i]",
"reflection. beta (float): A float used in point contraction. gamma (float): A float",
"float, float, bool, float, int, int, int]: Cleaned arguments. \"\"\" if not isinstance(function,",
"alpha is not a float. TypeError: Raised if argument beta is not a",
"if not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to be a str,",
"x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\"",
"1: raise ValueError( \"Expected argument max_interations to be a positive integer, instead it",
"- beta) * centroid + beta * maximum_point def __expand( centroid: np.ndarray, reflected_point:",
") -> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by argument alpha. Args:",
"= function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid),",
"a starting point. Args: start (np.ndarray): A numpy.ndarray representing the starting point for",
"(1 - gamma) * centroid - gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray,",
"be a numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start = np.reshape(start, -1)",
"points to the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A bool determining",
"the worst point of a simplex. beta (float): A float representing the amount",
"optional): An int representing the number of decimal digits to round numbers outputted",
"argument epsilon to be a positive float, instead it is \" f\"{epsilon}.\" )",
"is a negative number. TypeError: Raised if argument verbosity is not a str.",
"Search to find an n-D optimum of a function. Args: function (Function): A",
"float): raise TypeError( \"Expected argument sigma to be a float, instead it is",
"isinstance(function, Function): raise TypeError( \"Expected argument function to be a Function, instead it",
"0.5. use_jakobovic_expand (float, optional): A bool determining whether or not to use the",
"typing import Optional, Tuple, Union import numpy as np from . import constants",
"(float): A float representing the amount a point will be expanded. Returns: np.ndarray:",
"max_interations to be an int, instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations",
"Mead Simplex Search timed out after {max_iterations} \" \"iterations - result might not",
"it is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError( \"Expected argument",
") -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and returns them prepared",
"Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to",
"A float used in point reflection. beta (float): A float used in point",
"\" f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0] == 0: raise ValueError(",
"gamma to be a float, instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma,",
"x in simplex_points]) timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand",
"not a Function. TypeError: Raised if argument alpha is not a float. TypeError:",
"(np.ndarray): A numpy.ndarray representing the starting point for simplex generation. stride (Union[float, int]):",
"Function representing the loss function. alpha (float): A float used in point reflection.",
"simplex. gamma (float): A float representing the amount a point will be expanded.",
"float representing the error threshold. max_iterations (int): An int representing the maximum number",
"the value of the simplex centroid. epsilon (float): A float representing the error",
"the __get_simplex_points arguments and returns them prepared for work. Args: start (np.ndarray): A",
"for work. Args: start (np.ndarray): A numpy.ndarray representing the starting point for simplex",
"point expansion. Defaults to False. epsilon (float, optional): A float representing the error",
"np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, )",
"A float or int representing the stride. Raises: TypeError: Raised if argument start",
"(float, optional): A bool determining whether or not to use the __expand_jakobovic method",
"Raises: TypeError: Raised if argument start is not a numpy.ndarray. ValueError: Raised if",
"is a modified version which is supposedly the correct one, as said by",
"points = points + stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid:",
"returns the last found optimum. Defaults to 100000. verbosity (Optional[str], optional): A str",
"Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector of",
"start (np.ndarray): A numpy.ndarray representing the starting point of the search. stride (Union[float,",
"raise TypeError( \"Expected argument start to be a numpy.ndarray, instead it is \"",
"simplex generation. Defaults to 1. alpha (float, optional): A float used in point",
"outputted during algorithm execution. \"\"\" if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\")",
"Defaults to False. epsilon (float, optional): A float representing the error threshold. Defaults",
"if not isinstance(beta, float): raise TypeError( \"Expected argument beta to be a float,",
"available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys",
"point reflection. Defaults to 1.0. beta (float, optional): A float used in point",
"stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex points for",
"\"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \" verbosity_string",
"axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha",
"int): gamma = float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected argument gamma",
"argument verbosity to be a str, instead it is {type(verbosity)}.\" ) if verbosity",
"sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop(",
"): timed_out = False break if timed_out: print( f\"WARNING: Nelder Mead Simplex Search",
"result might not be a minimum.\", file=sys.stderr, ) # Do this to get",
"the output during algorithm execution. decimal_precision (int): An int representing the number of",
"is an invalid key. TypeError: Raised if argument decimal_precision is not an int.",
"(int, optional): An int representing the maximum number of iterations before the algorithm",
"- gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float )",
"' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError(",
"int, instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError(",
"since we're introducing a new point and value minimum_index = np.argmin(simplex_values) maximum_index =",
"str representing the verbosity of the output during algorithm execution. Defaults to None",
"_keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not",
"epsilon to be a float, instead it is \" f\"{type(epsilon)}.\" ) if epsilon",
"OF ANY KIND, either express or implied. # See the License for the",
"expansion. Defaults to False. epsilon (float, optional): A float representing the error threshold.",
"when moving points to the optimum. use_jakobovic_expand (bool): A bool determining whether or",
"to round numbers outputted during algorithm execution. \"\"\" if verbosity == 1: print(f\"c",
"with each row representing a point of the simplex. \"\"\" points = np.tile(start,",
"to the optimum. use_jakobovic_expand (bool): A bool determining whether or not to use",
"Args: function (Function): A Function representing the loss function. alpha (float): A float",
"np from . import constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function,",
"keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string +=",
"ValueError( \"Expected argument max_interations to be a positive integer, instead it is \"",
"moving points to the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A bool",
"to 1e-6. max_iterations (int, optional): An int representing the maximum number of iterations",
"start (np.ndarray): A numpy.ndarray representing the starting point for simplex generation. stride (float):",
"last found optimum. Defaults to 100000. verbosity (Optional[str], optional): A str representing the",
"float = 2.0, sigma: float = 0.5, use_jakobovic_expand: bool = False, epsilon: float",
"A numpy.ndarray representing the worst point of a simplex. gamma (float): A float",
"each row representing a point of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0],",
"float, instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta)",
"Defaults to 0.5. use_jakobovic_expand (float, optional): A bool determining whether or not to",
"Returns: np.ndarray: A numpy.ndarray representing the expanded point. \"\"\" return (1 - gamma)",
"to round numbers outputted during algorithm execution. Raises: TypeError: Raised if argument function",
"np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument reflected_point wrt",
"gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float ) ->",
"Raised if argument epsilon is not a float. ValueError: Raised if argument epsilon",
"representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of",
"points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray: \"\"\"",
"the expanded point. \"\"\" return (1 - gamma) * centroid + gamma *",
"int = 100000, verbosity: Optional[str] = None, decimal_precision: int = 3, ) ->",
"arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to be",
"= \"The available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x in",
"worst point of a simplex. gamma (float): A float representing the amount a",
"float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int,",
"__get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in simplex_points]) timed_out = True expansion_method",
"sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float,",
"gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) ->",
"else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values,",
"= float(beta) if not isinstance(beta, float): raise TypeError( \"Expected argument beta to be",
"\"\"\" Contracts argument maximum_points wrt centroid by argument beta. Args: centroid (np.ndarray): A",
"from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma:",
"def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts",
"expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value <",
"float. TypeError: Raised if argument sigma is not a float. TypeError: Raised if",
"Optional[str] = None, decimal_precision: int = 3, ) -> np.ndarray: \"\"\" Uses Nelder",
"an int. ValueError: Raised if argument decimal_precision is a negative number. Returns: Tuple[Function,",
"\" \"iterations - result might not be a minimum.\", file=sys.stderr, ) # Do",
"isinstance(beta, int): beta = float(beta) if not isinstance(beta, float): raise TypeError( \"Expected argument",
"an invalid key. TypeError: Raised if argument decimal_precision is not an int. ValueError:",
"TypeError( \"Expected argument max_interations to be an int, instead it is \" f\"{type(max_iterations)}.\"",
"float representing the amount a point will be contracted. Returns: np.ndarray: A numpy.ndarray",
"representing the value of the simplex centroid. epsilon (float): A float representing the",
"or agreed to in writing, software # distributed under the License is distributed",
"the starting point for simplex generation. stride (Union[float, int]): A float or int",
"__print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints the",
"simplex generation. stride (float): A float representing the stride. Returns: np.ndarray: A matrix",
"argument alpha to be a float, instead it is \" f\"{type(alpha)}.\" ) if",
"float or int, instead it is \" f\"{type(stride)}.\" ) stride = float(stride) return",
"f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to be",
"use the __expand_jakobovic method instead of the __expand method for point expansion. Defaults",
"last found optimum. verbosity (Optional[str]): A str representing the verbosity of the output",
"maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] =",
"-> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid by argument beta. Args: centroid",
"instead it is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha) if",
"stride = float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray:",
"= function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else:",
"\" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha, float):",
"0.5, use_jakobovic_expand: bool = False, epsilon: float = 1e-6, max_iterations: int = 100000,",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"not a float. TypeError: Raised if argument use_jakobovic_expand is not a bool. TypeError:",
"import numpy as np from . import constants from .function import Function def",
"= {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result = function(centroid, dont_count=True) result =",
"\"\"\" Uses Nelder Mead Simplex Search to find an n-D optimum of a",
"License. # You may obtain a copy of the License at # #",
"generation. stride (float): A float representing the stride. Returns: np.ndarray: A matrix with",
"np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts argument maximum_points wrt",
"simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value",
"float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) ->",
"expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index =",
"this here since we're introducing a new point and value minimum_index = np.argmin(simplex_values)",
"is \" f\"{type(stride)}.\" ) stride = float(stride) return start, stride def __get_simplex_points(start: np.ndarray,",
"np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float )",
"function. Args: function (Function): A Function representing the loss function. start (np.ndarray): A",
"work. Args: function (Function): A Function representing the loss function. alpha (float): A",
"import sys from typing import Optional, Tuple, Union import numpy as np from",
"representing the contracted point. \"\"\" return (1 - beta) * centroid + beta",
"constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to be an",
"to 0.5. gamma (float, optional): A float used in point expansion. Defaults to",
"a numpy.ndarray, instead it is \" f\"{type(start)}.\" ) start = np.reshape(start, -1) if",
"decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]:",
"start is not a numpy.ndarray. ValueError: Raised if argument start is a zero-length",
"argument epsilon to be a float, instead it is \" f\"{type(epsilon)}.\" ) if",
"(np.ndarray): A numpy.ndarray representing the worst point of a simplex. alpha (float): A",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"A numpy.ndarray representing the starting point of the search. stride (Union[float, int], optional):",
"+= f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not in the",
"+= ( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index]",
"( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) =",
"alpha. This is a modified version which is supposedly the correct one, as",
"sigma: float = 0.5, use_jakobovic_expand: bool = False, epsilon: float = 1e-6, max_iterations:",
"to be a float, instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int):",
"centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints the Nelder Mead Simplex",
"Simplex Search timed out after {max_iterations} \" \"iterations - result might not be",
"{max_iterations} \" \"iterations - result might not be a minimum.\", file=sys.stderr, ) #",
") if not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to be an",
"has potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, )",
"representing the amount a point will be contracted. Returns: np.ndarray: A numpy.ndarray representing",
"representing the reflected point. \"\"\" return (1 + alpha) * centroid - alpha",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"start.shape[0] == 0: raise ValueError( \"Expected argument starting point to be a vector",
"the starting point of the search. stride (Union[float, int], optional): A float or",
"3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\")",
"(int): An int representing the number of decimal digits to round numbers outputted",
"not a str. KeyError: Raised if argument verbosity is an invalid key. TypeError:",
"the reflected point. \"\"\" return (1 + alpha) * centroid - alpha *",
"isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride to be a float or",
") # Do this to get a more precise result maximum_index = np.argmax(simplex_values)",
"= expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point) if expanded_value < minimum_value:",
"decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value",
"algorithm times out and returns the last found optimum. verbosity (Optional[str]): A str",
"* centroid - gamma * reflected_point def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon:",
"a float, instead it is \" f\"{type(epsilon)}.\" ) if epsilon < 0: raise",
"(float): A float representing the amount a point will be reflected. Returns: np.ndarray:",
"optimum. verbosity (Optional[str]): A str representing the verbosity of the output during algorithm",
"if not isinstance(sigma, float): raise TypeError( \"Expected argument sigma to be a float,",
"not in the Nelder Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity =",
"str representing the verbosity of the output during algorithm execution. decimal_precision (int): An",
"if i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) *",
"1: raise ValueError( \"Expected argument decimal_precision to be a positive int, instead it",
"= points + stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray,",
"not a float. ValueError: Raised if argument epsilon is a negative number. TypeError:",
"def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex points for a",
"\"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to be a",
"points to the optimum. use_jakobovic_expand (bool): A bool determining whether or not to",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"if isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected",
"stride. Raises: TypeError: Raised if argument start is not a numpy.ndarray. ValueError: Raised",
"instead it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected",
"a simplex. alpha (float): A float representing the amount a point will be",
"int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float, float, float, bool,",
"* centroid + gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma:",
"raise TypeError( \"Expected argument alpha to be a float, instead it is \"",
"representing the worst point of a simplex. gamma (float): A float representing the",
"int, ): \"\"\" Prints the Nelder Mead Simplex Search values. Args: function (Function):",
"decimal digits to round numbers outputted during algorithm execution. Defaults to 3. Returns:",
"number of decimal digits to round numbers outputted during algorithm execution. Raises: TypeError:",
"in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is",
"argument sigma is not a float. TypeError: Raised if argument use_jakobovic_expand is not",
"simplex generation. stride (Union[float, int]): A float or int representing the stride. Raises:",
"isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected argument",
"points = np.tile(start, reps=(start.shape[0], 1)) points = points + stride * np.eye(points.shape[0]) return",
"gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride)",
"function (Function): A Function representing the loss function. alpha (float): A float used",
"centroid by argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid.",
"centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity (int): An int representing",
"A float or int representing the stride for simplex generation. Defaults to 1.",
"minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] =",
"numpy.ndarray representing the expanded point. \"\"\" return (1 - gamma) * centroid -",
"changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value =",
"- simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index]",
"Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument",
"representing the starting point for simplex generation. stride (float): A float representing the",
"key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are",
"< maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point in",
"= np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function,",
"instead it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError( \"Expected",
"np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints the Nelder Mead Simplex Search",
"to None (no output during algorithm execution). decimal_precision (int, optional): An int representing",
"of a simplex. alpha (float): A float representing the amount a point will",
"or implied. # See the License for the specific language governing permissions and",
"# We need this here since we're introducing a new point and value",
"instead it is empty.\" ) if not isinstance(stride, (float, int)): raise TypeError( \"Expected",
"< minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index]",
"found optimum. \"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity,",
"if argument gamma is not a float. TypeError: Raised if argument sigma is",
"outputted during algorithm execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing the",
"precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) return centroid",
"sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity, decimal_precision=decimal_precision, ) start, stride = clean_get_simplex_points(start=start, stride=stride) simplex_points",
"verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not in",
"float = 0.5, use_jakobovic_expand: bool = False, epsilon: float = 1e-6, max_iterations: int",
"= simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <=",
"decimal digits to round numbers outputted during algorithm execution. Raises: TypeError: Raised if",
"sigma to be a float, instead it is \" f\"{type(sigma)}.\" ) if not",
"int], optional): A float or int representing the stride for simplex generation. Defaults",
"the algorithm times out and returns the last found optimum. verbosity (Optional[str]): A",
"Raised if argument start is not a numpy.ndarray. ValueError: Raised if argument start",
"maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We need this here since",
"return (1 - gamma) * centroid + gamma * reflected_point def __expand_jakobovic( centroid:",
"gamma (float): A float used in point expansion. sigma (float): A float used",
"method for point expansion. Defaults to False. epsilon (float, optional): A float representing",
"of Nelder Mead Simplex Search has been met, False otherwise. \"\"\" difference_in_values =",
"be a float, instead it is \" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta",
"centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. beta",
"not a float. TypeError: Raised if argument gamma is not a float. TypeError:",
"algorithm execution). decimal_precision (int, optional): An int representing the number of decimal digits",
"int, ) -> Tuple[Function, float, float, float, float, bool, float, int, int, int]:",
"decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand, epsilon=epsilon, max_iterations=max_iterations, verbosity=verbosity,",
"to be a float or int, instead it is \" f\"{type(stride)}.\" ) stride",
"a negative number. TypeError: Raised if argument max_iterations is not an int. ValueError:",
"Returns: bool: True if the stopping condition of Nelder Mead Simplex Search has",
"is not a float. TypeError: Raised if argument sigma is not a float.",
"Mead Simplex Search has been met, False otherwise. \"\"\" difference_in_values = simplex_values -",
"Raised if argument stride is not a float or int. Returns: Tuple[np.ndarray, float]:",
"np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha: float ) -> np.ndarray:",
"stride to be a float or int, instead it is \" f\"{type(stride)}.\" )",
"function (Function): A Function representing the loss function. centroid (np.ndarray): A numpy.ndarray representing",
"centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts argument maximum_points",
"and returns the last found optimum. Defaults to 100000. verbosity (Optional[str], optional): A",
"return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, )",
"np.ndarray: A numpy.ndarray representing the contracted point. \"\"\" return (1 - beta) *",
"reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We",
"= function(centroid, dont_count=True) result = ( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\"",
"for i, simplex_point in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] += (",
"= reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if",
"not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to be a bool, instead",
"threshold. max_iterations (int): An int representing the maximum number of iterations before the",
"use this file except in compliance with the License. # You may obtain",
"the starting point for simplex generation. stride (float): A float representing the stride.",
"representing the level of verbosity of the output during algorithm execution. decimal_precision (int):",
"epsilon is a negative number. TypeError: Raised if argument max_iterations is not an",
"Raised if argument max_iterations is a negative number. TypeError: Raised if argument verbosity",
"minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to do this since",
"A numpy.ndarray representing the last found optimum. \"\"\" ( function, alpha, beta, gamma,",
"TypeError: Raised if argument verbosity is not a str. KeyError: Raised if argument",
"np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to find an n-D optimum of",
"argument epsilon is a negative number. TypeError: Raised if argument max_iterations is not",
"int, instead it is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma, sigma,",
"int = 3, ) -> np.ndarray: \"\"\" Uses Nelder Mead Simplex Search to",
"* maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray:",
"digits to round numbers outputted during algorithm execution. Raises: TypeError: Raised if argument",
"be a positive float, instead it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations,",
"centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value <",
"is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha,",
"reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value",
"float, beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int,",
"np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by",
"values. Args: function (Function): A Function representing the loss function. centroid (np.ndarray): A",
"0: verbosity_string = \"There are no keys available.\" elif verbosity_dict_length == 1: _key",
"float = 1e-6, max_iterations: int = 100000, verbosity: Optional[str] = None, decimal_precision: int",
"1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is \"{_key}\".' else:",
"introducing a new point and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) #",
"float representing the error threshold. Defaults to 1e-6. max_iterations (int, optional): An int",
") start = np.reshape(start, -1) if start.shape[0] == 0: raise ValueError( \"Expected argument",
"\"Expected argument max_interations to be a positive integer, instead it is \" f\"{max_iterations}.\"",
"a float. TypeError: Raised if argument sigma is not a float. TypeError: Raised",
"TypeError( \"Expected argument function to be a Function, instead it is \" f\"{type(function)}.\"",
"contraction. Defaults to 0.5. gamma (float, optional): A float used in point expansion.",
"used in point contraction. gamma (float): A float used in point expansion. sigma",
"if argument max_iterations is not an int. ValueError: Raised if argument max_iterations is",
"enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] )",
"use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma,",
"use_jakobovic_expand is not a bool. TypeError: Raised if argument epsilon is not a",
"list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys()))",
"TypeError: Raised if argument start is not a numpy.ndarray. ValueError: Raised if argument",
"and returns the last found optimum. verbosity (Optional[str]): A str representing the verbosity",
"output during algorithm execution). decimal_precision (int, optional): An int representing the number of",
"point for simplex generation. stride (Union[float, int]): A float or int representing the",
"numpy.ndarray representing the worst point of a simplex. alpha (float): A float representing",
"-> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. This is",
"the expanded point. \"\"\" return (1 - gamma) * centroid - gamma *",
"Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float, gamma: float, sigma: float,",
"vector. TypeError: Raised if argument stride is not a float or int. Returns:",
"Simplex Search has been met, False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value",
"not a float. TypeError: Raised if argument sigma is not a float. TypeError:",
"be a float, instead it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool):",
"isinstance(gamma, float): raise TypeError( \"Expected argument gamma to be a float, instead it",
"def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int] = 1, alpha: float",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"Defaults to 0.5. gamma (float, optional): A float used in point expansion. Defaults",
"used in point reflection. beta (float): A float used in point contraction. gamma",
"during algorithm execution. Raises: TypeError: Raised if argument function is not a Function.",
"\"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not in the Nelder Mead Simplex",
"or int representing the stride for simplex generation. Defaults to 1. alpha (float,",
"False break if timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed out after",
"np.ndarray: A numpy.ndarray representing the last found optimum. \"\"\" ( function, alpha, beta,",
"times out and returns the last found optimum. verbosity (Optional[str]): A str representing",
"be contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted point. \"\"\" return (1",
"continue simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i])",
"Args: function (Function): A Function representing the loss function. start (np.ndarray): A numpy.ndarray",
"verbosity of the output during algorithm execution. Defaults to None (no output during",
"np.array([function(x) for x in simplex_points]) timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand",
"TypeError: Raised if argument stride is not a float or int. Returns: Tuple[np.ndarray,",
"Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and returns",
"representing the worst point of a simplex. beta (float): A float representing the",
"= np.array([function(x) for x in simplex_points]) timed_out = True expansion_method = __expand_jakobovic if",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"as said by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex",
"* centroid + beta * maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma:",
"negative number. Returns: Tuple[Function, float, float, float, float, bool, float, int, int, int]:",
"of iterations before the algorithm times out and returns the last found optimum.",
"point contraction. gamma (float): A float used in point expansion. sigma (float): A",
"def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray: \"\"\" Expands",
"and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to do",
"f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma, float): raise",
"representing the verbosity of the output during algorithm execution. decimal_precision (int): An int",
"\"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected argument start to be a",
"arguments. \"\"\" if not isinstance(function, Function): raise TypeError( \"Expected argument function to be",
"int): raise TypeError( \"Expected argument max_interations to be an int, instead it is",
"for simplex generation. stride (float): A float representing the stride. Returns: np.ndarray: A",
"# Do this to get a more precise result maximum_index = np.argmax(simplex_values) centroid",
"reps=(start.shape[0], 1)) points = points + stride * np.eye(points.shape[0]) return np.vstack([start, points]) def",
"reflected_point wrt centroid by argument alpha. This is a modified version which is",
"to 3. Returns: np.ndarray: A numpy.ndarray representing the last found optimum. \"\"\" (",
"in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0),",
"None (no output during algorithm execution). decimal_precision (int, optional): An int representing the",
"stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector",
"f\"{max_iterations}.\" ) if verbosity is None: verbosity = \"none\" if not isinstance(verbosity, str):",
"instead it is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT)",
"This is a modified version which is supposedly the correct one, as said",
"centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if timed_out: print( f\"WARNING: Nelder Mead",
"verbosity of the output during algorithm execution. decimal_precision (int): An int representing the",
"\"Expected argument start to be a numpy.ndarray, instead it is \" f\"{type(start)}.\" )",
"it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma) if not",
"\" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma, float):",
"with the License. # You may obtain a copy of the License at",
"n-D optimum of a function. Args: function (Function): A Function representing the loss",
"instead of the __expand method for point expansion. Defaults to False. epsilon (float,",
"\"\"\" return (1 - gamma) * centroid - gamma * reflected_point def __time_to_stop(",
"float representing the value of the simplex centroid. epsilon (float): A float representing",
"start = np.reshape(start, -1) if start.shape[0] == 0: raise ValueError( \"Expected argument starting",
"point for simplex generation. stride (float): A float representing the stride. Returns: np.ndarray:",
"float): raise TypeError( \"Expected argument epsilon to be a float, instead it is",
"not isinstance(alpha, float): raise TypeError( \"Expected argument alpha to be a float, instead",
"centroid. epsilon (float): A float representing the error threshold. Returns: bool: True if",
"in point reflection. beta (float): A float used in point contraction. gamma (float):",
"np.argmax(simplex_values) # We need to do this since the maximum value has potentially",
"key. TypeError: Raised if argument decimal_precision is not an int. ValueError: Raised if",
"Function. TypeError: Raised if argument alpha is not a float. TypeError: Raised if",
"def __print_nmss_values( function: Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints",
"representing the verbosity of the output during algorithm execution. Defaults to None (no",
"law or agreed to in writing, software # distributed under the License is",
"int): beta = float(beta) if not isinstance(beta, float): raise TypeError( \"Expected argument beta",
"False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values =",
"and returns them prepared for work. Args: start (np.ndarray): A numpy.ndarray representing the",
"f'Verbosity key \"{verbosity}\" is not in the Nelder Mead Simplex Verbosity ' f\"dictionary.",
"(float): A float used in point expansion. sigma (float): A float used when",
") if decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision to be a",
"A numpy.ndarray representing the starting point for simplex generation. stride (float): A float",
"np.ndarray, centroid_value: float, epsilon: float ) -> bool: \"\"\" Checks if it's time",
"a negative number. TypeError: Raised if argument verbosity is not a str. KeyError:",
"during algorithm execution. Defaults to None (no output during algorithm execution). decimal_precision (int,",
"alpha (float): A float representing the amount a point will be reflected. Returns:",
"isinstance(alpha, float): raise TypeError( \"Expected argument alpha to be a float, instead it",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"representing the worst point of a simplex. alpha (float): A float representing the",
"f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError( \"Expected argument epsilon to be",
"A float representing the error threshold. Defaults to 1e-6. max_iterations (int, optional): An",
"beta (float): A float used in point contraction. gamma (float): A float used",
"use_jakobovic_expand (bool): A bool determining whether or not to use the __expand_jakobovic method",
"Mead Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision,",
"constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha: float, beta: float,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"A numpy.ndarray representing the worst point of a simplex. beta (float): A float",
") if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0:",
"simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"(np.ndarray): A numpy.ndarray representing the starting point for simplex generation. stride (float): A",
"(Function): A Function representing the loss function. alpha (float): A float used in",
"< 1: raise ValueError( \"Expected argument decimal_precision to be a positive int, instead",
"of the __expand method for point expansion. Defaults to False. epsilon (float): A",
"True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index",
"starting point of the search. stride (Union[float, int], optional): A float or int",
"float used in point contraction. gamma (float): A float used in point expansion.",
"error threshold. Defaults to 1e-6. max_iterations (int, optional): An int representing the maximum",
"isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search(",
"beta (float, optional): A float used in point contraction. Defaults to 0.5. gamma",
"centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. gamma",
"int]): A float or int representing the stride. Raises: TypeError: Raised if argument",
"== 0: raise ValueError( \"Expected argument starting point to be a vector with",
"__print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha )",
"= 0.5, use_jakobovic_expand: bool = False, epsilon: float = 1e-6, max_iterations: int =",
"Raised if argument beta is not a float. TypeError: Raised if argument gamma",
"contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value",
"argument gamma is not a float. TypeError: Raised if argument sigma is not",
"float, bool, float, int, int, int]: Cleaned arguments. \"\"\" if not isinstance(function, Function):",
"available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string",
"the worst point of a simplex. alpha (float): A float representing the amount",
"= contracted_value else: for i, simplex_point in enumerate(simplex_points): if i == minimum_index: continue",
"Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray",
"= np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values( function=function, centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point =",
") stride = float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride: float) ->",
"verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result =",
"ValueError: Raised if argument max_iterations is a negative number. TypeError: Raised if argument",
"in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There are",
"float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected argument alpha to be a",
"met, False otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values",
"not isinstance(verbosity, str): raise TypeError( f\"Expected argument verbosity to be a str, instead",
"int, int]: Cleaned arguments. \"\"\" if not isinstance(function, Function): raise TypeError( \"Expected argument",
"(float): A float representing the amount a point will be contracted. Returns: np.ndarray:",
"1.0, beta: float = 0.5, gamma: float = 2.0, sigma: float = 0.5,",
"Checks the __get_simplex_points arguments and returns them prepared for work. Args: start (np.ndarray):",
"(int): An int representing the maximum number of iterations before the algorithm times",
"(1 - beta) * centroid + beta * maximum_point def __expand( centroid: np.ndarray,",
"to be a Function, instead it is \" f\"{type(function)}.\" ) if isinstance(alpha, int):",
"Function representing the loss function. start (np.ndarray): A numpy.ndarray representing the starting point",
"be a float, instead it is \" f\"{type(epsilon)}.\" ) if epsilon < 0:",
"at least one \" \"element, instead it is empty.\" ) if not isinstance(stride,",
"to 2.0. sigma (float, optional): A float used when moving points to the",
"method instead of the __expand method for point expansion. Defaults to False. epsilon",
"not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There",
"(float, optional): A float used in point contraction. Defaults to 0.5. gamma (float,",
"argument max_interations to be a positive integer, instead it is \" f\"{max_iterations}.\" )",
"if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if timed_out: print(",
"verbosity to be a str, instead it is {type(verbosity)}.\" ) if verbosity not",
"\" f\"{type(stride)}.\" ) stride = float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride:",
"instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float): raise TypeError( \"Expected",
"float representing the error threshold. Returns: bool: True if the stopping condition of",
"a point will be reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected point.",
"algorithm times out and returns the last found optimum. Defaults to 100000. verbosity",
"function. alpha (float): A float used in point reflection. beta (float): A float",
"int)): raise TypeError( \"Expected argument stride to be a float or int, instead",
"None, decimal_precision: int = 3, ) -> np.ndarray: \"\"\" Uses Nelder Mead Simplex",
"\"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, )",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"point of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points = points",
"True if the stopping condition of Nelder Mead Simplex Search has been met,",
"( np.around(result, 3) if isinstance(result, np.ndarray) else f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)})",
"simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index,",
"= reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if",
"is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError( \"Expected argument max_interations",
"a Function, instead it is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha =",
"- gamma) * centroid + gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point:",
"max_iterations (int): An int representing the maximum number of iterations before the algorithm",
"float]: \"\"\" Checks the __get_simplex_points arguments and returns them prepared for work. Args:",
"argument sigma to be a float, instead it is \" f\"{type(sigma)}.\" ) if",
"constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There are no",
"\" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision to",
"execution. Raises: TypeError: Raised if argument function is not a Function. TypeError: Raised",
"raise TypeError( \"Expected argument function to be a Function, instead it is \"",
"if not isinstance(alpha, float): raise TypeError( \"Expected argument alpha to be a float,",
"bool determining whether or not to use the __expand_jakobovic method instead of the",
"function. centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity (int): An int",
"float used in point expansion. sigma (float): A float used when moving points",
"numbers outputted during algorithm execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing",
"else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \" verbosity_string +=",
"point. \"\"\" return (1 - gamma) * centroid - gamma * reflected_point def",
"representing the expanded point. \"\"\" return (1 - gamma) * centroid + gamma",
"str, instead it is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length =",
"is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length",
"elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key",
"argument reflected_point wrt centroid by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing",
"int representing the stride for simplex generation. Defaults to 1. alpha (float, optional):",
"not isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride to be a float",
"point of the search. stride (Union[float, int], optional): A float or int representing",
"this to get a more precise result maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points,",
"this file except in compliance with the License. # You may obtain a",
"np.ndarray, alpha: float ) -> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by",
"centroid + beta * maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float",
"a float, instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma =",
") verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision",
"positive float, instead it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise",
"epsilon (float): A float representing the error threshold. Returns: bool: True if the",
"result = function(centroid, dont_count=True) result = ( np.around(result, 3) if isinstance(result, np.ndarray) else",
"round numbers outputted during algorithm execution. Raises: TypeError: Raised if argument function is",
"\" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError( \"Expected argument max_interations to",
"np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. This is a",
"matrix with each row representing a point of the simplex. \"\"\" points =",
"argument gamma to be a float, instead it is \" f\"{type(gamma)}.\" ) if",
"it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1: raise ValueError( \"Expected argument",
"= 1.0, beta: float = 0.5, gamma: float = 2.0, sigma: float =",
"Cleaned arguments. \"\"\" if not isinstance(function, Function): raise TypeError( \"Expected argument function to",
"-> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. Args: centroid",
") if max_iterations < 1: raise ValueError( \"Expected argument max_interations to be a",
"if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument use_jakobovic_expand to be a bool,",
"the simplex centroid. verbosity (int): An int representing the level of verbosity of",
"Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector of simplex values.",
"be a float, instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma",
"return (1 + alpha) * centroid - alpha * maximum_point def __contract( centroid:",
"float) -> np.ndarray: \"\"\" Generates simplex points for a starting point. Args: start",
"be a vector with at least one \" \"element, instead it is empty.\"",
"raise ValueError( \"Expected argument epsilon to be a positive float, instead it is",
"A float representing the stride. Returns: np.ndarray: A matrix with each row representing",
"if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] =",
"reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We need this",
"TypeError: Raised if argument sigma is not a float. TypeError: Raised if argument",
"loss function. alpha (float): A float used in point reflection. beta (float): A",
"float): raise TypeError( \"Expected argument gamma to be a float, instead it is",
"centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values(",
"max_iterations is a negative number. TypeError: Raised if argument verbosity is not a",
"Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing the last found optimum. \"\"\"",
"epsilon (float): A float representing the error threshold. max_iterations (int): An int representing",
"= 2.0, sigma: float = 0.5, use_jakobovic_expand: bool = False, epsilon: float =",
"centroid=centroid, verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value =",
"stopping condition of Nelder Mead Simplex Search has been met, False otherwise. \"\"\"",
"permissions and # limitations under the License. import sys from typing import Optional,",
"float, int, int, int]: Cleaned arguments. \"\"\" if not isinstance(function, Function): raise TypeError(",
"100000. verbosity (Optional[str], optional): A str representing the verbosity of the output during",
"{verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument",
"else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value <",
"simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out",
"representing the number of decimal digits to round numbers outputted during algorithm execution.",
"f\"{type(start)}.\" ) start = np.reshape(start, -1) if start.shape[0] == 0: raise ValueError( \"Expected",
"maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a simplex. gamma (float):",
"int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and returns them",
"the loss function. centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity (int):",
"raise TypeError( \"Expected argument decimal_precision to be an int, instead it is \"",
"TypeError: Raised if argument use_jakobovic_expand is not a bool. TypeError: Raised if argument",
"expanded point. \"\"\" return (1 - gamma) * centroid - gamma * reflected_point",
"verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to",
"function (Function): A Function representing the loss function. start (np.ndarray): A numpy.ndarray representing",
"# limitations under the License. import sys from typing import Optional, Tuple, Union",
"contracted point. \"\"\" return (1 - beta) * centroid + beta * maximum_point",
"the optimum. use_jakobovic_expand (bool): A bool determining whether or not to use the",
"for point expansion. Defaults to False. epsilon (float, optional): A float representing the",
"A float used in point expansion. sigma (float): A float used when moving",
"\" f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError( \"Expected argument epsilon to",
"TypeError( \"Expected argument beta to be a float, instead it is \" f\"{type(beta)}.\"",
"= contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point in enumerate(simplex_points): if i",
"(int, optional): An int representing the number of decimal digits to round numbers",
"verbosity > 1: result = function(centroid, dont_count=True) result = ( np.around(result, 3) if",
"start: np.ndarray, stride: Union[float, int] ) -> Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points",
"f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma) if not isinstance(gamma, float): raise",
"argument start is a zero-length vector. TypeError: Raised if argument stride is not",
"= reflected_point simplex_values[maximum_index] = reflected_value # We need this here since we're introducing",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"the Nelder Mead Simplex Search arguments and returns them prepared for work. Args:",
"from . import constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function: Function, alpha:",
"optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A bool determining whether or not",
"if argument function is not a Function. TypeError: Raised if argument alpha is",
"the algorithm times out and returns the last found optimum. Defaults to 100000.",
"beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity:",
"(float, optional): A float used in point expansion. Defaults to 2.0. sigma (float,",
"(np.ndarray): A numpy.ndarray representing the starting point of the search. stride (Union[float, int],",
"new point and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need",
"outputted during algorithm execution. Raises: TypeError: Raised if argument function is not a",
"representing the last found optimum. \"\"\" ( function, alpha, beta, gamma, sigma, use_jakobovic_expand,",
"-1) if start.shape[0] == 0: raise ValueError( \"Expected argument starting point to be",
"the loss function. alpha (float): A float used in point reflection. beta (float):",
"required by applicable law or agreed to in writing, software # distributed under",
"float ) -> np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by argument alpha.",
"= np.reshape(start, -1) if start.shape[0] == 0: raise ValueError( \"Expected argument starting point",
"axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value",
"is not a numpy.ndarray. ValueError: Raised if argument start is a zero-length vector.",
"zero-length vector. TypeError: Raised if argument stride is not a float or int.",
"keys available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only",
"minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid = np.mean(np.delete(simplex_points, maximum_index, axis=0), axis=0) __print_nmss_values(",
"optional): A float used in point contraction. Defaults to 0.5. gamma (float, optional):",
"verbosity is an invalid key. TypeError: Raised if argument decimal_precision is not an",
"beta is not a float. TypeError: Raised if argument gamma is not a",
"stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray, alpha:",
"Args: function (Function): A Function representing the loss function. centroid (np.ndarray): A numpy.ndarray",
"Union import numpy as np from . import constants from .function import Function",
"Yalfoosh # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"representing the error threshold. Returns: bool: True if the stopping condition of Nelder",
"limitations under the License. import sys from typing import Optional, Tuple, Union import",
"max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride: Union[float, int] ) ->",
"Optional, Tuple, Union import numpy as np from . import constants from .function",
"representing the amount a point will be expanded. Returns: np.ndarray: A numpy.ndarray representing",
"f\"{result:.0{decimal_precision}f}\" ) print(f\"F(c = {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start:",
"float ) -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha.",
"Args: simplex_values (np.ndarray): A numpy.ndarray representing the vector of simplex values. centroid_value (float):",
"An int representing the number of decimal digits to round numbers outputted during",
"not to use the __expand_jakobovic method instead of the __expand method for point",
"instead it is \" f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError( \"Expected",
"be reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected point. \"\"\" return (1",
"it is \" f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha) if not",
"if max_iterations < 1: raise ValueError( \"Expected argument max_interations to be a positive",
"point will be reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected point. \"\"\"",
"threshold. Returns: bool: True if the stopping condition of Nelder Mead Simplex Search",
"simplex_point in enumerate(simplex_points): if i == minimum_index: continue simplex_points[i] += ( simplex_points[minimum_index] -",
"Function, centroid: np.ndarray, verbosity: int, decimal_precision: int, ): \"\"\" Prints the Nelder Mead",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"time to stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A numpy.ndarray representing",
"maximum value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index],",
"by argument alpha. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point",
"which is supposedly the correct one, as said by prof. Jakobović. Args: centroid",
"otherwise. \"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values)",
"contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point in enumerate(simplex_points): if i ==",
"decimal_precision is not an int. ValueError: Raised if argument decimal_precision is a negative",
"one \" \"element, instead it is empty.\" ) if not isinstance(stride, (float, int)):",
"TypeError: Raised if argument max_iterations is not an int. ValueError: Raised if argument",
"alpha: float, beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float, max_iterations:",
"TypeError: Raised if argument alpha is not a float. TypeError: Raised if argument",
"number of decimal digits to round numbers outputted during algorithm execution. Defaults to",
"them prepared for work. Args: function (Function): A Function representing the loss function.",
"the error threshold. max_iterations (int): An int representing the maximum number of iterations",
"numpy.ndarray representing the last found optimum. \"\"\" ( function, alpha, beta, gamma, sigma,",
"argument use_jakobovic_expand is not a bool. TypeError: Raised if argument epsilon is not",
"( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def",
"if it's time to stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray): A",
"float = 1.0, beta: float = 0.5, gamma: float = 2.0, sigma: float",
"function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point,",
"a simplex. gamma (float): A float representing the amount a point will be",
"returns the last found optimum. verbosity (Optional[str]): A str representing the verbosity of",
"the maximum number of iterations before the algorithm times out and returns the",
"argument max_iterations is not an int. ValueError: Raised if argument max_iterations is a",
"int): sigma = float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected argument sigma",
"simplex_points]) timed_out = True expansion_method = __expand_jakobovic if use_jakobovic_expand else __expand for _",
"as np from . import constants from .function import Function def clean_nelder_mead_simplex_search_arguments( function:",
"def __time_to_stop( simplex_values: np.ndarray, centroid_value: float, epsilon: float ) -> bool: \"\"\" Checks",
"Returns: np.ndarray: A matrix with each row representing a point of the simplex.",
"for point expansion. Defaults to False. epsilon (float): A float representing the error",
"amount a point will be contracted. Returns: np.ndarray: A numpy.ndarray representing the contracted",
"in point expansion. sigma (float): A float used when moving points to the",
"maximum_points wrt centroid by argument beta. Args: centroid (np.ndarray): A numpy.ndarray representing the",
"if argument decimal_precision is not an int. ValueError: Raised if argument decimal_precision is",
"raise TypeError( \"Expected argument gamma to be a float, instead it is \"",
"int representing the stride. Raises: TypeError: Raised if argument start is not a",
"raise ValueError( \"Expected argument decimal_precision to be a positive int, instead it is\"",
"np.ndarray: \"\"\" Reflects argument maximum_points wrt centroid by argument alpha. Args: centroid (np.ndarray):",
"correct one, as said by prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing",
"== 0: verbosity_string = \"There are no keys available.\" elif verbosity_dict_length == 1:",
"reflected_value # We need this here since we're introducing a new point and",
"the __expand_jakobovic method instead of the __expand method for point expansion. Defaults to",
"sigma is not a float. TypeError: Raised if argument use_jakobovic_expand is not a",
"# you may not use this file except in compliance with the License.",
"verbosity_string = f'The only available key is \"{_key}\".' else: _keys = list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string",
"is a zero-length vector. TypeError: Raised if argument stride is not a float",
"this since the maximum value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point =",
"= constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to be",
"float, instead it is \" f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError(",
"reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ): timed_out = False break if timed_out:",
"expanded_value = function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value",
"is not a str. KeyError: Raised if argument verbosity is an invalid key.",
"f\"{type(stride)}.\" ) stride = float(stride) return start, stride def __get_simplex_points(start: np.ndarray, stride: float)",
"be a minimum.\", file=sys.stderr, ) # Do this to get a more precise",
"Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError( \"Expected",
"Tuple[np.ndarray, float]: \"\"\" Checks the __get_simplex_points arguments and returns them prepared for work.",
"float, float, float, float, bool, float, int, int, int]: \"\"\" Checks the Nelder",
"gamma, sigma, use_jakobovic_expand, epsilon, max_iterations, verbosity, decimal_precision, ) def clean_get_simplex_points( start: np.ndarray, stride:",
"simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value # We need this here since we're",
"argument decimal_precision to be an int, instead it is \" f\"{type(decimal_precision)}.\" ) if",
"function: Function, start: np.ndarray, stride: Union[float, int] = 1, alpha: float = 1.0,",
"Mead Simplex Search values. Args: function (Function): A Function representing the loss function.",
"int. ValueError: Raised if argument decimal_precision is a negative number. Returns: Tuple[Function, float,",
"and \"{_keys[-1]}\"\".' raise KeyError( f'Verbosity key \"{verbosity}\" is not in the Nelder Mead",
"numpy.ndarray representing the worst point of a simplex. beta (float): A float representing",
"expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if",
"a float or int, instead it is \" f\"{type(stride)}.\" ) stride = float(stride)",
"alpha) * centroid - alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray,",
"License for the specific language governing permissions and # limitations under the License.",
"point of a simplex. beta (float): A float representing the amount a point",
"for simplex generation. stride (Union[float, int]): A float or int representing the stride.",
"function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for",
"A bool determining whether or not to use the __expand_jakobovic method instead of",
"break if timed_out: print( f\"WARNING: Nelder Mead Simplex Search timed out after {max_iterations}",
"beta * maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) ->",
"We need this here since we're introducing a new point and value minimum_index",
"1e-6, max_iterations: int = 100000, verbosity: Optional[str] = None, decimal_precision: int = 3,",
"loss function. start (np.ndarray): A numpy.ndarray representing the starting point of the search.",
"\"License\"); # you may not use this file except in compliance with the",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"loss function. centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. verbosity (int): An",
"isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected argument",
"float, float, float, float, bool, float, int, int, int]: Cleaned arguments. \"\"\" if",
"raise TypeError( \"Expected argument sigma to be a float, instead it is \"",
"int]: \"\"\" Checks the Nelder Mead Simplex Search arguments and returns them prepared",
"a zero-length vector. TypeError: Raised if argument stride is not a float or",
"the last found optimum. Defaults to 100000. verbosity (Optional[str], optional): A str representing",
"of simplex values. centroid_value (float): A float representing the value of the simplex",
"(Union[float, int], optional): A float or int representing the stride for simplex generation.",
"the simplex centroid. epsilon (float): A float representing the error threshold. Returns: bool:",
"maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value:",
"max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function, float, float, float, float,",
"str): raise TypeError( f\"Expected argument verbosity to be a str, instead it is",
"TypeError( \"Expected argument alpha to be a float, instead it is \" f\"{type(alpha)}.\"",
"during algorithm execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing the last",
"simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value): if reflected_value < maximum_value: simplex_points[maximum_index] =",
"is \" f\"{type(epsilon)}.\" ) if epsilon < 0: raise ValueError( \"Expected argument epsilon",
"float representing the amount a point will be reflected. Returns: np.ndarray: A numpy.ndarray",
"centroid - alpha * maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float",
"TypeError: Raised if argument function is not a Function. TypeError: Raised if argument",
"raise TypeError( \"Expected argument epsilon to be a float, instead it is \"",
"\"Expected argument stride to be a float or int, instead it is \"",
"of the simplex. \"\"\" points = np.tile(start, reps=(start.shape[0], 1)) points = points +",
"= list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is \"{_key}\".' else: _keys =",
"A float representing the error threshold. Returns: bool: True if the stopping condition",
"the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing the worst point of a",
"Contracts argument maximum_points wrt centroid by argument beta. Args: centroid (np.ndarray): A numpy.ndarray",
"find an n-D optimum of a function. Args: function (Function): A Function representing",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"the verbosity of the output during algorithm execution. decimal_precision (int): An int representing",
"in writing, software # distributed under the License is distributed on an \"AS",
"(Function): A Function representing the loss function. centroid (np.ndarray): A numpy.ndarray representing the",
"epsilon, max_iterations, verbosity, decimal_precision, ) = clean_nelder_mead_simplex_search_arguments( function=function, alpha=alpha, beta=beta, gamma=gamma, sigma=sigma, use_jakobovic_expand=use_jakobovic_expand,",
"prof. Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray):",
"Raised if argument use_jakobovic_expand is not a bool. TypeError: Raised if argument epsilon",
"point will be expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded point. \"\"\"",
"argument reflected_point wrt centroid by argument alpha. This is a modified version which",
"if verbosity_dict_length == 0: verbosity_string = \"There are no keys available.\" elif verbosity_dict_length",
"int] = 1, alpha: float = 1.0, beta: float = 0.5, gamma: float",
"1e-6. max_iterations (int, optional): An int representing the maximum number of iterations before",
"float(beta) if not isinstance(beta, float): raise TypeError( \"Expected argument beta to be a",
"simplex_values[maximum_index] = reflected_value else: maximum_value = simplex_values[maximum_index] if all(np.delete(simplex_values, maximum_index, axis=0) < reflected_value):",
"start is a zero-length vector. TypeError: Raised if argument stride is not a",
"in point expansion. Defaults to 2.0. sigma (float, optional): A float used when",
"= 1, alpha: float = 1.0, beta: float = 0.5, gamma: float =",
"empty.\" ) if not isinstance(stride, (float, int)): raise TypeError( \"Expected argument stride to",
"float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected argument gamma to be a",
"f\"{type(max_iterations)}.\" ) if max_iterations < 1: raise ValueError( \"Expected argument max_interations to be",
"simplex_values (np.ndarray): A numpy.ndarray representing the vector of simplex values. centroid_value (float): A",
"not an int. ValueError: Raised if argument decimal_precision is a negative number. Returns:",
"list(sorted(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())) verbosity_string = \"The available keys are \" verbosity_string += \", \".join([str(f'\"{x}\"') for",
"to be a float, instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int):",
"maximum_point def __contract( centroid: np.ndarray, maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\"",
"\"\"\" Generates simplex points for a starting point. Args: start (np.ndarray): A numpy.ndarray",
"= np.tile(start, reps=(start.shape[0], 1)) points = points + stride * np.eye(points.shape[0]) return np.vstack([start,",
"need this here since we're introducing a new point and value minimum_index =",
"reflected_value = function(reflected_point) minimum_value = simplex_values[minimum_index] if reflected_value < minimum_value: expanded_point = expansion_method(",
"TypeError: Raised if argument decimal_precision is not an int. ValueError: Raised if argument",
"= __expand_jakobovic if use_jakobovic_expand else __expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values)",
"number of decimal digits to round numbers outputted during algorithm execution. \"\"\" if",
"A float representing the value of the simplex centroid. epsilon (float): A float",
"decimal_precision < 1: raise ValueError( \"Expected argument decimal_precision to be a positive int,",
"\"Expected argument epsilon to be a float, instead it is \" f\"{type(epsilon)}.\" )",
"verbosity=verbosity, decimal_precision=decimal_precision, ) reflected_point = __reflect( centroid=centroid, maximum_point=simplex_points[maximum_index], alpha=alpha ) reflected_value = function(reflected_point)",
"simplex_values: np.ndarray, centroid_value: float, epsilon: float ) -> bool: \"\"\" Checks if it's",
"maximum_value: simplex_points[maximum_index] = contracted_point simplex_values[maximum_index] = contracted_value else: for i, simplex_point in enumerate(simplex_points):",
"\"\"\" difference_in_values = simplex_values - centroid_value squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return",
"to be an int, instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision <",
"if isinstance(beta, int): beta = float(beta) if not isinstance(beta, float): raise TypeError( \"Expected",
"if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT: verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string",
"False. epsilon (float): A float representing the error threshold. max_iterations (int): An int",
"\" f\"{type(alpha)}.\" ) if isinstance(beta, int): beta = float(beta) if not isinstance(beta, float):",
"representing the simplex centroid. verbosity (int): An int representing the level of verbosity",
"representing the loss function. start (np.ndarray): A numpy.ndarray representing the starting point of",
"a numpy.ndarray. ValueError: Raised if argument start is a zero-length vector. TypeError: Raised",
"verbosity_dict_length = len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There are no keys",
"reflected_value < minimum_value: expanded_point = expansion_method( centroid=centroid, reflected_point=reflected_point, gamma=gamma ) expanded_value = function(expanded_point)",
"available.\" elif verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available",
"use_jakobovic_expand: bool, epsilon: float, max_iterations: int, verbosity: Optional[str], decimal_precision: int, ) -> Tuple[Function,",
") -> np.ndarray: \"\"\" Expands argument reflected_point wrt centroid by argument alpha. This",
"A float used when moving points to the optimum. use_jakobovic_expand (bool): A bool",
"to be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon,",
"verbosity_string = \"There are no keys available.\" elif verbosity_dict_length == 1: _key =",
"in point contraction. gamma (float): A float used in point expansion. sigma (float):",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"alpha: float = 1.0, beta: float = 0.5, gamma: float = 2.0, sigma:",
"Raises: TypeError: Raised if argument function is not a Function. TypeError: Raised if",
"A float used in point contraction. gamma (float): A float used in point",
"\", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f' and \"{_keys[-1]}\"\".' raise KeyError(",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to be an int, instead",
"(float, int)): raise TypeError( \"Expected argument stride to be a float or int,",
"argument verbosity is not a str. KeyError: Raised if argument verbosity is an",
"or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise",
"if not isinstance(decimal_precision, int): raise TypeError( \"Expected argument decimal_precision to be an int,",
"# # Unless required by applicable law or agreed to in writing, software",
"value has potentially changed maximum_value = simplex_values[maximum_index] contracted_point = __contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta,",
"express or implied. # See the License for the specific language governing permissions",
"stride=stride) simplex_points = __get_simplex_points(start=start, stride=stride) simplex_values = np.array([function(x) for x in simplex_points]) timed_out",
"expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point",
"int representing the level of verbosity of the output during algorithm execution. decimal_precision",
"Simplex Search arguments and returns them prepared for work. Args: function (Function): A",
"either express or implied. # See the License for the specific language governing",
"here since we're introducing a new point and value minimum_index = np.argmin(simplex_values) maximum_index",
"centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A numpy.ndarray representing",
"function is not a Function. TypeError: Raised if argument alpha is not a",
"mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function: Function, centroid: np.ndarray,",
"\" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to",
"a Function. TypeError: Raised if argument alpha is not a float. TypeError: Raised",
"number. Returns: Tuple[Function, float, float, float, float, bool, float, int, int, int]: Cleaned",
"instead it is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand,",
"is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma = float(sigma) if not isinstance(sigma,",
"method for point expansion. Defaults to False. epsilon (float): A float representing the",
"point reflection. beta (float): A float used in point contraction. gamma (float): A",
"float): raise TypeError( \"Expected argument alpha to be a float, instead it is",
"maximum_point: np.ndarray, beta: float ) -> np.ndarray: \"\"\" Contracts argument maximum_points wrt centroid",
"(no output during algorithm execution). decimal_precision (int, optional): An int representing the number",
"argument use_jakobovic_expand to be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if",
"stride (float): A float representing the stride. Returns: np.ndarray: A matrix with each",
"isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected argument",
"beta = float(beta) if not isinstance(beta, float): raise TypeError( \"Expected argument beta to",
"times out and returns the last found optimum. Defaults to 100000. verbosity (Optional[str],",
"Simplex Search values. Args: function (Function): A Function representing the loss function. centroid",
"reflected_point simplex_values[maximum_index] = reflected_value # We need this here since we're introducing a",
"centroid. verbosity (int): An int representing the level of verbosity of the output",
"the License. # You may obtain a copy of the License at #",
"= {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int] = 1,",
"verbosity_dict_length == 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is",
"An int representing the level of verbosity of the output during algorithm execution.",
") if verbosity is None: verbosity = \"none\" if not isinstance(verbosity, str): raise",
"prepared for work. Args: function (Function): A Function representing the loss function. alpha",
"returns them prepared for work. Args: function (Function): A Function representing the loss",
"expansion. Defaults to False. epsilon (float): A float representing the error threshold. max_iterations",
"int, decimal_precision: int, ): \"\"\" Prints the Nelder Mead Simplex Search values. Args:",
"Defaults to False. epsilon (float): A float representing the error threshold. max_iterations (int):",
"if not isinstance(max_iterations, int): raise TypeError( \"Expected argument max_interations to be an int,",
"argument max_iterations is a negative number. TypeError: Raised if argument verbosity is not",
"argument decimal_precision is a negative number. Returns: Tuple[Function, float, float, float, float, bool,",
"it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand, bool): raise TypeError( \"Expected argument",
"(float): A float used in point contraction. gamma (float): A float used in",
"\" verbosity_string += \", \".join([str(f'\"{x}\"') for x in _keys[:-1]]) verbosity_string += f' and",
"to be a float, instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int):",
"instead it is \" f\"{type(beta)}.\" ) if isinstance(gamma, int): gamma = float(gamma) if",
"Jakobović. Args: centroid (np.ndarray): A numpy.ndarray representing the simplex centroid. maximum_point (np.ndarray): A",
"\"\"\" if verbosity == 1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1:",
"0.5. gamma (float, optional): A float used in point expansion. Defaults to 2.0.",
"beta) * centroid + beta * maximum_point def __expand( centroid: np.ndarray, reflected_point: np.ndarray,",
"not a numpy.ndarray. ValueError: Raised if argument start is a zero-length vector. TypeError:",
"for a starting point. Args: start (np.ndarray): A numpy.ndarray representing the starting point",
"A numpy.ndarray representing the expanded point. \"\"\" return (1 - gamma) * centroid",
"Tuple[Function, float, float, float, float, bool, float, int, int, int]: Cleaned arguments. \"\"\"",
"the worst point of a simplex. gamma (float): A float representing the amount",
"be a bool, instead it is \" f\"{type(use_jakobovic_expand)}.\" ) if not isinstance(epsilon, float):",
"bool: \"\"\" Checks if it's time to stop Nelder Mead Simplex Search. Args:",
"or int, instead it is \" f\"{type(stride)}.\" ) stride = float(stride) return start,",
"centroid + gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float",
"amount a point will be reflected. Returns: np.ndarray: A numpy.ndarray representing the reflected",
"\"iterations - result might not be a minimum.\", file=sys.stderr, ) # Do this",
"squared_difference_in_values = np.square(difference_in_values) mean_squared_difference_in_values = np.mean(squared_difference_in_values) return np.sqrt(mean_squared_difference_in_values) <= epsilon def __print_nmss_values( function:",
"used in point contraction. Defaults to 0.5. gamma (float, optional): A float used",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"of the output during algorithm execution. Defaults to None (no output during algorithm",
"be a positive int, instead it is\" f\"{decimal_precision}.\" ) return ( function, alpha,",
"Checks if it's time to stop Nelder Mead Simplex Search. Args: simplex_values (np.ndarray):",
"float, epsilon: float ) -> bool: \"\"\" Checks if it's time to stop",
"Function): raise TypeError( \"Expected argument function to be a Function, instead it is",
"(1 - gamma) * centroid + gamma * reflected_point def __expand_jakobovic( centroid: np.ndarray,",
"* reflected_point def __expand_jakobovic( centroid: np.ndarray, reflected_point: np.ndarray, gamma: float ) -> np.ndarray:",
"int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray): raise TypeError(",
"simplex_points[i] += ( simplex_points[minimum_index] - simplex_points[i] ) * sigma simplex_values[i] = function(simplex_points[i]) else:",
"a str. KeyError: Raised if argument verbosity is an invalid key. TypeError: Raised",
"= {np.around(centroid, decimal_precision)}) = {result}\") def nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float,",
"round numbers outputted during algorithm execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray",
"KeyError( f'Verbosity key \"{verbosity}\" is not in the Nelder Mead Simplex Verbosity '",
"== 1: _key = list(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT.keys())[0] verbosity_string = f'The only available key is \"{_key}\".'",
"if argument stride is not a float or int. Returns: Tuple[np.ndarray, float]: Cleaned",
"to be a float, instead it is \" f\"{type(sigma)}.\" ) if not isinstance(use_jakobovic_expand,",
"epsilon < 0: raise ValueError( \"Expected argument epsilon to be a positive float,",
"raise TypeError( \"Expected argument use_jakobovic_expand to be a bool, instead it is \"",
"point. \"\"\" return (1 - beta) * centroid + beta * maximum_point def",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"be a str, instead it is {type(verbosity)}.\" ) if verbosity not in constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT:",
"float, instead it is \" f\"{epsilon}.\" ) if not isinstance(max_iterations, int): raise TypeError(",
"if argument start is not a numpy.ndarray. ValueError: Raised if argument start is",
"a float. TypeError: Raised if argument use_jakobovic_expand is not a bool. TypeError: Raised",
"A numpy.ndarray representing the simplex centroid. verbosity (int): An int representing the level",
"Raised if argument verbosity is not a str. KeyError: Raised if argument verbosity",
"f\"WARNING: Nelder Mead Simplex Search timed out after {max_iterations} \" \"iterations - result",
"number of iterations before the algorithm times out and returns the last found",
"if verbosity is None: verbosity = \"none\" if not isinstance(verbosity, str): raise TypeError(",
"Raised if argument max_iterations is not an int. ValueError: Raised if argument max_iterations",
"= len(constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT) if verbosity_dict_length == 0: verbosity_string = \"There are no keys available.\"",
"representing the starting point of the search. stride (Union[float, int], optional): A float",
"output during algorithm execution. Defaults to None (no output during algorithm execution). decimal_precision",
"Uses Nelder Mead Simplex Search to find an n-D optimum of a function.",
"arguments and returns them prepared for work. Args: start (np.ndarray): A numpy.ndarray representing",
"optional): A float used when moving points to the optimum. Defaults to 0.5.",
"simplex_values[i] = function(simplex_points[i]) else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values,",
"Prints the Nelder Mead Simplex Search values. Args: function (Function): A Function representing",
"out and returns the last found optimum. Defaults to 100000. verbosity (Optional[str], optional):",
"Nelder Mead Simplex Search values. Args: function (Function): A Function representing the loss",
"int representing the number of decimal digits to round numbers outputted during algorithm",
"Raised if argument sigma is not a float. TypeError: Raised if argument use_jakobovic_expand",
"0.5, gamma: float = 2.0, sigma: float = 0.5, use_jakobovic_expand: bool = False,",
"point. \"\"\" return (1 - gamma) * centroid + gamma * reflected_point def",
"vector of simplex values. centroid_value (float): A float representing the value of the",
"out and returns the last found optimum. verbosity (Optional[str]): A str representing the",
"0: raise ValueError( \"Expected argument epsilon to be a positive float, instead it",
"except in compliance with the License. # You may obtain a copy of",
"gamma = float(gamma) if not isinstance(gamma, float): raise TypeError( \"Expected argument gamma to",
"Mead Simplex Search to find an n-D optimum of a function. Args: function",
"argument starting point to be a vector with at least one \" \"element,",
"verbosity is not a str. KeyError: Raised if argument verbosity is an invalid",
"returns them prepared for work. Args: start (np.ndarray): A numpy.ndarray representing the starting",
"argument decimal_precision is not an int. ValueError: Raised if argument decimal_precision is a",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"int. ValueError: Raised if argument max_iterations is a negative number. TypeError: Raised if",
"+ stride * np.eye(points.shape[0]) return np.vstack([start, points]) def __reflect( centroid: np.ndarray, maximum_point: np.ndarray,",
"verbosity (Optional[str]): A str representing the verbosity of the output during algorithm execution.",
"when moving points to the optimum. Defaults to 0.5. use_jakobovic_expand (float, optional): A",
"verbosity is None: verbosity = \"none\" if not isinstance(verbosity, str): raise TypeError( f\"Expected",
"contraction. gamma (float): A float used in point expansion. sigma (float): A float",
"it is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta, gamma, sigma, use_jakobovic_expand, epsilon,",
"decimal_precision: int, ): \"\"\" Prints the Nelder Mead Simplex Search values. Args: function",
"ValueError: Raised if argument epsilon is a negative number. TypeError: Raised if argument",
"a positive int, instead it is\" f\"{decimal_precision}.\" ) return ( function, alpha, beta,",
"= float(sigma) if not isinstance(sigma, float): raise TypeError( \"Expected argument sigma to be",
"simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value else: maximum_value =",
"stride (Union[float, int]): A float or int representing the stride. Raises: TypeError: Raised",
"return start, stride def __get_simplex_points(start: np.ndarray, stride: float) -> np.ndarray: \"\"\" Generates simplex",
"Simplex Verbosity ' f\"dictionary. {verbosity_string}\" ) verbosity = constants.NELDER_MEAD_SIMPLEX_VERBOSITY_DICT[verbosity] if not isinstance(decimal_precision, int):",
"not a float. TypeError: Raised if argument beta is not a float. TypeError:",
"bool): raise TypeError( \"Expected argument use_jakobovic_expand to be a bool, instead it is",
"optimum. use_jakobovic_expand (bool): A bool determining whether or not to use the __expand_jakobovic",
"__expand for _ in range(max_iterations): minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) centroid =",
"expansion. sigma (float): A float used when moving points to the optimum. use_jakobovic_expand",
"gamma: float = 2.0, sigma: float = 0.5, use_jakobovic_expand: bool = False, epsilon:",
"to be a positive float, instead it is \" f\"{epsilon}.\" ) if not",
"decimal digits to round numbers outputted during algorithm execution. \"\"\" if verbosity ==",
"point and value minimum_index = np.argmin(simplex_values) maximum_index = np.argmax(simplex_values) # We need to",
"determining whether or not to use the __expand_jakobovic method instead of the __expand",
"if argument start is a zero-length vector. TypeError: Raised if argument stride is",
"1: print(f\"c = {np.around(centroid, decimal_precision)}\") elif verbosity > 1: result = function(centroid, dont_count=True)",
"= float(alpha) if not isinstance(alpha, float): raise TypeError( \"Expected argument alpha to be",
"point to be a vector with at least one \" \"element, instead it",
"decimal_precision to be an int, instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision",
"Expands argument reflected_point wrt centroid by argument alpha. This is a modified version",
"__contract( centroid=centroid, maximum_point=simplex_points[maximum_index], beta=beta, ) contracted_value = function(contracted_point) if contracted_value < maximum_value: simplex_points[maximum_index]",
"else: simplex_points[maximum_index] = reflected_point simplex_values[maximum_index] = reflected_value if __time_to_stop( simplex_values=simplex_values, centroid_value=function(centroid), epsilon=epsilon, ):",
"Defaults to 100000. verbosity (Optional[str], optional): A str representing the verbosity of the",
"to 100000. verbosity (Optional[str], optional): A str representing the verbosity of the output",
"KeyError: Raised if argument verbosity is an invalid key. TypeError: Raised if argument",
"be a float, instead it is \" f\"{type(gamma)}.\" ) if isinstance(sigma, int): sigma",
"Search timed out after {max_iterations} \" \"iterations - result might not be a",
"\"Expected argument decimal_precision to be an int, instead it is \" f\"{type(decimal_precision)}.\" )",
"start: np.ndarray, stride: Union[float, int] = 1, alpha: float = 1.0, beta: float",
"moving points to the optimum. use_jakobovic_expand (bool): A bool determining whether or not",
"numpy.ndarray representing the worst point of a simplex. gamma (float): A float representing",
"be expanded. Returns: np.ndarray: A numpy.ndarray representing the expanded point. \"\"\" return (1",
"be an int, instead it is \" f\"{type(decimal_precision)}.\" ) if decimal_precision < 1:",
"nelder_mead_simplex_search( function: Function, start: np.ndarray, stride: Union[float, int] = 1, alpha: float =",
"algorithm execution. Defaults to 3. Returns: np.ndarray: A numpy.ndarray representing the last found",
"Function, alpha: float, beta: float, gamma: float, sigma: float, use_jakobovic_expand: bool, epsilon: float,",
"f\"{type(function)}.\" ) if isinstance(alpha, int): alpha = float(alpha) if not isinstance(alpha, float): raise",
"algorithm execution. Raises: TypeError: Raised if argument function is not a Function. TypeError:",
"simplex centroid. epsilon (float): A float representing the error threshold. Returns: bool: True",
"sys from typing import Optional, Tuple, Union import numpy as np from .",
"A float representing the amount a point will be contracted. Returns: np.ndarray: A",
"float or int. Returns: Tuple[np.ndarray, float]: Cleaned arguments. \"\"\" if not isinstance(start, np.ndarray):",
"function(expanded_point) if expanded_value < minimum_value: simplex_points[maximum_index] = expanded_point simplex_values[maximum_index] = expanded_value else: simplex_points[maximum_index]"
] |
[
"return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe in",
"remote = i_args.remote + '/' + i_args.org if remote not in uri: continue",
"if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show', sha] process",
"uris.split(): remote = i_args.remote + '/' + i_args.org if remote not in uri:",
"commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run",
"parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha, digits) print('sha",
"= ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput =",
"for') return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args = parse_arguments(i_args) digits",
"math import subprocess PIPE = subprocess.PIPE try: import git from git import GitCommandError",
"uris and look for # another bitbake variable that ends with _URI. uris",
"for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to scan for') return l_parser.parse_args(i_args)",
"found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git', 'add', recipe] process",
"stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split()",
"l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to scan for') l_parser.add_argument( '-o', '--org',",
"stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args =",
"uris we've gathered a complete (possibly multi-line) # assignment to a bitbake variable",
"bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg def",
"run\" print commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find bitbake",
"Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change",
"an OpenBMC project out of it. project = extract_project_from_uris(args, uris) if project is",
"Generate commits that update bitbake metadata files with SRCREV if given revision is",
"as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream",
"{}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg def parse_arguments(i_args):",
"= extract_project_from_uris(args, uris) if project is None: # We didn't find a project.",
"= fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe)",
"stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return []",
"in line: uris += line.split('\\\\')[0] if '\\\\' not in line: # In uris",
"git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput =",
"with SRCREV if given revision is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description)",
"[] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process =",
"git_commit(commit_msg) else: print \"dry run\" print commit_msg def parse_arguments(i_args): app_description = '''Local recipe",
"open(recipe) as fp: uris = '' project = None sha = None for",
"uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote + '/' + i_args.org if",
"with open(recipe) as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe,",
"import sys import math import subprocess PIPE = subprocess.PIPE try: import git from",
"bitbake variable that ends with _URI. # Try to pull an OpenBMC project",
"help='perform a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status",
"and sha: return (project, sha) print('No SRCREV or URI found in {}'.format(recipe)) return(project,",
"use the git.ibm.com and check the project repository for given revision. Generate commits",
"'') return None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris = ''",
"sha: return (project, sha) print('No SRCREV or URI found in {}'.format(recipe)) return(project, sha)",
"def git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput",
"as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as",
"remote value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to",
"argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change sha') l_parser.add_argument( 'project_sha', help='input sha",
"if given revision is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name',",
"if project_name in args.project_name: if args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe)",
"project repository for given revision. Generate commits that update bitbake metadata files with",
"to import git module') HAVE_GIT = False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg))",
"True except ImportError: # _log.debug('Failed to import git module') HAVE_GIT = False def",
"Try to pull an OpenBMC project out of it. project = extract_project_from_uris(args, uris)",
"not args.dry_run: recipe_content = None with open(recipe) as fd: recipe_content = fd.read() recipe_content",
"'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha =",
"line.split('\\\\')[0] if '\\\\' not in line: # In uris we've gathered a complete",
"status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to scan for') l_parser.add_argument(",
"remove SRC_URI = and quotes (does not handle escaped quotes) uris = uris.split('\"')[1]",
"update bitbake metadata files with SRCREV if given revision is new Generate commit.",
"= uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote + '/' + i_args.org",
"'{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry run\"",
"'-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal'",
"it. project = extract_project_from_uris(args, uris) if project is None: # We didn't find",
"given revision. Generate commits that update bitbake metadata files with SRCREV if given",
"process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git',",
"sh import sys import math import subprocess PIPE = subprocess.PIPE try: import git",
"sha) print('No SRCREV or URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args",
"another bitbake variable that ends with _URI. uris = '' if project and",
"pull an OpenBMC project out of it. project = extract_project_from_uris(args, uris) if project",
"= None with open(recipe) as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha)",
"fp: uris = '' project = None sha = None for line in",
"'-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal'",
"recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg)",
"recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content)",
"l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true',",
"stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org]",
"quotes (does not handle escaped quotes) uris = uris.split('\"')[1] for uri in uris.split():",
"SRCREV or URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git',",
"candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if",
"stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput",
"recipe bumping tool. Find bitbake metadata files (recipes) that use the git.ibm.com and",
"def git_add(recipe): git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput,",
"uri.split(';')[0] # the project is the right-most path segment return uri.split('/')[-1].replace('.git', '') return",
"else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args)",
"message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue if not",
"arguments uri = uri.split(';')[0] # the project is the right-most path segment return",
"(recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content",
"new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to",
"stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput return",
"digits = len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha, digits) print('sha number",
"= process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args =",
"= len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha, digits) print('sha number {}",
"import git module') HAVE_GIT = False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def",
"not project and uris or '_URI' in line: uris += line.split('\\\\')[0] if '\\\\'",
"git from git import GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed to",
"not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg def parse_arguments(i_args): app_description =",
"= None for line in fp: line = line.rstrip() if 'SRCREV' in line:",
"uris = '' if project and sha: return (project, sha) print('No SRCREV or",
"(l_args.project_sha, digits) print('sha number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not",
"line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project and",
"extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run: print project_name print recipe recipe_basename",
"stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE,",
"'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if",
"= argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change sha') l_parser.add_argument( 'project_sha', help='input",
"find a project. Unset uris and look for # another bitbake variable that",
"return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris",
"gathered a complete (possibly multi-line) # assignment to a bitbake variable that ends",
"def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI =",
"scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args = parse_arguments(i_args)",
"['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate()",
"sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes (does not handle",
"print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes =",
"in fp: line = line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip()",
"(possibly multi-line) # assignment to a bitbake variable that ends with _URI. #",
"if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project and uris",
"uri in uris.split(): remote = i_args.remote + '/' + i_args.org if remote not",
"uris += line.split('\\\\')[0] if '\\\\' not in line: # In uris we've gathered",
"= ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if",
"(project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run:",
"the project repository for given revision. Generate commits that update bitbake metadata files",
"complete (possibly multi-line) # assignment to a bitbake variable that ends with _URI.",
"number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha =",
"recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args =",
"40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument(",
"l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to scan for') return l_parser.parse_args(i_args) def",
"else: print \"dry run\" print commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping",
"in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run:",
"HAVE_GIT = False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): #",
"= process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show',",
"# remove SRC_URI = and quotes (does not handle escaped quotes) uris =",
"assignment to a bitbake variable that ends with _URI. # Try to pull",
"args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg def parse_arguments(i_args): app_description = '''Local",
"for uri in uris.split(): remote = i_args.remote + '/' + i_args.org if remote",
"a complete (possibly multi-line) # assignment to a bitbake variable that ends with",
"if 'fatal' in stdoutput: print('fatal') else: return stdoutput return [] def find_recipes(i_args): git_args",
"look for # another bitbake variable that ends with _URI. uris = ''",
"'project_name', help='target project name to change sha') l_parser.add_argument( 'project_sha', help='input sha commit length",
"= '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry",
"a project. Unset uris and look for # another bitbake variable that ends",
"that update bitbake metadata files with SRCREV if given revision is new Generate",
"process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m',",
"length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run only')",
"project_name in args.project_name: if args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe) if",
"subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def",
"args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes",
"\"dry run\" print commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find",
"def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args,",
"fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev",
"digits) print('sha number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run:",
"= '' if project and sha: return (project, sha) print('No SRCREV or URI",
"'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal'",
"sha = line.split('=')[-1].replace('\"', '').strip() elif not project and uris or '_URI' in line:",
"l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha,",
"as fp: uris = '' project = None sha = None for line",
"uris = uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote + '/' +",
"bumping tool. Find bitbake metadata files (recipes) that use the git.ibm.com and check",
"project name to change sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits')",
"'_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate()",
"and check the project repository for given revision. Generate commits that update bitbake",
"git_add(recipe): git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput",
"exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha) if __name__",
"help='set org value to scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse the",
"'project_sha', help='input sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform",
"help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to scan",
"# the project is the right-most path segment return uri.split('/')[-1].replace('.git', '') return None",
"python2 import argparse import os #import sh import sys import math import subprocess",
"git.ibm.com and check the project repository for given revision. Generate commits that update",
"for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name:",
"extract_project_from_uris(args, uris) if project is None: # We didn't find a project. Unset",
"sys import math import subprocess PIPE = subprocess.PIPE try: import git from git",
"is up to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None with",
"tool. Find bitbake metadata files (recipes) that use the git.ibm.com and check the",
"not in line: # In uris we've gathered a complete (possibly multi-line) #",
"date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None with open(recipe) as fd:",
"is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name",
"= (recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue if not args.dry_run:",
"= None sha = None for line in fp: line = line.rstrip() if",
"'--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote",
"except ImportError: # _log.debug('Failed to import git module') HAVE_GIT = False def log(msg,",
"app_description = '''Local recipe bumping tool. Find bitbake metadata files (recipes) that use",
"_log.debug('Failed to import git module') HAVE_GIT = False def log(msg, args): if args.noisy:",
"+ '/' + i_args.org if remote not in uri: continue # remove fetcher",
"up to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None with open(recipe)",
"= process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def",
"uris): # remove SRC_URI = and quotes (does not handle escaped quotes) uris",
"l_parser.add_argument( 'project_name', help='target project name to change sha') l_parser.add_argument( 'project_sha', help='input sha commit",
"'' if project and sha: return (project, sha) print('No SRCREV or URI found",
"metadata files (recipes) that use the git.ibm.com and check the project repository for",
"'-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput =",
"GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed to import git module') HAVE_GIT",
"False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI",
"return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process",
"if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha) if __name__ == '__main__':",
"to a bitbake variable that ends with _URI. # Try to pull an",
"remove fetcher arguments uri = uri.split(';')[0] # the project is the right-most path",
"project is None: # We didn't find a project. Unset uris and look",
"stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args = ['git',",
"stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput return []",
"if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to date",
"line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project and uris or '_URI' in",
"is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1',",
"is the right-most path segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe):",
"import subprocess PIPE = subprocess.PIPE try: import git from git import GitCommandError HAVE_GIT",
"not handle escaped quotes) uris = uris.split('\"')[1] for uri in uris.split(): remote =",
"out of it. project = extract_project_from_uris(args, uris) if project is None: # We",
"project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args))",
"print('sha number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha",
"'/' + i_args.org if remote not in uri: continue # remove fetcher arguments",
"def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris = '' project = None",
"# In uris we've gathered a complete (possibly multi-line) # assignment to a",
"= os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up",
"l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument( '-v', '--verbose',",
"stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args",
"default='ibm-openbmc', help='set org value to scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse",
"stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return",
"'-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set",
"sha = None for line in fp: line = line.rstrip() if 'SRCREV' in",
"verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to scan for')",
"value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to scan",
"git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate()",
"= parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha, digits)",
"dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument(",
"uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris =",
"= and quotes (does not handle escaped quotes) uris = uris.split('\"')[1] for uri",
"= args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args,",
"variable that ends with _URI. # Try to pull an OpenBMC project out",
"scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to scan for') return",
"({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None with open(recipe) as fd: recipe_content",
"print commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find bitbake metadata",
"os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to",
"line in fp: line = line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"',",
"recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue if",
"# Parse the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits !=",
"stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git',",
"_URI. uris = '' if project and sha: return (project, sha) print('No SRCREV",
"candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run: print",
"subprocess PIPE = subprocess.PIPE try: import git from git import GitCommandError HAVE_GIT =",
"recipe_content = None with open(recipe) as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha,",
"= '''Local recipe bumping tool. Find bitbake metadata files (recipes) that use the",
"fp: line = line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif",
"['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if",
"given revision is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target",
"extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris = '' project = None sha",
"right-most path segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with open(recipe)",
"if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes (does",
"bitbake metadata files (recipes) that use the git.ibm.com and check the project repository",
"In uris we've gathered a complete (possibly multi-line) # assignment to a bitbake",
"print('fatal') def git_show(sha): git_args = ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE)",
"project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10])",
"'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project and uris or",
"None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris = '' project =",
"the project is the right-most path segment return uri.split('/')[-1].replace('.git', '') return None def",
"name to change sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits') l_parser.add_argument(",
"project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else:",
"git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput =",
"project = extract_project_from_uris(args, uris) if project is None: # We didn't find a",
"'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process",
"(project, sha) print('No SRCREV or URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe):",
"args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args",
"with open(recipe) as fp: uris = '' project = None sha = None",
"'''Local recipe bumping tool. Find bitbake metadata files (recipes) that use the git.ibm.com",
"in args.project_name: if args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha",
"40: message_args = (l_args.project_sha, digits) print('sha number {} is {} not 40'.format(*message_args)) exit(1)",
"uris = '' project = None sha = None for line in fp:",
"stdoutput: print('fatal') else: return stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e',",
"project and uris or '_URI' in line: uris += line.split('\\\\')[0] if '\\\\' not",
"git_show(sha): git_args = ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput",
"= i_args.remote + '/' + i_args.org if remote not in uri: continue #",
"else: return stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and',",
"'' project = None sha = None for line in fp: line =",
"= ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate()",
"'--dry-run', dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true',",
"== recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue",
"project. Unset uris and look for # another bitbake variable that ends with",
"i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in",
"is None: # We didn't find a project. Unset uris and look for",
"with _URI. # Try to pull an OpenBMC project out of it. project",
"main(i_args): # Parse the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits",
"in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project and uris or '_URI'",
"recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if",
"check the project repository for given revision. Generate commits that update bitbake metadata",
"if project and sha: return (project, sha) print('No SRCREV or URI found in",
"if not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg def parse_arguments(i_args): app_description",
"!= 40: message_args = (l_args.project_sha, digits) print('sha number {} is {} not 40'.format(*message_args))",
"import git from git import GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed",
"process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show', sha]",
"dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value",
"sha) def git_add(recipe): git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE)",
"in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process =",
"# We didn't find a project. Unset uris and look for # another",
"to pull an OpenBMC project out of it. project = extract_project_from_uris(args, uris) if",
"that ends with _URI. uris = '' if project and sha: return (project,",
"'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal'",
"uri = uri.split(';')[0] # the project is the right-most path segment return uri.split('/')[-1].replace('.git',",
"to scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args =",
"ends with _URI. # Try to pull an OpenBMC project out of it.",
"project is the right-most path segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args,",
"stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def",
"in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha",
"URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git', 'add', recipe]",
"commits that update bitbake metadata files with SRCREV if given revision is new",
"if '\\\\' not in line: # In uris we've gathered a complete (possibly",
"'\\\\' not in line: # In uris we've gathered a complete (possibly multi-line)",
"None with open(recipe) as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with",
"subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else:",
"in line: # In uris we've gathered a complete (possibly multi-line) # assignment",
"open(recipe) as fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w')",
"OpenBMC project out of it. project = extract_project_from_uris(args, uris) if project is None:",
"= recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name,",
"'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process",
"a bitbake variable that ends with _URI. # Try to pull an OpenBMC",
"#import sh import sys import math import subprocess PIPE = subprocess.PIPE try: import",
"= '' project = None sha = None for line in fp: line",
"project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename,",
"repository for given revision. Generate commits that update bitbake metadata files with SRCREV",
"commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change sha')",
"print recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10])",
"message_args = (l_args.project_sha, digits) print('sha number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args)",
"# _log.debug('Failed to import git module') HAVE_GIT = False def log(msg, args): if",
"not in uri: continue # remove fetcher arguments uri = uri.split(';')[0] # the",
"'-o', '--org', default='ibm-openbmc', help='set org value to scan for') return l_parser.parse_args(i_args) def main(i_args):",
"HAVE_GIT = True except ImportError: # _log.debug('Failed to import git module') HAVE_GIT =",
"['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput",
"fetcher arguments uri = uri.split(';')[0] # the project is the right-most path segment",
"Unset uris and look for # another bitbake variable that ends with _URI.",
"arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40: message_args =",
"[] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes:",
"in uri: continue # remove fetcher arguments uri = uri.split(';')[0] # the project",
"recipe): with open(recipe) as fp: uris = '' project = None sha =",
"escaped quotes) uris = uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote +",
"def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE)",
"in stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show', sha] process = subprocess.Popen(git_args,",
"if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha",
"value to scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args",
"print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE,",
"try: import git from git import GitCommandError HAVE_GIT = True except ImportError: #",
"git import GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed to import git",
"#!/usr/bin/env python2 import argparse import os #import sh import sys import math import",
"and uris or '_URI' in line: uris += line.split('\\\\')[0] if '\\\\' not in",
"continue if not args.dry_run: recipe_content = None with open(recipe) as fd: recipe_content =",
"import math import subprocess PIPE = subprocess.PIPE try: import git from git import",
"# assignment to a bitbake variable that ends with _URI. # Try to",
"i_args.org if remote not in uri: continue # remove fetcher arguments uri =",
"'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in",
"'-r', '--remote', default='github.com', help='set remote value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc',",
"stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha):",
"stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args =",
"recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{} is",
"if args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha:",
"def extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes (does not handle escaped",
"in uris.split(): remote = i_args.remote + '/' + i_args.org if remote not in",
"commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in",
"for line in fp: line = line.rstrip() if 'SRCREV' in line: sha =",
"find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in",
"a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages')",
"args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes (does not",
"bitbake variable that ends with _URI. uris = '' if project and sha:",
"that use the git.ibm.com and check the project repository for given revision. Generate",
"recipe_sha[:10]) print('{} is up to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content =",
"downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print",
"We didn't find a project. Unset uris and look for # another bitbake",
"return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args = parse_arguments(i_args) digits =",
"None sha = None for line in fp: line = line.rstrip() if 'SRCREV'",
"quotes) uris = uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote + '/'",
"stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe",
"args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe)",
"commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find bitbake metadata files",
"open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg =",
"if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg]",
"= ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate()",
"find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha",
"action='store_true', help='perform a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose",
"log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove SRC_URI = and",
"files (recipes) that use the git.ibm.com and check the project repository for given",
"from git import GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed to import",
"stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args,",
"not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha) if __name__ == '__main__': main(sys.argv[1:])",
"project = None sha = None for line in fp: line = line.rstrip()",
"if project is None: # We didn't find a project. Unset uris and",
"project out of it. project = extract_project_from_uris(args, uris) if project is None: #",
"{}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args,",
"find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE,",
"= process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit',",
"sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry",
"recipe) if project_name in args.project_name: if args.dry_run: print project_name print recipe recipe_basename =",
"if remote not in uri: continue # remove fetcher arguments uri = uri.split(';')[0]",
"SRCREV if given revision is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument(",
"''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change sha') l_parser.add_argument(",
"uris or '_URI' in line: uris += line.split('\\\\')[0] if '\\\\' not in line:",
"ends with _URI. uris = '' if project and sha: return (project, sha)",
"sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in",
"line: uris += line.split('\\\\')[0] if '\\\\' not in line: # In uris we've",
"in stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process =",
"git module') HAVE_GIT = False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args,",
"that ends with _URI. # Try to pull an OpenBMC project out of",
"or URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git', 'add',",
"for given revision. Generate commits that update bitbake metadata files with SRCREV if",
"fd: recipe_content = fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd:",
"'fatal' in stdoutput: print('fatal') else: return stdoutput return [] def find_recipes(i_args): git_args =",
"line.split('=')[-1].replace('\"', '').strip() elif not project and uris or '_URI' in line: uris +=",
"not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha)",
"handle escaped quotes) uris = uris.split('\"')[1] for uri in uris.split(): remote = i_args.remote",
"to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None with open(recipe) as",
"recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10],",
"project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha =",
"variable that ends with _URI. uris = '' if project and sha: return",
"with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg",
"parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find bitbake metadata files (recipes) that",
"messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to scan for') l_parser.add_argument( '-o',",
"for # another bitbake variable that ends with _URI. uris = '' if",
"git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args)",
"stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array):",
"only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote',",
"# remove fetcher arguments uri = uri.split(';')[0] # the project is the right-most",
"l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project name to change sha') l_parser.add_argument( 'project_sha',",
"extract_project_from_uris(i_args, uris): # remove SRC_URI = and quotes (does not handle escaped quotes)",
"fd.read() recipe_content = recipe_content.replace(recipe_sha, project_sha) with open(recipe, 'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args",
"to change sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits') l_parser.add_argument( '-d',",
"stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return",
"and quotes (does not handle escaped quotes) uris = uris.split('\"')[1] for uri in",
"'_URI' in line: uris += line.split('\\\\')[0] if '\\\\' not in line: # In",
"process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args):",
"+= line.split('\\\\')[0] if '\\\\' not in line: # In uris we've gathered a",
"git_args = ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput",
"stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') else: print(stdoutput)",
"return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for",
"recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args = (recipe_basename, recipe_sha[:10]) print('{}",
"fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump",
"(recipes) that use the git.ibm.com and check the project repository for given revision.",
"segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp:",
"= uri.split(';')[0] # the project is the right-most path segment return uri.split('/')[-1].replace('.git', '')",
"in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args = ['git', 'add', recipe] process =",
"find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha) if __name__ ==",
"= subprocess.PIPE try: import git from git import GitCommandError HAVE_GIT = True except",
"40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h']) git_show(log_sha) if",
"PIPE = subprocess.PIPE try: import git from git import GitCommandError HAVE_GIT = True",
"bitbake metadata files with SRCREV if given revision is new Generate commit. '''",
"process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput:",
"def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes = find_recipes(args) for recipe in candidate_recipes: project_name,",
"(does not handle escaped quotes) uris = uris.split('\"')[1] for uri in uris.split(): remote",
"run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r',",
"elif not project and uris or '_URI' in line: uris += line.split('\\\\')[0] if",
"in stdoutput: print('fatal') else: return stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l',",
"stdoutput: print('fatal') else: return stdoutput.decode('utf-8').split() return [] def find_and_process_bumps(args): project_sha = args.project_sha candidate_recipes",
"if 'fatal' in stdoutput: print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array",
"metadata files with SRCREV if given revision is new Generate commit. ''' l_parser",
"len(str(l_args.project_sha)) if digits != 40: message_args = (l_args.project_sha, digits) print('sha number {} is",
"process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput return [] def find_recipes(i_args):",
"to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value to scan for')",
"print('fatal') else: return stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI',",
"dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable",
"os #import sh import sys import math import subprocess PIPE = subprocess.PIPE try:",
"def main(i_args): # Parse the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if",
"uri: continue # remove fetcher arguments uri = uri.split(';')[0] # the project is",
"git_args = ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput =",
"# Try to pull an OpenBMC project out of it. project = extract_project_from_uris(args,",
"with _URI. uris = '' if project and sha: return (project, sha) print('No",
"l_parser.parse_args(i_args) def main(i_args): # Parse the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha))",
"print('fatal') else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE,",
"print('{} is up to date ({})'.format(*message_args)) continue if not args.dry_run: recipe_content = None",
"revision is new Generate commit. ''' l_parser = argparse.ArgumentParser(description=app_description) l_parser.add_argument( 'project_name', help='target project",
"the right-most path segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with",
"{} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n 1', '--pretty=format:%h'])",
"argparse import os #import sh import sys import math import subprocess PIPE =",
"and look for # another bitbake variable that ends with _URI. uris =",
"Parse the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40:",
"import os #import sh import sys import math import subprocess PIPE = subprocess.PIPE",
"Find bitbake metadata files (recipes) that use the git.ibm.com and check the project",
"path segment return uri.split('/')[-1].replace('.git', '') return None def extract_sha_from_recipe(args, recipe): with open(recipe) as",
"srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print \"dry run\" print commit_msg",
"+ i_args.org if remote not in uri: continue # remove fetcher arguments uri",
"args.dry_run: recipe_content = None with open(recipe) as fd: recipe_content = fd.read() recipe_content =",
"= subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal')",
"of it. project = extract_project_from_uris(args, uris) if project is None: # We didn't",
"project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run: print project_name",
"{} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if not l_args.dry_run: log_sha = git_log(['-n",
"print project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha == recipe_sha: message_args =",
"digits != 40: message_args = (l_args.project_sha, digits) print('sha number {} is {} not",
"didn't find a project. Unset uris and look for # another bitbake variable",
"if not args.dry_run: recipe_content = None with open(recipe) as fd: recipe_content = fd.read()",
"= (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not",
"git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE)",
"= ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput,",
"print \"dry run\" print commit_msg def parse_arguments(i_args): app_description = '''Local recipe bumping tool.",
"# another bitbake variable that ends with _URI. uris = '' if project",
"'--remote', default='github.com', help='set remote value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set",
"= line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not project",
"stdoutput: print('fatal') def git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args,",
"action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com', help='set remote value to",
"print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput,",
"['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal'",
"module') HAVE_GIT = False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris):",
"recipe_sha = extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run: print project_name print",
"org value to scan for') return l_parser.parse_args(i_args) def main(i_args): # Parse the arguments",
"sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run',",
"digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument( '-v',",
"= process.communicate() if 'fatal' in stdoutput: print('fatal') else: return stdoutput return [] def",
"help='input sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run', dest='dry_run', action='store_true', help='perform a",
"= True except ImportError: # _log.debug('Failed to import git module') HAVE_GIT = False",
"def parse_arguments(i_args): app_description = '''Local recipe bumping tool. Find bitbake metadata files (recipes)",
"return (project, sha) print('No SRCREV or URI found in {}'.format(recipe)) return(project, sha) def",
"subprocess.PIPE try: import git from git import GitCommandError HAVE_GIT = True except ImportError:",
"['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if",
"'-d', '--dry-run', dest='dry_run', action='store_true', help='perform a dry run only') l_parser.add_argument( '-v', '--verbose', dest='noisy',",
"= False def log(msg, args): if args.noisy: sys.stderr.write('{}\\n'.format(msg)) def extract_project_from_uris(i_args, uris): # remove",
"line: # In uris we've gathered a complete (possibly multi-line) # assignment to",
"= line.split('=')[-1].replace('\"', '').strip() elif not project and uris or '_URI' in line: uris",
"git_commit(commit_msg): git_args = ['git', 'commit', '-m', commit_msg] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput,",
"import GitCommandError HAVE_GIT = True except ImportError: # _log.debug('Failed to import git module')",
"revision. Generate commits that update bitbake metadata files with SRCREV if given revision",
"line = line.rstrip() if 'SRCREV' in line: sha = line.split('=')[-1].replace('\"', '').strip() elif not",
"i_args.remote + '/' + i_args.org if remote not in uri: continue # remove",
"change sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40 digits') l_parser.add_argument( '-d', '--dry-run',",
"= extract_sha_from_recipe(args, recipe) if project_name in args.project_name: if args.dry_run: print project_name print recipe",
"stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg): git_args",
"SRC_URI = and quotes (does not handle escaped quotes) uris = uris.split('\"')[1] for",
"'').strip() elif not project and uris or '_URI' in line: uris += line.split('\\\\')[0]",
"multi-line) # assignment to a bitbake variable that ends with _URI. # Try",
"= (l_args.project_sha, digits) print('sha number {} is {} not 40'.format(*message_args)) exit(1) find_and_process_bumps(l_args) if",
"ImportError: # _log.debug('Failed to import git module') HAVE_GIT = False def log(msg, args):",
"'--org', default='ibm-openbmc', help='set org value to scan for') return l_parser.parse_args(i_args) def main(i_args): #",
"= find_recipes(args) for recipe in candidate_recipes: project_name, recipe_sha = extract_sha_from_recipe(args, recipe) if project_name",
"'--and', '-e', i_args.remote+'/'+i_args.org] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if",
"default='github.com', help='set remote value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org",
"return(project, sha) def git_add(recipe): git_args = ['git', 'add', recipe] process = subprocess.Popen(git_args, stdout=PIPE,",
"uris) if project is None: # We didn't find a project. Unset uris",
"remote not in uri: continue # remove fetcher arguments uri = uri.split(';')[0] #",
"else: print(stdoutput) def git_log(parms_array): git_args = ['git', 'log']+parms_array process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE)",
"the arguments l_args = parse_arguments(i_args) digits = len(str(l_args.project_sha)) if digits != 40: message_args",
"return stdoutput return [] def find_recipes(i_args): git_args = ['git','--no-pager','grep','-l', '-e', '_URI', '--and', '-e',",
"the git.ibm.com and check the project repository for given revision. Generate commits that",
"stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_show(sha): git_args",
"project and sha: return (project, sha) print('No SRCREV or URI found in {}'.format(recipe))",
"commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if",
"or '_URI' in line: uris += line.split('\\\\')[0] if '\\\\' not in line: #",
"help='set remote value to scan for') l_parser.add_argument( '-o', '--org', default='ibm-openbmc', help='set org value",
"return None def extract_sha_from_recipe(args, recipe): with open(recipe) as fp: uris = '' project",
"if digits != 40: message_args = (l_args.project_sha, digits) print('sha number {} is {}",
"import argparse import os #import sh import sys import math import subprocess PIPE",
"commit_msg = '{}: downstream srcrev bump {}..{}'.format(*commit_summary_args) if not args.dry_run: git_commit(commit_msg) else: print",
"we've gathered a complete (possibly multi-line) # assignment to a bitbake variable that",
"'fatal' in stdoutput: print('fatal') def git_show(sha): git_args = ['git', 'show', sha] process =",
"recipe] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in",
"def git_show(sha): git_args = ['git', 'show', sha] process = subprocess.Popen(git_args, stdout=PIPE, stderr=PIPE) stdoutput,",
"continue # remove fetcher arguments uri = uri.split(';')[0] # the project is the",
"help='target project name to change sha') l_parser.add_argument( 'project_sha', help='input sha commit length 40",
"None: # We didn't find a project. Unset uris and look for #",
"None for line in fp: line = line.rstrip() if 'SRCREV' in line: sha",
"_URI. # Try to pull an OpenBMC project out of it. project =",
"l_parser.add_argument( '-v', '--verbose', dest='noisy', action='store_true', help='enable verbose status messages') l_parser.add_argument( '-r', '--remote', default='github.com',",
"stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if 'fatal' in stdoutput: print('fatal') def git_commit(commit_msg):",
"'w') as fd: fd.write(recipe_content) git_add(recipe) commit_summary_args = (project_name, recipe_sha[:10], project_sha[:10]) commit_msg = '{}:",
"args.project_name: if args.dry_run: print project_name print recipe recipe_basename = os.path.basename(recipe) if project_sha ==",
"files with SRCREV if given revision is new Generate commit. ''' l_parser =",
"print('No SRCREV or URI found in {}'.format(recipe)) return(project, sha) def git_add(recipe): git_args ="
] |
[
"Generated by Django 1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals from django.db",
"migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations = [ migrations.RemoveField(",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations",
"class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations = [ migrations.RemoveField( model_name='identitysettings',",
"unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ]",
"1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals from django.db import migrations class",
"__future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wapps',",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations =",
"14:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies =",
"# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-08 14:52",
"import migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations = [",
"from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"on 2016-08-08 14:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):",
"-*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-08 14:52 from",
"coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-08 14:52 from __future__",
"2016-08-08 14:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies",
"by Django 1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals from django.db import",
"Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations = [ migrations.RemoveField( model_name='identitysettings', name='logo',",
"# Generated by Django 1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals from",
"import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wapps', '0004_add_wapps_image'),",
"utf-8 -*- # Generated by Django 1.9.7 on 2016-08-08 14:52 from __future__ import",
"= [ ('wapps', '0004_add_wapps_image'), ] operations = [ migrations.RemoveField( model_name='identitysettings', name='logo', ), ]",
"dependencies = [ ('wapps', '0004_add_wapps_image'), ] operations = [ migrations.RemoveField( model_name='identitysettings', name='logo', ),",
"Django 1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals from django.db import migrations",
"-*- # Generated by Django 1.9.7 on 2016-08-08 14:52 from __future__ import unicode_literals"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls,",
"<reponame>jajajaqlt/nsg # Copyright 2017 Rice University # # Licensed under the Apache License,",
"predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels = [], []",
"License. import argparse import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE",
"= loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws,",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"= [] for call, api_bool in zip(calls, apiOrNot): if api_bool and call >",
"psis, labels = [], [] for i in range(10000): nodes, edges, targets, var_decl_ids,",
"= helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis",
"License. # You may obtain a copy of the License at # #",
"jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis = [] for call, api_bool",
"api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], [] for state, label in",
"top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder):",
"help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/'",
"'3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs):",
"label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], [] for",
"classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords,",
"data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152",
"\\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types, keywords, method,",
"law or agreed to in writing, software # distributed under the License is",
"10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels = [],",
"apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi",
"the License for the specific language governing permissions and # limitations under the",
"parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename",
"compliance with the License. # You may obtain a copy of the License",
"== API_NODE for t, api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api)",
"predictor.close() new_states, new_labels = [], [] for state, label in zip(psis, labels): if",
"[], [] for state, label in zip(psis, labels): if len(label) != 0: new_states.append(state)",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"!= 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels,",
"apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to",
"this file except in compliance with the License. # You may obtain a",
"\\ apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch()",
"limitations under the License. import argparse import os from experiments.jaccard_metric.utils import plotter from",
"main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis,",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"under the License. import argparse import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast",
"method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types,",
"= predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method",
"> 0: api = vocab[call] apis.append(api) return apis if __name__ == '__main__': parser",
"you may not use this file except in compliance with the License. #",
"for the specific language governing permissions and # limitations under the License. import",
"ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot =",
"types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi)",
"classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for",
"if api_bool and call > 0: api = vocab[call] apis.append(api) return apis if",
"only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if",
"in zip(calls, apiOrNot): if api_bool and call > 0: api = vocab[call] apis.append(api)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"]",
"def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config)",
"= [], [] for i in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers,",
"keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot",
"[] for call, api_bool in zip(calls, apiOrNot): if api_bool and call > 0:",
"get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], [] for state, label",
"api = vocab[call] apis.append(api) return apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)",
"apis.append(api) return apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save',",
"type=str, default='save', help='directory to load model from') parser.add_argument('--top', type=int, default=10, help='plot only the",
"nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in,",
"print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename)",
"for call, api_bool in zip(calls, apiOrNot): if api_bool and call > 0: api",
"ANY KIND, either express or implied. # See the License for the specific",
"# see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10 predictor",
"specific language governing permissions and # limitations under the License. import argparse import",
"API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader",
"in compliance with the License. # You may obtain a copy of the",
"language governing permissions and # limitations under the License. import argparse import os",
"surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t, api_bool",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"load model from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data')",
"psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp,",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import",
"edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields,",
"apiOrNot = node_type_numbers == API_NODE for t, api_bool in zip(targets, apiOrNot): label =",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader",
"fp_in, fields, \\ apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method",
"labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector",
"if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector =",
"not use this file except in compliance with the License. # You may",
"Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def",
"argparse import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"get_apis(calls, apiOrNot, vocab): apis = [] for call, api_bool in zip(calls, apiOrNot): if",
"new_labels = [], [] for state, label in zip(psis, labels): if len(label) !=",
"vocab[call] apis.append(api) return apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str,",
"fields, \\ apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method =",
"Loader(clargs.data, predictor.config) psis, labels = [], [] for i in range(10000): nodes, edges,",
"See the License for the specific language governing permissions and # limitations under",
"vocab): apis = [] for call, api_bool in zip(calls, apiOrNot): if api_bool and",
"'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder + 'jaccard_' + clargs.continue_from main(clargs)",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] =",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types, keywords, method, classname,",
"expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types, keywords, method, classname, javadoc_kws,",
"\"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10",
"surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields,",
"surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method,",
"helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis =",
"Rice University # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder + 'jaccard_'",
"= \"1\" def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader =",
"for state, label in zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"call > 0: api = vocab[call] apis.append(api) return apis if __name__ == '__main__':",
"clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder",
"2017 Rice University # # Licensed under the Apache License, Version 2.0 (the",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels =",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"for t, api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close()",
"zip(calls, apiOrNot): if api_bool and call > 0: api = vocab[call] apis.append(api) return",
"psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t, api_bool in zip(targets, apiOrNot): label",
"javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t,",
"surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname,",
"experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"",
"= \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids =",
"OF ANY KIND, either express or implied. # See the License for the",
"import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import",
"zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix,",
"'__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from') parser.add_argument('--top',",
"synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader",
") psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t, api_bool in zip(targets, apiOrNot):",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"# you may not use this file except in compliance with the License.",
"ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types, keywords, method, classname, javadoc_kws, \\",
"BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels = [], [] for i",
"from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL']",
"apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], []",
"0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids)",
"len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states,",
"new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis = []",
"agreed to in writing, software # distributed under the License is distributed on",
"== '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from')",
"node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types, keywords,",
"if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load",
"os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids",
"= '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def",
"and call > 0: api = vocab[call] apis.append(api) return apis if __name__ ==",
"in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\",
"api_bool in zip(calls, apiOrNot): if api_bool and call > 0: api = vocab[call]",
"num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis = [] for",
"surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t, api_bool in",
"(the \"License\"); # you may not use this file except in compliance with",
"surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE for t, api_bool in zip(targets,",
"experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics",
"default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename =",
"# # Unless required by applicable law or agreed to in writing, software",
"#152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5)",
"t, api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states,",
"from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue",
"express or implied. # See the License for the specific language governing permissions",
"predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method )",
"the specific language governing permissions and # limitations under the License. import argparse",
"default='save', help='directory to load model from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] =",
"except in compliance with the License. # You may obtain a copy of",
"fp_in, fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers",
"by applicable law or agreed to in writing, software # distributed under the",
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"",
"\"1\" def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data,",
"from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs =",
"= [], [] for state, label in zip(psis, labels): if len(label) != 0:",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see",
"return def get_apis(calls, apiOrNot, vocab): apis = [] for call, api_bool in zip(calls,",
"= BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels = [], [] for",
"jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot,",
"parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from') parser.add_argument('--top', type=int, default=10, help='plot only",
"either express or implied. # See the License for the specific language governing",
"batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels = [], [] for i in",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"University # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"i in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val,",
"= 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder + 'jaccard_' + clargs.continue_from",
"targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"= node_type_numbers == API_NODE for t, api_bool in zip(targets, apiOrNot): label = get_apis(t,",
"apiOrNot, vocab): apis = [] for call, api_bool in zip(calls, apiOrNot): if api_bool",
"[], [] for i in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\",
"Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls,",
"clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder + 'jaccard_' +",
"labels = [], [] for i in range(10000): nodes, edges, targets, var_decl_ids, \\",
"loader = Loader(clargs.data, predictor.config) psis, labels = [], [] for i in range(10000):",
"in zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations')",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"call, api_bool in zip(calls, apiOrNot): if api_bool and call > 0: api =",
"apiOrNot): if api_bool and call > 0: api = vocab[call] apis.append(api) return apis",
"see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10 predictor =",
"name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis = [] for call, api_bool in",
"= Loader(clargs.data, predictor.config) psis, labels = [], [] for i in range(10000): nodes,",
"and # limitations under the License. import argparse import os from experiments.jaccard_metric.utils import",
"loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in, fields, method, classname, javadoc_kws, surr_ret,",
"file except in compliance with the License. # You may obtain a copy",
"state, label in zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call",
"import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import",
"permissions and # limitations under the License. import argparse import os from experiments.jaccard_metric.utils",
"node_type_numbers == API_NODE for t, api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool,",
"[] for state, label in zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label)",
"from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from",
"from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] =",
"var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls,",
"parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from') parser.add_argument('--top', type=int,",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"new_states, new_labels = [], [] for state, label in zip(psis, labels): if len(label)",
"License for the specific language governing permissions and # limitations under the License.",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"return apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory",
"parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args()",
"the License. # You may obtain a copy of the License at #",
"types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi =",
"= argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from') parser.add_argument('--top', type=int, default=10,",
"model from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"def get_apis(calls, apiOrNot, vocab): apis = [] for call, api_bool in zip(calls, apiOrNot):",
"javadoc_kws, \\ surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type,",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"ret_type, fp_in, fields, \\ apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret, surr_fp,",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type,",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Copyright 2017 Rice University # # Licensed under the Apache License, Version 2.0",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"]",
"required by applicable law or agreed to in writing, software # distributed under",
"\\ node_type_numbers, \\ type_helper_val, expr_type_val, ret_type_val, \\ ret_type, fp_in, fields, \\ apicalls, types,",
"predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], [] for state, label in zip(psis,",
"the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not",
"labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder)",
"applicable law or agreed to in writing, software # distributed under the License",
"predictor.config) psis, labels = [], [] for i in range(10000): nodes, edges, targets,",
"\\ ret_type, fp_in, fields, \\ apicalls, types, keywords, method, classname, javadoc_kws, \\ surr_ret,",
"method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers == API_NODE",
"API_NODE for t, api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label)",
"new_states.append(state) new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix,",
"jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab):",
"api_bool and call > 0: api = vocab[call] apis.append(api) return apis if __name__",
"to load model from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data',",
"= parser.parse_args() clargs.folder = 'results/test_jaccard/' if not os.path.exists(clargs.folder): os.makedirs(clargs.folder) clargs.filename = clargs.folder +",
"new_labels.append(label) print('API Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector,",
"from synthesis.ops.candidate_ast import API_NODE from trainer_vae.infer import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from",
"the License. import argparse import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import",
"labels.append(label) predictor.close() new_states, new_labels = [], [] for state, label in zip(psis, labels):",
"plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return def get_apis(calls, apiOrNot, vocab): apis = [] for call,",
"type=int, default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder",
"issue #152 os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" def main(clargs): num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from,",
"or agreed to in writing, software # distributed under the License is distributed",
"or implied. # See the License for the specific language governing permissions and",
"[] for i in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val,",
"Call Jaccard Calculations') jac_api_matrix, jac_api_vector = helper(new_states, new_labels, num_centroids=num_centroids) plotter(jac_api_matrix, jac_api_vector, name=clargs.filename) return",
"num_centroids = 10 predictor = BayesianPredictor(clargs.continue_from, batch_size=5) loader = Loader(clargs.data, predictor.config) psis, labels",
"help='directory to load model from') parser.add_argument('--top', type=int, default=10, help='plot only the top-k labels')",
"import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" #",
"for i in range(10000): nodes, edges, targets, var_decl_ids, \\ node_type_numbers, \\ type_helper_val, expr_type_val,",
"0: api = vocab[call] apis.append(api) return apis if __name__ == '__main__': parser =",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"api_bool in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels",
"zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [],",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"default=10, help='plot only the top-k labels') parser.add_argument('--data', default='../data_extraction/data_reader/data') clargs = parser.parse_args() clargs.folder =",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# limitations under the License. import argparse import os from experiments.jaccard_metric.utils import plotter",
"import argparse import os from experiments.jaccard_metric.utils import plotter from synthesis.ops.candidate_ast import API_NODE from",
"import BayesianPredictor from experiments.jaccard_metric.get_jaccard_metrics import helper from data_extraction.data_reader.data_loader import Loader os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'",
"= vocab[call] apis.append(api) return apis if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from',",
"in zip(targets, apiOrNot): label = get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels =",
"__name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model",
"# Copyright 2017 Rice University # # Licensed under the Apache License, Version",
"with the License. # You may obtain a copy of the License at",
"fields, method, classname, javadoc_kws, surr_ret, surr_fp, surr_method ) psis.extend(psi) apiOrNot = node_type_numbers ==",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--continue_from', type=str, default='save', help='directory to load model from') parser.add_argument('--top', type=int, default=10, help='plot",
"label in zip(psis, labels): if len(label) != 0: new_states.append(state) new_labels.append(label) print('API Call Jaccard",
"in writing, software # distributed under the License is distributed on an \"AS",
"apis = [] for call, api_bool in zip(calls, apiOrNot): if api_bool and call",
"governing permissions and # limitations under the License. import argparse import os from",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"= get_apis(t, api_bool, predictor.config.vocab.chars_api) labels.append(label) predictor.close() new_states, new_labels = [], [] for state,",
"\\ surr_ret, surr_fp, surr_method = loader.next_batch() psi = predictor.get_latent_state(apicalls, types, keywords, ret_type, fp_in,"
] |
[] |
[] |
[
"screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back':",
"permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button)",
"None property_value = str(index) # Removing underscores and writing values to the screen.",
"__ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng in the",
"and closing stream. stream.stop_stream() stream.close() # Converting stream data into a wave file.",
"ahead and play the video we're on. if SystemState.VideoState.video_count > 0: pygame =",
"right arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect')",
"1 else: index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items",
"# Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index)",
"and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values,",
"setting = SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing",
"= hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0,",
"== 'video': # Check for button presses, messages, and which mode we're in.",
"print that file was not removed from library. print \"Couldn't remove from library\"",
"path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in",
"\"Couldn't remove from library\" try: os.remove(full_video) except: # TODO: print that image not",
"be removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print",
"button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res and low",
"os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function",
"filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename)",
"Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen",
"the video is at the end of the list, send it back to",
"the next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState,",
"2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values = setting + '_values'",
"removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that",
"'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness':",
"True else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue =",
"process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files",
"audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action)",
"threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK =",
"SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode",
"variables for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE",
"property_name): \"\"\"Moves to the previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list)",
"button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3,",
"'.mpeg' wav_filepath = video_path + timestamp + '.wav' process_filepath = mjpeg_filepath + '.process'",
"TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows",
"'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode':",
"modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length()",
"= SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty, set it to none.",
"from library. print \"Couldn't remove from library\" try: os.remove(full_video) except: # TODO: print",
"+ '.wav' process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting",
"0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for each menu item.\"\"\" if",
"50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values",
"'PREVIEW-' and path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string))",
"the files above. try: os.remove(preview_video) except: # TODO:print that preview couldn't be removed.",
"__CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args = (timestamp) thread =",
"If there's more than one video, go ahead and play the video we're",
"file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting",
"screen.\"\"\" # If there's more than one video, go ahead and play the",
"property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each",
"SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if",
"RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res and low res video_archive. __StopRecordingAudio()",
"(0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375,",
"if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False",
"== 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back()",
"# Check if we are in a streaming mode. If so, throw frames",
"if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0],",
"elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif",
"Checking video message queue for record messages. if video_message_queue != None: recording_state =",
"'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom')",
"to delete the files above. try: os.remove(preview_video) except: # TODO:print that preview couldn't",
"10800 frames = [] # Clearing the queue messages just in case. with",
"0: SystemState.VideoState.video_index -= 1 # If the video is the last one, then",
"path for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive =",
"color=(57, 255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame",
"a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp):",
"+ '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files to make preview",
"> 0: SystemState.VideoState.video_index -= 1 # If the video is the last one,",
"False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting =",
"up all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action =",
"args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\" args",
"\"\"\"Display's items on screen when you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState,",
"video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg'",
"video is at the end of the list, send it back to the",
"60, 70, 80, 90, 100] hundred_container = [-100, -90, -80, -70, -60, -50,",
"3: # Remove 'PREVIEW-' and path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0]",
"wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables to stop recording audio.\"\"\"",
"full_video.split('.') full_video = full_video[0] + '.h264' # Attempting to delete the files above.",
"except: # TODO: print that image not removed. print \"Image not removed\" def",
"= [-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10,",
"= [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous",
"movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode",
"100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [",
"(preview) on the camera's screen.\"\"\" # If there's more than one video, go",
"5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0",
"item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso')",
"mpeg1video -an ' + mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a +",
"SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB'",
"state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the video file (preview)",
"one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If the",
"= 'none' elif button == 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False)",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif",
"100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of the video",
"= SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath = video_path + timestamp",
"go to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index +=",
"'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation':",
"= 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video",
"not at the end of the list, go to the next one. if",
"== 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode ==",
"list, go to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index",
"+ mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an",
"+ timestamp # Start recording a high res (.h264) and low res (.mjpeg).",
"threading function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video",
"size=20 ) # Check if we are in a streaming mode. If so,",
"videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the",
"elif button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso'",
"0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values",
"then go back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename",
"= wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all",
"property_list) index = getattr(SystemState.VideoState, property_name) if index > 0: index -= 1 else:",
"tuple: if index == 0: index = None property_value = str(index) # Removing",
"__NextVideo(): \"\"\"Moves to the next video in the library.\"\"\" # If the video",
"property_name): \"\"\"Moves to the next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list)",
"'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for",
"* 240 * 3)], (320, 240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width()",
"elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo()",
"SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream",
"0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause'",
"= 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization =",
"SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values = setting",
"0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count -",
"atexit import io import stat import os import signal import picamera import time",
"if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio",
"= False audio_action = {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def",
"Try placing the information inside the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False)",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a video in the",
"= 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode =",
"# Lists of camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500,",
"\"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was",
"+ '.h264' # Attempting to delete the files above. try: os.remove(preview_video) except: #",
"Setting up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True,",
"'none' # Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect =",
"arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif",
"import os import signal import picamera import time import sys import threading import",
"Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path",
"__ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files",
"+ ffmpeg_b # Executing the ffmpeg command and removing the process files. os.system(ffmpeg_convert)",
"'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom':",
"16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves",
"threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\"",
"= None property_value = str(index) # Removing underscores and writing values to the",
"video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path",
"that image not removed. print \"Image not removed\" def Main(): \"\"\"Main loop for",
"video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time()))",
"# System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7,",
"' + mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b #",
"local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp",
"output=True, frames_per_buffer=CHUNK ) # Recording data to a wave file. for i in",
"0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25,",
"SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename =",
"3)], (320, 240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() ) / 2",
"] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto',",
"(320 * 240 * 3)], (320, 240), 'RGB' ) xa = (320 -",
"- SystemState.VideoState.img.get_width() ) / 2 ya = (240 - SystemState.VideoState.img.get_height()) / 2 Screen.RefreshScreen(image=SystemState.VideoState.img,",
"empty, set it to none. except Queue.Empty: audio_message_queue = None #If there is",
"= full_video.split('.') full_video = full_video[0] + '.h264' # Attempting to delete the files",
"values when you first enter a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode",
"above. try: os.remove(preview_video) except: # TODO:print that preview couldn't be removed. print \"Couldn't",
"video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else:",
"SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty:",
"elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count >",
"state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20) ) def Process():",
"SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif",
"refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button",
"1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count)",
"released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res and low res video_archive.",
"Check if we are in a streaming mode. If so, throw frames at",
"__ConvertVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True)",
"from engine import Screen from engine import TextWriter from engine import Events import",
"0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix'",
"if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path",
"'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent',",
"0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) ==",
"a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid)",
"os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time and position of the photo",
"mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the",
"= threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a",
"False: break # Stopping and closing stream. stream.stop_stream() stream.close() # Converting stream data",
"elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif",
"SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path",
"Utilities from engine import Menu from engine import Screen from engine import TextWriter",
"SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable",
"'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness",
"Menu from engine import Screen from engine import TextWriter from engine import Events",
"messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio.",
"timestamp # Start recording a high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath",
"TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the video file",
"__PreviousVideo(): \"\"\"Moves to the previous video in the library.\"\"\" # If the video",
"= str(index) # Removing underscores and writing values to the screen. property_name =",
"# Makes 'zoom' human readable. if property_type is tuple: if index == 0:",
"__NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values',",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio button that starts recording.",
"next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name)",
"SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos,",
"= SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) #",
"stream. stream.stop_stream() stream.close() # Converting stream data into a wave file. wavefile =",
"-= 1 # If the video is the last one, then go back",
"button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty, set",
"SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a",
"0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4,",
"'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness')",
"def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\" args = (timestamp) thread",
"full_video = full_video.split('.') full_video = full_video[0] + '.h264' # Attempting to delete the",
"'.wav' RECORD_SECONDS = 10800 frames = [] # Clearing the queue messages just",
"== 'decline': Menu.Back() OpenAlbum() # Displaying settings title and values when you first",
"import picamera import time import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class",
"position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title",
"RECORD_SECONDS = 10800 frames = [] # Clearing the queue messages just in",
"time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time and position",
"def __ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\" pygame = SystemState.pygame screen",
"video_path + timestamp mjpeg_filepath = video_preview_path + timestamp # Start recording a high",
"'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() ) / 2 ya = (240",
"= 10800 frames = [] # Clearing the queue messages just in case.",
"of the list, go to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count -",
"function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start()",
"(320, 240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() ) / 2 ya",
"screen. if property_value == 0 and property_type is not bool: property_value = 'Auto'",
"else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename):",
"ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b",
"remove from library\" try: os.remove(full_video) except: # TODO: print that image not removed.",
"'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo() elif button ==",
"on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen =",
"mpjpeg video to mpeg which pygame can play.\"\"\" # Setting up local varables.",
"1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name):",
"OpenAlbum(): \"\"\"Opens the contents inside of the videos folder.\"\"\" # Setup the preview",
"'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 )",
"= [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake',",
"== 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ]",
"SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves",
"[ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values",
"elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif",
"there's a video in the directory, set it as current video. if SystemState.VideoState.video_count",
"'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation':",
"SystemState.VideoState.video_index += 1 # If the video is at the end of the",
"= 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button",
"recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio button that",
"TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif",
"to a wave file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data =",
"timestamp + '.wav' process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) #",
"= 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation =",
"menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values',",
"on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays",
"TODO: print that file was not removed from library. print \"Couldn't remove from",
"SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0)",
"2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None)",
"] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon',",
"= SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of",
"50, 60, 70, 80, 90, 100] hundred_container = [-100, -90, -80, -70, -60,",
"Writing the time and position of the photo on the screen. TextWriter.Write( state=SystemState,",
"90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50, 60, 70,",
"the previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState,",
"to none. except Queue.Empty: audio_message_queue = None #If there is something inside the",
"def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160,",
"loop for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while",
"== 4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that",
"'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization':",
"+ 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video",
"of the video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen # Setting up",
"< len(properties) - 1: index += 1 else: index = 0 __ProcessSettingsValues(property_name, properties,",
"be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video = full_video.split('.')",
"= 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue()",
"Ensures default 'auto' values are printed on screen. if property_value == 0 and",
"Displaying settings title and values when you first enter a menu. if SystemState.screen_mode",
"Check for button presses, messages, and which mode we're in. Events.CheckEvents() if SystemState.screen_mode",
"75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow()",
"underscores and writing values to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value)",
"time and position of the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90,",
"== 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting ==",
"in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream =",
"elif button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button ==",
"which mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream =",
"'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3,",
"properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them on screen",
"elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif",
"settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if",
"int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing the information inside",
"SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path leaving just unix time. utime_string",
"in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value)",
"240) while SystemState.application == 'video': # Check for button presses, messages, and which",
"return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in the menu.\"\"\"",
"just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream",
"the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False}",
"elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count >",
"button presses, messages, and which mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1,",
"SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path #",
"was not removed from library. print \"Couldn't remove from library\" try: os.remove(full_video) except:",
"refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness'",
"readable. if property_type is tuple: if index == 0: index = None property_value",
"SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If there's",
"SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting",
"timestamp mjpeg_filepath = video_preview_path + timestamp # Start recording a high res (.h264)",
"# Writing the time and position of the photo on the screen. TextWriter.Write(",
"the path for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive",
"__CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you first enter a menu.\"\"\" properties",
"elif button == 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button",
"each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255,",
"If there's a video in the directory, set it as current video. if",
"files above. try: os.remove(preview_video) except: # TODO:print that preview couldn't be removed. print",
"0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values =",
"'.wav' process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video",
"SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values = [0, 100, 200,",
"'.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write(",
"- 1: index += 1 else: index = 0 __ProcessSettingsValues(property_name, properties, index) def",
"== 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting ==",
"__RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up",
"frames = [] # Clearing the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex:",
"= 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button",
"timestamp + '.mpeg' wav_filepath = video_path + timestamp + '.wav' process_filepath = mjpeg_filepath",
"for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try",
"elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif",
"= SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath =",
"presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode",
"SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path leaving",
"elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif",
"thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\" args = (timestamp)",
"removed. print \"Image not removed\" def Main(): \"\"\"Main loop for the camera application.\"\"\"",
"= SystemState.pygame screen = SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie =",
"from engine import TextWriter from engine import Events import RPi.GPIO import pyaudio import",
"== 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting ==",
"video file (preview) on the camera's screen.\"\"\" # If there's more than one",
"def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16",
"Recording data to a wave file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)):",
"SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive",
"'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation')",
"30, 40, 50, 60, 70, 80, 90, 100] hundred_container = [-100, -90, -80,",
"process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of the",
"= {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video",
"SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240",
"text='Delete?', position=(125, 75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif button ==",
"'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum()",
"the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values",
"'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10,",
"enter a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting =",
"= None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration =",
"None #If there is something inside the queue, read it. if audio_message_queue !=",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"'.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the red button is released. RPi.GPIO.wait_for_edge(8,",
"OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video in the library.\"\"\" # If",
"Next and Previous. \"\"\" property_value = properties[index] # Setting values in SystemState.camera from",
"properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index < len(properties) -",
"removed from library. print \"Couldn't remove from library\" try: os.remove(full_video) except: # TODO:",
"recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording':",
"setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures default 'auto'",
"+ \" -target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an ' +",
"== 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode ==",
"\"\"\"Processing right arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values',",
"format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to a wave",
"the video more than the first one, then move backwards through the list.",
"write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True",
"'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list,",
"Queue.Empty: audio_message_queue = None #If there is something inside the queue, read it.",
"time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video in the",
"color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if we are in a streaming",
"1 # If the video is the last one, then go back to",
"'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint',",
"else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there",
"not removed from library. print \"Couldn't remove from library\" try: os.remove(full_video) except: #",
"== 0: index = None property_value = str(index) # Removing underscores and writing",
"' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\"",
"button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3,",
"for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application",
"== 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5)",
"index = None property_value = str(index) # Removing underscores and writing values to",
"in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream",
"str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording = False",
"elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization':",
"== 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting ==",
"mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath + \" -target ntsc-vcd \"",
"refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast'",
"> 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button ==",
"__ProcessRightArrow(): \"\"\"Processing right arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect':",
"video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True",
"when you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState,",
"end of the list, go to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count",
"Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img =",
"'decline': Menu.Back() OpenAlbum() # Displaying settings title and values when you first enter",
"= video_path + timestamp + '.wav' process_filepath = mjpeg_filepath + '.process' mode =",
"audio_action = {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records",
"= setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for",
"property_list) index = getattr(SystemState.VideoState, property_name) if index < len(properties) - 1: index +=",
"elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif",
"# Recording data to a wave file. for i in range(0, int(RATE/CHUNK *",
"of the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 )",
"color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\"",
"Makes 'zoom' human readable. if property_type is tuple: if index == 0: index",
"args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up",
"a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting",
"== 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting ==",
"queue is already empty, set it to none. except Queue.Empty: audio_message_queue = None",
"paths for videos. h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path + timestamp",
"for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting ==",
"while SystemState.application == 'video': # Check for button presses, messages, and which mode",
"the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index >",
"menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values',",
"'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation',",
"button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso':",
"+ '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video in",
"low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a",
"-target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an ' + mpeg_filepath +",
"= False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/'",
"def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button",
"= pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: # Remove",
"if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index",
"= time.ctime(int(utime_string)) # Writing the time and position of the photo on the",
"data to a wave file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data",
"-= 1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list,",
"SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' )",
"already empty, set it to none. except Queue.Empty: audio_message_queue = None #If there",
"is the last one, then go back to the beginning. else: SystemState.VideoState.video_index =",
"the list, go to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1:",
"= os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive)",
"full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video = full_video.split('.') full_video =",
"getattr(SystemState.VideoState, property_name) if index < len(properties) - 1: index += 1 else: index",
"state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a",
"except Queue.Empty: video_message_queue = None # Checking video message queue for record messages.",
"= (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo",
"than one video, go ahead and play the video we're on. if SystemState.VideoState.video_count",
"SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [",
"to the previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index =",
"= [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive)",
"> 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count",
"== 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting ==",
"__WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState,",
"'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent',",
"input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to a wave file. for i",
"index = getattr(SystemState.VideoState, property_name) if index < len(properties) - 1: index += 1",
"-70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50,",
"If the video is at the end of the list, send it back",
"# Setting up files to be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0]",
"not bool: property_value = 'Auto' # Makes 'zoom' human readable. if property_type is",
"os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of the videos folder.\"\"\"",
"into a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close()",
"gpio button that starts recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and",
"# TODO:print that preview couldn't be removed. print \"Couldn't remove preview image\" try:",
"if property_value == 0 and property_type is not bool: property_value = 'Auto' #",
"= SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path +",
"SystemState.pygame screen = SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename)",
"image not removed. print \"Image not removed\" def Main(): \"\"\"Main loop for the",
"import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init():",
"'.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until",
"SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1)",
"there's more than one video, go ahead and play the video we're on.",
"timestamp = time.ctime(int(utime_string)) # Writing the time and position of the photo on",
"'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off'",
"'ffmpeg -i ' + mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b = '",
"__PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values',",
"button = str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if",
"read it. if audio_message_queue != None: if audio_message_queue.get('recording') == False: break # Stopping",
"# TODO: print that image not removed. print \"Image not removed\" def Main():",
"= [0, 100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none',",
"FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800 frames = []",
"SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN,",
"SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif",
"permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu",
"hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225,",
"SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to a",
"mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp +",
"text='No Videos', position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture",
"str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\"",
"SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode",
"'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write(",
"videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True ) def",
"# Checking video message queue for record messages. if video_message_queue != None: recording_state",
"8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path",
"refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation'",
"= SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to",
"inside the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue",
"SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the",
"3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except",
"!= None and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path leaving just",
"'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def",
"in the directory, set it as current video. if SystemState.VideoState.video_count > 0: if",
"video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen # Setting up movie for",
"wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up",
"70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container",
"text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the video file (preview) on",
"= 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode =",
"SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/'",
"[ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8),",
"'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode':",
"Removing underscores and writing values to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name)",
"refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization'",
"len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next",
"SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording",
"\" ffmpeg_b = ' -vcodec mpeg1video -an ' + mpeg_filepath + ' -threads",
"is at the end of the list, send it back to the first",
"SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video in",
"Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values = [0, 100,",
"SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps',",
") def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen",
"the video file (preview) on the camera's screen.\"\"\" # If there's more than",
"import Utilities from engine import Menu from engine import Screen from engine import",
"= [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ]",
"SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are",
"position=(125, 75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow':",
"os import signal import picamera import time import sys import threading import Queue",
"-20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]",
"__WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10),",
"\"\"\"Moves to the previous video in the library.\"\"\" # If the video more",
"Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400,",
"== 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert",
"import atexit import io import stat import os import signal import picamera import",
"first one, then move backwards through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index",
"up local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path +",
"varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp +",
"elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast':",
"and values when you first enter a menu. if SystemState.screen_mode == 2 and",
"full_video[0] + full_video[1] full_video = full_video.split('.') full_video = full_video[0] + '.h264' # Attempting",
"'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"and writing values to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def",
"mjpeg_filepath = video_preview_path + timestamp # Start recording a high res (.h264) and",
"'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast':",
"[] # Clearing the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() #",
"index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you first enter a",
"SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting",
"def Main(): \"\"\"Main loop for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution =",
"camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values",
"= SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum()",
"in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def",
"'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation':",
"= SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath",
"__NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values',",
"'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom')",
"in the library.\"\"\" # If the video is not at the end of",
"'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values",
"position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing button",
"message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty,",
"ffmpeg_a + ffmpeg_b # Executing the ffmpeg command and removing the process files.",
"wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables to",
"0: index = None property_value = str(index) # Removing underscores and writing values",
"thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls",
"prints them on screen for Next and Previous. \"\"\" property_value = properties[index] #",
"signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash",
"item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20) )",
"None: if audio_message_queue.get('recording') == False: break # Stopping and closing stream. stream.stop_stream() stream.close()",
"recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action = {'recording': False}",
"== 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif",
"__ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which pygame can play.\"\"\" # Setting",
"getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index < len(properties) - 1: index",
"True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False:",
"index): \"\"\"Fetches values and prints them on screen for Next and Previous. \"\"\"",
"else: index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on",
"(320, 240) while SystemState.application == 'video': # Check for button presses, messages, and",
"recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state",
"frames.append(data) # Try placing the information inside the audio message queue. try: audio_message_queue",
"engine import SystemState from engine import Utilities from engine import Menu from engine",
"index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values",
"'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness')",
"property_name) if index > 0: index -= 1 else: index = len(properties) -",
"unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time and",
"button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() #",
"pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos =",
"(0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275,",
"a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index)",
"== 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting ==",
"elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio button",
"and which mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream",
"def __ProcessRightArrow(): \"\"\"Processing right arrow input for each menu item.\"\"\" if SystemState.VideoState.setting ==",
"'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState",
"SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application == 'video': # Check for button",
"hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1,",
"SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index]",
"\"\"\"Processing left arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values',",
"Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0",
"property_name): \"\"\"Display's items on screen when you first enter a menu.\"\"\" properties =",
"that starts recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode ==",
"\"\"\"Opens the contents inside of the videos folder.\"\"\" # Setup the preview path",
"SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting)",
"= io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb)",
"str(index) # Removing underscores and writing values to the screen. property_name = '",
"folder.\"\"\" # Setup the preview path as the path for the video count.",
"0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path",
"+ 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous",
"SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If the video is the last",
"= [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film',",
"else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves",
"'auto' values are printed on screen. if property_value == 0 and property_type is",
"state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text):",
"__ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect':",
"'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play()",
"if we are in a streaming mode. If so, throw frames at the",
"presses, messages, and which mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2,",
"\"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid,",
"1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng in",
"'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back()",
"'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0,",
"SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) #",
"engine import Screen from engine import TextWriter from engine import Events import RPi.GPIO",
"__PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow():",
"the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally =",
"setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if",
"'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode')",
"-10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values",
"print \"Couldn't remove from library\" try: os.remove(full_video) except: # TODO: print that image",
"range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing the information",
"== 3: setting = SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def",
"SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video)",
"= None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count =",
"if index < len(properties) - 1: index += 1 else: index = 0",
"centered=True, size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for",
"send it back to the first one. else: SystemState.VideoState.video_index = 0 filename =",
"def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you first enter a menu.\"\"\"",
"SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If the video is at the",
"= threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK",
"until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high",
"0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325,",
"permatext=True, state=SystemState, size=20 ) # Check if we are in a streaming mode.",
"wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio",
"button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo() elif",
"up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK",
"500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint',",
"== 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo()",
"SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) #",
"index) property_type = type(property_value) # Ensures default 'auto' values are printed on screen.",
"that file was not removed from library. print \"Couldn't remove from library\" try:",
"== 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275,",
"folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def",
"'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button ==",
"the list, send it back to the first one. else: SystemState.VideoState.video_index = 0",
"TextWriter from engine import Events import RPi.GPIO import pyaudio import wave import atexit",
"+ '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu",
"there are no videos, just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos',",
"+ ' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the ffmpeg",
"__StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a video. __CallConvertVideo(timestamp) def",
"__NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if",
"remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was not",
"'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2'",
"pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP)",
"'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon',",
"= 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button",
"10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0",
"] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30,",
"args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args",
"file (preview) on the camera's screen.\"\"\" # If there's more than one video,",
"text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing",
"values and prints them on screen for Next and Previous. \"\"\" property_value =",
"except: # TODO: print that file was not removed from library. print \"Couldn't",
"stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action = {'recording':",
"import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): # System",
"SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next",
"SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count",
"\"\"\"Shows a picture of the video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen",
"video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path =",
"the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of",
"ffmpeg_b = ' -vcodec mpeg1video -an ' + mpeg_filepath + ' -threads 0'",
"current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video)",
"picture of the video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen # Setting",
"640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen',",
"index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen",
"180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50, 60, 70, 80,",
"< SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If the video is at",
"0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit',",
"# If the video more than the first one, then move backwards through",
"SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action)",
"#Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState =",
"= 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button",
"the first one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index",
"is tuple: if index == 0: index = None property_value = str(index) #",
"button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3,",
"messages, and which mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3):",
"SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path +",
"def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which pygame can play.\"\"\" #",
"property_type = type(property_value) # Ensures default 'auto' values are printed on screen. if",
"= 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup",
"SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9,",
"than the first one, then move backwards through the list. if SystemState.VideoState.video_index >",
"button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3,",
"SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off'",
"Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect'",
"os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count",
"def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu item.\"\"\" if SystemState.VideoState.setting ==",
"to the first one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally =",
"SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None #",
"a picture of the video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen #",
"'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting",
"SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800 frames = [] # Clearing",
"= 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom =",
"property_name, index) property_type = type(property_value) # Ensures default 'auto' values are printed on",
"10), centered=True, size=25, permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\"",
"SystemState.camera.resolution = (320, 240) while SystemState.application == 'video': # Check for button presses,",
"is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res and low res",
"os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\" args",
"def __NextVideo(): \"\"\"Moves to the next video in the library.\"\"\" # If the",
"= 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' +",
"screen = SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1)",
"SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking",
"0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4,",
"* 3)], (320, 240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() ) /",
"== 0 and property_type is not bool: property_value = 'Auto' # Makes 'zoom'",
"# Attempting to delete the files above. try: os.remove(preview_video) except: # TODO:print that",
"for record messages. if video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state ==",
"(1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try: video_message_queue =",
"camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application == 'video':",
"TODO:print that preview couldn't be removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video)",
"SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting",
"None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False",
"left arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect')",
"SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting",
"removed\" def Main(): \"\"\"Main loop for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution",
"= full_video[0] + full_video[1] full_video = full_video.split('.') full_video = full_video[0] + '.h264' #",
"255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write(",
"(timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function",
"the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application ==",
"human readable. if property_type is tuple: if index == 0: index = None",
"audio_message_queue = None #If there is something inside the queue, read it. if",
"== 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting ==",
"the preview path as the path for the video count. path = SystemState.VideoState.video_preview_path",
") elif button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button",
"== 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting ==",
"set it to none. except Queue.Empty: audio_message_queue = None #If there is something",
"0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot',",
"SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\" args =",
"input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting",
"'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash',",
"Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow()",
"file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) #",
"SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting",
"0 and property_type is not bool: property_value = 'Auto' # Makes 'zoom' human",
"pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] #",
"setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each",
"- 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng",
"print that image not removed. print \"Image not removed\" def Main(): \"\"\"Main loop",
"> 0: index -= 1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties,",
"SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio button that starts recording. if",
"__ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\" pygame = SystemState.pygame screen =",
"one video, go ahead and play the video we're on. if SystemState.VideoState.video_count >",
"'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode')",
"it back to the first one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index]",
"__ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them on screen for Next and",
"= None #If there is something inside the queue, read it. if audio_message_queue",
"values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type =",
"= stream.read(CHUNK) frames.append(data) # Try placing the information inside the audio message queue.",
"at the end of the list, send it back to the first one.",
"# Converting stream data into a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS)",
"elif button == 'decline': Menu.Back() OpenAlbum() # Displaying settings title and values when",
"preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath + \"",
"If there are no videos, just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No",
"stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK )",
"os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\"",
"arrow input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif",
"SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath =",
"__PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values',",
"RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting",
"stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data",
"video in the library.\"\"\" # If the video is not at the end",
"SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 #",
"SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4)",
"Wait until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the",
"SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures default",
"input for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting",
"SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting",
"0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values =",
"'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count",
"index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to",
"and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True,",
"import TextWriter from engine import Events import RPi.GPIO import pyaudio import wave import",
"thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in",
"contents inside of the videos folder.\"\"\" # Setup the preview path as the",
"If so, throw frames at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream =",
"== 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting ==",
"= getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and",
"255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame =",
"= 'ffmpeg -i ' + mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b =",
"state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif button",
"thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls",
"audio_message_queue != None: if audio_message_queue.get('recording') == False: break # Stopping and closing stream.",
"video in the library.\"\"\" # If the video more than the first one,",
"Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState,",
"up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and",
"case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream = SystemState.pyaudio.open(",
"Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() # Displaying settings title and",
"SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's",
"= 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button",
"convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which",
"application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application == 'video': #",
"SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking video message queue for record",
"leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the",
"property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches",
"OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() # Displaying settings title and values",
"0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6),",
"thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args =",
"list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If the video is",
"RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating",
"= SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def",
"button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3,",
"= SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking video message queue for",
"on the camera's screen.\"\"\" # If there's more than one video, go ahead",
"SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button",
"position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the video file (preview) on the",
"camera's screen.\"\"\" # If there's more than one video, go ahead and play",
"'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath()",
"__RecordVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True)",
"each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso':",
"1: SystemState.VideoState.video_index += 1 # If the video is at the end of",
"Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect",
"Events import RPi.GPIO import pyaudio import wave import atexit import io import stat",
"engine import Events import RPi.GPIO import pyaudio import wave import atexit import io",
"'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button ==",
"'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports',",
"] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to",
"\"\"\" property_value = properties[index] # Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name,",
"engine import TextWriter from engine import Events import RPi.GPIO import pyaudio import wave",
"'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture into",
"mpeg which pygame can play.\"\"\" # Setting up local varables. video_path = SystemState.VideoState.video_path",
"240 * 3)], (320, 240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() )",
"queue for record messages. if video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state",
"video is the last one, then go back to the beginning. else: SystemState.VideoState.video_index",
"record messages. if video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state == True:",
"video we're on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16)",
"10, 20, 30, 40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container",
"menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20)",
"video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath",
"size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\" pygame",
"more than the first one, then move backwards through the list. if SystemState.VideoState.video_index",
"__ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you first",
"SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and",
"video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking video message queue",
"elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif",
"them on screen for Next and Previous. \"\"\" property_value = properties[index] # Setting",
"size=25, permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\" button =",
"one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1)",
"SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting",
"= SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive]",
"SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0:",
"= SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) +",
"list, send it back to the first one. else: SystemState.VideoState.video_index = 0 filename",
"low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3,",
"a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files to be deleted. full_video",
"'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button ==",
"button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none'",
"+ '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the red button is released.",
"SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2,",
"'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode':",
"ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an ' + mpeg_filepath + '",
"= [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8,",
"properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng in the menu.\"\"\"",
"property_name) if index < len(properties) - 1: index += 1 else: index =",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If the video",
"'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight',",
"SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225,",
"== False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write(",
"recording a high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2,",
"If the video more than the first one, then move backwards through the",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"= SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back()",
"\"\"\"Plays the video file (preview) on the camera's screen.\"\"\" # If there's more",
"for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57,",
"video more than the first one, then move backwards through the list. if",
"SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting",
"timestamp + '.wav' RECORD_SECONDS = 10800 frames = [] # Clearing the queue",
"# If there are no videos, just write \"no videos\". else: TextWriter.Write( state=SystemState,",
"-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70,",
"'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if",
"110), centered=True, size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values",
"elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif",
"wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the",
"(0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ]",
"index += 1 else: index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name):",
"for each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting ==",
"1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS =",
"video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for",
"== 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button",
"audio_message_queue.get('recording') == False: break # Stopping and closing stream. stream.stop_stream() stream.close() # Converting",
"'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation':",
"to the next video in the library.\"\"\" # If the video is not",
"SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none'",
"__PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values',",
"pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration +",
"elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb':",
"io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close()",
"200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch',",
"def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng in the menu.\"\"\" properties =",
"= video_preview_path + timestamp # Start recording a high res (.h264) and low",
"== 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting ==",
"If the queue is already empty, set it to none. except Queue.Empty: audio_message_queue",
"for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode ==",
"Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally",
"the videos folder.\"\"\" # Setup the preview path as the path for the",
"recording_state = video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording",
"in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def",
"SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif",
"+ '.mpeg' wav_filepath = video_path + timestamp + '.wav' process_filepath = mjpeg_filepath +",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0,",
"title values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25,",
"== 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting ==",
"pygame = SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application == 'video': # Check",
"button that starts recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode",
"button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo()",
"is not bool: property_value = 'Auto' # Makes 'zoom' human readable. if property_type",
"-60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60,",
"property_value == 0 and property_type is not bool: property_value = 'Auto' # Makes",
"# Start recording a high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath +",
"SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40,",
"wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables to stop recording",
"button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3,",
"0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6,",
"for button presses, messages, and which mode we're in. Events.CheckEvents() if SystemState.screen_mode in",
"SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True,",
"= len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a video in the directory,",
"if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10,",
"'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"stream data into a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE)",
"10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hundred_container = [-100,",
"first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name,",
"library.\"\"\" # If the video is not at the end of the list,",
"go back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename =",
"starts recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1:",
"'_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu item.\"\"\"",
"0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0",
"30, 40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values =",
"position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of the",
"SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try:",
"0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4),",
"elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif",
"1 # If the video is at the end of the list, send",
"video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath = video_path +",
"the previous video in the library.\"\"\" # If the video more than the",
"SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night',",
"SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' ) xa = (320",
") def __PlayVideo(): \"\"\"Plays the video file (preview) on the camera's screen.\"\"\" #",
"not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10),",
"inside of the videos folder.\"\"\" # Setup the preview path as the path",
"False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a",
"i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing",
"1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video =",
"high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function",
"= getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index > 0: index -=",
"3: setting = SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow():",
"+ mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing",
"the video is not at the end of the list, go to the",
"stream.read(CHUNK) frames.append(data) # Try placing the information inside the audio message queue. try:",
"SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting",
"= 0600|stat.S_IRUSR time.sleep(1) # Converting video files to make preview files. os.mknod(process_filepath, mode)",
"a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp):",
"button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count > 0:",
"directory, set it as current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in",
"Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso",
"is something inside the queue, read it. if audio_message_queue != None: if audio_message_queue.get('recording')",
"= 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness =",
"= ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu",
") / 2 ya = (240 - SystemState.VideoState.img.get_height()) / 2 Screen.RefreshScreen(image=SystemState.VideoState.img, wx=xa, wy=ya)",
"SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif",
"If the video is not at the end of the list, go to",
"= hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9),",
"thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in",
"System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False)",
"splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)],",
"FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path +",
"> 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for each menu item.\"\"\"",
"button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode =",
"SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue =",
"False audio_action = {'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp):",
"pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: # Remove 'PREVIEW-'",
"into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0:",
"0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1),",
"to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally",
"the information inside the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If",
"for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path,",
"= True else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue",
"in a streaming mode. If so, throw frames at the screen. if SystemState.VideoState.video_stream",
"= video_preview_path + timestamp + '.mpeg' wav_filepath = video_path + timestamp + '.wav'",
"SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting",
".02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video in the library.\"\"\" #",
"the library.\"\"\" # If the video more than the first one, then move",
"elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept':",
"# Remove 'PREVIEW-' and path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp",
"[-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20,",
"__DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() # Displaying settings title",
"engine import Menu from engine import Screen from engine import TextWriter from engine",
"'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness')",
"back to the first one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally",
"SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]",
"time import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def",
"(0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4,",
"0600|stat.S_IRUSR time.sleep(1) # Converting video files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a",
"= os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time and position of the",
"the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the",
"== 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20",
"values are printed on screen. if property_value == 0 and property_type is not",
"go ahead and play the video we're on. if SystemState.VideoState.video_count > 0: pygame",
"SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif",
"import io import stat import os import signal import picamera import time import",
"__NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values',",
"timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath = video_path",
"4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds",
"if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif",
"def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting",
"the next video in the library.\"\"\" # If the video is not at",
"elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif",
"[ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur',",
"CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav'",
"the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index <",
"+ full_video[1] full_video = full_video.split('.') full_video = full_video[0] + '.h264' # Attempting to",
"sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a video in",
"__PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if",
"the library.\"\"\" # If the video is not at the end of the",
"[] # If there's a video in the directory, set it as current",
"preview_video = SystemState.VideoState.current_video # Setting up files to be deleted. full_video = preview_video.split('/.preview')",
"70, 80, 90, 100] hundred_container = [-100, -90, -80, -70, -60, -50, -40,",
"import stat import os import signal import picamera import time import sys import",
"the camera's screen.\"\"\" # If there's more than one video, go ahead and",
"None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0",
"str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the",
"SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists",
"+ '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait",
"thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192 FORMAT",
"SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values =",
"SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If the video is",
"\" -target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an ' + mpeg_filepath",
"stream.stop_stream() stream.close() # Converting stream data into a wave file. wavefile = wave.open(FILENAME,",
"False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec',",
"high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080))",
"file was not removed from library. print \"Couldn't remove from library\" try: os.remove(full_video)",
"= 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode =",
"def __StopRecordingAudio(): \"\"\"Setting up all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio =",
"on screen. if property_value == 0 and property_type is not bool: property_value =",
"SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting",
"__PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState,",
"= 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness =",
"RPi.GPIO.RISING) # Stop recording the high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2)",
"preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video = full_video.split('.') full_video = full_video[0] +",
"= 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button",
"SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera",
"each menu item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso':",
"(0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35,",
"== 2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values = setting +",
"that preview couldn't be removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except:",
"couldn't be removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO:",
"False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue",
"SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration",
"= (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables",
"Queue.Empty: video_message_queue = None # Checking video message queue for record messages. if",
"'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif button ==",
"files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for videos.",
"def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\" args = (timestamp) thread",
"centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\"",
"play the video we're on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes",
"'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness')",
"elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom':",
"= [] # If there's a video in the directory, set it as",
"'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button",
"= video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg'",
"path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing",
"True elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio",
"refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?',",
"in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index",
"\"\"\"Setting up all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action",
"try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking video message",
"use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 *",
"if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values =",
"TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if we",
"str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up",
"SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' ) xa",
"'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20,",
"__WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110),",
"== 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"and path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) #",
"and Previous. \"\"\" property_value = properties[index] # Setting values in SystemState.camera from SystemState.VideoState.",
"None: recording_state = video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp)",
"= SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left",
"SystemState.VideoState.img.get_width() ) / 2 ya = (240 - SystemState.VideoState.img.get_height()) / 2 Screen.RefreshScreen(image=SystemState.VideoState.img, wx=xa,",
"SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0),",
"the video file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen # Setting up movie",
"Clearing the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up",
"we're on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen",
"\"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files to be deleted.",
"== 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"centered=True, size=25, permatext=True, color=(57, 255, 20) ) def Process(): \"\"\"Processing button presses.\"\"\" button",
"in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def",
"one, then go back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1",
"> 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path)",
"'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return",
"__PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values',",
"'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1',",
"each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255,",
"\"\"\"Moves to the next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index",
"import RPi.GPIO import pyaudio import wave import atexit import io import stat import",
"'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables",
"= SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video",
"# Executing the ffmpeg command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath)",
"for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57,",
"SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting",
"# Clearing the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting",
"= VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation =",
"= 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue()",
"[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hundred_container =",
"== 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo()",
"button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif",
"'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0,",
"== 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting ==",
"to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action =",
"'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization')",
"a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which pygame",
"10), size=12 ) def __PlayVideo(): \"\"\"Plays the video file (preview) on the camera's",
"== 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"as the path for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path)",
"SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom",
"so, throw frames at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO()",
"= 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline':",
"= str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if button",
"hundred_container = [-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0,",
"== 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"\"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo,",
"SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path",
"SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif",
"'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode':",
"= False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking",
"# Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img",
"80, 90, 100] hundred_container = [-100, -90, -80, -70, -60, -50, -40, -30,",
"__NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values',",
"'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy',",
"OpenAlbum() # Displaying settings title and values when you first enter a menu.",
"= hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0, 1.0), (0.1,",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path",
"video_preview_path + timestamp # Start recording a high res (.h264) and low res",
"the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream",
"400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss',",
"values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True,",
"none. except Queue.Empty: audio_message_queue = None #If there is something inside the queue,",
"to mpeg which pygame can play.\"\"\" # Setting up local varables. video_path =",
"preview path as the path for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive",
"'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ]",
"def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files to",
"throw frames at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() #",
"Start recording a high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264',",
"'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach',",
"100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize',",
"- 1: SystemState.VideoState.video_index += 1 # If the video is at the end",
"4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for",
"'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap',",
"mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files to make",
"property_type is not bool: property_value = 'Auto' # Makes 'zoom' human readable. if",
"SystemState.VideoState.setting = 'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif",
"if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1",
"True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb')",
"refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode'",
"if audio_message_queue.get('recording') == False: break # Stopping and closing stream. stream.stop_stream() stream.close() #",
"= Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values = [0,",
"when you first enter a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode ==",
"settings title and values when you first enter a menu. if SystemState.screen_mode ==",
"size=12 ) def __PlayVideo(): \"\"\"Plays the video file (preview) on the camera's screen.\"\"\"",
"RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing the information inside the audio",
"\"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True,",
"mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video -an '",
"Converting video files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i",
"and property_type is not bool: property_value = 'Auto' # Makes 'zoom' human readable.",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"screen for Next and Previous. \"\"\" property_value = properties[index] # Setting values in",
"SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif",
"0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3,",
"RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup",
"if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif",
"'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow',",
"in the library.\"\"\" # If the video more than the first one, then",
"Lists of camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500, 640,",
"index = getattr(SystemState.VideoState, property_name) if index > 0: index -= 1 else: index",
"True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check",
"full_video = full_video[0] + '.h264' # Attempting to delete the files above. try:",
"# If the queue is already empty, set it to none. except Queue.Empty:",
"the ffmpeg command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum():",
"import signal import picamera import time import sys import threading import Queue signal.signal(signal.SIGINT,",
"-an ' + mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b",
"'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count",
"60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values =",
"full_video[1] full_video = full_video.split('.') full_video = full_video[0] + '.h264' # Attempting to delete",
"print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file",
"= [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hundred_container",
"+ '.wav' RECORD_SECONDS = 10800 frames = [] # Clearing the queue messages",
"'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto',",
"'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() #",
"the queue, read it. if audio_message_queue != None: if audio_message_queue.get('recording') == False: break",
"'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"+ '.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath = video_path +",
"next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 # If",
"Setting up paths for videos. h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path",
"'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() # Displaying settings",
"os.remove(preview_video) except: # TODO:print that preview couldn't be removed. print \"Couldn't remove preview",
"__WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(),",
"= threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a",
"None # Checking video message queue for record messages. if video_message_queue != None:",
"elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode':",
"-i ' + mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b = ' -vcodec",
"= (320, 240) while SystemState.application == 'video': # Check for button presses, messages,",
"= [0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50,",
"def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them on screen for Next",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath + \" -target",
"= SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration",
"timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording",
"and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg',",
"preview couldn't be removed. print \"Couldn't remove preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: #",
"__CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which pygame can play.\"\"\"",
"if index > 0: index -= 1 else: index = len(properties) - 1",
"stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 *",
"SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the red button is",
"videos folder.\"\"\" # Setup the preview path as the path for the video",
"SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was not removed from library. print",
"'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [",
"the last one, then go back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count",
"ffmpeg command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens",
"'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name):",
"= len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def __NextSetting(property_list, property_name): \"\"\"Moves to the",
"frames at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture",
"'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4:",
"= getattr(SystemState.VideoState, property_name) if index > 0: index -= 1 else: index =",
"property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures default 'auto' values",
"20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write( state=SystemState,",
"RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0),",
"videos, just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True,",
"__CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\" args = (timestamp) thread =",
"\"\"\"Calls the __RecordVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo,",
"end of the list, send it back to the first one. else: SystemState.VideoState.video_index",
"'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values",
"on screen for Next and Previous. \"\"\" property_value = properties[index] # Setting values",
"elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum()",
"SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath = video_path + timestamp mjpeg_filepath",
"mode. If so, throw frames at the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream",
"pygame = SystemState.pygame screen = SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie",
"== 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting ==",
"library.\"\"\" # If the video more than the first one, then move backwards",
"Call threading function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg",
"= SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' ) xa =",
"'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise',",
"= SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if",
"= int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800 frames",
"if index == 0: index = None property_value = str(index) # Removing underscores",
"Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally =",
"== 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting ==",
"== 'zoom': __NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting ==",
"'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode':",
"def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen =",
"item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20) )",
"video files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i '",
"#Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' #",
"of camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500, 640, 800]",
"elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode':",
"which pygame can play.\"\"\" # Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path",
"pyaudio import wave import atexit import io import stat import os import signal",
"the time and position of the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp,",
"SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder",
"properties[index] # Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name,",
"SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting",
"'none' elif button == 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif",
"= False TextWriter.ClearPermatext() # Checking the gpio button that starts recording. if SystemState.VideoState.video_recording",
"a high res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920,",
"'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values =",
"the end of the list, go to the next one. if SystemState.VideoState.video_index <",
"are printed on screen. if property_value == 0 and property_type is not bool:",
"\"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode",
"SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index =",
"Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo() elif button == 'settings':",
"= None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream =",
"refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness'",
"def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path)",
"SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness",
"elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast') elif",
"\"\"\"Convert's second mpjpeg video to mpeg which pygame can play.\"\"\" # Setting up",
"90, 100] hundred_container = [-100, -90, -80, -70, -60, -50, -40, -30, -20,",
"False TextWriter.ClearPermatext() # Checking the gpio button that starts recording. if SystemState.VideoState.video_recording ==",
"it as current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index",
") def __ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\" pygame = SystemState.pygame",
"'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def",
"SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state",
"thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args = (timestamp)",
"full_video = full_video[0] + full_video[1] full_video = full_video.split('.') full_video = full_video[0] + '.h264'",
"int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800 frames =",
"Menu.Back() OpenAlbum() # Displaying settings title and values when you first enter a",
"the gpio button that starts recording. if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8)",
"Utilities.GracefulExit) class VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO",
"for videos. h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path + timestamp #",
"removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside",
"+ timestamp mjpeg_filepath = video_preview_path + timestamp # Start recording a high res",
"SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup SystemState.VideoState.current_video =",
"__ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them on",
"'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates",
"= 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button",
"SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif",
"queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for",
"TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20) ) def",
"SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the",
"deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video = full_video.split('.') full_video",
"== 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete':",
"resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the red",
"'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button ==",
"SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting",
"= video_path + timestamp mjpeg_filepath = video_preview_path + timestamp # Start recording a",
"Previous. \"\"\" property_value = properties[index] # Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera,",
"= pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration",
"0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5),",
"video_message_queue = None # Checking video message queue for record messages. if video_message_queue",
"# If the video is not at the end of the list, go",
"SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240),",
"'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode')",
"a wave file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK)",
"time.ctime(int(utime_string)) # Writing the time and position of the photo on the screen.",
"1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7),",
"files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' +",
"0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif button == 'right_arrow':",
"#If there is something inside the queue, read it. if audio_message_queue != None:",
"function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start()",
"the high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading",
"elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness':",
"the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def",
"property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them",
"'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values",
"h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path + timestamp # Start recording",
"streaming mode. If so, throw frames at the screen. if SystemState.VideoState.video_stream == True:",
"if SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True})",
"= getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties,",
"'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue",
"\"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True,",
"'.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values",
"else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index +",
"audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty, set it to",
"Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play':",
"is already empty, set it to none. except Queue.Empty: audio_message_queue = None #If",
"set it as current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive:",
"[ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight',",
"try: os.remove(preview_video) except: # TODO:print that preview couldn't be removed. print \"Couldn't remove",
"the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic)",
"10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0",
"text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if we are",
"as current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index =",
"in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing the",
"40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container",
"import time import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass",
"def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo function in a thread.\"\"\" args = (timestamp) thread",
"index -= 1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index) def",
"property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures default 'auto' values are",
"SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState,",
"on screen when you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index",
"SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting",
"RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect =",
"__NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values',",
"1: index += 1 else: index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list,",
"If the video is the last one, then go back to the beginning.",
"Videos', position=(110, 100), centred=True, size=20, permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of",
"SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode",
"'zoom' human readable. if property_type is tuple: if index == 0: index =",
"else: SystemState.VideoState.video_stream = False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None",
"1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just write",
"# If there's more than one video, go ahead and play the video",
"RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState = VideoState",
"10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if we are in a",
"'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast')",
"and position of the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10),",
"SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths for videos. h264_filepath = video_path",
"video_path + timestamp + '.wav' process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR",
"__CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext()",
"str(SystemState.pressed_button) pygame = SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if button ==",
"'.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files to make preview files.",
"if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif",
"len(properties) - 1: index += 1 else: index = 0 __ProcessSettingsValues(property_name, properties, index)",
"to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings",
"'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270] SystemState.VideoState.brightness_values =",
"Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None",
"red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res and",
"'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization':",
"= 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast =",
"-80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40,",
"__NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values',",
"in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video =",
"== 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting ==",
"def OpenAlbum(): \"\"\"Opens the contents inside of the videos folder.\"\"\" # Setup the",
"'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180, 270]",
"0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [",
"to the previous video in the library.\"\"\" # If the video more than",
"import Menu from engine import Screen from engine import TextWriter from engine import",
"= 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS",
"- 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just",
"type(property_value) # Ensures default 'auto' values are printed on screen. if property_value ==",
"'/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video in the",
"message queue for record messages. if video_message_queue != None: recording_state = video_message_queue.get('recording') if",
"__ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting =",
"library. print \"Couldn't remove from library\" try: os.remove(full_video) except: # TODO: print that",
"= type(property_value) # Ensures default 'auto' values are printed on screen. if property_value",
"OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button ==",
"= 'Auto' # Makes 'zoom' human readable. if property_type is tuple: if index",
"= SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no",
"None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0",
"True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/'",
"# If there's a video in the directory, set it as current video.",
"'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation')",
"video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files to be deleted. full_video =",
"SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for each menu",
"elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness':",
"the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1 #",
"properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index > 0: index",
"signal import picamera import time import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit)",
"SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation",
"== 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"and play the video we're on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame",
"__PlayVideo(): \"\"\"Plays the video file (preview) on the camera's screen.\"\"\" # If there's",
"SystemState.VideoState.current_video in SystemState.VideoState.video_archive: SystemState.VideoState.video_index = SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video",
"(0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5, 0.5), (0.325,",
"elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif",
"all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording':",
"a streaming mode. If so, throw frames at the screen. if SystemState.VideoState.video_stream ==",
"elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif",
"__PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for each menu item.\"\"\" if SystemState.VideoState.setting",
"SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty, set it to none. except",
"wav_filepath = video_path + timestamp + '.wav' process_filepath = mjpeg_filepath + '.process' mode",
"0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375,",
"import SystemState from engine import Utilities from engine import Menu from engine import",
"SystemState.application == 'video': # Check for button presses, messages, and which mode we're",
"# Checking the gpio button that starts recording. if SystemState.VideoState.video_recording == False: if",
"args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192",
"{'recording': False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\"",
"== True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state ==",
"= True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path =",
"state=SystemState, size=20 ) # Check if we are in a streaming mode. If",
"'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness':",
"+ '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue = Queue.Queue() # Lists of camera effects",
"closing stream. stream.stop_stream() stream.close() # Converting stream data into a wave file. wavefile",
"'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness':",
"wave file. for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data)",
"the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording the high res",
"elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation':",
"__PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values',",
"function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to",
"video is not at the end of the list, go to the next",
"permatext=True ) def __ShowVideo(filename): \"\"\"Shows a picture of the video file.\"\"\" pygame =",
"Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if",
"video message queue for record messages. if video_message_queue != None: recording_state = video_message_queue.get('recording')",
"(.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240))",
"1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video",
"print \"Image not removed\" def Main(): \"\"\"Main loop for the camera application.\"\"\" pygame",
"'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten',",
"os.remove(full_video) except: # TODO: print that image not removed. print \"Image not removed\"",
"' -threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the ffmpeg command",
"(0.0, 0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25,",
"= str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to",
"== 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3)",
"data = stream.read(CHUNK) frames.append(data) # Try placing the information inside the audio message",
"the queue is already empty, set it to none. except Queue.Empty: audio_message_queue =",
"RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800",
"= 0 # Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None",
"SystemState.VideoState.setting == 'image_effect': __PreviousSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting",
"' -vcodec mpeg1video -an ' + mpeg_filepath + ' -threads 0' ffmpeg_convert =",
"# Stop recording the high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3)",
"for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) #",
"__PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values',",
"[False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting",
"# Converting video files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg",
"SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode",
"+= 1 # If the video is at the end of the list,",
"= (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the __ConvertVideo",
"SystemState.VideoState.setting = 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif",
"__MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in the",
"inside the queue, read it. if audio_message_queue != None: if audio_message_queue.get('recording') == False:",
"# Try placing the information inside the audio message queue. try: audio_message_queue =",
"screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo(): \"\"\"Plays the video",
"can play.\"\"\" # Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path",
"SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting",
"index == 0: index = None property_value = str(index) # Removing underscores and",
"just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20,",
"VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0",
"320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise',",
"file.\"\"\" pygame = SystemState.pygame screen = SystemState.screen # Setting up movie for pygame",
"80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values",
"20, 30, 40, 50, 60, 70, 80, 90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values",
"[0, 100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values = [ 'none', 'negative',",
"== 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of the videos folder.\"\"\" # Setup",
"if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75), size=20 ) elif",
"__DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting up files to be",
"os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of the videos folder.\"\"\" #",
"pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp +",
"'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight',",
"SystemState.VideoState.video_archive.index(SystemState.VideoState.current_video) else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If",
"try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was not removed from library.",
"'auto', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values =",
"90, 100] SystemState.VideoState.saturation_values = hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values =",
"__NextSetting(property_list, property_name): \"\"\"Moves to the next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState,",
"getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index > 0: index -= 1",
"TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20) ) def",
"mode we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True",
"== False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the gpio button that starts",
"count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic",
"text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes",
"def __PreviousVideo(): \"\"\"Moves to the previous video in the library.\"\"\" # If the",
"the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is",
"__CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu item.\"\"\" if",
"to the next settng in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index =",
"SystemState.VideoState.video_index -= 1 # If the video is the last one, then go",
"bool: property_value = 'Auto' # Makes 'zoom' human readable. if property_type is tuple:",
"= pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME = SystemState.VideoState.video_path + timestamp",
"title and values when you first enter a menu. if SystemState.screen_mode == 2",
"stream.close() # Converting stream data into a wave file. wavefile = wave.open(FILENAME, 'wb')",
"recording the high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call",
"delete the files above. try: os.remove(preview_video) except: # TODO:print that preview couldn't be",
"__CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() #",
"def __PlayVideo(): \"\"\"Plays the video file (preview) on the camera's screen.\"\"\" # If",
"False} video_action = {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path",
"ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the ffmpeg command and removing the",
"screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes settings values for",
"SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization",
"+= 1 else: index = 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's",
"menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 10), centered=True, size=25, permatext=True, color=(57, 255, 20)",
"SystemState.VideoState.video_archive = os.listdir(path) SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive =",
"[0, 90, 180, 270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50, 60,",
"-40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80,",
"the first one, then move backwards through the list. if SystemState.VideoState.video_index > 0:",
"(.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath +",
"'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4:",
"screen when you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index =",
"item.\"\"\" if SystemState.VideoState.setting == 'image_effect': __NextSetting('image_effect_values', 'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso')",
"elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif",
"refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation'",
"> 0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16)",
"elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation') elif",
"__StopRecordingAudio(): \"\"\"Setting up all the variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False",
"default 'auto' values are printed on screen. if property_value == 0 and property_type",
"Main(): \"\"\"Main loop for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320,",
"SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS,",
"\"\"\"Calls the _RecordAudio function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio,",
"in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If",
"just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time",
"video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg which pygame can",
"= 'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button",
"import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7,",
"# If the video is the last one, then go back to the",
"thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\"",
"something inside the queue, read it. if audio_message_queue != None: if audio_message_queue.get('recording') ==",
"previous video in the library.\"\"\" # If the video more than the first",
"if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input for each",
"(0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average',",
"args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the",
"io import stat import os import signal import picamera import time import sys",
"= SystemState.screen screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button",
"+ .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to the next video in the library.\"\"\"",
"' + mjpeg_filepath + \" -target ntsc-vcd \" ffmpeg_b = ' -vcodec mpeg1video",
"getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints",
"'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button ==",
"placing the information inside the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) #",
"backwards through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If",
"elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect': Menu.JumpTo(screen_mode=3,",
"40, 50, 60, 70, 80, 90, 100] hundred_container = [-100, -90, -80, -70,",
"0.6), (0.3, 0.3, 0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3),",
"audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording",
"SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation",
"the video is the last one, then go back to the beginning. else:",
"* RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) # Try placing the information inside the",
"values to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text): \"\"\"Writes",
"0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the ffmpeg command and removing",
"0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1,",
"= 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME =",
"wave import atexit import io import stat import os import signal import picamera",
"'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo() def",
"import pyaudio import wave import atexit import io import stat import os import",
"mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files to make preview files. os.mknod(process_filepath,",
"# Stopping and closing stream. stream.stop_stream() stream.close() # Converting stream data into a",
"sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): #",
"pygame = SystemState.pygame screen = SystemState.screen screen_mode = SystemState.screen_mode if button == 'library':",
"threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\"",
"240), 'RGB' ) xa = (320 - SystemState.VideoState.img.get_width() ) / 2 ya =",
"if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button == 'go_back': Menu.Back() SystemState.VideoState.setting =",
"= (320 - SystemState.VideoState.img.get_width() ) / 2 ya = (240 - SystemState.VideoState.img.get_height()) /",
"movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02)",
"def __WriteSettingsValue(text): \"\"\"Writes settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160,",
"# Ensures default 'auto' values are printed on screen. if property_value == 0",
"from engine import SystemState from engine import Utilities from engine import Menu from",
"= Queue.Queue() # Lists of camera effects SystemState.VideoState.iso_values = [0, 100, 200, 320,",
"20, 30, 40, 50, 60, 70, 80, 90, 100] hundred_container = [-100, -90,",
") xa = (320 - SystemState.VideoState.img.get_width() ) / 2 ya = (240 -",
"# Setting up paths for videos. h264_filepath = video_path + timestamp mjpeg_filepath =",
"None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True",
"0.3), (0.375, 0.375, 0.2, 0.2), (0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [",
"'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode')",
"= str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a",
"(0.4, 0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ]",
"SystemState.VideoState.setting == 'exposure_mode': __NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0:",
"for Next and Previous. \"\"\" property_value = properties[index] # Setting values in SystemState.camera",
"elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count >",
"+ str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video in the library.\"\"\"",
"messages. if video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state == True: timestamp",
"xa = (320 - SystemState.VideoState.img.get_width() ) / 2 ya = (240 - SystemState.VideoState.img.get_height())",
"try: os.remove(full_video) except: # TODO: print that image not removed. print \"Image not",
"items on screen when you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list)",
"# Call threading function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second",
"'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"SystemState.VideoState.setting = 'exposure_mode' elif button == 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button ==",
"= ' -vcodec mpeg1video -an ' + mpeg_filepath + ' -threads 0' ffmpeg_convert",
"0.4, 0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values",
"more than one video, go ahead and play the video we're on. if",
"effects SystemState.VideoState.iso_values = [0, 100, 200, 320, 400, 500, 640, 800] SystemState.VideoState.image_effect_values =",
"'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness':",
"__PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button == 'delete': if SystemState.VideoState.video_count",
"SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3: #",
"not removed\" def Main(): \"\"\"Main loop for the camera application.\"\"\" pygame = SystemState.pygame",
"SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/'",
"elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values', 'video_stabilization') elif",
"== 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20",
"second mpjpeg video to mpeg which pygame can play.\"\"\" # Setting up local",
"previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name)",
"= SystemState.VideoState.current_video # Setting up files to be deleted. full_video = preview_video.split('/.preview') full_video",
"0 # Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive",
"__ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just write \"no videos\". else: TextWriter.Write(",
"up files to be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1]",
"engine import Utilities from engine import Menu from engine import Screen from engine",
"SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting",
"not removed. print \"Image not removed\" def Main(): \"\"\"Main loop for the camera",
"from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures",
"through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If the",
"from engine import Utilities from engine import Menu from engine import Screen from",
"'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing",
"\"\"\"Moves to the previous setting in the menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index",
"to be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video =",
"resize=(320, 240)) # Wait until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) #",
"ffmpeg_b # Executing the ffmpeg command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath)",
"button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3,",
"# Check for button presses, messages, and which mode we're in. Events.CheckEvents() if",
"from library\" try: os.remove(full_video) except: # TODO: print that image not removed. print",
"SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp):",
"holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls",
"0.0, 1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25,",
"Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting =",
"== False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in",
"position of the photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12",
"properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you first enter",
"video to mpeg which pygame can play.\"\"\" # Setting up local varables. video_path",
"the end of the list, send it back to the first one. else:",
"__MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path,",
"pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo():",
"(timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function",
"= str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording = True elif recording_state == False: SystemState.VideoState.video_recording =",
"back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index]",
"0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10",
"except: # TODO:print that preview couldn't be removed. print \"Couldn't remove preview image\"",
"== 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting ==",
"SystemState.VideoState.video_archive = [os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count =",
"frames_per_buffer=CHUNK ) # Recording data to a wave file. for i in range(0,",
"you first enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name)",
"\"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100), centred=True, size=20, permatext=True )",
"button == 'play': __PlayVideo() elif button == 'settings': Menu.JumpTo(screen_mode=2, refresh_screen=False) elif button ==",
"SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in the menu.\"\"\" properties",
"+ timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath =",
"+ timestamp + '.wav' RECORD_SECONDS = 10800 frames = [] # Clearing the",
"= sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a video",
"# Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive =",
"= pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum()",
"printed on screen. if property_value == 0 and property_type is not bool: property_value",
"we are in a streaming mode. If so, throw frames at the screen.",
"first enter a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting",
"the video we're on. if SystemState.VideoState.video_count > 0: pygame = SystemState.pygame modes =",
"the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If the video",
"\"\"\"Fetches values and prints them on screen for Next and Previous. \"\"\" property_value",
"for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE =",
"'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values', 'contrast')",
"__NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __NextSetting('video_stabilization_values',",
"-90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30,",
"information inside the audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the",
"def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in the menu.\"\"\" properties =",
"TODO: print that image not removed. print \"Image not removed\" def Main(): \"\"\"Main",
"0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3, 0.5,",
"SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete",
"size=20, permatext=True, color=(57, 255, 20) ) def __WriteSettingsTitle(text): \"\"\"Writes title values for each",
"'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button ==",
"0.1, 0.1), ] SystemState.VideoState.meter_mode_values = [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values =",
"'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout', 'posterise', 'colorpoint', 'colorbalance',",
"\"Image not removed\" def Main(): \"\"\"Main loop for the camera application.\"\"\" pygame =",
"size=20 ) elif button == 'right_arrow': __ProcessRightArrow() elif button == 'left_arrow': __ProcessLeftArrow() elif",
"thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192 FORMAT =",
"0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count)",
"'/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video #",
"'image_effect') elif SystemState.VideoState.setting == 'iso': __NextSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __NextSetting('rotation_values', 'rotation')",
"= mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1) # Converting video files to",
"class VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8,",
"mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath = video_path + timestamp +",
"if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 # If the video is the",
"= [] # Clearing the queue messages just in case. with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear()",
"pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive != None and SystemState.screen_mode == 3:",
"refresh_screen=False) SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode'",
"CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate']) FILENAME",
"and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents",
"'video': # Check for button presses, messages, and which mode we're in. Events.CheckEvents()",
"video in the directory, set it as current video. if SystemState.VideoState.video_count > 0:",
"Converting stream data into a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT))",
"splitter_port=3, resize=(320, 240)) # Wait until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING)",
"True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves to the previous setting in",
"'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization')",
"0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3, 0.3,",
"video_preview_path + timestamp + '.mpeg' wav_filepath = video_path + timestamp + '.wav' process_filepath",
"SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path = SystemState.VideoState.video_path + '.preview/' SystemState.VideoState.audio_message_queue = Queue.Queue() SystemState.VideoState.video_message_queue =",
"wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio(): \"\"\"Setting up all the variables to stop",
"that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False: os.makedirs(SystemState.VideoState.video_preview_path) os.chown(SystemState.VideoState.video_preview_path, SystemState.uid, SystemState.gid) def __CallRecordAudio(timestamp):",
"= 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state = 'pause' SystemState.VideoState.video_path = 'media/video/' SystemState.VideoState.video_preview_path =",
") # Check if we are in a streaming mode. If so, throw",
"# TODO: print that file was not removed from library. print \"Couldn't remove",
"stat import os import signal import picamera import time import sys import threading",
"properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name,",
"0.5, 0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2,",
"move backwards through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1 #",
"'.h264' # Attempting to delete the files above. try: os.remove(preview_video) except: # TODO:print",
"= getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index < len(properties) - 1:",
"picamera import time import sys import threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object):",
"audio message queue. try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is already",
"TextWriter.ClearPermatext() # Checking the gpio button that starts recording. if SystemState.VideoState.video_recording == False:",
"elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right",
"= 0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup SystemState.VideoState.current_video = None",
"photo on the screen. TextWriter.Write( state=SystemState, text=timestamp, position=(90, 10), size=12 ) def __PlayVideo():",
"'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False,",
"values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20, permatext=True,",
"property_type is tuple: if index == 0: index = None property_value = str(index)",
"!= None: if audio_message_queue.get('recording') == False: break # Stopping and closing stream. stream.stop_stream()",
"pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable Setup SystemState.VideoState",
"wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def __StopRecordingAudio():",
"'.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath = video_path + timestamp",
"= preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video = full_video.split('.') full_video = full_video[0]",
"a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames)) wavefile.close() def",
"elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values', 'meter_mode') elif",
"a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp):",
"Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None SystemState.VideoState.video_tally = None",
"Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream =",
"Checking the gpio button that starts recording. if SystemState.VideoState.video_recording == False: if not",
"# Wait until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop recording",
"and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path leaving just unix time.",
"Screen from engine import TextWriter from engine import Events import RPi.GPIO import pyaudio",
"at the end of the list, go to the next one. if SystemState.VideoState.video_index",
"camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = int(SystemState.pyaudio.get_device_info_by_index(0)['defaultSampleRate'])",
"+ str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video # Setting",
"== 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button == 'video_stabilization': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"# Setup the preview path as the path for the video count. path",
"# Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath =",
"'Auto' # Makes 'zoom' human readable. if property_type is tuple: if index ==",
"= 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording = False SystemState.VideoState.playback_state =",
"thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting",
"res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320,",
"SystemState.screen # Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive",
"thread.setDaemon(True) thread.start() def __CallRecordVideo(timestamp): \"\"\"Calls the __RecordVideo function in a thread.\"\"\" args =",
"channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to a wave file.",
"# If the video is at the end of the list, send it",
"'off' ] SystemState.VideoState.video_stabilization_values = [False, True] __MakeVideoPath() return SystemState def __PreviousSetting(property_list, property_name): \"\"\"Moves",
"if audio_message_queue != None: if audio_message_queue.get('recording') == False: break # Stopping and closing",
"'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode')",
"SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting",
"1.0, 1.0), (0.1, 0.1, 0.9, 0.9), (0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7,",
"last one, then go back to the beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count -",
"for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos = []",
"SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) #",
"0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup SystemState.VideoState.current_video",
"20) ) def Process(): \"\"\"Processing button presses.\"\"\" button = str(SystemState.pressed_button) pygame = SystemState.pygame",
"the contents inside of the videos folder.\"\"\" # Setup the preview path as",
"RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none' # Iterating Variable",
"(320 - SystemState.VideoState.img.get_width() ) / 2 ya = (240 - SystemState.VideoState.img.get_height()) / 2",
"Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso =",
"0.5), (0.325, 0.325, 0.4, 0.4), (0.35, 0.25, 0.3, 0.3), (0.375, 0.375, 0.2, 0.2),",
"'left_arrow': __ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button ==",
"'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button ==",
"data into a wave file. wavefile = wave.open(FILENAME, 'wb') wavefile.setnchannels(CHANNELS) wavefile.setsampwidth(SystemState.pyaudio.get_sample_size(FORMAT)) wavefile.setframerate(RATE) wavefile.writeframes(b''.join(frames))",
"command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the",
"except Queue.Empty: audio_message_queue = None #If there is something inside the queue, read",
"property_value = properties[index] # Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value)",
"= SystemState.pygame SystemState.camera.resolution = (320, 240) while SystemState.application == 'video': # Check for",
"index) def __NextSetting(property_list, property_name): \"\"\"Moves to the next settng in the menu.\"\"\" properties",
"\"\"\"Moves to the next video in the library.\"\"\" # If the video is",
"menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3: setting = SystemState.VideoState.setting setting_values",
"SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE,",
"'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation', 'colorswap', 'washedout',",
"_RecordAudio function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True)",
"-threads 0' ffmpeg_convert = ffmpeg_a + ffmpeg_b # Executing the ffmpeg command and",
"# Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect = 0",
"rate=RATE, input=True, output=True, frames_per_buffer=CHUNK ) # Recording data to a wave file. for",
"the directory, set it as current video. if SystemState.VideoState.video_count > 0: if SystemState.VideoState.current_video",
"first one. else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index +",
"button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125, 75),",
"processing_videos = [] # If there's a video in the directory, set it",
"import wave import atexit import io import stat import os import signal import",
"Stopping and closing stream. stream.stop_stream() stream.close() # Converting stream data into a wave",
"splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the",
"then move backwards through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -= 1",
"1080)) SystemState.camera.start_recording(mjpeg_filepath + '.mjpeg', splitter_port=3, resize=(320, 240)) # Wait until the red button",
"10 SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0",
"== 3: # Remove 'PREVIEW-' and path leaving just unix time. utime_string =",
"index < len(properties) - 1: index += 1 else: index = 0 __ProcessSettingsValues(property_name,",
"False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path =",
"getattr(SystemState.VideoState, property_name) if index > 0: index -= 1 else: index = len(properties)",
"'colorpoint', 'colorbalance', 'cartoon', 'deinterlace1', 'deinterlace2' ] SystemState.VideoState.awb_mode_values = [ 'auto', 'sunlight', 'cloudy', 'shade',",
"SystemState.VideoState.video_recording == False: if not RPi.GPIO.input(8) and SystemState.screen_mode == 1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6)",
"800] SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel',",
"__ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video in the library.\"\"\" # If",
"the screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory",
"enter a menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties,",
"SystemState.VideoState.current_video # Setting up files to be deleted. full_video = preview_video.split('/.preview') full_video =",
"# Setting up movie for pygame SystemState.VideoState.movie = pygame.movie.Movie(filename) SystemState.VideoState.movie.render_frame(1) if SystemState.VideoState.video_archive !=",
"__ProcessLeftArrow() elif button == 'iso': Menu.JumpTo(screen_mode=3) SystemState.VideoState.setting = 'iso' elif button == 'image_effect':",
"= SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just write \"no videos\".",
"in (1, 2, 3): SystemState.VideoState.video_stream = True else: SystemState.VideoState.video_stream = False try: video_message_queue",
"__NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\" if os.path.exists(SystemState.VideoState.video_preview_path) == False:",
"no videos, just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110, 100),",
"SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo():",
"time.sleep(1) # Converting video files to make preview files. os.mknod(process_filepath, mode) ffmpeg_a =",
"__PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values',",
"= None SystemState.VideoState.video_count = 0 SystemState.VideoState.video_stream = True SystemState.VideoState.video_duration = 0 SystemState.VideoState.video_recording =",
"VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN,",
"SystemState.VideoState.setting = 'video_stabilization' elif button == 'exposure_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'exposure_mode' elif",
"[os.path.join(path, pic) for pic in SystemState.VideoState.video_archive] SystemState.VideoState.video_archive = sorted(SystemState.VideoState.video_archive) SystemState.VideoState.video_count = len(SystemState.VideoState.video_archive) processing_videos",
"SystemState from engine import Utilities from engine import Menu from engine import Screen",
"from engine import Events import RPi.GPIO import pyaudio import wave import atexit import",
"refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode'",
"preview image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was not removed",
"= 'brightness' elif button == 'saturation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'saturation' elif button",
"button == 'decline': Menu.Back() OpenAlbum() # Displaying settings title and values when you",
"pygame can play.\"\"\" # Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path =",
"'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting",
"we're in. Events.CheckEvents() if SystemState.screen_mode in (1, 2, 3): SystemState.VideoState.video_stream = True else:",
"video, go ahead and play the video we're on. if SystemState.VideoState.video_count > 0:",
"!= None: recording_state = video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp)",
"screen. if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream",
"__NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values',",
"menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index > 0:",
"'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values =",
"0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when you",
"__NextSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values',",
"property_value = 'Auto' # Makes 'zoom' human readable. if property_type is tuple: if",
"to make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath",
"Attempting to delete the files above. try: os.remove(preview_video) except: # TODO:print that preview",
"\"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS =",
"None and SystemState.screen_mode == 3: # Remove 'PREVIEW-' and path leaving just unix",
"SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def __NextVideo(): \"\"\"Moves to",
"Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO",
"== 'accept': __DeleteVideo() Menu.Back() OpenAlbum() elif button == 'decline': Menu.Back() OpenAlbum() # Displaying",
"240)) # Wait until the red button is released. RPi.GPIO.wait_for_edge(8, RPi.GPIO.RISING) # Stop",
"SystemState.VideoState.video_preview_path mjpeg_filepath = video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp",
"os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath + \" -target ntsc-vcd",
"make preview files. os.mknod(process_filepath, mode) ffmpeg_a = 'ffmpeg -i ' + mjpeg_filepath +",
"hundred_container SystemState.VideoState.contrast_values = hundred_container SystemState.VideoState.sharpness_values = hundred_container SystemState.VideoState.zoom_values = [ (0.0, 0.0, 1.0,",
"0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast = 10",
"len(SystemState.VideoState.video_archive) processing_videos = [] # If there's a video in the directory, set",
"'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks', 'off' ] SystemState.VideoState.video_stabilization_values = [False, True]",
"'meter_mode' elif button == 'awb': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'awb_mode' elif button ==",
"elif SystemState.VideoState.setting == 'iso': __PreviousSetting('iso_values', 'iso') elif SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif",
"= ffmpeg_a + ffmpeg_b # Executing the ffmpeg command and removing the process",
"utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp = time.ctime(int(utime_string)) # Writing the time and position of",
"__RecordAudio(timestamp): \"\"\"Setting up variables for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS",
"SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration =",
"Executing the ffmpeg command and removing the process files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def",
"SystemState.VideoState.setting == 'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting",
"getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def __ProcessSettingsValues(property_name, properties, index):",
"= getattr(SystemState.VideoState, property_name) if index < len(properties) - 1: index += 1 else:",
"the __RecordVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,))",
"__PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast': __PreviousSetting('contrast_values',",
"== 'sharpness': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False)",
"= {'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path",
"SystemState.VideoState.setting == 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting",
"'none' SystemState.VideoState.image_effect = 0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5",
"= True elif recording_state == False: SystemState.VideoState.video_recording = False TextWriter.ClearPermatext() # Checking the",
"and prints them on screen for Next and Previous. \"\"\" property_value = properties[index]",
"- 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' +",
"# Removing underscores and writing values to the screen. property_name = ' '.join(property_name.split('_'))",
"try: audio_message_queue = SystemState.VideoState.audio_message_queue.get(False) # If the queue is already empty, set it",
"up variables for camera.\"\"\" CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1",
"property_value = str(index) # Removing underscores and writing values to the screen. property_name",
"1: SystemState.VideoState.video_message_queue.put({'recording': True}) Menu.JumpTo(screen_mode=6) TextWriter.Write( text='Rec', position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 )",
"] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong',",
"position=(10, 10), color=(255,0,0), permatext=True, state=SystemState, size=20 ) # Check if we are in",
"RPi.GPIO import pyaudio import wave import atexit import io import stat import os",
"'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom' elif button ==",
"SystemState.VideoState.image_effect_values = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint', 'hatch','gpen', 'pastel', 'watercolor',",
"to convert a video. __CallConvertVideo(timestamp) def __ConvertVideo(timestamp): \"\"\"Convert's second mpjpeg video to mpeg",
"play.\"\"\" # Setting up local varables. video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path mjpeg_filepath",
"SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow",
"+ timestamp + '.wav' process_filepath = mjpeg_filepath + '.process' mode = 0600|stat.S_IRUSR time.sleep(1)",
"= 0 __ProcessSettingsValues(property_name, properties, index) def __CurrentSetting(property_list, property_name): \"\"\"Display's items on screen when",
"setattr(SystemState.VideoState, property_name, index) property_type = type(property_value) # Ensures default 'auto' values are printed",
"it. if audio_message_queue != None: if audio_message_queue.get('recording') == False: break # Stopping and",
"are no videos, just write \"no videos\". else: TextWriter.Write( state=SystemState, text='No Videos', position=(110,",
"of the list, send it back to the first one. else: SystemState.VideoState.video_index =",
"Remove 'PREVIEW-' and path leaving just unix time. utime_string = os.path.basename(filename).split('-')[-1].split('.')[0] timestamp =",
"Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): # System Setup RPi.GPIO.setup(7, RPi.GPIO.OUT)",
"SystemState.gid) def __CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\" args = (timestamp)",
"'brightness': __NextSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __NextSetting('saturation_values', 'saturation') elif SystemState.VideoState.setting == 'contrast':",
"SystemState.screen screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif button ==",
"elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a",
"path as the path for the video count. path = SystemState.VideoState.video_preview_path SystemState.VideoState.video_archive =",
"0: pygame = SystemState.pygame modes = pygame.display.list_modes(16) movie_screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen)",
"function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,)) thread.setDaemon(True) thread.start()",
"str(SystemState.VideoState.video_count) __ShowVideo(filename) def __PreviousVideo(): \"\"\"Moves to the previous video in the library.\"\"\" #",
"menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) if index < len(properties)",
"+ '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo(): \"\"\"Delete a video.\"\"\" preview_video = SystemState.VideoState.current_video",
"next video in the library.\"\"\" # If the video is not at the",
"0 SystemState.VideoState.video_stabilization = 0 # Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename",
"Setting up files to be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] +",
"properties, index): \"\"\"Fetches values and prints them on screen for Next and Previous.",
"# Displaying settings title and values when you first enter a menu. if",
"\"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path = SystemState.VideoState.video_preview_path # Setting up paths",
"the _RecordAudio function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__RecordAudio, args=(timestamp,))",
"full_video[0] + '.h264' # Attempting to delete the files above. try: os.remove(preview_video) except:",
"a video in the directory, set it as current video. if SystemState.VideoState.video_count >",
"= SystemState.VideoState.video_path + timestamp + '.wav' RECORD_SECONDS = 10800 frames = [] #",
"image\" try: SystemState.VideoState.video_archive.remove(preview_video) except: # TODO: print that file was not removed from",
"__CallRecordAudio(timestamp): \"\"\"Calls the _RecordAudio function in a thread.\"\"\" args = (timestamp) thread =",
") # Recording data to a wave file. for i in range(0, int(RATE/CHUNK",
"Setup the preview path as the path for the video count. path =",
"variables to stop recording audio.\"\"\" SystemState.VideoState.recording_audio = False audio_action = {'recording': False} video_action",
"pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) SystemState.VideoState.movie.set_display(movie_screen) SystemState.VideoState.movie.play() SystemState.VideoState.movie_duration = SystemState.VideoState.movie.get_length() time.sleep(SystemState.VideoState.movie_duration + .02) OpenAlbum() def",
"__NextSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __NextSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __NextSetting('zoom_values',",
"(0.225, 0.225, 0.8, 0.8), (0.25, 0.25, 0.7, 0.7), (0.275, 0.275, 0.6, 0.6), (0.3,",
"== 'go_back': Menu.Back() SystemState.VideoState.setting = 'none' elif button == 'play': __PlayVideo() elif button",
"__PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode': __PreviousSetting('meter_mode_values',",
"SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just write \"no videos\". else:",
"= properties[index] # Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState,",
"= 'none' # Iterating Variable Setup SystemState.VideoState = VideoState SystemState.VideoState.setting = 'none' SystemState.VideoState.image_effect",
"= 'zoom' elif button == 'meter_mode': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'meter_mode' elif button",
"setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input",
"queue, read it. if audio_message_queue != None: if audio_message_queue.get('recording') == False: break #",
"res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to",
"0 SystemState.VideoState.awb_mode = 0 SystemState.VideoState.exposure_mode = 0 SystemState.VideoState.video_stabilization = 0 # Video Associated",
"video_preview_path + timestamp + '.mjpeg' mpeg_filepath = video_preview_path + timestamp + '.mpeg' wav_filepath",
"if video_message_queue != None: recording_state = video_message_queue.get('recording') if recording_state == True: timestamp =",
"if SystemState.VideoState.video_stream == True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream,",
"Video Associated Variable Setup SystemState.VideoState.current_video = None SystemState.VideoState.video_filename = None SystemState.VideoState.video_archive = None",
"'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90, 180,",
"SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) + '/' + str(SystemState.VideoState.video_count) __ShowVideo(filename) def __DeleteVideo():",
"library\" try: os.remove(full_video) except: # TODO: print that image not removed. print \"Image",
"'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting == 'exposure_mode': __PreviousSetting('exposure_mode_values', 'exposure_mode')",
"-30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90,",
"else: SystemState.VideoState.video_index = 0 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index + 1) +",
"SystemState.VideoState.contrast = 10 SystemState.VideoState.sharpness = 10 SystemState.VideoState.zoom = 0 SystemState.VideoState.meter_mode = 0 SystemState.VideoState.awb_mode",
") def __WriteSettingsTitle(text): \"\"\"Writes title values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(),",
"'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values', 'saturation')",
"are in a streaming mode. If so, throw frames at the screen. if",
"= [ 'average', 'spot', 'backlit', 'matrix' ] SystemState.VideoState.exposure_mode_values = [ 'auto', 'night', 'nightpreview',",
"\"\"\"Main loop for the camera application.\"\"\" pygame = SystemState.pygame SystemState.camera.resolution = (320, 240)",
"elif button == 'image_effect': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'image_effect' elif button == 'rotation':",
"Stop recording the high res and low res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) #",
"== 'rotation': __PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting ==",
"the __ConvertVideo function in a thread.\"\"\" args = (timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,))",
"if property_type is tuple: if index == 0: index = None property_value =",
"args = (timestamp) thread = threading.Thread(target=__RecordVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __CallConvertVideo(timestamp): \"\"\"Calls the",
"# Setting up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True,",
"video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a video. __CallConvertVideo(timestamp)",
"in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320",
"+ timestamp + '.mpeg' wav_filepath = video_path + timestamp + '.wav' process_filepath =",
"RPi.GPIO.OUT) #Flash RPi.GPIO RPi.GPIO.setup(8, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) #Button RPi.GPIO RPi.GPIO.output(7, False) SystemState.camera.image_effect = 'none'",
"100] hundred_container = [-100, -90, -80, -70, -60, -50, -40, -30, -20, -10,",
"import Screen from engine import TextWriter from engine import Events import RPi.GPIO import",
"= video_message_queue.get('recording') if recording_state == True: timestamp = str(int(time.time())) __CallRecordAudio(timestamp) __CallRecordVideo(timestamp) SystemState.VideoState.video_recording =",
"up paths for videos. h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path +",
"{'recording': False} SystemState.VideoState.video_message_queue.put(video_action) SystemState.VideoState.audio_message_queue.put(audio_action) def __RecordVideo(timestamp): \"\"\"Records video files.\"\"\" video_path = SystemState.VideoState.video_path video_preview_path",
"index > 0: index -= 1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name,",
"import Events import RPi.GPIO import pyaudio import wave import atexit import io import",
"beginning. else: SystemState.VideoState.video_index = SystemState.VideoState.video_count - 1 filename = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] SystemState.VideoState.video_tally = str(SystemState.VideoState.video_index",
"'cloudy', 'shade', 'tungsten', 'fluorescent', 'incandescent', 'flash', 'horizon', 'off' ] SystemState.VideoState.rotation_values = [0, 90,",
"one, then move backwards through the list. if SystemState.VideoState.video_index > 0: SystemState.VideoState.video_index -=",
"0 SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10",
"False try: video_message_queue = SystemState.VideoState.video_message_queue.get(None) except Queue.Empty: video_message_queue = None # Checking video",
"= None # Checking video message queue for record messages. if video_message_queue !=",
"refresh_screen=False) SystemState.VideoState.setting = 'sharpness' elif button == 'zoom': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'zoom'",
"SystemState.VideoState.setting setting_values = setting + '_values' __CurrentSetting(setting_values, setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow",
"Setting values in SystemState.camera from SystemState.VideoState. setattr(SystemState.camera, property_name, property_value) setattr(SystemState.VideoState, property_name, index) property_type",
"__NextSetting('exposure_mode_values', 'exposure_mode') elif SystemState.screen_mode == 4: if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath():",
"'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom': __PreviousSetting('zoom_values', 'zoom') elif SystemState.VideoState.setting == 'meter_mode':",
"format='rgb') SystemState.VideoState.stream.seek(0) SystemState.VideoState.stream.readinto(SystemState.rgb) SystemState.VideoState.stream.close() SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320,",
"screen = SystemState.screen screen_mode = SystemState.screen_mode if button == 'library': OpenAlbum() Menu.JumpTo(screen_mode=4) elif",
"button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button == 'sharpness': Menu.JumpTo(screen_mode=3,",
"index) def __ProcessSettingsValues(property_name, properties, index): \"\"\"Fetches values and prints them on screen for",
"= 'image_effect' elif button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button",
"= full_video[0] + '.h264' # Attempting to delete the files above. try: os.remove(preview_video)",
"__PreviousSetting('rotation_values', 'rotation') elif SystemState.VideoState.setting == 'brightness': __PreviousSetting('brightness_values', 'brightness') elif SystemState.VideoState.setting == 'saturation': __PreviousSetting('saturation_values',",
"to the next one. if SystemState.VideoState.video_index < SystemState.VideoState.video_count - 1: SystemState.VideoState.video_index += 1",
"files to be deleted. full_video = preview_video.split('/.preview') full_video = full_video[0] + full_video[1] full_video",
"if SystemState.VideoState.video_count > 0: __NextVideo() def __MakeVideoPath(): \"\"\"Creates a folder that holds videos.\"\"\"",
"settings values for each menu item.\"\"\" TextWriter.Write( state=SystemState, text=str(text).title(), position=(160, 110), centered=True, size=20,",
"of the videos folder.\"\"\" # Setup the preview path as the path for",
"you first enter a menu. if SystemState.screen_mode == 2 and SystemState.next_screen_mode == 3:",
"== True: SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0,",
"SystemState.VideoState.iso = 0 SystemState.VideoState.rotation = 0 SystemState.VideoState.brightness = 5 SystemState.VideoState.saturation = 10 SystemState.VideoState.contrast",
"'contrast': __PreviousSetting('contrast_values', 'contrast') elif SystemState.VideoState.setting == 'sharpness': __PreviousSetting('sharpness_values', 'sharpness') elif SystemState.VideoState.setting == 'zoom':",
"res (.h264) and low res (.mjpeg). SystemState.camera.start_recording(h264_filepath + '.h264', splitter_port=2, resize=(1920, 1080)) SystemState.camera.start_recording(mjpeg_filepath",
"270] SystemState.VideoState.brightness_values = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90,",
"== 'awb_mode': __PreviousSetting('awb_mode_values', 'awb_mode') elif SystemState.VideoState.setting == 'video_stabilization': __PreviousSetting('video_stabilization_values', 'video_stabilization') elif SystemState.VideoState.setting ==",
"threading import Queue signal.signal(signal.SIGINT, Utilities.GracefulExit) class VideoState(object): pass def Init(): # System Setup",
"res video_archive. __StopRecordingAudio() SystemState.camera.stop_recording(splitter_port=2) SystemState.camera.stop_recording(splitter_port=3) # Call threading function to convert a video.",
"0: index -= 1 else: index = len(properties) - 1 __ProcessSettingsValues(property_name, properties, index)",
"(timestamp) thread = threading.Thread(target=__ConvertVideo, args=(timestamp,)) thread.setDaemon(True) thread.start() def __RecordAudio(timestamp): \"\"\"Setting up variables for",
"with SystemState.VideoState.audio_message_queue.mutex: SystemState.VideoState.audio_message_queue.queue.clear() # Setting up stream for audio. stream = SystemState.pyaudio.open( format=FORMAT,",
"menu.\"\"\" properties = getattr(SystemState.VideoState, property_list) index = getattr(SystemState.VideoState, property_name) __ProcessSettingsValues(property_name, properties, index) def",
"there is something inside the queue, read it. if audio_message_queue != None: if",
"button == 'rotation': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'rotation' elif button == 'brightness': Menu.JumpTo(screen_mode=3,",
"== False: break # Stopping and closing stream. stream.stop_stream() stream.close() # Converting stream",
"'saturation' elif button == 'contrast': Menu.JumpTo(screen_mode=3, refresh_screen=False) SystemState.VideoState.setting = 'contrast' elif button ==",
"break # Stopping and closing stream. stream.stop_stream() stream.close() # Converting stream data into",
"setting) def __ProcessLeftArrow(): \"\"\"Processing left arrow input for each menu item.\"\"\" if SystemState.VideoState.setting",
"-vcodec mpeg1video -an ' + mpeg_filepath + ' -threads 0' ffmpeg_convert = ffmpeg_a",
"writing values to the screen. property_name = ' '.join(property_name.split('_')) __WriteSettingsTitle(property_name) __WriteSettingsValue(property_value) def __WriteSettingsValue(text):",
"files. os.system(ffmpeg_convert) os.remove(mjpeg_filepath) os.remove(process_filepath) def OpenAlbum(): \"\"\"Opens the contents inside of the videos",
"elif button == 'delete': if SystemState.VideoState.video_count > 0: Menu.JumpTo(screen_mode=5) TextWriter.Write( state=SystemState, text='Delete?', position=(125,",
"it to none. except Queue.Empty: audio_message_queue = None #If there is something inside",
"[ 'auto', 'night', 'nightpreview', 'backlight', 'spotlight', 'sports', 'snow', 'beach', 'verylong', 'fixedfps', 'antishake', 'fireworks',",
"videos. h264_filepath = video_path + timestamp mjpeg_filepath = video_preview_path + timestamp # Start",
"== 4: if SystemState.VideoState.video_count > 0: __PreviousVideo() def __ProcessRightArrow(): \"\"\"Processing right arrow input",
"from engine import Menu from engine import Screen from engine import TextWriter from",
"is not at the end of the list, go to the next one.",
"SystemState.VideoState.current_video = SystemState.VideoState.video_archive[SystemState.VideoState.video_index] __ShowVideo(SystemState.VideoState.current_video) # If there are no videos, just write \"no",
"elif SystemState.VideoState.setting == 'meter_mode': __NextSetting('meter_mode_values', 'meter_mode') elif SystemState.VideoState.setting == 'awb_mode': __NextSetting('awb_mode_values', 'awb_mode') elif"
] |
[
"Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in",
"UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [ \"CheckConstraint\",",
"# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import",
"License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from",
"-------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint",
"information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key",
"CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint",
"-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the",
"import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import",
"rights reserved. # Licensed under the MIT License. See License.txt in the project",
"import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [",
"PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [ \"CheckConstraint\", \"UniqueConstraint\", \"PrimaryKeyConstraint\", \"ForeignKeyConstraint\" ]",
"license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from",
"# Licensed under the MIT License. See License.txt in the project root for",
"mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ =",
"mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [ \"CheckConstraint\", \"UniqueConstraint\", \"PrimaryKeyConstraint\",",
"project root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique",
"in the project root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint",
"MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------",
"the project root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from",
"from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from",
"root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import",
"mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key",
"under the MIT License. See License.txt in the project root for license information.",
"reserved. # Licensed under the MIT License. See License.txt in the project root",
"See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check",
"for license information. # -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.",
"Licensed under the MIT License. See License.txt in the project root for license",
"All rights reserved. # Licensed under the MIT License. See License.txt in the",
"from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [ \"CheckConstraint\", \"UniqueConstraint\",",
"from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"import PrimaryKeyConstraint from mysqlsmo.objects.table_constraints.foreign_key import ForeignKeyConstraint __all__ = [ \"CheckConstraint\", \"UniqueConstraint\", \"PrimaryKeyConstraint\", \"ForeignKeyConstraint\"",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt",
"# -------------------------------------------------------------------------------------------- from mysqlsmo.objects.table_constraints.check import CheckConstraint from mysqlsmo.objects.table_constraints.unique import UniqueConstraint from mysqlsmo.objects.table_constraints.primary_key import",
"the MIT License. See License.txt in the project root for license information. #"
] |
[
"'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir,",
"width, channels = ( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key =",
"def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir",
"in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def",
"BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder",
"= [np.squeeze(image).transpose((1, 2, 0)) for image in images] labels = data[b'labels'] return [(images[i],",
"3 num_train_files = 5 class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',",
"os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py')",
"i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints",
"import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim",
"return [(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel",
"= 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir)",
"from __future__ import print_function import os import hashlib import shutil import sys from",
"from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as",
"import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils",
"-*- from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with",
"output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def",
"image_channel = 3 num_train_files = 5 class_names = [ 'airplane', 'automobile', 'bird', 'cat',",
"cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files = 5 class_names = [",
"= self._coder.encode_png(image) image_format = 'png' height, width, channels = ( self.image_size, self.image_size, self.image_channel",
"import hashlib import shutil import sys from six.moves import cPickle import numpy as",
"super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder()",
"val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names =",
"'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file()",
"'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self,",
"extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir )",
"range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename)",
"import tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset",
"tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from",
"width, channels, key, encoded, image_format, class_name, label) def load(self, split_name, reader=None): # TODO(tmattio):",
"key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format, class_name, label) def",
"data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1,",
"images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image in images]",
"= [] for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i",
"self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError:",
"for i in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files",
"_get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info < (3,): data = cPickle.load(f)",
"% (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints",
"public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir",
"import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath,",
"self._coder.encode_png(image) image_format = 'png' height, width, channels = ( self.image_size, self.image_size, self.image_channel )",
"import numpy as np import tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz",
"'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name =",
"import division from __future__ import print_function import os import hashlib import shutil import",
"in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files = 5",
"def _get_data_points(self): train_datapoints = [] for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py',",
"data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images =",
"'png' height, width, channels = ( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label]",
"in images] labels = data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)] class",
"shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point encoded = self._coder.encode_png(image) image_format =",
"self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key,",
"+= _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints",
"= self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format, class_name,",
"return create_image_example(height, width, channels, key, encoded, image_format, class_name, label) def load(self, split_name, reader=None):",
"create_image_example(height, width, channels, key, encoded, image_format, class_name, label) def load(self, split_name, reader=None): #",
"import print_function import os import hashlib import shutil import sys from six.moves import",
"dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder =",
"= cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3,",
"= ( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return",
"utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import",
"images = [np.squeeze(image).transpose((1, 2, 0)) for image in images] labels = data[b'labels'] return",
"= data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images =",
"[ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url",
"self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels,",
"= ['train', 'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split,",
"six.moves import cPickle import numpy as np import tensorflow as tf from tf_datasets.core.download",
"-*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from",
"sys.version_info < (3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images =",
"download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path):",
"height, width, channels = ( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key",
"else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images =",
"np import tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import",
"tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from",
"np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names = ['train', 'validation'] for split,",
"as np import tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset",
"'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url =",
"_get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names = ['train', 'validation']",
"if sys.version_info < (3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images",
"(3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images",
"= 'png' height, width, channels = ( self.image_size, self.image_size, self.image_channel ) class_name =",
"'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True)",
"__future__ import print_function import os import hashlib import shutil import sys from six.moves",
"data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images,",
"encoded, image_format, class_name, label) def load(self, split_name, reader=None): # TODO(tmattio): Implement the load",
"from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath):",
"tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim =",
"cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images",
"create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb')",
"32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image in images] labels =",
"labels = data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size",
"'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except",
"create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def",
"= os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self):",
"_get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def",
"slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info <",
"for image in images] labels = data[b'labels'] return [(images[i], labels[i]) for i in",
"data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size = 32",
"num_train_files = 5 class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog',",
"os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path)",
"] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10'",
"0)) for image in images] labels = data[b'labels'] return [(images[i], labels[i]) for i",
"'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if",
"FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self):",
"'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints =",
"cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point encoded = self._coder.encode_png(image) image_format",
"= images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image in",
"os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = [] for i in range(self.num_train_files):",
"'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = [] for i in range(self.num_train_files): filename",
"'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir):",
"'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path =",
"5 class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship',",
"'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py',",
"'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points()",
"in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints +=",
"self._get_data_points() split_names = ['train', 'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir,",
"import cPickle import numpy as np import tensorflow as tf from tf_datasets.core.download import",
"'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'",
"self.download_dir ) def _get_data_points(self): train_datapoints = [] for i in range(self.num_train_files): filename =",
"labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel = 3",
"self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point encoded",
"label = data_point encoded = self._coder.encode_png(image) image_format = 'png' height, width, channels =",
"'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def",
"zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self):",
"os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz(",
"def _convert_to_example(self, data_point): image, label = data_point encoded = self._coder.encode_png(image) image_format = 'png'",
"extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = [] for i in",
"channels = ( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest()",
"= images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0))",
"for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1))",
"download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir,",
"['train', 'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example)",
"os import hashlib import shutil import sys from six.moves import cPickle import numpy",
"image_size = 32 image_channel = 3 num_train_files = 5 class_names = [ 'airplane',",
"= ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz')",
"key, encoded, image_format, class_name, label) def load(self, split_name, reader=None): # TODO(tmattio): Implement the",
"tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils",
"_get_data_points(self): train_datapoints = [] for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d'",
"'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names,",
"(i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints =",
"split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self):",
"__future__ import division from __future__ import print_function import os import hashlib import shutil",
"for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def",
"= os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits",
"= 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir =",
"num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2,",
"image_format = 'png' height, width, channels = ( self.image_size, self.image_size, self.image_channel ) class_name",
"import os import hashlib import shutil import sys from six.moves import cPickle import",
"= [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ]",
"from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import ImageCoder slim",
"range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files = 5 class_names",
"'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names",
"class_name, label) def load(self, split_name, reader=None): # TODO(tmattio): Implement the load methods pass",
"train_datapoints = [] for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' %",
"print_function import os import hashlib import shutil import sys from six.moves import cPickle",
"= hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format, class_name, label) def load(self,",
"= cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0]",
"[(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel =",
"output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path =",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import os",
"def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download')",
"create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image,",
"from __future__ import division from __future__ import print_function import os import hashlib import",
"class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format,",
"data_point): image, label = data_point encoded = self._coder.encode_png(image) image_format = 'png' height, width,",
"pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path",
"_convert_to_example(self, data_point): image, label = data_point encoded = self._coder.encode_png(image) image_format = 'png' height,",
"sys from six.moves import cPickle import numpy as np import tensorflow as tf",
"division from __future__ import print_function import os import hashlib import shutil import sys",
"data_point encoded = self._coder.encode_png(image) image_format = 'png' height, width, channels = ( self.image_size,",
"images = images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image",
"<reponame>tmattio/tf_datasets # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import",
"os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path",
"splits = self._get_data_points() split_names = ['train', 'validation'] for split, split_name in zip(splits, split_names):",
"[] for i in range(self.num_train_files): filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i +",
"self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def",
"as f: if sys.version_info < (3,): data = cPickle.load(f) else: data = cPickle.load(f,",
"output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'),",
"from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from",
"image_format, class_name, label) def load(self, split_name, reader=None): # TODO(tmattio): Implement the load methods",
"= self._get_data_points() split_names = ['train', 'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10',",
"1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return",
"not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = [] for",
") class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded,",
"convert(self): splits = self._get_data_points() split_names = ['train', 'validation'] for split, split_name in zip(splits,",
"with open(filepath, 'rb') as f: if sys.version_info < (3,): data = cPickle.load(f) else:",
"hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format, class_name, label) def load(self, split_name,",
"import shutil import sys from six.moves import cPickle import numpy as np import",
"test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self):",
"from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example",
"encoding='bytes') images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32))",
"= 32 image_channel = 3 num_train_files = 5 class_names = [ 'airplane', 'automobile',",
"images] labels = data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset):",
"except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def",
"= os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass",
"class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck',",
"split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point",
"os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits =",
"import absolute_import from __future__ import division from __future__ import print_function import os import",
"( self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height,",
"i in range(num_images)] class cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files =",
"'dog', 'frog', 'horse', 'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir,",
"def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info < (3,): data =",
"self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label",
"< (3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data']",
"os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints",
"not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not os.path.exists(output_path):",
"return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names = ['train', 'validation'] for",
"# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division",
"'ship', 'truck', ] public_url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' def __init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name",
"ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info",
"= os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename =",
"__init__(self, dataset_dir): super().__init__(dataset_dir, self.class_names, zero_based_labels=True) self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder",
"zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self,",
"hashlib import shutil import sys from six.moves import cPickle import numpy as np",
"= data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)] class cifar10(BaseDataset): image_size =",
"images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images",
"= 3 num_train_files = 5 class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer',",
"coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__",
"def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not",
"if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir, 'cifar-10-batches-py') if not",
"f: if sys.version_info < (3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes')",
"def convert(self): splits = self._get_data_points() split_names = ['train', 'validation'] for split, split_name in",
"= tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info < (3,):",
"if not os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = []",
"os.path.exists(output_path): extract_tgz( os.path.join(self.download_dir, 'cifar-10-python.tar.gz'), self.download_dir ) def _get_data_points(self): train_datapoints = [] for i",
"self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width, channels, key, encoded, image_format, class_name, label)",
"image in images] labels = data[b'labels'] return [(images[i], labels[i]) for i in range(num_images)]",
"split_names = ['train', 'validation'] for split, split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name,",
"import sys from six.moves import cPickle import numpy as np import tensorflow as",
"train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints),",
"32 image_channel = 3 num_train_files = 5 class_names = [ 'airplane', 'automobile', 'bird',",
"extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split",
"'rb') as f: if sys.version_info < (3,): data = cPickle.load(f) else: data =",
"from six.moves import cPickle import numpy as np import tensorflow as tf from",
"split_name in zip(splits, split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir)",
"32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image in images] labels = data[b'labels']",
"open(filepath, 'rb') as f: if sys.version_info < (3,): data = cPickle.load(f) else: data",
"self.dataset_name = 'cifar10' self.download_dir = os.path.join(self.dataset_dir, 'download') self._coder = ImageCoder() def download(self): try:",
"os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir,",
"split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label =",
"def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point encoded = self._coder.encode_png(image)",
"tf_datasets.core.dataset_utils import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f:",
"class cifar10(BaseDataset): image_size = 32 image_channel = 3 num_train_files = 5 class_names =",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point): image, label = data_point encoded =",
"as tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils",
"encoded = self._coder.encode_png(image) image_format = 'png' height, width, channels = ( self.image_size, self.image_size,",
"try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url,",
"3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for image in images] labels",
"self.image_size, self.image_size, self.image_channel ) class_name = self.labels_to_class_names[label] key = hashlib.sha256(encoded).hexdigest() return create_image_example(height, width,",
"'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch')",
"channels, key, encoded, image_format, class_name, label) def load(self, split_name, reader=None): # TODO(tmattio): Implement",
"= 5 class_names = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',",
"numpy as np import tensorflow as tf from tf_datasets.core.download import download_http, extract_tgz from",
"val_datapoints def convert(self): splits = self._get_data_points() split_names = ['train', 'validation'] for split, split_name",
"[np.squeeze(image).transpose((1, 2, 0)) for image in images] labels = data[b'labels'] return [(images[i], labels[i])",
"download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import",
"= os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if not os.path.exists(output_path): download_http(self.public_url, output_path) def extract(self): output_path = os.path.join(self.download_dir,",
"+ 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'test_batch') val_datapoints = _get_data_points_from_cifar_file(test_filename)",
"import BaseDataset from tf_datasets.core.dataset_utils import create_image_example from tf_datasets.core.dataset_utils import create_dataset_split from tf_datasets.core.dataset_utils import",
"image, label = data_point encoded = self._coder.encode_png(image) image_format = 'png' height, width, channels",
"images.shape[0] images = images.reshape((num_images, 3, 32, 32)) images = [np.squeeze(image).transpose((1, 2, 0)) for",
"shutil import sys from six.moves import cPickle import numpy as np import tensorflow",
"= _get_data_points_from_cifar_file(test_filename) return np.stack(train_datapoints), val_datapoints def convert(self): splits = self._get_data_points() split_names = ['train',",
"cPickle import numpy as np import tensorflow as tf from tf_datasets.core.download import download_http,",
"2, 0)) for image in images] labels = data[b'labels'] return [(images[i], labels[i]) for",
"import ImageCoder slim = tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if",
"self._coder = ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir,",
"tf.contrib.slim def _get_data_points_from_cifar_file(filepath): with open(filepath, 'rb') as f: if sys.version_info < (3,): data",
"ImageCoder() def download(self): try: os.makedirs(self.download_dir) except FileExistsError: pass output_path = os.path.join(self.download_dir, 'cifar-10-python.tar.gz') if",
"filename = os.path.join(self.download_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) train_datapoints += _get_data_points_from_cifar_file(filename) test_filename",
"cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32,",
"= data_point encoded = self._coder.encode_png(image) image_format = 'png' height, width, channels = (",
"absolute_import from __future__ import division from __future__ import print_function import os import hashlib",
"split_names): create_dataset_split('cifar10', self.dataset_dir, split_name, split, self._convert_to_example) self.write_label_file() def cleanup(self): shutil.rmtree(self.download_dir) def _convert_to_example(self, data_point):",
"tf from tf_datasets.core.download import download_http, extract_tgz from tf_datasets.core.base_dataset import BaseDataset from tf_datasets.core.dataset_utils import",
") def _get_data_points(self): train_datapoints = [] for i in range(self.num_train_files): filename = os.path.join(self.download_dir,"
] |
[
"after nok9\" group = 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description =",
"devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150,",
"sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150, 150), speed =",
"'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits =",
"description = \"sc2 height after nok9\" group = 'lowlevel' devices = dict( sc2",
"= 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits",
"device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150, 150), speed = 1., unit",
"abslimits = (-150, 150), speed = 1., unit = 'mm', # refpos =",
"= (-150, 150), speed = 1., unit = 'mm', # refpos = -7.2946,",
"nok9\" group = 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2",
"dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150, 150), speed",
"= \"sc2 height after nok9\" group = 'lowlevel' devices = dict( sc2 =",
"150), speed = 1., unit = 'mm', # refpos = -7.2946, ), )",
"'sc2 Motor', abslimits = (-150, 150), speed = 1., unit = 'mm', #",
"(-150, 150), speed = 1., unit = 'mm', # refpos = -7.2946, ),",
"description = 'sc2 Motor', abslimits = (-150, 150), speed = 1., unit =",
"group = 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor',",
"= 'sc2 Motor', abslimits = (-150, 150), speed = 1., unit = 'mm',",
"= dict( sc2 = device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150, 150),",
"= device('nicos.devices.generic.VirtualMotor', description = 'sc2 Motor', abslimits = (-150, 150), speed = 1.,",
"height after nok9\" group = 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor', description",
"\"sc2 height after nok9\" group = 'lowlevel' devices = dict( sc2 = device('nicos.devices.generic.VirtualMotor',",
"Motor', abslimits = (-150, 150), speed = 1., unit = 'mm', # refpos"
] |
[] |
[
"model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True,",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department',",
"model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True,",
"3.1.5 on 2021-05-23 08:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'),",
"migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True,",
"to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField(",
"= [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity',",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ),",
"2021-05-23 08:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate',",
"name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'),",
"verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion',",
"model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True,",
"('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True,",
"# Generated by Django 3.1.5 on 2021-05-23 08:10 from django.db import migrations, models",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField(",
"model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='senator_mandate', to='communities.department', verbose_name='Département'), ), ]",
"on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ),",
"'0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'),",
"<filename>officials/migrations/0003_auto_20210523_0810.py # Generated by Django 3.1.5 on 2021-05-23 08:10 from django.db import migrations,",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations =",
"by Django 3.1.5 on 2021-05-23 08:10 from django.db import migrations, models import django.db.models.deletion",
"), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city',",
"[ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True,",
"model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True,",
"on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'),",
"migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True,",
"to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField(",
"name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'),",
"Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField(",
"migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True,",
"model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ),",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city',",
"to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField(",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'),",
"on 2021-05-23 08:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True,",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ]",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities',",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom',",
"verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment',",
"[ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom',",
"= [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department',",
"verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom',",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials',",
"verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom',",
"migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True,",
"'0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom',",
"to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department',",
"on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='senator_mandate', to='communities.department', verbose_name='Département'),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'),",
"operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField(",
"to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate',",
"verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department',",
"to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField(",
"migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True,",
"), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department',",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom',",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='senator_mandate', to='communities.department',",
"migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True,",
"on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField(",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations",
"name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ),",
"to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField(",
"class Migration(migrations.Migration): dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [",
"migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True,",
"verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity',",
"), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True,",
"model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True,",
"field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department',",
"), migrations.AlterField( model_name='mandateintercom', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region',",
"name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AddField( model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"Django 3.1.5 on 2021-05-23 08:10 from django.db import migrations, models import django.db.models.deletion class",
"on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ),",
"dependencies = [ ('communities', '0002_auto_20210523_0725'), ('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity',",
"name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='senator_mandate',",
"name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'), ), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ),",
"Generated by Django 3.1.5 on 2021-05-23 08:10 from django.db import migrations, models import",
"model_name='mandateintercom', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True,",
"), migrations.AlterField( model_name='mandateregion', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.region'), ), migrations.AlterField( model_name='mpmandate', name='department', field=models.ForeignKey(blank=True,",
"on_delete=django.db.models.deletion.CASCADE, to='communities.department'), ), migrations.AlterField( model_name='senatormandate', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='senator_mandate', to='communities.department', verbose_name='Département'), ),",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AddField( model_name='mandatecity', name='intercom', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.intercom', verbose_name='Intercommunalité'),",
"), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department',",
"name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.city', verbose_name='Commune'), ), migrations.AlterField( model_name='mandatedepartment', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"08:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"('officials', '0002_auto_20210522_1139'), ] operations = [ migrations.AddField( model_name='mandatecity', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department',",
"name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='communities.department', verbose_name='Département'), ), migrations.AlterField( model_name='mandatecity', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,"
] |
[
"from reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self):",
"self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster",
"import Data from reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver = driver",
"dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster = Select(self.driver.find_element_by_name(\"myCluster\"))",
"GetData class click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p = GetData()",
"test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block",
"class click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20)",
"GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2)",
"def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver)",
"self.driver = driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist =",
"from Data.parameters import Data from reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver",
"= Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster = Select(self.driver.find_element_by_name(\"myCluster\")) cluster.select_by_index(2)",
"def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver)",
"Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster = Select(self.driver.find_element_by_name(\"myCluster\")) cluster.select_by_index(2) self.p.page_loading(self.driver)",
"selenium.webdriver.support.select import Select from Data.parameters import Data from reuse_func import GetData class click_on_home():",
"Data.parameters import Data from reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver =",
"Select from Data.parameters import Data from reuse_func import GetData class click_on_home(): def __init__(self,driver):",
"self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block =",
"Data from reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver = driver def",
"self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver)",
"from selenium.webdriver.support.select import Select from Data.parameters import Data from reuse_func import GetData class",
"self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster =",
"= driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\"))",
"reuse_func import GetData class click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p",
"dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster = Select(self.driver.find_element_by_name(\"myCluster\")) cluster.select_by_index(2) self.p.page_loading(self.driver) self.driver.find_element_by_id(Data.homeicon).click()",
"= GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2) self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\"))",
"driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist = Select(self.driver.find_element_by_name(\"myDistrict\")) dist.select_by_index(2)",
"click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click()",
"self.p.page_loading(self.driver) block = Select(self.driver.find_element_by_name(\"myBlock\")) block.select_by_index(2) self.p.page_loading(self.driver) cluster = Select(self.driver.find_element_by_name(\"myCluster\")) cluster.select_by_index(2) self.p.page_loading(self.driver) self.driver.find_element_by_id(Data.homeicon).click() self.p.page_loading(self.driver)",
"__init__(self,driver): self.driver = driver def test_homeicon(self): self.p = GetData() self.driver.implicitly_wait(20) self.driver.find_element_by_xpath(Data.hyper).click() self.p.page_loading(self.driver) dist",
"import Select from Data.parameters import Data from reuse_func import GetData class click_on_home(): def",
"import GetData class click_on_home(): def __init__(self,driver): self.driver = driver def test_homeicon(self): self.p ="
] |
[
"1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 #",
"import Pin gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1",
"输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式",
"# GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号",
"23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。",
"整型。 # IN 输入模式 # OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式",
"浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平",
"from machine import Pin gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i",
"# 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号",
"# GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 #",
"gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1 # GPIOn",
"utime i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 #",
"输入模式 # OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式",
"pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 # level",
"199 # GPIO5–引脚号 204 # direction 整型。 # IN 输入模式 # OUT 输出模式",
"direction 整型。 # IN 输入模式 # OUT 输出模式 # pullMode 整型。 # PULL_DISABLE",
"# pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 #",
"204 # direction 整型。 # IN 输入模式 # OUT 输出模式 # pullMode 整型。",
"# IN 输入模式 # OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 #",
"Pin.PULL_DISABLE, 0) import utime i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: #",
"= 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23",
"# direction 整型。 # IN 输入模式 # OUT 输出模式 # pullMode 整型。 #",
"0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1) gpio1.write(1) utime.sleep(1) i +=",
"# OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 #",
"整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 #",
"IN 输入模式 # OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU",
"OUT 输出模式 # pullMode 整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD",
"GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178",
"# level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1)",
"# GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 #",
"import utime i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22",
"# PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 #",
"下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0)",
"GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号",
"PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 # 1",
"引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199",
"PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 # 0",
"22 # GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204",
"整型。 # PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。",
"machine import Pin gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i =",
"# GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。 # IN 输入模式 #",
"= Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1 # GPIOn 整型。引脚号。",
"<reponame>chain01/wiki<gh_stars>10-100 from machine import Pin gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime",
"# GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。 #",
"GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。 # IN 输入模式 # OUT",
"# PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while",
"Pin gpio1 = Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1 #",
"# GPIO5–引脚号 204 # direction 整型。 # IN 输入模式 # OUT 输出模式 #",
"PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100:",
"上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平",
"Pin(GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1 # GPIOn 整型。引脚号。 #",
"整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1) gpio1.write(1) utime.sleep(1)",
"GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。 # IN",
"i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号 22 # GPIO2–引脚号",
"# PULL_DISABLE 浮空模式 # PULL_PU 上拉模式 # PULL_PD 下拉模式 # level 整型。引脚电平。 #",
"level 整型。引脚电平。 # 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1) gpio1.write(1)",
"GPIO5–引脚号 204 # direction 整型。 # IN 输入模式 # OUT 输出模式 # pullMode",
"设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1) gpio1.write(1) utime.sleep(1) i += 1",
"0) import utime i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下: # GPIO1–引脚号",
"Pin.OUT, Pin.PULL_DISABLE, 0) import utime i = 1 # GPIOn 整型。引脚号。 # 引脚对应关系如下:",
"# 0 设置引脚为低电平 # 1 设置引脚为高电平 while i<100: gpio1.write(0) utime.sleep(1) gpio1.write(1) utime.sleep(1) i",
"178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction 整型。 # IN 输入模式",
"GPIO2–引脚号 23 # GPIO3–引脚号 178 # GPIO4–引脚号 199 # GPIO5–引脚号 204 # direction"
] |
[
"(mugen_list(), [1, 1, 1, 1, 1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo')",
"lists from mugen.lists import MugenList class Dummy(object): foo = 1 @pytest.fixture def mugen_list()",
"def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList())",
"Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1,",
"[ ([1, [2, 3], [[4, 5], [6, 7]]], [1, 2, 3, 4, 5,",
"5, 6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list():",
"def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\",",
"mugen.lists import MugenList class Dummy(object): foo = 1 @pytest.fixture def mugen_list() -> MugenList:",
"1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1,",
"assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5], [6,",
"4, 5, 6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def",
"[1, 2, 3, 4, 5, 6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l)",
"assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) == MugenList assert",
"Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1, 1]) ])",
"MugenList class Dummy(object): foo = 1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(),",
"]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() +",
"test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) ==",
"expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5], [6, 7]]], [1, 2,",
"expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1, 1]) ]) def test_lget(l, expected_foo):",
"expected_l\", [ ([1, [2, 3], [[4, 5], [6, 7]]], [1, 2, 3, 4,",
"== expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) == MugenList assert type(MugenList()[1:2]) ==",
"@pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5], [6, 7]]], [1, 2, 3,",
"mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [",
"1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()])",
"= 1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(),",
"MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1,",
"2, 3, 4, 5, 6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) ==",
"lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) == MugenList assert type(MugenList()[1:2])",
"[6, 7]]], [1, 2, 3, 4, 5, 6, 7]) ]) def test_flatten(l, expected_l):",
"1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [",
"[ (mugen_list(), [1, 1, 1, 1, 1, 1]) ]) def test_lget(l, expected_foo): assert",
"1, 1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\",",
"class Dummy(object): foo = 1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(),",
"@pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1, 1]) ]) def test_lget(l,",
"[1, 1, 1, 1, 1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') ==",
"import lists from mugen.lists import MugenList class Dummy(object): foo = 1 @pytest.fixture def",
"pytest from mugen import lists from mugen.lists import MugenList class Dummy(object): foo =",
"6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert",
"7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList()",
"@pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l,",
"from mugen import lists from mugen.lists import MugenList class Dummy(object): foo = 1",
"from mugen.lists import MugenList class Dummy(object): foo = 1 @pytest.fixture def mugen_list() ->",
"foo = 1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(),",
"mugen import lists from mugen.lists import MugenList class Dummy(object): foo = 1 @pytest.fixture",
"import MugenList class Dummy(object): foo = 1 @pytest.fixture def mugen_list() -> MugenList: return",
"3, 4, 5, 6, 7]) ]) def test_flatten(l, expected_l): assert lists.flatten(l) == expected_l",
"MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1,",
"([1, [2, 3], [[4, 5], [6, 7]]], [1, 2, 3, 4, 5, 6,",
"== expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5], [6, 7]]], [1,",
"5], [6, 7]]], [1, 2, 3, 4, 5, 6, 7]) ]) def test_flatten(l,",
"1, 1, 1, 1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo",
"-> MugenList: return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(),",
"3], [[4, 5], [6, 7]]], [1, 2, 3, 4, 5, 6, 7]) ])",
"l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5], [6, 7]]],",
"def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3],",
"7]]], [1, 2, 3, 4, 5, 6, 7]) ]) def test_flatten(l, expected_l): assert",
"1, 1, 1, 1]) ]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l,",
"Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1, 1])",
"return MugenList([Dummy(), Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1,",
"expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) == MugenList assert type(MugenList()[1:2]) == MugenList",
"Dummy(), Dummy(), Dummy(), Dummy(), Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1,",
"[[4, 5], [6, 7]]], [1, 2, 3, 4, 5, 6, 7]) ]) def",
"Dummy(object): foo = 1 @pytest.fixture def mugen_list() -> MugenList: return MugenList([Dummy(), Dummy(), Dummy(),",
"test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4,",
"import pytest from mugen import lists from mugen.lists import MugenList class Dummy(object): foo",
"expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2, 3], [[4, 5],",
"[2, 3], [[4, 5], [6, 7]]], [1, 2, 3, 4, 5, 6, 7])",
"expected_l): assert lists.flatten(l) == expected_l def test_mugen_list__operations_yield_mugen_list(): assert type(MugenList() + MugenList()) == MugenList",
"]) def test_lget(l, expected_foo): assert l.lget('foo') == expected_foo @pytest.mark.parametrize(\"l, expected_l\", [ ([1, [2,",
"Dummy()]) @pytest.mark.parametrize(\"l, expected_foo\", [ (mugen_list(), [1, 1, 1, 1, 1, 1]) ]) def"
] |
[
"% type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item:",
"from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def",
"class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key,",
"if not value: return elif isinstance(value, dict): for key, val in sorted(value.items()): if",
"{'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []} window = ViewTree(v2) window.show()",
"path = path[::-1] if __name__ == '__main__': app = QApplication([]) v1 = {'key1':",
"isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item,",
"QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def",
"val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if",
"else: fill_item(item, val) elif isinstance(value, (list, tuple)): for val in value: text =",
"new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child)",
"value) def click(self, item: QModelIndex): from pathlib import Path path = [] path.append(item.data())",
"{1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files':",
"child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not",
"fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib import Path path = []",
"value: text = (str(val) if not isinstance(val, (dict, list, tuple)) else '[%s]' %",
"new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from",
"def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None): child",
"from pathlib import Path path = [] path.append(item.data()) parent = item.parent() while parent.data():",
"'2': {'10': 10}, 'key3': [1, 2, 3, {1: 3, 7: 9}]} v2 =",
"super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if",
"text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib",
"not in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value, (list,",
"{'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3",
"def fill_item(item, value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val,",
"import Path path = [] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent",
"for key, val in sorted(value.items()): if key not in ['dirs', 'files']: new_item(item, str(key),",
"'[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self,",
"if key not in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val) elif",
"val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib import",
"sorted(value.items()): if key not in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val)",
"[] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path =",
"not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value,",
"def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val)",
"val in sorted(value.items()): if key not in ['dirs', 'files']: new_item(item, str(key), val) else:",
"def click(self, item: QModelIndex): from pathlib import Path path = [] path.append(item.data()) parent",
"{'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\':",
"self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not",
"elif isinstance(value, dict): for key, val in sorted(value.items()): if key not in ['dirs',",
"__init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None): child =",
"__name__ == '__main__': app = QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10},",
"in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value, (list, tuple)):",
"key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True)",
"for val in value: text = (str(val) if not isinstance(val, (dict, list, tuple))",
"not isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val) else:",
"in value: text = (str(val) if not isinstance(val, (dict, list, tuple)) else '[%s]'",
"v1 = {'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2, 3, {1: 3,",
"(str(val) if not isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text,",
"7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}},",
"elif isinstance(value, (list, tuple)): for val in value: text = (str(val) if not",
"Path path = [] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent =",
"PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self,",
"pathlib import Path path = [] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data())",
"str(key), val) else: fill_item(item, val) elif isinstance(value, (list, tuple)): for val in value:",
"fill_item(item, val) elif isinstance(value, (list, tuple)): for val in value: text = (str(val)",
"app = QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2,",
"QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2, 3, {1:",
"new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib import Path path",
"item: QModelIndex): from pathlib import Path path = [] path.append(item.data()) parent = item.parent()",
"'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py',",
"child.setExpanded(True) if not value: return elif isinstance(value, dict): for key, val in sorted(value.items()):",
"= parent.parent() path = path[::-1] if __name__ == '__main__': app = QApplication([]) v1",
"'value1', '2': {'10': 10}, 'key3': [1, 2, 3, {1: 3, 7: 9}]} v2",
"[1, 2, 3, {1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev':",
"from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item,",
"value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key])",
"['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value, (list, tuple)): for",
"QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return",
"path = [] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent()",
"key, val in sorted(value.items()): if key not in ['dirs', 'files']: new_item(item, str(key), val)",
"path.append(parent.data()) parent = parent.parent() path = path[::-1] if __name__ == '__main__': app =",
"v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []} window =",
"click(self, item: QModelIndex): from pathlib import Path path = [] path.append(item.data()) parent =",
"item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1] if __name__ ==",
"import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def",
"{'10': 10}, 'key3': [1, 2, 3, {1: 3, 7: 9}]} v2 = {'dirs':",
"{}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs':",
"<filename>utilities/mytests/fileexplorerdict.py from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget):",
"'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}",
"str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value, dict): for",
"isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value, dict):",
"val) parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value, dict): for key, val",
"parent.parent() path = path[::-1] if __name__ == '__main__': app = QApplication([]) v1 =",
"PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value):",
"not value: return elif isinstance(value, dict): for key, val in sorted(value.items()): if key",
"str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib import Path path =",
"QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent,",
"[]} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []} window",
"tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value)",
"else '[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def",
"= QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value:",
"return elif isinstance(value, dict): for key, val in sorted(value.items()): if key not in",
"val) elif isinstance(value, (list, tuple)): for val in value: text = (str(val) if",
"9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files':",
"fill_item(item, value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str):",
"== '__main__': app = QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10}, 'key3':",
"(dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item, str(value))",
"key not in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value,",
"if not isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val)",
"2, 3, {1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs':",
"while parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1] if __name__ == '__main__':",
"3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py',",
"new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value, (list, tuple)): for val in",
"parent = parent.parent() path = path[::-1] if __name__ == '__main__': app = QApplication([])",
"list, tuple)) else '[%s]' % type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(),",
"value): def new_item(parent, key, val=None): child = QTreeWidgetItem([key]) if not isinstance(val, str): fill_item(child,",
"= (str(val) if not isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__) new_item(item,",
"if not isinstance(val, str): fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return elif",
"type(val).__name__) new_item(item, text, val) else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex):",
"text = (str(val) if not isinstance(val, (dict, list, tuple)) else '[%s]' % type(val).__name__)",
"if __name__ == '__main__': app = QApplication([]) v1 = {'key1': 'value1', '2': {'10':",
"in sorted(value.items()): if key not in ['dirs', 'files']: new_item(item, str(key), val) else: fill_item(item,",
"value: return elif isinstance(value, dict): for key, val in sorted(value.items()): if key not",
"'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {},",
"= [] path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path",
"{'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs':",
"= path[::-1] if __name__ == '__main__': app = QApplication([]) v1 = {'key1': 'value1',",
"parent = item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1] if",
"[]}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files':",
"(list, tuple)): for val in value: text = (str(val) if not isinstance(val, (dict,",
"isinstance(value, (list, tuple)): for val in value: text = (str(val) if not isinstance(val,",
"v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}},",
"['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files':",
"= {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files':",
"QModelIndex): from pathlib import Path path = [] path.append(item.data()) parent = item.parent() while",
"isinstance(value, dict): for key, val in sorted(value.items()): if key not in ['dirs', 'files']:",
"val in value: text = (str(val) if not isinstance(val, (dict, list, tuple)) else",
"QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click)",
"else: new_item(item, str(value)) fill_item(self.invisibleRootItem(), value) def click(self, item: QModelIndex): from pathlib import Path",
"path[::-1] if __name__ == '__main__': app = QApplication([]) v1 = {'key1': 'value1', '2':",
"= item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1] if __name__",
"'__main__': app = QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10}, 'key3': [1,",
"'files']: new_item(item, str(key), val) else: fill_item(item, val) elif isinstance(value, (list, tuple)): for val",
"= {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []} window = ViewTree(v2)",
"val) else: fill_item(item, val) elif isinstance(value, (list, tuple)): for val in value: text",
"3, {1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {},",
"10}, 'key3': [1, 2, 3, {1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\':",
"{'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []} v3 =",
"tuple)): for val in value: text = (str(val) if not isinstance(val, (dict, list,",
"'key3': [1, 2, 3, {1: 3, 7: 9}]} v2 = {'dirs': {'C:\\\\': {'dirs':",
"ViewTree(QTreeWidget): def __init__(self, value): super().__init__() self.clicked.connect(self.click) def fill_item(item, value): def new_item(parent, key, val=None):",
"{'dirs': {'C:\\\\': {'dirs': {'dev': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []}}, 'files': []}",
"QApplication, QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value): super().__init__()",
"fill_item(child, val) parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value, dict): for key,",
"= QApplication([]) v1 = {'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2, 3,",
"parent.addChild(child) child.setExpanded(True) if not value: return elif isinstance(value, dict): for key, val in",
"'files': []}}, 'files': []} v3 = {'dirs': {'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}},",
"= {'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2, 3, {1: 3, 7:",
"import QApplication, QTreeWidget, QTreeWidgetItem from PyQt5.QtCore import QModelIndex class ViewTree(QTreeWidget): def __init__(self, value):",
"{'C:\\\\': {'dirs': {}, 'files': ['device_start.py', 'test.py']}}, 'files': []} window = ViewTree(v2) window.show() app.exec_()",
"dict): for key, val in sorted(value.items()): if key not in ['dirs', 'files']: new_item(item,",
"{'key1': 'value1', '2': {'10': 10}, 'key3': [1, 2, 3, {1: 3, 7: 9}]}",
"path.append(item.data()) parent = item.parent() while parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1]",
"parent.data(): path.append(parent.data()) parent = parent.parent() path = path[::-1] if __name__ == '__main__': app"
] |
[
"1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw(): roads =",
"Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool), display (bool) Output: all good",
"= get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON,",
"= 2, min_radius = 4.5, drive_right = True, display = True): \"\"\" Integrates",
"display (bool) Output: all good -> 0 \"\"\" def cwd_relpath(): # returns path",
"@win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding =",
"half_gauge = 2, min_radius = 4.5, drive_right = True, display = True): \"\"\"",
"into \" + osm_path) # display window if display: WINDOW_RESOLUTION = (1920, 1020)",
"import * from scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json",
"with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in",
"(float), max_radius, drive_left (bool), display (bool) Output: all good -> 0 \"\"\" def",
"WINDOW_RESOLUTION = (1920, 1020) # 1020 + window head = 1080 win =",
"scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge =",
"\"\"\" def cwd_relpath(): # returns path from current working directory to this script",
"script, the application. Inputs: from console Output: Window animation + console metrics (potentially)",
"(str), half_gauge (float), max_radius, drive_left (bool), display (bool) Output: all good -> 0",
"generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right = True, display = True):",
"optionally displays OpenGL lines of these rails in a system window Includes: cwd_relpath()",
"(bool) Output: all good -> 0 \"\"\" def cwd_relpath(): # returns path from",
"these rails in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines()",
"osm_path (str), half_gauge (float), max_radius, drive_left (bool), display (bool) Output: all good ->",
"win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3]",
"import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2,",
"prefix = \".\" for char in working_dir: if char == '/': prefix +=",
"graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius",
"rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding = (15, 15), multiplier=1.5) for road",
"= rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding = (15, 15), multiplier=1.5) for",
"with main script, the application. Inputs: from console Output: Window animation + console",
"json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] +",
"import json import os from pyglet.gl import * from scripts.read_json import get_dict from",
"from scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge",
"\"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3]",
"scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails",
"\"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] +",
"\".\" for char in working_dir: if char == '/': prefix += \"/..\" return",
"working_dir = working_dir[len(common):] prefix = \".\" for char in working_dir: if char ==",
"= pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] +",
"\" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks",
"if display: WINDOW_RESOLUTION = (1920, 1020) # 1020 + window head = 1080",
"pyglet.gl import * from scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines from",
"script (str) file_path = __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path",
"\"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as",
"system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge",
"working_dir: if char == '/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\",",
"\"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \" + osm_path)",
"= 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw(): roads",
"\"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph",
".JSON with rails, optionally displays OpenGL lines of these rails in a system",
"char in working_dir: if char == '/': prefix += \"/..\" return prefix +",
"replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right = True,",
"__file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir =",
"os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for char",
"all components of the generator, from .osm file to .JSON with rails, optionally",
"get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path,",
"+ \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3]",
"This is the main function with main script, the application. Inputs: from console",
"half_gauge, False, min_radius) print(\"\\nInserted tracks into \" + osm_path) # display window if",
"components of the generator, from .osm file to .JSON with rails, optionally displays",
"0 \"\"\" def cwd_relpath(): # returns path from current working directory to this",
"path from current working directory to this script (str) file_path = __file__ working_dir",
"Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool),",
"import pyglet import subprocess import json import os from pyglet.gl import * from",
"encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3] + \"json\")",
"with rails, optionally displays OpenGL lines of these rails in a system window",
"Output: Window animation + console metrics (potentially) \"\"\" import pyglet import subprocess import",
"if char == '/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath()",
"the application. Inputs: from console Output: Window animation + console metrics (potentially) \"\"\"",
"file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] +",
"1), padding = (15, 15), multiplier=1.5) for road in roads: road.draw(GL_LINES) return pyglet.app.run()",
"the generator, from .osm file to .JSON with rails, optionally displays OpenGL lines",
"= os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for",
"# display window if display: WINDOW_RESOLUTION = (1920, 1020) # 1020 + window",
"+ \"json\", (1, 1, 1), padding = (15, 15), multiplier=1.5) for road in",
"Output: all good -> 0 \"\"\" def cwd_relpath(): # returns path from current",
"osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \"",
"rails, optionally displays OpenGL lines of these rails in a system window Includes:",
"file to .JSON with rails, optionally displays OpenGL lines of these rails in",
"4.5, drive_right = True, display = True): \"\"\" Integrates all components of the",
"= __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir",
"\"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1),",
"file_path = __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):]",
"animation + console metrics (potentially) \"\"\" import pyglet import subprocess import json import",
"roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding = (15, 15), multiplier=1.5)",
"(potentially) \"\"\" import pyglet import subprocess import json import os from pyglet.gl import",
"import os from pyglet.gl import * from scripts.read_json import get_dict from scripts.render_json import",
"window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float),",
"json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\",",
"to this script (str) file_path = __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path,",
"working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):]",
"+ \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \" + osm_path) # display",
"os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix =",
"the main function with main script, the application. Inputs: from console Output: Window",
"def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right = True, display =",
"in working_dir: if char == '/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))]",
"import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right =",
"<filename>src/osm2paths.py \"\"\" This is the main function with main script, the application. Inputs:",
"this script (str) file_path = __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir])",
"cwd_relpath(): # returns path from current working directory to this script (str) file_path",
"= True): \"\"\" Integrates all components of the generator, from .osm file to",
"= \".\" for char in working_dir: if char == '/': prefix += \"/..\"",
"tracks into \" + osm_path) # display window if display: WINDOW_RESOLUTION = (1920,",
"from scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json,",
"1020 + window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\")",
"+ window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event",
"+ \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote",
"* from scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json import",
"get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file)",
"window if display: WINDOW_RESOLUTION = (1920, 1020) # 1020 + window head =",
"common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\"",
"= 4.5, drive_right = True, display = True): \"\"\" Integrates all components of",
"a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str),",
"from console Output: Window animation + console metrics (potentially) \"\"\" import pyglet import",
"good -> 0 \"\"\" def cwd_relpath(): # returns path from current working directory",
"display window if display: WINDOW_RESOLUTION = (1920, 1020) # 1020 + window head",
"2, min_radius = 4.5, drive_right = True, display = True): \"\"\" Integrates all",
"min_radius) print(\"\\nInserted tracks into \" + osm_path) # display window if display: WINDOW_RESOLUTION",
"True): \"\"\" Integrates all components of the generator, from .osm file to .JSON",
"Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius,",
"of the generator, from .osm file to .JSON with rails, optionally displays OpenGL",
"\"\"\" Integrates all components of the generator, from .osm file to .JSON with",
"insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right = True, display",
"write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool), display (bool) Output:",
"max_radius, drive_left (bool), display (bool) Output: all good -> 0 \"\"\" def cwd_relpath():",
"console Output: Window animation + console metrics (potentially) \"\"\" import pyglet import subprocess",
"working_dir[len(common):] prefix = \".\" for char in working_dir: if char == '/': prefix",
"+ \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" +",
"1, 1), padding = (15, 15), multiplier=1.5) for road in roads: road.draw(GL_LINES) return",
"display: WINDOW_RESOLUTION = (1920, 1020) # 1020 + window head = 1080 win",
"print(\"Wrote graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False,",
"= \"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1,",
"display = True): \"\"\" Integrates all components of the generator, from .osm file",
"from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5,",
"directory to this script (str) file_path = __file__ working_dir = os.getcwd() common =",
"working directory to this script (str) file_path = __file__ working_dir = os.getcwd() common",
"Window animation + console metrics (potentially) \"\"\" import pyglet import subprocess import json",
"+ \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \" +",
"json import os from pyglet.gl import * from scripts.read_json import get_dict from scripts.render_json",
"False, min_radius) print(\"\\nInserted tracks into \" + osm_path) # display window if display:",
"file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for char in working_dir: if char",
"\"\"\" import pyglet import subprocess import json import os from pyglet.gl import *",
"window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def",
"1020) # 1020 + window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption =",
"import subprocess import json import os from pyglet.gl import * from scripts.read_json import",
"drive_left (bool), display (bool) Output: all good -> 0 \"\"\" def cwd_relpath(): #",
"osm_path) # display window if display: WINDOW_RESOLUTION = (1920, 1020) # 1020 +",
"\"json\", (1, 1, 1), padding = (15, 15), multiplier=1.5) for road in roads:",
"(bool), display (bool) Output: all good -> 0 \"\"\" def cwd_relpath(): # returns",
"as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3]",
"(1, 1, 1), padding = (15, 15), multiplier=1.5) for road in roads: road.draw(GL_LINES)",
"rails_lines from scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius =",
"from current working directory to this script (str) file_path = __file__ working_dir =",
"open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \"",
"min_radius = 4.5, drive_right = True, display = True): \"\"\" Integrates all components",
"current working directory to this script (str) file_path = __file__ working_dir = os.getcwd()",
"\"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\")",
"graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius)",
"= os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix",
"char == '/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() +",
"Inputs: from console Output: Window animation + console metrics (potentially) \"\"\" import pyglet",
"== '/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\",",
"returns path from current working directory to this script (str) file_path = __file__",
"print(\"\\nInserted tracks into \" + osm_path) # display window if display: WINDOW_RESOLUTION =",
"cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left",
"is the main function with main script, the application. Inputs: from console Output:",
"+= \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\",",
"# 1020 + window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated",
"rails in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input:",
"head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw():",
"Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool), display",
"working_dir]) file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for char in",
"JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding",
"return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON",
"render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool), display (bool) Output: all",
"console metrics (potentially) \"\"\" import pyglet import subprocess import json import os from",
"= file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for char in working_dir: if",
"displays OpenGL lines of these rails in a system window Includes: cwd_relpath() Uses:",
"Integrates all components of the generator, from .osm file to .JSON with rails,",
"\" + osm_path) # display window if display: WINDOW_RESOLUTION = (1920, 1020) #",
"half_gauge (float), max_radius, drive_left (bool), display (bool) Output: all good -> 0 \"\"\"",
"def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding = (15,",
"on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1, 1, 1), padding = (15, 15),",
"scripts.write_json import replicate_json, insert_rails def generate_paths(osm_path, half_gauge = 2, min_radius = 4.5, drive_right",
"# returns path from current working directory to this script (str) file_path =",
"subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\")",
"\"w\", encoding=\"utf-8\") as json_file: json.dump(roads_JSON, json_file) print(\"Wrote graph in \" + osm_path[:-3] +",
"+ file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3]",
"osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\",",
"= (1920, 1020) # 1020 + window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION,",
".osm file to .JSON with rails, optionally displays OpenGL lines of these rails",
"True, display = True): \"\"\" Integrates all components of the generator, from .osm",
"cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with",
"main script, the application. Inputs: from console Output: Window animation + console metrics",
"subprocess import json import os from pyglet.gl import * from scripts.read_json import get_dict",
"insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \" + osm_path) #",
"(1920, 1020) # 1020 + window head = 1080 win = pyglet.window.Window(*WINDOW_RESOLUTION, caption",
"def cwd_relpath(): # returns path from current working directory to this script (str)",
"file_path = file_path[len(common):] working_dir = working_dir[len(common):] prefix = \".\" for char in working_dir:",
"= working_dir[len(common):] prefix = \".\" for char in working_dir: if char == '/':",
"application. Inputs: from console Output: Window animation + console metrics (potentially) \"\"\" import",
"pyglet.window.Window(*WINDOW_RESOLUTION, caption = \"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\",",
"+ console metrics (potentially) \"\"\" import pyglet import subprocess import json import os",
"pyglet import subprocess import json import os from pyglet.gl import * from scripts.read_json",
"prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path,",
"\"\"\" This is the main function with main script, the application. Inputs: from",
"main function with main script, the application. Inputs: from console Output: Window animation",
"metrics (potentially) \"\"\" import pyglet import subprocess import json import os from pyglet.gl",
"(str) file_path = __file__ working_dir = os.getcwd() common = os.path.commonpath([file_path, working_dir]) file_path =",
"\"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into \" + osm_path) # display window",
"caption = \"Generated JSON\") @win.event def on_draw(): roads = rails_lines(osm_path[:-3] + \"json\", (1,",
"\"-f\", osm_path, \"-n\", \"c\"]) roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\",",
"for char in working_dir: if char == '/': prefix += \"/..\" return prefix",
"os from pyglet.gl import * from scripts.read_json import get_dict from scripts.render_json import graph_lines,",
"-> 0 \"\"\" def cwd_relpath(): # returns path from current working directory to",
"from pyglet.gl import * from scripts.read_json import get_dict from scripts.render_json import graph_lines, rails_lines",
"= True, display = True): \"\"\" Integrates all components of the generator, from",
"OpenGL lines of these rails in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph()",
"all good -> 0 \"\"\" def cwd_relpath(): # returns path from current working",
"function with main script, the application. Inputs: from console Output: Window animation +",
"in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path",
"from .osm file to .JSON with rails, optionally displays OpenGL lines of these",
"of these rails in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict() write_json.insert_rails()",
"prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"]) roads_JSON =",
"import get_dict from scripts.render_json import graph_lines, rails_lines from scripts.write_json import replicate_json, insert_rails def",
"generator, from .osm file to .JSON with rails, optionally displays OpenGL lines of",
"'/': prefix += \"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\",",
"roads_JSON = get_dict(osm_path[:-3] + \"pycgr\") with open(osm_path[:-3] + \"json\", \"w\", encoding=\"utf-8\") as json_file:",
"json_file) print(\"Wrote graph in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge,",
"in \" + osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted",
"lines of these rails in a system window Includes: cwd_relpath() Uses: Vendors/OsmToRoadGraph/run.convert_osm_to_roadgraph() read_json.get_dict()",
"drive_right = True, display = True): \"\"\" Integrates all components of the generator,",
"to .JSON with rails, optionally displays OpenGL lines of these rails in a",
"+ osm_path[:-3] + \"json\") insert_rails(osm_path[:-3] + \"json\", half_gauge, False, min_radius) print(\"\\nInserted tracks into",
"+ osm_path) # display window if display: WINDOW_RESOLUTION = (1920, 1020) # 1020",
"read_json.get_dict() write_json.insert_rails() render_json.rails_lines() Input: osm_path (str), half_gauge (float), max_radius, drive_left (bool), display (bool)",
"\"/..\" return prefix + file_path[:-len(list(\"osm2paths.py\"))] subprocess.run([\"python\", cwd_relpath() + \"vendors/OsmToRoadGraph/run.py\", \"-f\", osm_path, \"-n\", \"c\"])"
] |
[
"in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region, 'showlegend': True } }",
"html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19. I dati sono aggiornati automaticamente",
"in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type ==",
"value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' )",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP",
"from pathlib import Path import dash import dash_core_components as dcc import dash_html_components as",
"[{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia'",
"'value': i} for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']],",
"return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable):",
"import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output,",
"Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ),",
"return [{'label': label, 'value': key} for key, label in covid_data.fields.items()] elif plot_type ==",
"html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i,",
"@app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type",
"'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else",
"Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return {",
"'Dettaglio Regione': region = plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(),",
"'layout': { 'title': 'Trend ' + region, 'showlegend': True } } elif plot_type",
"State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets,",
"aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i in ['Confronto",
"by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali",
"set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label': label, 'value': key} for key,",
"if plot_type == 'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(),",
"= plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible':",
"'__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port')",
"e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''),",
"covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update =",
"external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region()",
"]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni':",
"= Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi' app.layout",
"'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else 'true' } for nome_regione",
"parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port') args",
"} elif plot_type == 'Dettaglio Regione': region = plot_variable return { 'data': [{",
"debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port') args = parser.parse_args() app.run_server(debug=True,",
"plot_type == 'Dettaglio Regione': region = plot_variable return { 'data': [{ 'x': by_region[key][region].index,",
"True } } elif plot_type == 'Dettaglio Province per Regione': region = plot_variable",
"True } } elif plot_type == 'Dettaglio Regione': region = plot_variable return {",
"), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')])",
"-*- import argparse from datetime import datetime from pathlib import Path import dash",
"id='plot-type', options=[{'label': i, 'value': i} for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio",
"return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if",
"'Confronto Regioni': return [{'label': label, 'value': key} for key, label in covid_data.fields.items()] elif",
"]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for",
"region = plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key],",
"'Casi totali - ' + region, 'showlegend': True } } if __name__ ==",
"== 'Dettaglio Regione': return [{'label': r, 'value': r} for r in covid_data.extended_regions] elif",
"server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port') args = parser.parse_args() app.run_server(debug=True, port=args.port)",
"{ 'title': 'Casi totali - ' + region, 'showlegend': True } } if",
"update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index,",
"'value')] ) def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return { 'data':",
"'' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento",
"iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi'",
"{ 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type == 'Dettaglio Regione': region",
"{ 'title': 'Trend ' + region, 'showlegend': True } } elif plot_type ==",
"covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else 'true' } for key in",
"'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi",
"del COVID-19. I dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione",
"try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale",
"'true' } for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True }",
"pass app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([",
"import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts,",
"I dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'),",
"Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot',",
"dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State",
"'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type == 'Dettaglio Regione':",
"'Italia' else 'true' } for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend':",
"'showlegend': True } } if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server')",
"''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open",
"'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable',",
"external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = ''",
"'.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i}",
"= ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province",
"import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import",
"dcc import dash_html_components as html from dash.dependencies import Input, Output, State import covid_data",
"{ 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key",
"'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph(",
"= html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19.",
"[\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region =",
"r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback(",
"} if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int,",
"last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[",
"# -*- coding: utf-8 -*- import argparse from datetime import datetime from pathlib",
"licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento:",
"in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione': return [{'label': r, 'value':",
"<gh_stars>1-10 # -*- coding: utf-8 -*- import argparse from datetime import datetime from",
"from dash.dependencies import Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets =",
"'title': 'Trend ' + region, 'showlegend': True } } elif plot_type == 'Dettaglio",
"Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi' app.layout =",
"elif plot_type == 'Dettaglio Regione': return [{'label': r, 'value': r} for r in",
"'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label': label,",
"nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type",
"if plot_type == 'Confronto Regioni': return [{'label': label, 'value': key} for key, label",
"codice è open source sotto licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'),",
"True } } if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port',",
"== 'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione,",
"href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source sotto licenza MIT e disponibile",
"else 'true' } for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' +",
"labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ])",
") ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type ==",
"plot_variable): if plot_type == 'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y':",
"covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'),",
"def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return { 'data': [{ 'x':",
"+ region, 'showlegend': True } } if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run",
"pathlib import Path import dash import dash_core_components as dcc import dash_html_components as html",
"id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type):",
"{last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i in ['Confronto Regioni',",
"return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name",
"Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it'",
"== 'Dettaglio Regione': region = plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y':",
"return [{'label': r, 'value': r} for r in covid_data.extended_regions] elif plot_type == 'Dettaglio",
"'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]],",
"Regione': return [{'label': r, 'value': r} for r in covid_data.extended_regions] elif plot_type ==",
"dash_html_components as html from dash.dependencies import Input, Output, State import covid_data external_scripts =",
"by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip()",
"'Dettaglio Province per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data':",
"[{'label': r, 'value': r} for r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province",
"href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value':",
"'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else 'true' }",
"for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value']",
"Province per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{",
"'value': r} for r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione':",
"elif plot_type == 'Dettaglio Province per Regione': return [{'label': r, 'value': r} for",
"as html from dash.dependencies import Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"]",
"Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) )",
"r} for r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione': return",
"COVID-19. I dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione civile',",
"Visualizzazione degli andamenti territoriali del COVID-19. I dati sono aggiornati automaticamente dalla ''',",
"Regione': return [{'label': r, 'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'),",
"by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp)",
"html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i",
") ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto",
"Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type ==",
"Path import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies",
"html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19. I",
"['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province =",
"'Dettaglio Province per Regione': return [{'label': r, 'value': r} for r in covid_data.regions]",
"dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def",
"'legendonly' if key == 'tamponi' else 'true' } for key in covid_data.fields.keys()], 'layout':",
"options=[{'label': i, 'value': i} for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province",
"dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.',",
"== 'Dettaglio Province per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return {",
"elif plot_type == 'Dettaglio Province per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0]",
"è open source sotto licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.'",
"plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name':",
"= covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except:",
"= covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update",
"'layout': { 'title': 'Casi totali - ' + region, 'showlegend': True } }",
"'title': 'Casi totali - ' + region, 'showlegend': True } } if __name__",
"app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ '''",
"su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type',",
"Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label':",
"plot_type == 'Dettaglio Province per Regione': return [{'label': r, 'value': r} for r",
"per Regione': return [{'label': r, 'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable',",
"= [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region",
"i} for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto",
"by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]], 'layout': { 'title':",
"return [{'label': r, 'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable',",
"dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input,",
"della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source sotto licenza",
"by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else 'true'",
"} for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region, 'showlegend':",
"totali - ' + region, 'showlegend': True } } if __name__ == '__main__':",
"app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del",
"} for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } }",
"'Il codice è open source sotto licenza MIT e disponibile su ', html.A('github',",
"id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type',",
"label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label': r, 'value': r}",
"protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source sotto licenza MIT",
"'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible':",
"'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type == 'Dettaglio Regione': region =",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080,",
"'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else",
"covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type == 'Dettaglio",
"[{'label': label, 'value': key} for key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio",
"} } elif plot_type == 'Dettaglio Province per Regione': region = plot_variable key",
"Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(",
"in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - ' + region, 'showlegend': True",
"elif plot_type == 'Dettaglio Regione': region = plot_variable return { 'data': [{ 'x':",
"list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for",
"in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label': r, 'value': r} for",
"dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è",
"sotto licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo",
"Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app =",
"for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True } } elif",
"plot_type == 'Confronto Regioni': return [{'label': label, 'value': key} for key, label in",
"html.Br(), 'Il codice è open source sotto licenza MIT e disponibile su ',",
"sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(),",
"'showlegend': True } } elif plot_type == 'Dettaglio Regione': region = plot_variable return",
"key == 'tamponi' else 'true' } for key in covid_data.fields.keys()], 'layout': { 'title':",
"by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else 'true' } for",
"return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if",
"[Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')]",
"import datetime from pathlib import Path import dash import dash_core_components as dcc import",
"'tamponi' else 'true' } for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend '",
"'value': key} for key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return",
"[Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni':",
"last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title",
"} for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - ' +",
"= 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione",
"), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable',",
"dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update =",
"'visible': 'legendonly' if key == 'tamponi' else 'true' } for key in covid_data.fields.keys()],",
"r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione': return [{'label': r,",
"'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback(",
"== 'Dettaglio Province per Regione': return [{'label': r, 'value': r} for r in",
"covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - ' + region, 'showlegend': True }",
"import Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app",
"covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region, 'showlegend': True } } elif",
"territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti",
"andamenti territoriali del COVID-19. I dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale",
"contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali",
"= list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name }",
"url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp",
"'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] )",
"region = plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y':",
"html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19. I dati",
"territoriali del COVID-19. I dati sono aggiornati automaticamente dalla ''', html.A('fonte ufficiale della",
"covid_data.get_data_by_province() last_update = '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass",
"-*- coding: utf-8 -*- import argparse from datetime import datetime from pathlib import",
"civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source sotto licenza MIT e",
"per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict(",
"'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione ==",
"datetime import datetime from pathlib import Path import dash import dash_core_components as dcc",
"source sotto licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f'''",
"as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import",
"= datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento",
"[Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label': label, 'value':",
"key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label': r, 'value':",
"argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port') args = parser.parse_args()",
"aggiornati automaticamente dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il",
"else 'true' } for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable], 'showlegend': True",
"covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label': r, 'value': r} for r",
"plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly'",
"== 'Italia' else 'true' } for nome_regione in covid_data.extended_regions], 'layout': { 'title': covid_data.fields[plot_variable],",
"r, 'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def",
"'Trend ' + region, 'showlegend': True } } elif plot_type == 'Dettaglio Province",
"dcc.Dropdown( id='plot-variable' ), dcc.Graph( id='trend-plot', config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'),",
"territoriale COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19. I dati sono",
"by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else 'true'",
"'showlegend': True } } elif plot_type == 'Dettaglio Province per Regione': region =",
"Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index,",
"r, 'value': r} for r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per",
"available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if",
"Regione': region = plot_variable return { 'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name':",
"'data': [{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key ==",
"'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type == 'Confronto",
"html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source",
"Province per Regione': return [{'label': r, 'value': r} for r in covid_data.regions] @app.callback(",
"import argparse from datetime import datetime from pathlib import Path import dash import",
"MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update}",
"'''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i in ['Confronto Regioni', 'Dettaglio",
"{ 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly' if nome_regione",
"key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name",
"key} for key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label':",
"coding: utf-8 -*- import argparse from datetime import datetime from pathlib import Path",
"= dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update",
"disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems(",
"label, 'value': key} for key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione':",
"for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region, 'showlegend': True",
"region, 'showlegend': True } } elif plot_type == 'Dettaglio Province per Regione': region",
"datetime from pathlib import Path import dash import dash_core_components as dcc import dash_html_components",
"'name': province_name } for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali -",
"html from dash.dependencies import Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets",
"+ region, 'showlegend': True } } elif plot_type == 'Dettaglio Province per Regione':",
"[{'label': r, 'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')])",
"if key == 'tamponi' else 'true' } for key in covid_data.fields.keys()], 'layout': {",
"= '' try: iso_timestamp = Path('update_timestamp.txt').read_text().strip() last_update = datetime.fromisoformat(iso_timestamp) except: pass app.title =",
"i, 'value': i} for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per",
"external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' )",
"'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else 'true' } for key",
"covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione': return [{'label': r, 'value': r}",
"@app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return",
"plot_type == 'Confronto Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name':",
"except: pass app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'),",
"'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return",
"', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]), html.Div(f''' Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label':",
"''' Visualizzazione degli andamenti territoriali del COVID-19. I dati sono aggiornati automaticamente dalla",
"in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'}",
"Ultimo aggiornamento: {last_update} '''), dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i in",
"province_name } for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - '",
"utf-8 -*- import argparse from datetime import datetime from pathlib import Path import",
"by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else 'true' } for",
"i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display':",
"' + region, 'showlegend': True } } elif plot_type == 'Dettaglio Province per",
"for province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - ' + region,",
"set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def update_graph(plot_type,",
"== '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server",
"@app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type',",
"from datetime import datetime from pathlib import Path import dash import dash_core_components as",
"covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/'",
"'visible': 'legendonly' if nome_regione == 'Italia' else 'true' } for nome_regione in covid_data.extended_regions],",
"nome_regione == 'Italia' else 'true' } for nome_regione in covid_data.extended_regions], 'layout': { 'title':",
") def update_graph(plot_type, plot_variable): if plot_type == 'Confronto Regioni': return { 'data': [{",
"'legendonly' if nome_regione == 'Italia' else 'true' } for nome_regione in covid_data.extended_regions], 'layout':",
"Regioni': return [{'label': label, 'value': key} for key, label in covid_data.fields.items()] elif plot_type",
"in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot',",
"plot_type == 'Dettaglio Province per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return",
"locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if plot_type",
"' + region, 'showlegend': True } } if __name__ == '__main__': parser =",
"'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]], 'layout': {",
"region, 'showlegend': True } } if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug",
"province_name in covid_data.provinces[region]], 'layout': { 'title': 'Casi totali - ' + region, 'showlegend':",
"= plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(),",
"['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ),",
"== 'tamponi' else 'true' } for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend",
"'.', html.Br(), 'Il codice è open source sotto licenza MIT e disponibile su",
"'value')]) def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label': label, 'value': key}",
"import dash_html_components as html from dash.dependencies import Input, Output, State import covid_data external_scripts",
"for key, label in covid_data.fields.items()] elif plot_type == 'Dettaglio Regione': return [{'label': r,",
"'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi' else 'true' }",
"covid_data.fields[plot_variable], 'showlegend': True } } elif plot_type == 'Dettaglio Regione': region = plot_variable",
"automaticamente dalla ''', html.A('fonte ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice",
"{ 'data': [{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in",
"r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return",
"Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown(",
"app = dash.Dash( external_stylesheets=external_stylesheets, external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province()",
"import Path import dash import dash_core_components as dcc import dash_html_components as html from",
"== 'Confronto Regioni': return [{'label': label, 'value': key} for key, label in covid_data.fields.items()]",
"datetime.fromisoformat(iso_timestamp) except: pass app.title = 'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale",
"open source sotto licenza MIT e disponibile su ', html.A('github', href='https://github.com/doppioandante/covid_andamento_regionale'), '.' ]),",
"def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'), Input('plot-variable', 'value')] ) def",
"'true' } for key in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region,",
") by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try: iso_timestamp =",
"- ' + region, 'showlegend': True } } if __name__ == '__main__': parser",
"COVID-19'), html.Div([ ''' Visualizzazione degli andamenti territoriali del COVID-19. I dati sono aggiornati",
"Regioni': return { 'data': [{ 'x': by_region[plot_variable][nome_regione].index, 'y': by_region[plot_variable][nome_regione].to_list(), 'name': nome_regione, 'visible': 'legendonly'",
"dash.dependencies import Input, Output, State import covid_data external_scripts = [\"https://cdn.plot.ly/plotly-locale-it-latest.js\"] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']",
"= argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port', type=int, default=8080, help='HTTP server port') args =",
"for i in ['Confronto Regioni', 'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni',",
"nome_regione, 'visible': 'legendonly' if nome_regione == 'Italia' else 'true' } for nome_regione in",
"} } if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run debug server') parser.add_argument('--port', dest='port',",
"[{ 'x': by_region[key][region].index, 'y': by_region[key][region].to_list(), 'name': covid_data.fields[key], 'visible': 'legendonly' if key == 'tamponi'",
"per Regione': region = plot_variable key = list(covid_data.province_fields.keys())[0] return { 'data': [{ 'x':",
"def set_dropdown_options(plot_type): if plot_type == 'Confronto Regioni': return [{'label': label, 'value': key} for",
"config=dict( locale='it' ) ) ]) @app.callback( Output('plot-variable', 'options'), [Input('plot-type', 'value')]) def set_dropdown_options(plot_type): if",
"'Andamento territoriale contagi' app.layout = html.Div(children=[ html.H1(children='Andamento territoriale COVID-19'), html.Div([ ''' Visualizzazione degli",
"plot_type == 'Dettaglio Regione': return [{'label': r, 'value': r} for r in covid_data.extended_regions]",
"[{ 'x': by_province[key][region][province_name].index, 'y': by_province[key][region][province_name].to_list(), 'name': province_name } for province_name in covid_data.provinces[region]], 'layout':",
"key in covid_data.fields.keys()], 'layout': { 'title': 'Trend ' + region, 'showlegend': True }",
"degli andamenti territoriali del COVID-19. I dati sono aggiornati automaticamente dalla ''', html.A('fonte",
"'Dettaglio Regione', 'Dettaglio Province per Regione']], value='Confronto Regioni', labelStyle={'display': 'inline-block'} ), dcc.Dropdown( id='plot-variable'",
"argparse from datetime import datetime from pathlib import Path import dash import dash_core_components",
"ufficiale della protezione civile', href='https://github.com/pcm-dpc/COVID-19'), '.', html.Br(), 'Il codice è open source sotto",
"for r in covid_data.extended_regions] elif plot_type == 'Dettaglio Province per Regione': return [{'label':",
"'value': r} for r in covid_data.regions] @app.callback( Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options):",
"if nome_regione == 'Italia' else 'true' } for nome_regione in covid_data.extended_regions], 'layout': {",
"external_scripts=external_scripts, url_base_pathname='/covid-19/' ) by_region = covid_data.get_data_by_region() by_province = covid_data.get_data_by_province() last_update = '' try:",
"'Dettaglio Regione': return [{'label': r, 'value': r} for r in covid_data.extended_regions] elif plot_type",
"} elif plot_type == 'Dettaglio Province per Regione': region = plot_variable key =",
"dcc.RadioItems( id='plot-type', options=[{'label': i, 'value': i} for i in ['Confronto Regioni', 'Dettaglio Regione',",
"Output('plot-variable', 'value'), [Input('plot-variable', 'options')]) def set_plot_variable(available_options): return available_options[0]['value'] @app.callback( Output('trend-plot', 'figure'), [Input('plot-type', 'value'),",
"} } elif plot_type == 'Dettaglio Regione': region = plot_variable return { 'data':"
] |
[
"0 ) return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items,",
"1) if heroes.count() > 0 else 0 ) return context class ItemPageView(TemplateView): template_name",
"HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs):",
"items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular}",
"except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args,",
"( random.randint(0, heroes.count() - 1) if heroes.count() > 0 else 0 ) return",
"from django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name =",
"template_name = \"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs): try: self.item =",
"> 0 else 0 ) return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def",
"\"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if heroes.count() > 0",
"regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if heroes.count() > 0 else",
"import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name",
"= \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context =",
"0 else 0 ) return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self,",
"class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"]",
"= \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context =",
"heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"]",
"= item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] =",
"from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView class",
"<NAME> \"\"\" import random from django.http import HttpResponseRedirect from django.urls import reverse from",
"CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] =",
"\"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs =",
"2015 :Author: <NAME> \"\"\" import random from django.http import HttpResponseRedirect from django.urls import",
"class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs): try:",
"= ( random.randint(0, heroes.count() - 1) if heroes.count() > 0 else 0 )",
"return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"]",
"def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\")",
"def dispatch(self, request, items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist:",
":Author: <NAME> \"\"\" import random from django.http import HttpResponseRedirect from django.urls import reverse",
"verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def",
"context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs):",
"if heroes.count() > 0 else 0 ) return context class ItemPageView(TemplateView): template_name =",
"= {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if",
"context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if heroes.count() > 0 else 0",
"import reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView):",
"slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list",
"random from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView",
"TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self,",
"- 1) if heroes.count() > 0 else 0 ) return context class ItemPageView(TemplateView):",
"random.randint(0, heroes.count() - 1) if heroes.count() > 0 else 0 ) return context",
"= items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\":",
"items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request,",
"items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\":",
"\"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except",
"django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView class HomeView(TemplateView):",
"= items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return",
"context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"]",
"regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0,",
"from django.urls import reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\"",
"super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item context[\"absolute_uri\"]",
"heroes.count() - 1) if heroes.count() > 0 else 0 ) return context class",
"else 0 ) return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request,",
"items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes =",
"items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower()",
"item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes,",
"July 2015 :Author: <NAME> \"\"\" import random from django.http import HttpResponseRedirect from django.urls",
"reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name",
"return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items, slug, *args,",
"dispatch(self, request, items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural",
"get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes",
"import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def",
"request, items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural =",
"*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item context[\"absolute_uri\"] =",
"**kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item context[\"absolute_uri\"] = self.request.build_absolute_uri()",
"{\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if heroes.count()",
"\"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs)",
"*args, **kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list =",
"item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = (",
") return context class ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items, slug,",
"get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item context[\"absolute_uri\"] = self.request.build_absolute_uri() return context",
"def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item context[\"absolute_uri\"] = self.request.build_absolute_uri() return",
"item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() -",
"heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1) if heroes.count() >",
"HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] =",
"**kwargs): try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural)",
"self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list))",
"ItemPageView(TemplateView): template_name = \"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs): try: self.item",
"\"\"\" import random from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic",
"django.urls import reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class",
"context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular",
"return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[\"item\"] = self.item",
"try: self.item = items.objects.get(slug=slug) except items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return",
"\"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs)",
":Created: 13 July 2015 :Author: <NAME> \"\"\" import random from django.http import HttpResponseRedirect",
"template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower()",
"class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items,",
"items.DoesNotExist: verbose_name_plural = items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs)",
"= \"item-page.html\" def dispatch(self, request, items, slug, *args, **kwargs): try: self.item = items.objects.get(slug=slug)",
"= items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self,",
"items._meta.verbose_name_plural.lower() items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs):",
"13 July 2015 :Author: <NAME> \"\"\" import random from django.http import HttpResponseRedirect from",
"= items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False) context[\"items\"] =",
"import random from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import",
"context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count() - 1)",
"heroes.count() > 0 else 0 ) return context class ItemPageView(TemplateView): template_name = \"item-page.html\"",
"= item_qs.filter(hero=False) context[\"items\"] = {\"heroes\": heroes, \"regular\": regular} context[\"random_hero_unit_index\"] = ( random.randint(0, heroes.count()",
"django.views.generic import TemplateView class HomeView(TemplateView): template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\"",
"HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView class HomeView(TemplateView): template_name =",
"= \"category-page.html\" def get_context_data(self, items, **kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs",
"\"\"\" :Created: 13 July 2015 :Author: <NAME> \"\"\" import random from django.http import",
"items_list = \"{items}:{items}_list\".format(items=verbose_name_plural) return HttpResponseRedirect(reverse(items_list)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context",
"super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular = item_qs.filter(hero=False)",
"= super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True) regular =",
"**kwargs): context = super().get_context_data(**kwargs) context[\"page\"] = items._meta.verbose_name_plural.lower() item_qs = items.objects.filter(visible=True).order_by(\"order\") heroes = item_qs.filter(hero=True)",
"template_name = \"home.html\" class CategoryPageView(TemplateView): template_name = \"category-page.html\" def get_context_data(self, items, **kwargs): context"
] |
[
"ctx, client, state, url): if client and client.channel: try: video = Video(url, ctx.author)",
"temp # TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx,",
"import math import random import heapq from urllib import request from ..video import",
"self.config = config[__name__.split(\".\")[ -1]] # retrieve module name, find config entry self.states =",
"channel = message.channel users_in_channel = len([ member for member in voice_channel.members if not",
"than zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\")",
"\"⏭\": # skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing )",
"def __init__(self, setlists): # list((num, userid)) self.user_playtime = [(0, u) for u in",
"logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\"))",
"ctx, *, url): state = self.get_state(ctx.guild) # get the guild's state try: ret",
"reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current song at beginning",
"0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source,",
"def _queue_text(self, queue): \"\"\"Returns a block of text describing a given song queue.\"\"\"",
"the current play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text",
"= state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0:",
"if client and client.channel and client.source: return True else: raise commands.CommandError(\"Not currently playing",
"await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current",
"# TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop the current song and",
"users_in_channel) if required_votes == 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to",
"0: message = [f\"{len(queue)} songs in queue:\"] message += [ f\" {index+1}. **{song.title}**",
"the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and",
"+= \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of",
"ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await",
"currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command sender is",
"get_num(self, num): ret = [] # TODO: yeah this is a problem. #",
"youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was an error",
"def playnext(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO:",
"heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's runs out video = self.user_setlists[userid].pop(0)",
"# ensure the first song picked is random # userid -> Setlist #",
"async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay",
"state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes = set() self.now_playing",
"in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel: await",
"= set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS),",
"def extend(self, ctx, *, num): try: num = int(num) if num <= 0:",
"async def debug(self, ctx, *, url): state = self.get_state(ctx.guild) # get the guild's",
"always just take from the front for _,v in self.user_setlists.items(): random.shuffle(v) # Get",
"# check if max volume is set # clamp volume to [0, max_vol]",
"check if max volume is set # clamp volume to [0, max_vol] if",
"nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\" state = self.get_state(ctx.guild) message =",
"@commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state = self.get_state(ctx.guild) #",
"information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks",
"config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state",
"ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating play queue.\")",
"def volume(self, ctx, volume: int): \"\"\"Change the volume of currently playing audio (values",
"discord import asyncio import youtube_dl import logging import math import random import heapq",
"update the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self,",
"voted to skip, so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def",
"queue): \"\"\"Returns a block of text describing a given song queue.\"\"\" if len(queue)",
"raise commands.CommandError( \"You need to be in the channel to do that.\") async",
"else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self,",
"new_index: int): \"\"\"Moves song at an index to `new_index` in queue.\"\"\" state =",
"self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate",
"queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)} songs in queue:\"] message +=",
"# don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes ==",
"message.add_reaction(control) # TODO: Holy crap absolutely don't expose this one to the public.",
"pops played songs self.user_setlists = {u:v.copy() for u,v in setlists.items()} # TODO: probably",
"channel.members if not member.bot ]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"]",
"ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel:",
"+= list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all the songs together",
"yeah this is a problem. # This function stalls if you build too",
"(or performs a search for <url> and plays the first result).\"\"\" client =",
"from each user's setlists for user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x,",
"abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1",
"\"\"\"Helper class to manage a playlist state\"\"\" # users: list(userid, userid...) def __init__(self,",
"increment play times def get_num(self, num): ret = [] # TODO: yeah this",
"the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret =",
"front for _,v in self.user_setlists.items(): random.shuffle(v) # Get a list of <num> songs,",
"self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await",
"state.volume # update the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async",
"votes to skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator",
"control in CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely don't expose this",
"make sure volume is nonnegative if volume < 0: volume = 0 max_vol",
") # insert current song at beginning of playlist client.stop() # skip ahead",
"= [] state.now_playing = None else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\",",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state if url",
"# get the guild's state if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted",
"user is in the channel, and that the bot is # in a",
"integer greater than zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered",
"state = self.get_state(ctx.guild) # get state for this guild if 1 <= song",
"do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command sender is the song",
"if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state: await",
"CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely don't expose this one to",
"= e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self):",
"extend(self, ctx, *, num): try: num = int(num) if num <= 0: raise",
"current song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\",",
"> 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop)",
"self.get_state(ctx.guild) if not client: await self._play(ctx, client, state, url) else: try: video =",
"play(self, ctx, *, url): \"\"\"Plays audio hosted at <url> (or performs a search",
"def __init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes = set() self.now_playing =",
"await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num):",
"ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e await ctx.send(f\"{ret}\") class",
"that.\") class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def __init__(self, bot, config):",
"sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url> to the requesting",
"should be the only behavior, and it only queues out maybe 10 in",
"skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song:",
"]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes",
"to be in the channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that",
"song) in enumerate(queue) ] # add individual songs return \"\\n\".join(message) else: return \"The",
"new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client state =",
"https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio",
"one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url):",
"* users_in_channel) if required_votes == 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted",
"# skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client",
"self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking logic if not client: await",
"or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\": #",
"# users: list(userid, userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime = [(0,",
"*, url): \"\"\"Plays audio hosted at <url> (or performs a search for <url>",
"state.playlist.insert( 0, state.now_playing ) # insert current song at beginning of playlist client.stop()",
"behavior, and it only queues out maybe 10 in advance if num >=",
"each user's setlists for user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x, user),",
"state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate a new queue\") @commands.guild_only()",
"song at index... state.playlist.insert(new_index - 1, song) # and insert it. await ctx.send(self._queue_text(state.playlist))",
"setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked is random # userid ->",
"_queue_text(self, queue): \"\"\"Returns a block of text describing a given song queue.\"\"\" if",
"queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"skip was pressed, that vote skipping is # enabled, the user is in",
"num = 20 for i in range(num): ret.append(self.next()) return ret # Return a",
"currently playing song, or votes to skip it.\"\"\" state = self.get_state(ctx.guild) client =",
"bot is # in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) #",
"= float(volume) / 100.0 client.source.volume = state.volume # update the AudioSource's volume to",
"information about the current song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed())",
"play music.\"\"\" def __init__(self, bot, config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]]",
"\"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay",
"client, state, song): state.now_playing = song state.skip_votes = set() # clear skip votes",
"the front for _,v in self.user_setlists.items(): random.shuffle(v) # Get a list of <num>",
"entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for",
"for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's",
"@commands.command(brief=\"Register the playlist at <url> to the requesting user\") @commands.guild_only() async def setlist(self,",
"max_vol] if volume > max_vol: volume = max_vol client = ctx.guild.voice_client state.volume =",
"# enabled, the user is in the channel, and that the bot is",
"user class PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\" # users: list(userid,",
"self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper",
"def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel)",
"= GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the",
"creating it if it does not exist.\"\"\" if guild.id in self.states: return self.states[guild.id]",
"ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url)",
"== self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel = user.voice and",
"{e}\") await ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.append(video)",
"file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options",
"playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume is nonnegative",
"ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping",
"user != self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild and",
"await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx):",
"self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async",
"== user class PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\" # users:",
"out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration heapq.heappush(self.user_playtime, (time,",
"20 for i in range(num): ret.append(self.next()) return ret # Return a video object",
"greater than zero\") await self._build(ctx, num) async def _build(self, ctx, num): state =",
"the state for `guild`, creating it if it does not exist.\"\"\" if guild.id",
"\"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not",
"# announce vote users_in_channel = len([ member for member in channel.members if not",
"discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if",
"FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options to",
"setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build",
"if it does not exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id]",
"an integer greater than zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No",
"*, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state",
"state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self,",
"state.playlist = temp # TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def",
"len(queue) > 0: message = [f\"{len(queue)} songs in queue:\"] message += [ f\"",
"self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice channel, if",
"logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was an error downloading your video,",
"@commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state = self.get_state(ctx.guild) # get the",
"state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\"",
"state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction,",
"# pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio client.stop() elif",
"manage a playlist state\"\"\" # users: list(userid, userid...) def __init__(self, setlists): # list((num,",
"\"\"\"Moves song at an index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) #",
"currently playing\") @commands.guild_only() async def playnext(self, ctx, *, url): client = ctx.guild.voice_client state",
"await ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.append(video) message",
"= state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"])",
"in CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely don't expose this one",
"need to be in a voice channel to do that.\") @commands.command(brief=\"Queue <url> to",
"at beginning of playlist client.stop() # skip ahead elif reaction.emoji == \"⏭\" and",
"if client and client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e:",
"= ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel ==",
"sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message)",
"= self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist = [] state.now_playing =",
"the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await",
"an index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get state for",
"e: ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\"",
"else: raise commands.CommandError( \"You need to be the song requester to do that.\")",
"!= self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client:",
"song channel = client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([ member",
"state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if",
"volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the",
"playing song, or votes to skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client",
"f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is",
"voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\")",
"{u:v.copy() for u,v in setlists.items()} # TODO: probably make this configurable self.target_length =",
"True else: raise commands.CommandError( \"You need to be in the channel to do",
"else: raise commands.CommandError( \"You need to be in a voice channel to do",
"build too much, so this needs to be reconsidered. # Maybe autoplay should",
"def in_voice_channel(ctx): \"\"\"Checks that the command sender is in the same voice channel",
"not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state =",
"one currently playing\") @commands.guild_only() async def playnext(self, ctx, *, url): client = ctx.guild.voice_client",
"volume = 0 max_vol = self.config[\"max_volume\"] if max_vol > -1: # check if",
"user) if message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel ==",
"client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self,",
"__init__(self, bot, config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module",
"_shuffle_setlists(self, state, client): temp = [] # Grab a random 5 songs from",
"a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel =",
"ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try: video = Video(url, ctx.author) except",
"member in voice_channel.members if not member.bot ]) # don't count bots required_votes =",
"the volume of currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make",
"num): ret = [] # TODO: yeah this is a problem. # This",
"song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"])",
"to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member in",
"__init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes = set() self.now_playing = None",
"next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing)",
"= bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module name, find config entry",
"len([ member for member in voice_channel.members if not member.bot ]) # don't count",
"user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if",
"text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def",
"def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's",
"ctx.send( \"There was an error downloading your video, sorry.\") return client = await",
"len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(),",
"# Shuffle all the songs together random.shuffle(temp) state.playlist = temp # TODO: rename",
"self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member in channel.members if not member.bot",
"except: await ctx.send(f\"{num} is not an integer greater than zero\") state = self.get_state(ctx.guild)",
"client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([ member for member in",
"state = self.get_state(ctx.guild) # get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except",
"self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([ member for member in channel.members",
"@commands.command(brief=\"Queue <url> to play after the one currently playing\") @commands.guild_only() async def playnext(self,",
"individual songs return \"\\n\".join(message) else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only()",
"if not state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build to start\") return",
"# Shuffle each setlist so we can always just take from the front",
"vote users_in_channel = len([ member for member in channel.members if not member.bot ])",
"it if it does not exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else:",
"return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url> to the requesting user\")",
"a voice channel to do that.\") @commands.command(brief=\"Queue <url> to play after the one",
"\"\"\"Skips the currently playing song, or votes to skip it.\"\"\" state = self.get_state(ctx.guild)",
"that.\") @commands.command(brief=\"Queue <url> to play after the one currently playing\") @commands.guild_only() async def",
"e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume",
"await ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode not",
"def queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild) text =",
"for control in CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely don't expose",
"{song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing = song state.skip_votes",
"index... state.playlist.insert(new_index - 1, song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise",
"client, state, url) async def _play(self, ctx, client, state, url): if client and",
"1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self,",
"def setlist(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get",
"# immediately skip if requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote to",
"is currently playing before continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel and",
"state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif not",
"def play(self, ctx, *, url): \"\"\"Plays audio hosted at <url> (or performs a",
"as e: ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild",
"state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist)",
"[\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control) # TODO: Holy crap",
"= set() self.now_playing = None # userid -> Setlist self.setlists = {} self.playlist_state",
"skip song channel = client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([",
"state = self.get_state(ctx.guild) # get the guild's state await self._play(ctx, client, state, url)",
"self._build(ctx, num) async def _build(self, ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items():",
"= await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is",
"state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only()",
"self.skip_votes = set() self.now_playing = None # userid -> Setlist self.setlists = {}",
"have voted to skip, so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async",
"that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command sender is the song requester.\"\"\"",
"# get the guild's state await self._play(ctx, client, state, url) async def _play(self,",
"def _play_song(self, client, state, song): state.now_playing = song state.skip_votes = set() # clear",
"it does not exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] =",
"= ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send(",
"state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists)",
"youtube_dl import logging import math import random import heapq from urllib import request",
"_play(self, ctx, client, state, url): if client and client.channel: try: video = Video(url,",
"if state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif",
"if len(queue) > 0: message = [f\"{len(queue)} songs in queue:\"] message += [",
"the current song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message)",
"sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions =",
"state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member in channel.members if",
"= ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume = state.volume # update the",
"client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state,",
"bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted to",
"1, song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use",
"state for `guild`, creating it if it does not exist.\"\"\" if guild.id in",
"voice_channel.members if not member.bot ]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"]",
"= 1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise",
"CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control) # TODO:",
"insert current song at beginning of playlist client.stop() # skip ahead elif reaction.emoji",
"users_in_channel = len([ member for member in channel.members if not member.bot ]) #",
"queue:\"] message += [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song)",
"self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays",
"self.get_state(ctx.guild) # get state for this guild if 1 <= song <= len(state.playlist)",
"empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play queue",
"\"You need to be the song requester to do that.\") class Music(commands.Cog): \"\"\"Bot",
"state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist",
"_build(self, ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists,",
"in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True)",
"state.playlist.insert(0, video) # TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop the current",
"Shuffle all the songs together random.shuffle(temp) state.playlist = temp # TODO: rename to",
"commands import discord import asyncio import youtube_dl import logging import math import random",
"help play music.\"\"\" def __init__(self, bot, config): self.bot = bot self.config = config[__name__.split(\".\")[",
"all user's setlists together def _shuffle_setlists(self, state, client): temp = [] # Grab",
"skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote for `member` to",
"ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx,",
"video: {e}\") await ctx.send( \"There was an error downloading your video, sorry.\") return",
"await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio from",
"right now\") @commands.guild_only() async def playnow(self, ctx, *, url): client = ctx.guild.voice_client state",
"10 # Shuffle each setlist so we can always just take from the",
"state = self.get_state(ctx.guild) # make sure volume is nonnegative if volume < 0:",
"reactions to control playback.\"\"\" message = reaction.message if user != self.bot.user and message.author",
"except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was an",
"something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num): try: num =",
"# TODO: Holy crap absolutely don't expose this one to the public. @commands.command()",
"Grab a random 5 songs from each user's setlists for user,setlist in state.setlists.items():",
"playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command sender is in",
"Setlist # TODO: abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect",
"@commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state = self.get_state(ctx.guild) # get",
"the current song and play <url> right now\") @commands.guild_only() async def playnow(self, ctx,",
"@commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\"",
"for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked is random",
"member in channel.members if not member.bot ]) # don't count bots if (float(len(state.skip_votes))",
"= self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self,",
"and plays the first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get",
"do that.\") @commands.command(brief=\"Queue <url> to play after the one currently playing\") @commands.guild_only() async",
"\"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for `guild`, creating it if it",
"has been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state: await",
"@commands.guild_only() async def extend(self, ctx, *, num): try: num = int(num) if num",
"playing '{video.title}'\") else: raise commands.CommandError( \"You need to be in a voice channel",
"#self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together",
"state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e await",
"async def is_audio_requester(ctx): \"\"\"Checks that the command sender is the song requester.\"\"\" music",
"[] # Grab a random 5 songs from each user's setlists for user,setlist",
"= [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index:",
"discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist)",
"votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else:",
"TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num):",
"at an index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get state",
") else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register",
"only behavior, and it only queues out maybe 10 in advance if num",
"it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking logic",
"ctx, *, url): \"\"\"Plays audio hosted at <url> (or performs a search for",
"song at an index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get",
"to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state",
"class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist",
"# make sure volume is nonnegative if volume < 0: volume = 0",
"logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for",
"`new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get state for this guild if",
"await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume =",
"reactions to a message that can be used to control the bot.\"\"\" CONTROLS",
"current song at beginning of playlist client.stop() # skip ahead elif reaction.emoji ==",
"try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There was",
"to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def",
"if num >= 20: num = 20 for i in range(num): ret.append(self.next()) return",
"playlist state\"\"\" # users: list(userid, userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime",
"<= 0: raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is not an",
"client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\",",
"self.user_playtime = [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first",
"each setlist so we can always just take from the front for _,v",
"song <= len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song - 1) #",
"self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about",
"in channel.members if not member.bot ]) # don't count bots if (float(len(state.skip_votes)) /",
"as the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice",
"= await channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message)",
"= await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You",
"if num <= 0: raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is",
"queues out maybe 10 in advance if num >= 20: num = 20",
"video, sorry.\") return client = await channel.connect() self._play_song(client, state, video) message = await",
"playnext(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe",
"client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about the",
"= self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member in channel.members if not",
"message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if permissions.administrator or ( user_in_channel and",
"@commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song",
"await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and",
"temp = [] # Grab a random 5 songs from each user's setlists",
"reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip",
"return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def",
"@commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current play queue.\"\"\"",
"= self.get_state(ctx.guild) # get the guild's state if url == \"remove\": del state.setlists[ctx.author.id]",
"self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self,",
"vote skipping is # enabled, the user is in the channel, and that",
"\"\"\"Respods to reactions added to the bot's messages, allowing reactions to control playback.\"\"\"",
"= Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There was an error",
"users_in_channel = len([ member for member in voice_channel.members if not member.bot ]) #",
"ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester or admin",
"and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was pressed, that vote skipping",
"max volume is set # clamp volume to [0, max_vol] if volume >",
"\"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of text",
"user's setlists for user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist,",
"get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret",
"= len([ member for member in channel.members if not member.bot ]) # don't",
"1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry,",
"this guild if 1 <= song <= len(state.playlist) and 1 <= new_index: song",
"get the guild's state await self._play(ctx, client, state, url) async def _play(self, ctx,",
"{} self.playlist_state = None self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by ==",
"voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses",
"u,v in setlists.items()} # TODO: probably make this configurable self.target_length = 10 #",
"> max_vol: volume = max_vol client = ctx.guild.voice_client state.volume = float(volume) / 100.0",
"problem. # This function stalls if you build too much, so this needs",
"in queue:\"] message += [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index,",
"del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await",
"await ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.insert(0, video)",
"client = await channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed()) await",
"await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message):",
"def _vote_skip(self, channel, member): \"\"\"Register a vote for `member` to skip the song",
"= self.get_state(ctx.guild) if not client: await self._play(ctx, client, state, url) else: try: video",
"TODO: yeah this is a problem. # This function stalls if you build",
"video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration heapq.heappush(self.user_playtime, (time, userid))",
"discord.ext import commands import discord import asyncio import youtube_dl import logging import math",
"a block of text describing a given song queue.\"\"\" if len(queue) > 0:",
"and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else: raise commands.CommandError(",
"from ..video import Video from ..video import Setlist # TODO: abstract FFMPEG options",
"the channel, and that the bot is # in a voice channel voice_channel",
"state.volume = float(volume) / 100.0 client.source.volume = state.volume # update the AudioSource's volume",
"to be in a voice channel to do that.\") @commands.command(brief=\"Queue <url> to play",
"added to the bot's messages, allowing reactions to control playback.\"\"\" message = reaction.message",
"to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member)",
"\"⏭\"] for control in CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely don't",
"is random # userid -> Setlist # copy from guild state, pops played",
"= self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await",
"audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume is nonnegative if",
"if not member.bot ]) # don't count bots if (float(len(state.skip_votes)) / users_in_channel) >=",
"[] state.now_playing = None else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"])",
"self.config[\"vote_skip_ratio\"]: # enough members have voted to skip, so skip the song logging.info(f\"Enough",
"for member in voice_channel.members if not member.bot ]) # don't count bots required_votes",
"`member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild)",
"for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state,",
"ctx): \"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client):",
"song = state.playlist.pop(song - 1) # take song at index... state.playlist.insert(new_index - 1,",
"bot's messages, allowing reactions to control playback.\"\"\" message = reaction.message if user !=",
"= 20 for i in range(num): ret.append(self.next()) return ret # Return a video",
"from discord.ext import commands import discord import asyncio import youtube_dl import logging import",
"Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state,",
"@commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice channel, if currently in",
"\"You need to be in a voice channel to do that.\") @commands.command(brief=\"Queue <url>",
"the playlist at <url> to the requesting user\") @commands.guild_only() async def setlist(self, ctx,",
"async def clearqueue(self, ctx): \"\"\"Clears the play queue without leaving the channel.\"\"\" state",
"was an error downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the",
"not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay",
"ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await self._play(ctx, client, state,",
"start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\",",
"make this admin-only, vote, etc @commands.command(brief=\"Stop the current song and play <url> right",
"on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to the bot's messages, allowing reactions",
"vote, etc @commands.command(brief=\"Stop the current song and play <url> right now\") @commands.guild_only() async",
"channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel = message.channel users_in_channel",
"is not None and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try: video",
"video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await",
"def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has",
"self.get_state(ctx.guild) # make sure volume is nonnegative if volume < 0: volume =",
"\"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip",
"command sender is in the same voice channel as the bot.\"\"\" voice =",
"url) async def _play(self, ctx, client, state, url): if client and client.channel: try:",
"# Get a list of <num> songs, increment play times def get_num(self, num):",
"= self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx,",
"= self.get_state(ctx.guild) # get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception",
"and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else:",
"== 0: required_votes = 1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\"",
"channel = client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([ member for",
"and bot_voice.channel and voice.channel == bot_voice.channel: return True else: raise commands.CommandError( \"You need",
"options to pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information.",
"count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes",
"bot, config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module name,",
"in channel.members if not member.bot ]) # don't count bots required_votes = math.ceil(",
"and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try: video = Video(url, ctx.author)",
"client and client.channel and client.source: return True else: raise commands.CommandError(\"Not currently playing any",
"as e: await ctx.send( \"There was an error downloading your video, sorry.\") return",
"client): temp = [] # Grab a random 5 songs from each user's",
"text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block",
"in setlists.items()} # TODO: probably make this configurable self.target_length = 10 # Shuffle",
"skip, so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None):",
"bot_voice.channel: return True else: raise commands.CommandError( \"You need to be in the channel",
"Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There",
"= ctx.guild.voice_client if client and client.channel and client.source: return True else: raise commands.CommandError(\"Not",
"self.now_playing = None # userid -> Setlist self.setlists = {} self.playlist_state = None",
"client, state, url): if client and client.channel: try: video = Video(url, ctx.author) except",
"= Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client,",
"name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets",
"autoplay should be the only behavior, and it only queues out maybe 10",
"[f\"{len(queue)} songs in queue:\"] message += [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\"",
"@commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change",
"than zero\") await self._build(ctx, num) async def _build(self, ctx, num): state = self.get_state(ctx.guild)",
"to the bot's messages, allowing reactions to control playback.\"\"\" message = reaction.message if",
"not None and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try: video =",
"raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async",
"\"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx):",
"into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\"",
"state for this guild if 1 <= song <= len(state.playlist) and 1 <=",
"video = Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There was an",
"in advance if num >= 20: num = 20 for i in range(num):",
"Video(x, user), random.sample(setlist, k=5))) # Shuffle all the songs together random.shuffle(temp) state.playlist =",
"async def queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild) text",
"same voice channel as the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if",
"enabled, the user is in the channel, and that the bot is #",
"Return a video object for the next song to play def next(self): time,",
"client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together def _shuffle_setlists(self, state, client):",
"audio_playing(ctx): \"\"\"Checks that audio is currently playing before continuing.\"\"\" client = ctx.guild.voice_client if",
"self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing = song state.skip_votes = set() #",
"get state for this guild if 1 <= song <= len(state.playlist) and 1",
"= state.volume # update the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel)",
"None @commands.command(brief=\"Reshuffle user setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def",
"_pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester)",
"current song and play <url> right now\") @commands.guild_only() async def playnow(self, ctx, *,",
"self.playlist = [] self.skip_votes = set() self.now_playing = None # userid -> Setlist",
"async def audio_playing(ctx): \"\"\"Checks that audio is currently playing before continuing.\"\"\" client =",
"voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel = message.channel",
"client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video:",
"= False def is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class",
"ret = [] # TODO: yeah this is a problem. # This function",
"len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song - 1) # take song",
"state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url,",
"= reaction.message if user != self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user)",
"client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to",
"sure volume is nonnegative if volume < 0: volume = 0 max_vol =",
"and message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel =",
"TODO: abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed",
"downloading your video, sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added to queue.\",",
"= len([ member for member in voice_channel.members if not member.bot ]) # don't",
"\"You need to be in the channel to do that.\") async def is_audio_requester(ctx):",
"together random.shuffle(temp) state.playlist = temp # TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only()",
"probably make this admin-only, vote, etc @commands.command(brief=\"Stop the current song and play <url>",
"is nonnegative if volume < 0: volume = 0 max_vol = self.config[\"max_volume\"] if",
"1.0 self.playlist = [] self.skip_votes = set() self.now_playing = None # userid ->",
"-reconnect_delay_max 5' \"\"\" Command line options to pass to `ffmpeg` before the `-i`.",
"_vote_skip(self, channel, member): \"\"\"Register a vote for `member` to skip the song playing.\"\"\"",
"is_audio_requester(ctx): \"\"\"Checks that the command sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\")",
"the same voice channel as the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client",
"the channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command sender",
"not None: channel = ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError as",
"setlist so we can always just take from the front for _,v in",
"is not None: channel = ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError",
"is in the channel, and that the bot is # in a voice",
"user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state =",
"random.shuffle(v) # Get a list of <num> songs, increment play times def get_num(self,",
"guild if 1 <= song <= len(state.playlist) and 1 <= new_index: song =",
"def __init__(self, bot, config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]] # retrieve",
"= ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return",
"object for the next song to play def next(self): time, userid = heapq.heappop(self.user_playtime)",
"ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True",
"to manage a playlist state\"\"\" # users: list(userid, userid...) def __init__(self, setlists): #",
"zero\") except: await ctx.send(f\"{num} is not an integer greater than zero\") state =",
"and it only queues out maybe 10 in advance if num >= 20:",
"or admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip song channel = client.channel",
"return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"])",
"url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\"",
"# TODO: refill playlist when a user's runs out video = self.user_setlists[userid].pop(0) video",
"class managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes",
"client.source: return True else: raise commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx):",
"\"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist = []",
"client and client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error",
"song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state,",
"in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel",
"await ctx.send(f\"{num} is not an integer greater than zero\") await self._build(ctx, num) async",
"song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a",
"sender is in the same voice channel as the bot.\"\"\" voice = ctx.author.voice",
"@commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change the volume of",
"{'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx, 10)",
"# Grab a random 5 songs from each user's setlists for user,setlist in",
"return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await",
"\"\"\" Command line options to pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434",
"state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num): try: num = int(num)",
"@commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play queue without leaving the",
"TODO: Holy crap absolutely don't expose this one to the public. @commands.command() @commands.guild_only()",
"self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio client.stop() elif reaction.emoji == \"⏮\":",
"-1: # check if max volume is set # clamp volume to [0,",
"if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def",
"= self.get_state(ctx.guild) # get the guild's state await self._play(ctx, client, state, url) async",
"else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx):",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await self._play(ctx,",
"at <url> to the requesting user\") @commands.guild_only() async def setlist(self, ctx, *, url):",
"leave(self, ctx): \"\"\"Leaves the voice channel, if currently in one.\"\"\" client = ctx.guild.voice_client",
"try: num = int(num) if num <= 0: raise Exception(\"not greater than zero\")",
"0, state.now_playing ) # insert current song at beginning of playlist client.stop() #",
"# TODO: probably make this configurable self.target_length = 10 # Shuffle each setlist",
"async def leave(self, ctx): \"\"\"Leaves the voice channel, if currently in one.\"\"\" client",
"# update the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def",
"ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to the bot's",
"\"\"\"Returns a block of text describing a given song queue.\"\"\" if len(queue) >",
"not member.bot ]) # don't count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]:",
"is a problem. # This function stalls if you build too much, so",
"playlist at <url> to the requesting user\") @commands.guild_only() async def setlist(self, ctx, *,",
"and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was pressed, that",
"# announce vote channel = message.channel users_in_channel = len([ member for member in",
"after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more))",
"ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await",
"= client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel = len([ member for member",
"greater than zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists,",
"skipping is # enabled, the user is in the channel, and that the",
"plays the first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the",
"state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num): try: num =",
"that the command sender is in the same voice channel as the bot.\"\"\"",
"# clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def",
"of playlist client.stop() # skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and",
"= self.config[\"max_volume\"] if max_vol > -1: # check if max volume is set",
"async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to a message that",
"songs return \"\\n\".join(message) else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing)",
"# list((num, userid)) self.user_playtime = [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) #",
"math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1 await channel.send(",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking",
"# TODO: maybe make better \"nowplaying\" checking logic if not client: await self._play(ctx,",
"client, state, url) else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e:",
"self.config[\"vote_skip\"]: # vote to skip song channel = client.channel self._vote_skip(channel, ctx.author) # announce",
"@commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays audio",
"self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else",
"commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote for",
"e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was an error downloading your",
"@commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self,",
"Shuffle each setlist so we can always just take from the front for",
"self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together def _shuffle_setlists(self, state,",
"be the only behavior, and it only queues out maybe 10 in advance",
"@commands.guild_only() async def playnext(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"if not client: await self._play(ctx, client, state, url) else: try: video = Video(url,",
"audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command sender is in the same",
"= config[__name__.split(\".\")[ -1]] # retrieve module name, find config entry self.states = {}",
"the bot is # in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user)",
"= temp # TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self,",
"(values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume is nonnegative if volume",
"channel.members if not member.bot ]) # don't count bots if (float(len(state.skip_votes)) / users_in_channel)",
"and client.channel: await client.disconnect() state.playlist = [] state.now_playing = None else: raise commands.CommandError(\"Not",
"await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user):",
"set() self.now_playing = None # userid -> Setlist self.setlists = {} self.playlist_state =",
"await ctx.send(f\"{num} is not an integer greater than zero\") state = self.get_state(ctx.guild) if",
"song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist",
"the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel =",
"list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all the songs together random.shuffle(temp)",
"the first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's",
"error downloading your video, sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added to",
"reactions added to the bot's messages, allowing reactions to control playback.\"\"\" message =",
"self.get_state(ctx.guild) # get the guild's state if url == \"remove\": del state.setlists[ctx.author.id] await",
"list(userid, userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime = [(0, u) for",
"song: int, new_index: int): \"\"\"Moves song at an index to `new_index` in queue.\"\"\"",
"the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def",
"= [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song",
"in voice_channel.members if not member.bot ]) # don't count bots required_votes = math.ceil(",
"now\") @commands.guild_only() async def playnow(self, ctx, *, url): client = ctx.guild.voice_client state =",
"return state.playlist.insert(0, video) # TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop the",
"state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if",
"state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need to be the song requester",
"# clamp volume to [0, max_vol] if volume > max_vol: volume = max_vol",
"\"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author)",
"ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for",
"self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue):",
"own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line",
"def playnow(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not",
"to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not None and ctx.author.voice.channel",
"5' \"\"\" Command line options to pass to `ffmpeg` before the `-i`. See",
"from ..video import Setlist # TODO: abstract FFMPEG options into their own file?",
"@commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get",
"# take song at index... state.playlist.insert(new_index - 1, song) # and insert it.",
"that audio is currently playing before continuing.\"\"\" client = ctx.guild.voice_client if client and",
"find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the",
"play times def get_num(self, num): ret = [] # TODO: yeah this is",
"self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1 await channel.send( f\"{user.mention}",
"if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns",
"else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def",
"self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist = [] state.now_playing = None",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state if url ==",
"if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song):",
"embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not None and ctx.author.voice.channel is not",
"ctx.author.voice is not None and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try:",
"after the one currently playing\") @commands.guild_only() async def playnext(self, ctx, *, url): client",
"_play_song(self, client, state, song): state.now_playing = song state.skip_votes = set() # clear skip",
"= self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing)",
"you build too much, so this needs to be reconsidered. # Maybe autoplay",
"None # userid -> Setlist self.setlists = {} self.playlist_state = None self.autoplay =",
"better \"nowplaying\" checking logic if not client: await self._play(ctx, client, state, url) else:",
"https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async",
"(requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] # add individual songs",
"voice channel, if currently in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if",
"audio from <url>.\") @commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays audio hosted",
"self.get_state(ctx.guild) # get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as",
"a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx):",
"to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command sender is the",
"def debug(self, ctx, *, url): state = self.get_state(ctx.guild) # get the guild's state",
"get the guild's state if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist",
"voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else: raise commands.CommandError( \"You",
"a given song queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)} songs in",
"state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately",
"needs to be reconsidered. # Maybe autoplay should be the only behavior, and",
"setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay",
"skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if",
"channel, if currently in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client",
"ctx.send(f\"{num} is not an integer greater than zero\") state = self.get_state(ctx.guild) if not",
"required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1",
"guild = message.guild state = self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)):",
"return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client,",
"audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause()",
"state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *,",
"can always just take from the front for _,v in self.user_setlists.items(): random.shuffle(v) #",
"voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel'",
"ensure that skip was pressed, that vote skipping is # enabled, the user",
"not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate a new queue\")",
"reconsidered. # Maybe autoplay should be the only behavior, and it only queues",
"the guild's state if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for",
"def get_num(self, num): ret = [] # TODO: yeah this is a problem.",
"user\") @commands.guild_only() async def setlist(self, ctx, *, url): client = ctx.guild.voice_client state =",
"url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state if",
"one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel: await client.disconnect()",
"import Setlist # TODO: abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS =",
"ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\")",
"a playlist state\"\"\" # users: list(userid, userid...) def __init__(self, setlists): # list((num, userid))",
"for user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) #",
"\"There was an error downloading your video, sorry.\") return state.playlist.insert(0, video) # TODO:",
"(index, song) in enumerate(queue) ] # add individual songs return \"\\n\".join(message) else: return",
"= self.get_state(ctx.guild) # get state for this guild if 1 <= song <=",
"asyncio import youtube_dl import logging import math import random import heapq from urllib",
"\"nowplaying\" checking logic if not client: await self._play(ctx, client, state, url) else: try:",
"ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist =",
"insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays",
"= discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length -",
"client.stop() elif self.config[\"vote_skip\"]: # vote to skip song channel = client.channel self._vote_skip(channel, ctx.author)",
"ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\")",
"not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user",
"an error downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist",
"100.0 client.source.volume = state.volume # update the AudioSource's volume to match @commands.command() @commands.guild_only()",
"url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await self._play(ctx, client,",
"client.stop() # skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and",
"make better \"nowplaying\" checking logic if not client: await self._play(ctx, client, state, url)",
"@commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\" state",
"def _shuffle_setlists(self, state, client): temp = [] # Grab a random 5 songs",
"reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state",
"song and play <url> right now\") @commands.guild_only() async def playnow(self, ctx, *, url):",
"if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"])",
"ctx.send(f\"{num} is not an integer greater than zero\") await self._build(ctx, num) async def",
"after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about the current",
"/ users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted to skip, so skip",
"playlist client.stop() # skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel",
"= self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration heapq.heappush(self.user_playtime, (time, userid)) return",
"immediately skip if requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip",
"play <url> right now\") @commands.guild_only() async def playnow(self, ctx, *, url): client =",
"result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await",
"votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to a",
"else: raise commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only()",
"ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only()",
"pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio client.stop() elif reaction.emoji",
"ctx.send(\"Playlist mode not activated, use !build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle",
"expose this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx,",
"return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self,",
"ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await self._play(ctx, client, state, url) else:",
"etc @commands.command(brief=\"Stop the current song and play <url> right now\") @commands.guild_only() async def",
"state.now_playing = None else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only()",
"\"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently playing",
"ctx): \"\"\"Displays information about the current song.\"\"\" state = self.get_state(ctx.guild) message = await",
"ctx): \"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if",
"don't count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have",
"channel to do that.\") @commands.command(brief=\"Queue <url> to play after the one currently playing\")",
"voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True",
"function stalls if you build too much, so this needs to be reconsidered.",
"state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async",
"reaction.emoji == \"⏭\": # skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0,",
"clearqueue(self, ctx): \"\"\"Clears the play queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild)",
"ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods",
"@commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play queue without leaving",
"return True else: raise commands.CommandError( \"You need to be the song requester to",
"play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay",
"= PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async",
"# Maybe autoplay should be the only behavior, and it only queues out",
"option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is currently playing before",
"is # in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce",
"state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None",
"{ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client)",
"ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There was an error downloading your",
"state.is_requester(ctx.author): # immediately skip if requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote",
"-1]] # retrieve module name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\")",
"userid)) self.user_playtime = [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the",
"k=5))) # Shuffle all the songs together random.shuffle(temp) state.playlist = temp # TODO:",
"return ret # Return a video object for the next song to play",
"bot_voice.channel and voice.channel == bot_voice.channel: return True else: raise commands.CommandError( \"You need to",
"song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing",
"exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id]",
"embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need to be",
"better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num): try: num = int(num)",
"not exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return",
"in state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all",
"# get the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist))",
"use !build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered",
"votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel, member):",
"0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" )",
"await ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist",
"elif self.config[\"vote_skip\"]: # vote to skip song channel = client.channel self._vote_skip(channel, ctx.author) #",
"was pressed, that vote skipping is # enabled, the user is in the",
"skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author):",
"[] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index: int):",
"pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html",
"absolutely don't expose this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def",
"command line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is currently",
"return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice channel,",
"to a message that can be used to control the bot.\"\"\" CONTROLS =",
"a 'control-panel' of reactions to a message that can be used to control",
"ensure the first song picked is random # userid -> Setlist # copy",
"take from the front for _,v in self.user_setlists.items(): random.shuffle(v) # Get a list",
"volume of currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure",
"self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more =",
"else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video:",
"crap absolutely don't expose this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async",
"bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes =",
"was an error downloading your video, sorry.\") return state.playlist.insert(0, video) # TODO: probably",
"so we can always just take from the front for _,v in self.user_setlists.items():",
"random.sample(setlist, k=5))) # Shuffle all the songs together random.shuffle(temp) state.playlist = temp #",
"this needs to be reconsidered. # Maybe autoplay should be the only behavior,",
"about the current song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await",
"song to play def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist",
"await ctx.send( \"There was an error downloading your video, sorry.\") return client =",
"probably make this configurable self.target_length = 10 # Shuffle each setlist so we",
"try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e await ctx.send(f\"{ret}\")",
"# get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e:",
"commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def",
"skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await",
"playback.\"\"\" message = reaction.message if user != self.bot.user and message.author == self.bot.user: await",
"await self._build(ctx, num) async def _build(self, ctx, num): state = self.get_state(ctx.guild) if not",
"userid -> Setlist # copy from guild state, pops played songs self.user_setlists =",
"queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions",
"video) client.stop() @commands.command(brief=\"Register the playlist at <url> to the requesting user\") @commands.guild_only() async",
"commands to help play music.\"\"\" def __init__(self, bot, config): self.bot = bot self.config",
"this is a problem. # This function stalls if you build too much,",
"# in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote",
"this configurable self.target_length = 10 # Shuffle each setlist so we can always",
"for `guild`, creating it if it does not exist.\"\"\" if guild.id in self.states:",
"module name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild):",
"hosted at <url> (or performs a search for <url> and plays the first",
"channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def",
"self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song:",
"admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip song channel = client.channel self._vote_skip(channel,",
"is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote for `member` to skip",
"for the next song to play def next(self): time, userid = heapq.heappop(self.user_playtime) #",
"Setlist self.setlists = {} self.playlist_state = None self.autoplay = False def is_requester(self, user):",
"not state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build to start\") return state.playlist",
"Maybe autoplay should be the only behavior, and it only queues out maybe",
"bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel",
"'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state",
"the user is in the channel, and that the bot is # in",
"in enumerate(queue) ] # add individual songs return \"\\n\".join(message) else: return \"The play",
"state\"\"\" # users: list(userid, userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime =",
"= max_vol client = ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume = state.volume",
"from <url>.\") @commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays audio hosted at",
"in queue.\"\"\" state = self.get_state(ctx.guild) # get state for this guild if 1",
">= 20: num = 20 for i in range(num): ret.append(self.next()) return ret #",
"self.bot = bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module name, find config",
"= 1.0 self.playlist = [] self.skip_votes = set() self.now_playing = None # userid",
"to control playback.\"\"\" message = reaction.message if user != self.bot.user and message.author ==",
"def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to the bot's messages, allowing",
"] # add individual songs return \"\\n\".join(message) else: return \"The play queue is",
"the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state =",
"await client.disconnect() state.playlist = [] state.now_playing = None else: raise commands.CommandError(\"Not in a",
"= message.channel users_in_channel = len([ member for member in voice_channel.members if not member.bot",
"zero\") except: await ctx.send(f\"{num} is not an integer greater than zero\") await self._build(ctx,",
"1) # take song at index... state.playlist.insert(new_index - 1, song) # and insert",
"- 1, song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must",
"<= song <= len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song - 1)",
"state = self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state,",
"message.channel users_in_channel = len([ member for member in voice_channel.members if not member.bot ])",
"in the channel, and that the bot is # in a voice channel",
"voice channel as the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice",
"# TODO: yeah this is a problem. # This function stalls if you",
"setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client",
"= music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else: raise",
"skip if requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip song",
"their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command",
"by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] # add individual songs return",
"if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return",
"ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was",
"to [0, max_vol] if volume > max_vol: volume = max_vol client = ctx.guild.voice_client",
"ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's",
"if permissions.administrator or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji ==",
"permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You",
"add individual songs return \"\\n\".join(message) else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"])",
"@commands.command(brief=\"Reshuffle user setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self,",
"\"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current song at beginning of playlist",
"TODO: maybe make better \"nowplaying\" checking logic if not client: await self._play(ctx, client,",
"@commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) #",
"..video import Setlist # TODO: abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS",
"ctx.guild.voice_client if client and client.channel and client.source: return True else: raise commands.CommandError(\"Not currently",
"channel as the bot.\"\"\" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and",
"state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int,",
"guild's state if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\")",
"is not an integer greater than zero\") state = self.get_state(ctx.guild) if not state.setlists.items():",
"<url> and plays the first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) #",
"message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError(",
"asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information",
"= self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client)",
"youtube_dl.DownloadError as e: await ctx.send( \"There was an error downloading your video, sorry.\")",
"return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\"",
"client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num): try: num",
"get_state(self, guild): \"\"\"Gets the state for `guild`, creating it if it does not",
"downloading your video, sorry.\") return state.playlist.insert(0, video) # TODO: probably make this admin-only,",
"if requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip song channel",
"as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send( \"There was an error downloading",
"`ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command",
"to skip, so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self,",
"a message that can be used to control the bot.\"\"\" CONTROLS = [\"⏮\",",
"is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play",
"self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\")",
"int, new_index: int): \"\"\"Moves song at an index to `new_index` in queue.\"\"\" state",
"state.playlist = [] state.now_playing = None else: raise commands.CommandError(\"Not in a voice channel.\")",
"math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1 await ctx.send(",
"async def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client)",
"error downloading your video, sorry.\") return client = await channel.connect() self._play_song(client, state, video)",
"setlist(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the",
"required_votes = 1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async",
"= None else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing)",
"= [f\"{len(queue)} songs in queue:\"] message += [ f\" {index+1}. **{song.title}** (requested by",
"and client.source: return True else: raise commands.CommandError(\"Not currently playing any audio.\") async def",
"== 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\"",
"> -1: # check if max volume is set # clamp volume to",
"managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes =",
"command sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions",
"ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel:",
"<url> to play after the one currently playing\") @commands.guild_only() async def playnext(self, ctx,",
"self._play(ctx, client, state, url) else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as",
"message that can be used to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\",",
"match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently playing",
"play def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when a",
"must use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self,",
"set # clamp volume to [0, max_vol] if volume > max_vol: volume =",
"member in channel.members if not member.bot ]) # don't count bots required_votes =",
"import logging import math import random import heapq from urllib import request from",
"is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of text describing",
"be used to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await self._play(ctx, client,",
"asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def nowplaying(self, ctx):",
"to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num): try: num",
"GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice",
"queue.\"\"\" state = self.get_state(ctx.guild) # get state for this guild if 1 <=",
"self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if",
"music.\"\"\" def __init__(self, bot, config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]] #",
"@commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change the volume of currently playing",
"audio is currently playing before continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel",
"else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester)",
"Get a list of <num> songs, increment play times def get_num(self, num): ret",
"async def volume(self, ctx, volume: int): \"\"\"Change the volume of currently playing audio",
"first song picked is random # userid -> Setlist # copy from guild",
"GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist =",
"options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'",
"error downloading your video, sorry.\") return state.playlist.insert(0, video) # TODO: probably make this",
"audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio client.stop() elif reaction.emoji ==",
"self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention}",
"@commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play queue without leaving the channel.\"\"\"",
"client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together def",
"if max volume is set # clamp volume to [0, max_vol] if volume",
"channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds",
"*, num): try: num = int(num) if num <= 0: raise Exception(\"not greater",
"# Shuffle all user's setlists together def _shuffle_setlists(self, state, client): temp = []",
"self._vote_skip(voice_channel, user) # announce vote channel = message.channel users_in_channel = len([ member for",
"x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all the songs together random.shuffle(temp) state.playlist",
"heapq from urllib import request from ..video import Video from ..video import Setlist",
"\"\"\"Plays audio hosted at <url> (or performs a search for <url> and plays",
"- 1) # take song at index... state.playlist.insert(new_index - 1, song) # and",
"userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime = [(0, u) for u",
"self.get_state(ctx.guild) # get the guild's state await self._play(ctx, client, state, url) async def",
"await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to the",
"permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need to be the",
"await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote",
"\"\"\"Checks that audio is currently playing before continuing.\"\"\" client = ctx.guild.voice_client if client",
"of <num> songs, increment play times def get_num(self, num): ret = [] #",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await self._play(ctx, client, state, url)",
"is not an integer greater than zero\") await self._build(ctx, num) async def _build(self,",
"currently playing before continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel and client.source:",
"message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user)",
"= '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options to pass",
"10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate a",
"song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([",
"requester or admin client.stop() elif self.config[\"vote_skip\"]: # vote to skip song channel =",
"@commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\"",
"state.playlist.insert(new_index - 1, song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You",
"0: volume = 0 max_vol = self.config[\"max_volume\"] if max_vol > -1: # check",
"def get_state(self, guild): \"\"\"Gets the state for `guild`, creating it if it does",
"member for member in voice_channel.members if not member.bot ]) # don't count bots",
"for i in range(num): ret.append(self.next()) return ret # Return a video object for",
"= 1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def",
"@commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice channel, if currently in one.\"\"\"",
"url) else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading",
"ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state:",
"state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists",
"\"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if",
"self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for `guild`,",
"import asyncio import youtube_dl import logging import math import random import heapq from",
"if required_votes == 0: required_votes = 1 await channel.send( f\"{user.mention} voted to skip",
"of currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume",
"beginning of playlist client.stop() # skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"]",
"if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": #",
"= {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for `guild`, creating",
"state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx,",
"and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client =",
"and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid index.\")",
"await self._play(ctx, client, state, url) else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError",
"# userid -> Setlist # copy from guild state, pops played songs self.user_setlists",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating play",
"= message.guild state = self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)): client",
"a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self, ctx, *,",
"= ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need",
"None else: raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel)",
"video, sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added to queue.\", embed=video.get_embed()) await",
"def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song at an index to",
"raise commands.CommandError( \"You need to be the song requester to do that.\") class",
"registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num)",
"use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self, ctx,",
"queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the",
"block of text describing a given song queue.\"\"\" if len(queue) > 0: message",
"\"\\n\".join(message) else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async",
"song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator",
"sorry.\") return client = await channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\",",
"and play <url> right now\") @commands.guild_only() async def playnow(self, ctx, *, url): client",
"state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build to start\") return state.playlist +=",
"debug(self, ctx, *, url): state = self.get_state(ctx.guild) # get the guild's state try:",
"and 1 <= new_index: song = state.playlist.pop(song - 1) # take song at",
"client and client.channel: await client.disconnect() state.playlist = [] state.now_playing = None else: raise",
"if message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel",
"and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client)",
"else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing = song state.skip_votes =",
"= message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji ==",
"that can be used to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"]",
"take song at index... state.playlist.insert(new_index - 1, song) # and insert it. await",
"currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume()",
"ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make",
"be the song requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands to help",
"state await self._play(ctx, client, state, url) async def _play(self, ctx, client, state, url):",
"ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def __init__(self): self.volume = 1.0",
"self.config[\"max_volume\"] if max_vol > -1: # check if max volume is set #",
"make this configurable self.target_length = 10 # Shuffle each setlist so we can",
"if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if",
"`guild`, creating it if it does not exist.\"\"\" if guild.id in self.states: return",
"@commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild)",
"= not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\") if",
"in range(num): ret.append(self.next()) return ret # Return a video object for the next",
"None self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState:",
"\"\"\"Gets the state for `guild`, creating it if it does not exist.\"\"\" if",
"is # enabled, the user is in the channel, and that the bot",
"'{video.title}'\") else: raise commands.CommandError( \"You need to be in a voice channel to",
"i in range(num): ret.append(self.next()) return ret # Return a video object for the",
"not an integer greater than zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await",
"= message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if permissions.administrator or ( user_in_channel",
"music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author):",
"registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all",
"volume > max_vol: volume = max_vol client = ctx.guild.voice_client state.volume = float(volume) /",
"volume is set # clamp volume to [0, max_vol] if volume > max_vol:",
"the only behavior, and it only queues out maybe 10 in advance if",
"Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is not an integer greater than",
"without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing)",
"requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def",
"bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel",
"return True else: raise commands.CommandError( \"You need to be in the channel to",
"a search for <url> and plays the first result).\"\"\" client = ctx.guild.voice_client state",
"# Return a video object for the next song to play def next(self):",
"elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: #",
"= self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip",
"# enough members have voted to skip, so skip the song logging.info(f\"Enough votes,",
"Exception as e: ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing",
"vote skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote for `member`",
"*, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await self._play(ctx,",
"await self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and",
"integer greater than zero\") await self._build(ctx, num) async def _build(self, ctx, num): state",
"to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\",",
"Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There was an error downloading",
"ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester or admin client.stop() elif self.config[\"vote_skip\"]:",
"( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\": # pause",
"config): self.bot = bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module name, find",
"skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert",
"ctx): \"\"\"Leaves the voice channel, if currently in one.\"\"\" client = ctx.guild.voice_client state",
"5 songs from each user's setlists for user,setlist in state.setlists.items(): temp += list(map(lambda",
"client = message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji",
"async def playnext(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) #",
"self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state:",
"message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was pressed, that vote skipping is",
"*, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make better",
"= None @commands.command(brief=\"Reshuffle user setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async",
"queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist)",
"+= [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue)",
"async def play(self, ctx, *, url): \"\"\"Plays audio hosted at <url> (or performs",
"@commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears the play queue without",
"is set # clamp volume to [0, max_vol] if volume > max_vol: volume",
"if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state",
"state, url): if client and client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not client: await self._play(ctx, client, state,",
"guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only()",
"ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode not activated,",
"to play def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when",
"url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] =",
"{e}\") await ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.insert(0,",
"@commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently playing song,",
"temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all the songs",
"request from ..video import Video from ..video import Setlist # TODO: abstract FFMPEG",
"except Exception as e: ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class",
"state = self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist = [] state.now_playing",
"build(self, ctx, *, num): try: num = int(num) if num <= 0: raise",
"len([ member for member in channel.members if not member.bot ]) # don't count",
"in a voice channel to do that.\") @commands.command(brief=\"Queue <url> to play after the",
"def _build(self, ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered",
"Command line options to pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for",
"for member in channel.members if not member.bot ]) # don't count bots required_votes",
"that the command sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state =",
"your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url> to",
"member for member in channel.members if not member.bot ]) # don't count bots",
"return state.playlist.append(video) message = await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else:",
"user_in_channel = user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild",
"a problem. # This function stalls if you build too much, so this",
"the songs together random.shuffle(temp) state.playlist = temp # TODO: rename to something better",
"TODO: refill playlist when a user's runs out video = self.user_setlists[userid].pop(0) video =",
"that vote skipping is # enabled, the user is in the channel, and",
"= int(num) if num <= 0: raise Exception(\"not greater than zero\") except: await",
"user) # announce vote channel = message.channel users_in_channel = len([ member for member",
"state, video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else:",
"enough members have voted to skip, so skip the song logging.info(f\"Enough votes, skipping...\")",
"leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True)",
"of text describing a given song queue.\"\"\" if len(queue) > 0: message =",
"== \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url,",
"async def reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the",
"{ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists",
"- len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song =",
"next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing) async def",
"@commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves",
"autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been",
"runs out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration heapq.heappush(self.user_playtime,",
"= Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\") await ctx.send(",
"for member in channel.members if not member.bot ]) # don't count bots if",
"current play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text +=",
"for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state =",
"TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop the current song and play",
"play after the one currently playing\") @commands.guild_only() async def playnext(self, ctx, *, url):",
"if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id]",
"client.source.volume = state.volume # update the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing)",
"bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else: raise",
"before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line",
"for command line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is",
"ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state if url == \"remove\":",
"= ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester or",
"# ensure that skip was pressed, that vote skipping is # enabled, the",
"currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume is",
"skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel",
"line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is currently playing",
"to do that.\") @commands.command(brief=\"Queue <url> to play after the one currently playing\") @commands.guild_only()",
"playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered for {ctx.author.display_name}\")",
"def leave(self, ctx): \"\"\"Leaves the voice channel, if currently in one.\"\"\" client =",
"index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays",
"async def _build(self, ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No",
"and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state",
"`-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference.",
"count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted",
"out maybe 10 in advance if num >= 20: num = 20 for",
"state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle all the",
"raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is not an integer greater",
"except: await ctx.send(f\"{num} is not an integer greater than zero\") await self._build(ctx, num)",
"0-250).\"\"\" state = self.get_state(ctx.guild) # make sure volume is nonnegative if volume <",
"== \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio",
"state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else:",
"self.target_length = 10 # Shuffle each setlist so we can always just take",
"client.channel: await client.disconnect() state.playlist = [] state.now_playing = None else: raise commands.CommandError(\"Not in",
"\"\"\"Displays information about the current song.\"\"\" state = self.get_state(ctx.guild) message = await ctx.send(\"\",",
"num = int(num) if num <= 0: raise Exception(\"not greater than zero\") except:",
"int): \"\"\"Moves song at an index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild)",
"**{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] # add individual",
"is in the same voice channel as the bot.\"\"\" voice = ctx.author.voice bot_voice",
"that skip was pressed, that vote skipping is # enabled, the user is",
"to be reconsidered. # Maybe autoplay should be the only behavior, and it",
"\"\"\"Leaves the voice channel, if currently in one.\"\"\" client = ctx.guild.voice_client state =",
"voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and",
"client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester",
"state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url> to the requesting user\") @commands.guild_only()",
"Setlist # copy from guild state, pops played songs self.user_setlists = {u:v.copy() for",
"music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError(",
"setlists together def _shuffle_setlists(self, state, client): temp = [] # Grab a random",
"song requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\"",
"channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command sender is",
"({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to",
"# This function stalls if you build too much, so this needs to",
"ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: await ctx.send( \"There",
"\"\"\"Bot commands to help play music.\"\"\" def __init__(self, bot, config): self.bot = bot",
"@commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently playing song, or",
"the song requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands to help play",
"reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure",
"enumerate(queue) ] # add individual songs return \"\\n\".join(message) else: return \"The play queue",
"channel.guild.voice_client.stop() async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None)",
"the one currently playing\") @commands.guild_only() async def playnext(self, ctx, *, url): client =",
"don't expose this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self,",
"messages, allowing reactions to control playback.\"\"\" message = reaction.message if user != self.bot.user",
"get the guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async",
"\"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change the",
"20: num = 20 for i in range(num): ret.append(self.next()) return ret # Return",
"= self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking logic if not client:",
"client.disconnect() state.playlist = [] state.now_playing = None else: raise commands.CommandError(\"Not in a voice",
"# skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) #",
"<= len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song - 1) # take",
"skip(self, ctx): \"\"\"Skips the currently playing song, or votes to skip it.\"\"\" state",
"num <= 0: raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is not",
"state, url) else: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error",
"userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's runs out video",
"songs together random.shuffle(temp) state.playlist = temp # TODO: rename to something better @commands.command(brief=\"TODO\")",
"<num> songs, increment play times def get_num(self, num): ret = [] # TODO:",
"state = self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client",
"stalls if you build too much, so this needs to be reconsidered. #",
"and client.channel and client.source: return True else: raise commands.CommandError(\"Not currently playing any audio.\")",
"refill playlist when a user's runs out video = self.user_setlists[userid].pop(0) video = Video(video,",
"(float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted to skip, so",
"= None self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by == user class",
"!build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\",",
"disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote for `member` to skip the",
"play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def clearqueue(self, ctx): \"\"\"Clears",
"self._add_reaction_controls(message) else: if ctx.author.voice is not None and ctx.author.voice.channel is not None: channel",
"client = ctx.guild.voice_client if client and client.channel and client.source: return True else: raise",
"playing\") @commands.guild_only() async def playnext(self, ctx, *, url): client = ctx.guild.voice_client state =",
"self.user_setlists = {u:v.copy() for u,v in setlists.items()} # TODO: probably make this configurable",
"any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command sender is in the",
"guild's state await ctx.send(\"Regenerating play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self,",
"channel, and that the bot is # in a voice channel voice_channel =",
"need to be in the channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks",
"\"\"\"Checks that the command sender is in the same voice channel as the",
"f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper",
"= user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild =",
"ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build to",
"to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of",
"raise commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command",
"so this needs to be reconsidered. # Maybe autoplay should be the only",
"else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume:",
"client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current song",
"ctx, *, num): try: num = int(num) if num <= 0: raise Exception(\"not",
"class PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\" # users: list(userid, userid...)",
"retrieve module name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self,",
"message): \"\"\"Adds a 'control-panel' of reactions to a message that can be used",
"self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for `guild`, creating it if",
"= song state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source =",
"]) # don't count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough",
"self._play(ctx, client, state, url) async def _play(self, ctx, client, state, url): if client",
"[ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ]",
"self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration heapq.heappush(self.user_playtime, (time, userid)) return video",
"ctx.channel.permissions_for(ctx.author) if permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need to",
"@commands.guild_only() async def playnow(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"state = self.get_state(ctx.guild) if not client: await self._play(ctx, client, state, url) else: try:",
"@commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves the voice channel, if currently",
"from guild state, pops played songs self.user_setlists = {u:v.copy() for u,v in setlists.items()}",
"# get state for this guild if 1 <= song <= len(state.playlist) and",
"this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *,",
"that the bot is # in a voice channel voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel,",
"volume is nonnegative if volume < 0: volume = 0 max_vol = self.config[\"max_volume\"]",
"None and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel try: video = Video(url,",
"raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a vote",
"> 0: message = [f\"{len(queue)} songs in queue:\"] message += [ f\" {index+1}.",
"registered setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode not activated, use",
"ret # Return a video object for the next song to play def",
"votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member",
"def build(self, ctx, *, num): try: num = int(num) if num <= 0:",
"client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int):",
"votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay:",
"\"There was an error downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register",
"be in a voice channel to do that.\") @commands.command(brief=\"Queue <url> to play after",
"ctx, song: int, new_index: int): \"\"\"Moves song at an index to `new_index` in",
"await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need",
"playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member",
"elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current song at",
"None: channel = ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e:",
"to be the song requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands to",
"await ctx.send(\"Playlist mode not activated, use !build to start\") return state.playlist += state.playlist_state.get_num(num)",
"message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\":",
"state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together def _shuffle_setlists(self, state, client): temp",
"self.volume = 1.0 self.playlist = [] self.skip_votes = set() self.now_playing = None #",
"random.shuffle(temp) state.playlist = temp # TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async",
"import youtube_dl import logging import math import random import heapq from urllib import",
"def is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to manage",
"\"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is currently playing before continuing.\"\"\" client",
"for (index, song) in enumerate(queue) ] # add individual songs return \"\\n\".join(message) else:",
"message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if permissions.administrator or",
"0: required_votes = 1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" )",
"member.bot ]) # don't count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: #",
"requesting user\") @commands.guild_only() async def setlist(self, ctx, *, url): client = ctx.guild.voice_client state",
"self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only() @commands.check(audio_playing)",
"message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions",
"= ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist =",
"= heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's runs out video =",
"if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester or admin client.stop()",
"an error downloading your video, sorry.\") return client = await channel.connect() self._play_song(client, state,",
"1 <= new_index: song = state.playlist.pop(song - 1) # take song at index...",
"<url> (or performs a search for <url> and plays the first result).\"\"\" client",
"await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and not",
"guild): \"\"\"Gets the state for `guild`, creating it if it does not exist.\"\"\"",
"pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self,",
"else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel, member): \"\"\"Register a",
"\"\"\"Adds a 'control-panel' of reactions to a message that can be used to",
"not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist",
"= self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay",
"ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume = state.volume # update the AudioSource's",
"message.guild.voice_client.channel: # ensure that skip was pressed, that vote skipping is # enabled,",
"checking logic if not client: await self._play(ctx, client, state, url) else: try: video",
"user's setlists together def _shuffle_setlists(self, state, client): temp = [] # Grab a",
"members have voted to skip, so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop()",
"else: raise commands.CommandError( \"You need to be in the channel to do that.\")",
"= state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx,",
"and not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle",
"control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await",
"error downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at",
"See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\"",
"= self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if not",
"def skip(self, ctx): \"\"\"Skips the currently playing song, or votes to skip it.\"\"\"",
"\"There was an error downloading your video, sorry.\") return client = await channel.connect()",
"import discord import asyncio import youtube_dl import logging import math import random import",
"not member.bot ]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel)",
"max_vol client = ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume = state.volume #",
"if volume < 0: volume = 0 max_vol = self.config[\"max_volume\"] if max_vol >",
"def is_audio_requester(ctx): \"\"\"Checks that the command sender is the song requester.\"\"\" music =",
"elif reaction.emoji == \"⏭\": # skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert(",
"volume(self, ctx, volume: int): \"\"\"Change the volume of currently playing audio (values 0-250).\"\"\"",
"return True else: raise commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks",
"random.shuffle(self.user_playtime) # ensure the first song picked is random # userid -> Setlist",
"picked is random # userid -> Setlist # copy from guild state, pops",
"state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self,",
"video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url> to the",
"== \"⏭\": # skip audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing",
"index to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get state for this",
"the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option",
"await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need to be in",
"to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for",
"commands.CommandError( \"You need to be in the channel to do that.\") async def",
"<url>.\") @commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays audio hosted at <url>",
"been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx,",
"False def is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to",
"state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def",
"Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that",
"be in the channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the",
"at <url> (or performs a search for <url> and plays the first result).\"\"\"",
"num): try: num = int(num) if num <= 0: raise Exception(\"not greater than",
"maybe 10 in advance if num >= 20: num = 20 for i",
"@commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently",
"for <url> and plays the first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"0 max_vol = self.config[\"max_volume\"] if max_vol > -1: # check if max volume",
"float(volume) / 100.0 client.source.volume = state.volume # update the AudioSource's volume to match",
"the AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx):",
"@commands.command(brief=\"Stop the current song and play <url> right now\") @commands.guild_only() async def playnow(self,",
"guild state, pops played songs self.user_setlists = {u:v.copy() for u,v in setlists.items()} #",
"await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of text describing a given",
"def nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\" state = self.get_state(ctx.guild) message",
"channel, member): \"\"\"Register a vote for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name}",
"== message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if permissions.administrator",
"state, client): temp = [] # Grab a random 5 songs from each",
"to do that.\") class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def __init__(self,",
"<= new_index: song = state.playlist.pop(song - 1) # take song at index... state.playlist.insert(new_index",
"text describing a given song queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)}",
"member): \"\"\"Register a vote for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes",
"num) async def _build(self, ctx, num): state = self.get_state(ctx.guild) if not state.setlists.items(): await",
"raise commands.CommandError(\"Not in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async",
"an error downloading your video, sorry.\") return state.playlist.insert(0, video) # TODO: probably make",
"to help play music.\"\"\" def __init__(self, bot, config): self.bot = bot self.config =",
"= {u:v.copy() for u,v in setlists.items()} # TODO: probably make this configurable self.target_length",
"if state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay: state.playlist_state =",
"urllib import request from ..video import Video from ..video import Setlist # TODO:",
"message = reaction.message if user != self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction,",
"voice_channel = message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel = message.channel users_in_channel =",
"await self._add_reaction_controls(message) else: if ctx.author.voice is not None and ctx.author.voice.channel is not None:",
"ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.insert(0, video) #",
"message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel = message.channel users_in_channel = len([ member",
"\"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not None and",
"async def setlist(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) #",
"registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild)",
"clamp volume to [0, max_vol] if volume > max_vol: volume = max_vol client",
"raise commands.CommandError( \"You need to be in a voice channel to do that.\")",
"self.playlist_state = None self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by == user",
"async def nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\" state = self.get_state(ctx.guild)",
"random import heapq from urllib import request from ..video import Video from ..video",
"aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay =",
"or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need to be the song",
"an error downloading your video, sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added",
"Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def __init__(self, bot, config): self.bot =",
"control playback.\"\"\" message = reaction.message if user != self.bot.user and message.author == self.bot.user:",
"max_vol: volume = max_vol client = ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume",
"self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num): try:",
"greater than zero\") except: await ctx.send(f\"{num} is not an integer greater than zero\")",
"embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the",
"@commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change the volume",
"ctx, volume: int): \"\"\"Change the volume of currently playing audio (values 0-250).\"\"\" state",
"a user's runs out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time +=",
"mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state",
"a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client state",
"pressed, that vote skipping is # enabled, the user is in the channel,",
"self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel",
"state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only()",
"return client = await channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed())",
"\"\"\"Register a vote for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to",
"can be used to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for",
"not activated, use !build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode",
"self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current play",
"@commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state =",
"@commands.command(brief=\"TODO\") @commands.guild_only() async def extend(self, ctx, *, num): try: num = int(num) if",
"await message.add_reaction(control) # TODO: Holy crap absolutely don't expose this one to the",
"user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5))) # Shuffle",
"if permissions.administrator or state.is_requester(ctx.author): return True else: raise commands.CommandError( \"You need to be",
"ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need to",
"-> Setlist self.setlists = {} self.playlist_state = None self.autoplay = False def is_requester(self,",
"requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if permissions.administrator or",
"required_votes == 0: required_votes = 1 await channel.send( f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes}",
"@commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently playing song, or votes to",
"int(num) if num <= 0: raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num}",
"state.skip_votes.add(member) users_in_channel = len([ member for member in channel.members if not member.bot ])",
"\"There was an error downloading your video, sorry.\") return state.playlist.append(video) message = await",
"self.setlists = {} self.playlist_state = None self.autoplay = False def is_requester(self, user): return",
"@commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client",
"list of <num> songs, increment play times def get_num(self, num): ret = []",
"to skip song channel = client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel =",
"generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx): client = ctx.guild.voice_client",
"in the same voice channel as the bot.\"\"\" voice = ctx.author.voice bot_voice =",
"in the channel to do that.\") async def is_audio_requester(ctx): \"\"\"Checks that the command",
"for _,v in self.user_setlists.items(): random.shuffle(v) # Get a list of <num> songs, increment",
"source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length",
"@commands.check(audio_playing) async def nowplaying(self, ctx): \"\"\"Displays information about the current song.\"\"\" state =",
"'control-panel' of reactions to a message that can be used to control the",
"Shuffle all user's setlists together def _shuffle_setlists(self, state, client): temp = [] #",
"self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need to be in a",
"admin-only, vote, etc @commands.command(brief=\"Stop the current song and play <url> right now\") @commands.guild_only()",
"permissions = message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild) if permissions.administrator or (",
"zero\") await self._build(ctx, num) async def _build(self, ctx, num): state = self.get_state(ctx.guild) if",
"state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(),",
"the guild's state await self._play(ctx, client, state, url) async def _play(self, ctx, client,",
"bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control) #",
"= [] # TODO: yeah this is a problem. # This function stalls",
"be reconsidered. # Maybe autoplay should be the only behavior, and it only",
"a video object for the next song to play def next(self): time, userid",
"_add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to a message that can be",
"just take from the front for _,v in self.user_setlists.items(): random.shuffle(v) # Get a",
"play queue.\") self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to",
"in_voice_channel(ctx): \"\"\"Checks that the command sender is in the same voice channel as",
"async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added to the bot's messages,",
"@commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num): try: num = int(num) if",
"message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel",
"state.playlist.pop(song - 1) # take song at index... state.playlist.insert(new_index - 1, song) #",
"currently in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel:",
"songs in queue:\"] message += [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for",
"list((num, userid)) self.user_playtime = [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure",
"per-guild state.\"\"\" def __init__(self): self.volume = 1.0 self.playlist = [] self.skip_votes = set()",
"song picked is random # userid -> Setlist # copy from guild state,",
"return if not state.playlist_state: await ctx.send(\"Playlist mode not activated, use !build to start\")",
"This function stalls if you build too much, so this needs to be",
"else: if ctx.author.voice is not None and ctx.author.voice.channel is not None: channel =",
"together def _shuffle_setlists(self, state, client): temp = [] # Grab a random 5",
"state, pops played songs self.user_setlists = {u:v.copy() for u,v in setlists.items()} # TODO:",
"config[__name__.split(\".\")[ -1]] # retrieve module name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add,",
"state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a",
"<url> to the requesting user\") @commands.guild_only() async def setlist(self, ctx, *, url): client",
"the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author) if",
"song at beginning of playlist client.stop() # skip ahead elif reaction.emoji == \"⏭\"",
"#await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle all user's setlists together def _shuffle_setlists(self,",
"songs, increment play times def get_num(self, num): ret = [] # TODO: yeah",
"logging import math import random import heapq from urllib import request from ..video",
"bot self.config = config[__name__.split(\".\")[ -1]] # retrieve module name, find config entry self.states",
"nonnegative if volume < 0: volume = 0 max_vol = self.config[\"max_volume\"] if max_vol",
"before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more",
"random 5 songs from each user's setlists for user,setlist in state.setlists.items(): temp +=",
"= 10 # Shuffle each setlist so we can always just take from",
"times def get_num(self, num): ret = [] # TODO: yeah this is a",
"@commands.check(audio_playing) @commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song at",
"u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked is",
"[0, max_vol] if volume > max_vol: volume = max_vol client = ctx.guild.voice_client state.volume",
"from the front for _,v in self.user_setlists.items(): random.shuffle(v) # Get a list of",
"def _play(self, ctx, client, state, url): if client and client.channel: try: video =",
"reaction, user): \"\"\"Respods to reactions added to the bot's messages, allowing reactions to",
"state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song",
"\"\"\"Change the volume of currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild) #",
"the command sender is in the same voice channel as the bot.\"\"\" voice",
"\"\"\"Clears the play queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist =",
"in a voice channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self,",
"than zero\") except: await ctx.send(f\"{num} is not an integer greater than zero\") state",
"num): state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return",
"/ 100.0 client.source.volume = state.volume # update the AudioSource's volume to match @commands.command()",
"audio client.stop() elif reaction.emoji == \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current",
"-> Setlist # copy from guild state, pops played songs self.user_setlists = {u:v.copy()",
"guild's state await self._play(ctx, client, state, url) async def _play(self, ctx, client, state,",
"song): state.now_playing = song state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop)",
"playing before continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel and client.source: return",
"public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True) async def debug(self, ctx, *, url): state = self.get_state(ctx.guild)",
"and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild state = self.get_state(guild)",
"1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options to pass to `ffmpeg`",
"PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\" # users: list(userid, userid...) def",
"@commands.guild_only() async def play(self, ctx, *, url): \"\"\"Plays audio hosted at <url> (or",
"self.states[guild.id] = GuildState() return self.states[guild.id] @commands.command(aliases=[\"stop\"]) @commands.guild_only() @commands.has_permissions(administrator=True) async def leave(self, ctx): \"\"\"Leaves",
"maybe make better \"nowplaying\" checking logic if not client: await self._play(ctx, client, state,",
"ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop()",
"do that.\") class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def __init__(self, bot,",
"ret.append(self.next()) return ret # Return a video object for the next song to",
"is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild) permissions = ctx.channel.permissions_for(ctx.author)",
"playnow(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if not client:",
"a random 5 songs from each user's setlists for user,setlist in state.setlists.items(): temp",
"ctx.guild.voice_client state = self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking logic if",
"state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio self._pause_audio(client) elif",
"@commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client",
"ctx.send( \"There was an error downloading your video, sorry.\") return state.playlist.append(video) message =",
"it only queues out maybe 10 in advance if num >= 20: num",
"message.guild state = self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)): client =",
"url): if client and client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as",
"# copy from guild state, pops played songs self.user_setlists = {u:v.copy() for u,v",
"class Music(commands.Cog): \"\"\"Bot commands to help play music.\"\"\" def __init__(self, bot, config): self.bot",
"skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions",
"volume = max_vol client = ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume =",
"try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading video: {e}\")",
"skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self,",
"to `new_index` in queue.\"\"\" state = self.get_state(ctx.guild) # get state for this guild",
"zero\") state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return",
"AudioSource's volume to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips",
"continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel and client.source: return True else:",
"self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to manage a playlist state\"\"\" #",
"@commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client =",
"state if url == \"remove\": del state.setlists[ctx.author.id] await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return",
"client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async",
"message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel = user.voice",
"and that the bot is # in a voice channel voice_channel = message.guild.voice_client.channel",
"await ctx.send(f\"Deleted playlist for {ctx.author.display_name}\") return state.setlists[ctx.author.id] = Setlist(url, ctx.author) await ctx.send(f\"Playlist registered",
"video, sorry.\") return state.playlist.insert(0, video) # TODO: probably make this admin-only, vote, etc",
"state.playlist.pop(0).video_url) # Shuffle all user's setlists together def _shuffle_setlists(self, state, client): temp =",
"< 0: volume = 0 max_vol = self.config[\"max_volume\"] if max_vol > -1: #",
"this admin-only, vote, etc @commands.command(brief=\"Stop the current song and play <url> right now\")",
"user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was pressed, that vote",
"vote to skip song channel = client.channel self._vote_skip(channel, ctx.author) # announce vote users_in_channel",
"queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is",
"reference. \"\"\" async def audio_playing(ctx): \"\"\"Checks that audio is currently playing before continuing.\"\"\"",
"= math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0: required_votes = 1 await",
"of reactions to a message that can be used to control the bot.\"\"\"",
"TODO: probably make this configurable self.target_length = 10 # Shuffle each setlist so",
"and message.guild.voice_client.channel: # ensure that skip was pressed, that vote skipping is #",
"async def skip(self, ctx): \"\"\"Skips the currently playing song, or votes to skip",
"users: list(userid, userid...) def __init__(self, setlists): # list((num, userid)) self.user_playtime = [(0, u)",
"import Video from ..video import Setlist # TODO: abstract FFMPEG options into their",
"users_in_channel) if required_votes == 0: required_votes = 1 await channel.send( f\"{user.mention} voted to",
"# and insert it. await ctx.send(self._queue_text(state.playlist)) else: raise commands.CommandError(\"You must use a valid",
"message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def",
"ctx): \"\"\"Clears the play queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist",
"state = self.get_state(ctx.guild) # TODO: maybe make better \"nowplaying\" checking logic if not",
"'-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options to pass to",
"# don't count bots if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members",
"**{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] # add individual songs return \"\\n\".join(message)",
"first result).\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state",
"reaction.message if user != self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user) if",
"announce vote users_in_channel = len([ member for member in channel.members if not member.bot",
"for more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async def",
"[] # TODO: yeah this is a problem. # This function stalls if",
"range(num): ret.append(self.next()) return ret # Return a video object for the next song",
"played songs self.user_setlists = {u:v.copy() for u,v in setlists.items()} # TODO: probably make",
"logic if not client: await self._play(ctx, client, state, url) else: try: video =",
"self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji",
"the next song to play def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO:",
"copy from guild state, pops played songs self.user_setlists = {u:v.copy() for u,v in",
"await channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now",
"to pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more information. Also,",
"and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was",
"num >= 20: num = 20 for i in range(num): ret.append(self.next()) return ret",
"message = await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice",
"else: raise commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the",
"await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not",
"to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS:",
"if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client,",
"rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *, num): try:",
"def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to a message that can",
"not client: await self._play(ctx, client, state, url) else: try: video = Video(url, ctx.author)",
"state, song): state.now_playing = song state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song),",
"state.now_playing ) # insert current song at beginning of playlist client.stop() # skip",
"= ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"])",
"announce vote channel = message.channel users_in_channel = len([ member for member in voice_channel.members",
"volume=state.volume) def after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more >",
"@commands.guild_only() async def build(self, ctx, *, num): try: num = int(num) if num",
"@commands.guild_only() async def setlist(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked is random #",
"from urllib import request from ..video import Video from ..video import Setlist #",
"= self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client =",
"else 'disabled'}\") if state.autoplay and not state.playlist_state: await self._build(ctx, 10) elif not state.autoplay:",
"ctx.author) # announce vote users_in_channel = len([ member for member in channel.members if",
"when a user's runs out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time",
"state.now_playing = song state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source",
"self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async",
"advance if num >= 20: num = 20 for i in range(num): ret.append(self.next())",
"logging.info(f\"Now playing '{video.title}'\") else: raise commands.CommandError( \"You need to be in a voice",
"more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state,",
"the currently playing song, or votes to skip it.\"\"\" state = self.get_state(ctx.guild) client",
"state = self.get_state(ctx.guild) message = await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only()",
"= [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control) # TODO: Holy",
"users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted to skip, so skip the",
"user), random.sample(setlist, k=5))) # Shuffle all the songs together random.shuffle(temp) state.playlist = temp",
"self.bot.user: await message.remove_reaction(reaction, user) if message.guild and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel",
"# TODO: abstract FFMPEG options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1",
"user): \"\"\"Respods to reactions added to the bot's messages, allowing reactions to control",
"= self.get_state(ctx.guild) # make sure volume is nonnegative if volume < 0: volume",
"state.playlist.append(video) message = await ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if",
"def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self,",
"the command sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state = music.get_state(ctx.guild)",
"@commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently playing song, or votes",
"\"\"\"Display the current play queue.\"\"\" state = self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay:",
"setlists for user,setlist in state.setlists.items(): temp += list(map(lambda x: Video(x, user), random.sample(setlist, k=5)))",
"PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\") @commands.guild_only() async def",
"allowing reactions to control playback.\"\"\" message = reaction.message if user != self.bot.user and",
"and client.channel: try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: logging.warn(f\"Error downloading",
"self._shuffle_setlists(state, client) await ctx.send(self._queue_text(state.playlist)) async def on_reaction_add(self, reaction, user): \"\"\"Respods to reactions added",
"import commands import discord import asyncio import youtube_dl import logging import math import",
"enabled.\" await ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of text describing a",
"= state.playlist.pop(song - 1) # take song at index... state.playlist.insert(new_index - 1, song)",
"__init__(self, setlists): # list((num, userid)) self.user_playtime = [(0, u) for u in setlists.keys()]",
"time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's runs out",
"state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing)",
"ctx.guild.voice_client state = self.get_state(ctx.guild) if client and client.channel: await client.disconnect() state.playlist = []",
"await ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) #",
"= [] # Grab a random 5 songs from each user's setlists for",
"@commands.has_permissions(administrator=True) async def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song at an",
"1 -reconnect_delay_max 5' \"\"\" Command line options to pass to `ffmpeg` before the",
"self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing)",
"user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to manage a playlist",
"= await ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self,",
"[(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked",
"given song queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)} songs in queue:\"]",
"voice channel to do that.\") @commands.command(brief=\"Queue <url> to play after the one currently",
"userid -> Setlist self.setlists = {} self.playlist_state = None self.autoplay = False def",
"than zero\") except: await ctx.send(f\"{num} is not an integer greater than zero\") await",
"client.resume() else: client.pause() @commands.command(aliases=[\"vol\", \"v\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx,",
"except youtube_dl.DownloadError as e: await ctx.send( \"There was an error downloading your video,",
"async def playnow(self, ctx, *, url): client = ctx.guild.voice_client state = self.get_state(ctx.guild) if",
"* users_in_channel) if required_votes == 0: required_votes = 1 await channel.send( f\"{user.mention} voted",
"ret = e await ctx.send(f\"{ret}\") class GuildState: \"\"\"Helper class managing per-guild state.\"\"\" def",
"def reshuffle(self, ctx): client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's",
"we can always just take from the front for _,v in self.user_setlists.items(): random.shuffle(v)",
"self.get_state(ctx.guild) text = self._queue_text(state.playlist) if state.autoplay: text += \"\\n\\nAutoplay is enabled.\" await ctx.send(text)",
"is_requester(self, user): return self.now_playing.requested_by == user class PlaylistState: \"\"\"Helper class to manage a",
"== bot_voice.channel: return True else: raise commands.CommandError( \"You need to be in the",
"ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and",
"next song to play def next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill",
"\"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control) # TODO: Holy crap absolutely",
"def audio_playing(ctx): \"\"\"Checks that audio is currently playing before continuing.\"\"\" client = ctx.guild.voice_client",
"before continuing.\"\"\" client = ctx.guild.voice_client if client and client.channel and client.source: return True",
"volume: int): \"\"\"Change the volume of currently playing audio (values 0-250).\"\"\" state =",
"async def _set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def",
"# add individual songs return \"\\n\".join(message) else: return \"The play queue is empty.\"",
"more = state.playlist_state.target_length - len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) >",
"self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing = song",
"channel = ctx.author.voice.channel try: video = Video(url, ctx.author) except youtube_dl.DownloadError as e: await",
") async def _add_reaction_controls(self, message): \"\"\"Adds a 'control-panel' of reactions to a message",
"{index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] # add",
"@commands.check(in_voice_channel) @commands.check(is_audio_requester) async def volume(self, ctx, volume: int): \"\"\"Change the volume of currently",
"mode not activated, use !build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay",
"# userid -> Setlist self.setlists = {} self.playlist_state = None self.autoplay = False",
"class to manage a playlist state\"\"\" # users: list(userid, userid...) def __init__(self, setlists):",
"so skip the song logging.info(f\"Enough votes, skipping...\") channel.guild.voice_client.stop() async def _set_status(self, song=None): if",
"commands.CommandError( \"You need to be in a voice channel to do that.\") @commands.command(brief=\"Queue",
"search for <url> and plays the first result).\"\"\" client = ctx.guild.voice_client state =",
"= f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e await ctx.send(f\"{ret}\") class GuildState:",
"skip\") state = self.get_state(channel.guild) state.skip_votes.add(member) users_in_channel = len([ member for member in channel.members",
"ctx.send( \"Added to queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not None",
"\"⏯\": # pause audio self._pause_audio(client) elif reaction.emoji == \"⏭\": # skip audio client.stop()",
"*, url): state = self.get_state(ctx.guild) # get the guild's state try: ret =",
"= None # userid -> Setlist self.setlists = {} self.playlist_state = None self.autoplay",
"next(self): time, userid = heapq.heappop(self.user_playtime) # TODO: refill playlist when a user's runs",
"video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing '{video.title}'\") else: raise",
"video object for the next song to play def next(self): time, userid =",
"your video, sorry.\") return state.playlist.append(video) message = await ctx.send( \"Added to queue.\", embed=video.get_embed())",
"the play queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = []",
"the voice channel, if currently in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild)",
"if not member.bot ]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] *",
"only queues out maybe 10 in advance if num >= 20: num =",
"your video, sorry.\") return client = await channel.connect() self._play_song(client, state, video) message =",
"song queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)} songs in queue:\"] message",
"in setlists.keys()] random.shuffle(self.user_playtime) # ensure the first song picked is random # userid",
"ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url) @commands.command(brief=\"TODO\")",
"user's runs out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester) time += video.duration",
"async def extend(self, ctx, *, num): try: num = int(num) if num <=",
"queue.\", embed=video.get_embed()) await self._add_reaction_controls(message) else: if ctx.author.voice is not None and ctx.author.voice.channel is",
"_set_status(self, song=None): if song: await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client,",
"client: await self._play(ctx, client, state, url) else: try: video = Video(url, ctx.author) except",
"an integer greater than zero\") await self._build(ctx, num) async def _build(self, ctx, num):",
"# retrieve module name, find config entry self.states = {} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def",
"math import random import heapq from urllib import request from ..video import Video",
"jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song at an index to `new_index`",
"to play after the one currently playing\") @commands.guild_only() async def playnext(self, ctx, *,",
"elif not state.autoplay: state.playlist_state = None @commands.command(brief=\"Reshuffle user setlists and generate a new",
"the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in CONTROLS: await message.add_reaction(control)",
"import random import heapq from urllib import request from ..video import Video from",
"0: raise Exception(\"not greater than zero\") except: await ctx.send(f\"{num} is not an integer",
"len(state.playlist) if more > 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0)",
">= self.config[\"vote_skip_ratio\"]: # enough members have voted to skip, so skip the song",
"all the songs together random.shuffle(temp) state.playlist = temp # TODO: rename to something",
"= [] self.skip_votes = set() self.now_playing = None # userid -> Setlist self.setlists",
"= {} self.playlist_state = None self.autoplay = False def is_requester(self, user): return self.now_playing.requested_by",
"asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err): if state.autoplay: more",
"downloading video: {e}\") await ctx.send( \"There was an error downloading your video, sorry.\")",
"volume < 0: volume = 0 max_vol = self.config[\"max_volume\"] if max_vol > -1:",
"client = ctx.guild.voice_client state.volume = float(volume) / 100.0 client.source.volume = state.volume # update",
"or votes to skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for(",
"was an error downloading your video, sorry.\") return state.playlist.append(video) message = await ctx.send(",
"self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client = ctx.guild.voice_client",
"state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\")",
"= 0 max_vol = self.config[\"max_volume\"] if max_vol > -1: # check if max",
"it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): #",
"10 in advance if num >= 20: num = 20 for i in",
"async def in_voice_channel(ctx): \"\"\"Checks that the command sender is in the same voice",
"channel.connect() self._play_song(client, state, video) message = await ctx.send(\"\", embed=video.get_embed()) await self._add_reaction_controls(message) logging.info(f\"Now playing",
"async def jumpqueue(self, ctx, song: int, new_index: int): \"\"\"Moves song at an index",
"random # userid -> Setlist # copy from guild state, pops played songs",
"int): \"\"\"Change the volume of currently playing audio (values 0-250).\"\"\" state = self.get_state(ctx.guild)",
"self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that skip was pressed,",
"state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return if not state.playlist_state: await ctx.send(\"Playlist mode",
"volume to [0, max_vol] if volume > max_vol: volume = max_vol client =",
"url): \"\"\"Plays audio hosted at <url> (or performs a search for <url> and",
"don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if required_votes == 0:",
"if required_votes == 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to skip",
"<url> right now\") @commands.guild_only() async def playnow(self, ctx, *, url): client = ctx.guild.voice_client",
"ctx.send(\"\", embed=state.now_playing.get_embed()) await self._add_reaction_controls(message) @commands.command(aliases=[\"q\", \"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display",
"1 <= song <= len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song -",
"Holy crap absolutely don't expose this one to the public. @commands.command() @commands.guild_only() @commands.has_permissions(administrator=True)",
"_,v in self.user_setlists.items(): random.shuffle(v) # Get a list of <num> songs, increment play",
"for this guild if 1 <= song <= len(state.playlist) and 1 <= new_index:",
"if user != self.bot.user and message.author == self.bot.user: await message.remove_reaction(reaction, user) if message.guild",
"# TODO: rename to something better @commands.command(brief=\"TODO\") @commands.guild_only() async def build(self, ctx, *,",
"self.user_setlists.items(): random.shuffle(v) # Get a list of <num> songs, increment play times def",
"import request from ..video import Video from ..video import Setlist # TODO: abstract",
"await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing = song state.skip_votes = set()",
"describing a given song queue.\"\"\" if len(queue) > 0: message = [f\"{len(queue)} songs",
"the bot's messages, allowing reactions to control playback.\"\"\" message = reaction.message if user",
"your video, sorry.\") return state.playlist.insert(0, video) # TODO: probably make this admin-only, vote,",
"or state.is_requester(ctx.author): # immediately skip if requester or admin client.stop() elif self.config[\"vote_skip\"]: #",
"state, url) async def _play(self, ctx, client, state, url): if client and client.channel:",
"-reconnect_streamed 1 -reconnect_delay_max 5' \"\"\" Command line options to pass to `ffmpeg` before",
"member.bot ]) # don't count bots required_votes = math.ceil( self.config[\"vote_skip_ratio\"] * users_in_channel) if",
"valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def play(self, ctx, *, url):",
"if you build too much, so this needs to be reconsidered. # Maybe",
"audio hosted at <url> (or performs a search for <url> and plays the",
"client.channel and client.source: return True else: raise commands.CommandError(\"Not currently playing any audio.\") async",
"channel.\") @commands.command(aliases=[\"resume\", \"p\"]) @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) @commands.check(is_audio_requester) async def pause(self, ctx): \"\"\"Pauses any",
"= ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await self._play(ctx, client, state, state.playlist.pop(0).video_url)",
"if client and client.channel: await client.disconnect() state.playlist = [] state.now_playing = None else:",
"songs self.user_setlists = {u:v.copy() for u,v in setlists.items()} # TODO: probably make this",
"@commands.guild_only() async def autoplay(self, ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await",
"songs from each user's setlists for user,setlist in state.setlists.items(): temp += list(map(lambda x:",
"== \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and message.guild.voice_client.channel: # ensure that",
"to match @commands.command() @commands.guild_only() @commands.check(audio_playing) @commands.check(in_voice_channel) async def skip(self, ctx): \"\"\"Skips the currently",
"e: await ctx.send( \"There was an error downloading your video, sorry.\") return client",
"a vote for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\")",
"downloading your video, sorry.\") return state.playlist.insert(0, video) client.stop() @commands.command(brief=\"Register the playlist at <url>",
"ctx): \"\"\"Skips the currently playing song, or votes to skip it.\"\"\" state =",
"[] self.skip_votes = set() self.now_playing = None # userid -> Setlist self.setlists =",
"playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused(): client.resume() else:",
"new_index: song = state.playlist.pop(song - 1) # take song at index... state.playlist.insert(new_index -",
"for u,v in setlists.items()} # TODO: probably make this configurable self.target_length = 10",
"await self.bot.change_presence(activity=discord.Game(name=f\"♫ {song.title}\")) else: await self.bot.change_presence(activity=None) def _play_song(self, client, state, song): state.now_playing =",
"import heapq from urllib import request from ..video import Video from ..video import",
"used to control the bot.\"\"\" CONTROLS = [\"⏮\", \"⏯\", \"⏭\"] for control in",
"state = self.get_state(ctx.guild) if not state.setlists.items(): await ctx.send(\"No registered setlists, ignoring\") return client",
"performs a search for <url> and plays the first result).\"\"\" client = ctx.guild.voice_client",
"True else: raise commands.CommandError( \"You need to be the song requester to do",
"guild's state try: ret = f\"```{str(eval(url))[:1900]}```\" except Exception as e: ret = e",
"autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx):",
"setlists): # list((num, userid)) self.user_playtime = [(0, u) for u in setlists.keys()] random.shuffle(self.user_playtime)",
"f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in enumerate(queue) ] #",
"commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that the command sender",
"vote for `member` to skip the song playing.\"\"\" logging.info(f\"{member.name} votes to skip\") state",
"def clearqueue(self, ctx): \"\"\"Clears the play queue without leaving the channel.\"\"\" state =",
"async def build(self, ctx, *, num): try: num = int(num) if num <=",
"if currently in one.\"\"\" client = ctx.guild.voice_client state = self.get_state(ctx.guild) if client and",
"need to be the song requester to do that.\") class Music(commands.Cog): \"\"\"Bot commands",
"message = [f\"{len(queue)} songs in queue:\"] message += [ f\" {index+1}. **{song.title}** (requested",
"if 1 <= song <= len(state.playlist) and 1 <= new_index: song = state.playlist.pop(song",
"too much, so this needs to be reconsidered. # Maybe autoplay should be",
"{} self.bot.add_listener(self.on_reaction_add, \"on_reaction_add\") def get_state(self, guild): \"\"\"Gets the state for `guild`, creating it",
"ctx.send(text) def _queue_text(self, queue): \"\"\"Returns a block of text describing a given song",
"downloading your video, sorry.\") return client = await channel.connect() self._play_song(client, state, video) message",
"and message.guild.voice_client: user_in_channel = user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions =",
"set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume)",
"def after_playing(err): if state.autoplay: more = state.playlist_state.target_length - len(state.playlist) if more > 0:",
"at index... state.playlist.insert(new_index - 1, song) # and insert it. await ctx.send(self._queue_text(state.playlist)) else:",
"..video import Video from ..video import Setlist # TODO: abstract FFMPEG options into",
"state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop) asyncio.run_coroutine_threadsafe(self._set_status(), self.bot.loop) client.play(source, after=after_playing) @commands.command(aliases=[\"np\"]) @commands.guild_only()",
"required_votes == 0: required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes}",
"client.stop() @commands.command(brief=\"Register the playlist at <url> to the requesting user\") @commands.guild_only() async def",
"sorry.\") return state.playlist.insert(0, video) # TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop",
"\"\"\"Checks that the command sender is the song requester.\"\"\" music = ctx.bot.get_cog(\"Music\") state",
"queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only()",
"setlists, ignoring\") return client = ctx.guild.voice_client state.playlist_state = PlaylistState(state.setlists) state.playlist = state.playlist_state.get_num(num) await",
"a list of <num> songs, increment play times def get_num(self, num): ret =",
"max_vol = self.config[\"max_volume\"] if max_vol > -1: # check if max volume is",
"line options to pass to `ffmpeg` before the `-i`. See https://stackoverflow.com/questions/43218292/youtubedl-read-error-with-discord-py/44490434#44490434 for more",
"0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else:",
"commands.CommandError(\"You must use a valid index.\") @commands.command(brief=\"Plays audio from <url>.\") @commands.guild_only() async def",
"voice.channel == bot_voice.channel: return True else: raise commands.CommandError( \"You need to be in",
"skip ahead elif reaction.emoji == \"⏭\" and self.config[\"vote_skip\"] and user_in_channel and message.guild.voice_client and",
"return \"\\n\".join(message) else: return \"The play queue is empty.\" @commands.command(aliases=[\"cq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True)",
"if ctx.author.voice is not None and ctx.author.voice.channel is not None: channel = ctx.author.voice.channel",
"user setlists and generate a new queue\") @commands.guild_only() @commands.check(audio_playing) async def reshuffle(self, ctx):",
"the first song picked is random # userid -> Setlist # copy from",
"if volume > max_vol: volume = max_vol client = ctx.guild.voice_client state.volume = float(volume)",
"if (float(len(state.skip_votes)) / users_in_channel) >= self.config[\"vote_skip_ratio\"]: # enough members have voted to skip,",
"f\"{user.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) async def _add_reaction_controls(self, message): \"\"\"Adds a",
"the requesting user\") @commands.guild_only() async def setlist(self, ctx, *, url): client = ctx.guild.voice_client",
"message += [ f\" {index+1}. **{song.title}** (requested by **{song.requested_by.display_name}**)\" for (index, song) in",
"= self.get_state(guild) if permissions.administrator or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if",
"FFMPEG options into their own file? FFMPEG_BEFORE_OPTS = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max",
"not an integer greater than zero\") await self._build(ctx, num) async def _build(self, ctx,",
"required_votes = 1 await ctx.send( f\"{ctx.author.mention} voted to skip ({len(state.skip_votes)}/{required_votes} votes)\" ) else:",
"user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\": # pause audio",
"ctx): state = self.get_state(ctx.guild) state.autoplay = not state.autoplay await ctx.send(f\"Autoplay has been {'enabled'",
"Video from ..video import Setlist # TODO: abstract FFMPEG options into their own",
"async def _play(self, ctx, client, state, url): if client and client.channel: try: video",
"if max_vol > -1: # check if max volume is set # clamp",
"song, or votes to skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if",
"much, so this needs to be reconsidered. # Maybe autoplay should be the",
"== \"⏮\": state.playlist.insert( 0, state.now_playing ) # insert current song at beginning of",
"# insert current song at beginning of playlist client.stop() # skip ahead elif",
"to skip it.\"\"\" state = self.get_state(ctx.guild) client = ctx.guild.voice_client if ctx.channel.permissions_for( ctx.author).administrator or",
"clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(song.stream_url, before_options=FFMPEG_BEFORE_OPTS), volume=state.volume) def after_playing(err):",
"from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async def autoplay(self, ctx): state =",
"state = self.get_state(ctx.guild) # get the guild's state if url == \"remove\": del",
"setlists.items()} # TODO: probably make this configurable self.target_length = 10 # Shuffle each",
"and voice.channel == bot_voice.channel: return True else: raise commands.CommandError( \"You need to be",
"play queue without leaving the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"])",
"url): state = self.get_state(ctx.guild) # get the guild's state try: ret = f\"```{str(eval(url))[:1900]}```\"",
"more information. Also, https://ffmpeg.org/ffmpeg-protocols.html for command line option reference. \"\"\" async def audio_playing(ctx):",
"= ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel",
"any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def _pause_audio(self, client): if client.is_paused():",
"({len(state.skip_votes)}/{required_votes} votes)\" ) else: raise commands.CommandError(\"Sorry, vote skipping is disabled.\") def _vote_skip(self, channel,",
"if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song) else: asyncio.run_coroutine_threadsafe(client.disconnect(), self.bot.loop)",
"state.autoplay await ctx.send(f\"Autoplay has been {'enabled' if state.autoplay else 'disabled'}\") if state.autoplay and",
"def pause(self, ctx): \"\"\"Pauses any currently playing audio.\"\"\" client = ctx.guild.voice_client self._pause_audio(client) def",
"await self._play(ctx, client, state, url) async def _play(self, ctx, client, state, url): if",
"configurable self.target_length = 10 # Shuffle each setlist so we can always just",
"vote channel = message.channel users_in_channel = len([ member for member in voice_channel.members if",
"song state.skip_votes = set() # clear skip votes asyncio.run_coroutine_threadsafe(self._set_status(song=song), self.bot.loop) source = discord.PCMVolumeTransformer(",
"\"playlist\"]) @commands.guild_only() @commands.check(audio_playing) async def queue(self, ctx): \"\"\"Display the current play queue.\"\"\" state",
"# vote to skip song channel = client.channel self._vote_skip(channel, ctx.author) # announce vote",
"does not exist.\"\"\" if guild.id in self.states: return self.states[guild.id] else: self.states[guild.id] = GuildState()",
"ctx.send(f\"Playlist registered for {ctx.author.display_name}\") #self._shuffle_setlists(state, client) #await self._play(ctx, client, state, state.playlist.pop(0).video_url) # Shuffle",
"video) # TODO: probably make this admin-only, vote, etc @commands.command(brief=\"Stop the current song",
"True else: raise commands.CommandError(\"Not currently playing any audio.\") async def in_voice_channel(ctx): \"\"\"Checks that",
"activated, use !build to start\") return state.playlist += state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from",
"client = ctx.guild.voice_client state = self.get_state(ctx.guild) # get the guild's state await ctx.send(\"Regenerating",
"to reactions added to the bot's messages, allowing reactions to control playback.\"\"\" message",
"ctx.channel.permissions_for( ctx.author).administrator or state.is_requester(ctx.author): # immediately skip if requester or admin client.stop() elif",
"in self.user_setlists.items(): random.shuffle(v) # Get a list of <num> songs, increment play times",
"> 0: state.playlist.append(state.playlist_state.get_num(more)) if len(state.playlist) > 0: next_song = state.playlist.pop(0) self._play_song(client, state, next_song)",
"to the requesting user\") @commands.guild_only() async def setlist(self, ctx, *, url): client =",
"commands.CommandError( \"You need to be the song requester to do that.\") class Music(commands.Cog):",
"user.voice and user.voice.channel and user.voice.channel == message.guild.voice_client.channel permissions = message.channel.permissions_for(user) guild = message.guild",
"= message.guild.voice_client.channel self._vote_skip(voice_channel, user) # announce vote channel = message.channel users_in_channel = len([",
"max_vol > -1: # check if max volume is set # clamp volume",
"the channel.\"\"\" state = self.get_state(ctx.guild) state.playlist = [] @commands.command(aliases=[\"jq\"]) @commands.guild_only() @commands.check(audio_playing) @commands.has_permissions(administrator=True) async",
"playlist when a user's runs out video = self.user_setlists[userid].pop(0) video = Video(video, self.user_setlists[userid].requester)",
"+= state.playlist_state.get_num(num) @commands.command(brief=\"Toggle autoplay mode from registered setlists\", aliases=[\"a\", \"ap\", \"yolo\"]) @commands.guild_only() async",
"permissions.administrator or ( user_in_channel and state.is_requester(user)): client = message.guild.voice_client if reaction.emoji == \"⏯\":",
"was an error downloading your video, sorry.\") return client = await channel.connect() self._play_song(client,"
] |
[
"'Operation in progress', -6: 'Illegal value', -7: 'Operation would block', -8: 'Address in",
"memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation in progress',",
"reset', -15: 'Connection closed', -16: 'Illegal argument', } def __init__(self, code): self._code =",
"-1: 'Out of memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5:",
"-11: 'Not connected', -12: 'Low level interface error', -13: 'Connection aborted', -14: 'Connection",
"-3: 'Timeout', -4: 'Routing problem', -5: 'Operation in progress', -6: 'Illegal value', -7:",
"progress', -6: 'Illegal value', -7: 'Operation would block', -8: 'Address in use', -9:",
"interface error', -13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal",
"self._code = code def __str__(self): return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException):",
"'Connection aborted', -14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal argument', } def",
"'Low level interface error', -13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection closed',",
"def __str__(self): return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error",
"codes.\"\"\" _mapping = { -1: 'Out of memory', -2: 'Buffer error', -3: 'Timeout',",
"-14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal argument', } def __init__(self, code):",
"-5: 'Operation in progress', -6: 'Illegal value', -7: 'Operation would block', -8: 'Address",
"-9: 'Already connecting', -10: 'Connection already established', -11: 'Not connected', -12: 'Low level",
"'Connection reset', -15: 'Connection closed', -16: 'Illegal argument', } def __init__(self, code): self._code",
"error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation in progress', -6: 'Illegal value',",
"= { -1: 'Out of memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing",
"connected', -12: 'Low level interface error', -13: 'Connection aborted', -14: 'Connection reset', -15:",
"'Illegal argument', } def __init__(self, code): self._code = code def __str__(self): return self._mapping[self._code]",
"-7: 'Operation would block', -8: 'Address in use', -9: 'Already connecting', -10: 'Connection",
"get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\" def",
"-2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation in progress', -6:",
"representing lwip error codes.\"\"\" _mapping = { -1: 'Out of memory', -2: 'Buffer",
"class StackException(Exception): \"\"\"Base class for stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error",
"code): self._code = code def __str__(self): return self._mapping[self._code] def get_code(self): return self._code class",
"-16: 'Illegal argument', } def __init__(self, code): self._code = code def __str__(self): return",
"'Address in use', -9: 'Already connecting', -10: 'Connection already established', -11: 'Not connected',",
"would block', -8: 'Address in use', -9: 'Already connecting', -10: 'Connection already established',",
"already established', -11: 'Not connected', -12: 'Low level interface error', -13: 'Connection aborted',",
"__str__(self): return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error in",
"'Connection already established', -11: 'Not connected', -12: 'Low level interface error', -13: 'Connection",
"} def __init__(self, code): self._code = code def __str__(self): return self._mapping[self._code] def get_code(self):",
"'Already connecting', -10: 'Connection already established', -11: 'Not connected', -12: 'Low level interface",
"'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation in progress', -6: 'Illegal",
"AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\" def __str__(self): return 'Allocation failed'",
"closed', -16: 'Illegal argument', } def __init__(self, code): self._code = code def __str__(self):",
"'Connection closed', -16: 'Illegal argument', } def __init__(self, code): self._code = code def",
"use', -9: 'Already connecting', -10: 'Connection already established', -11: 'Not connected', -12: 'Low",
"-4: 'Routing problem', -5: 'Operation in progress', -6: 'Illegal value', -7: 'Operation would",
"_mapping = { -1: 'Out of memory', -2: 'Buffer error', -3: 'Timeout', -4:",
"value', -7: 'Operation would block', -8: 'Address in use', -9: 'Already connecting', -10:",
"self._code class AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\" def __str__(self): return",
"connecting', -10: 'Connection already established', -11: 'Not connected', -12: 'Low level interface error',",
"class for stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping =",
"in progress', -6: 'Illegal value', -7: 'Operation would block', -8: 'Address in use',",
"for stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping = {",
"stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping = { -1:",
"def __init__(self, code): self._code = code def __str__(self): return self._mapping[self._code] def get_code(self): return",
"StackException(Exception): \"\"\"Base class for stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\"",
"class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping = { -1: 'Out of",
"in use', -9: 'Already connecting', -10: 'Connection already established', -11: 'Not connected', -12:",
"'Routing problem', -5: 'Operation in progress', -6: 'Illegal value', -7: 'Operation would block',",
"argument', } def __init__(self, code): self._code = code def __str__(self): return self._mapping[self._code] def",
"\"\"\"Class representing lwip error codes.\"\"\" _mapping = { -1: 'Out of memory', -2:",
"\"\"\"Base class for stack-related exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping",
"class AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\" def __str__(self): return 'Allocation",
"-13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal argument', }",
"exceptions.\"\"\" class LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping = { -1: 'Out",
"-12: 'Low level interface error', -13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection",
"'Operation would block', -8: 'Address in use', -9: 'Already connecting', -10: 'Connection already",
"'Timeout', -4: 'Routing problem', -5: 'Operation in progress', -6: 'Illegal value', -7: 'Operation",
"'Out of memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation",
"'Illegal value', -7: 'Operation would block', -8: 'Address in use', -9: 'Already connecting',",
"problem', -5: 'Operation in progress', -6: 'Illegal value', -7: 'Operation would block', -8:",
"def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\"",
"self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error in stack memory",
"LwipError(StackException): \"\"\"Class representing lwip error codes.\"\"\" _mapping = { -1: 'Out of memory',",
"code def __str__(self): return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing",
"-8: 'Address in use', -9: 'Already connecting', -10: 'Connection already established', -11: 'Not",
"{ -1: 'Out of memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem',",
"-10: 'Connection already established', -11: 'Not connected', -12: 'Low level interface error', -13:",
"__init__(self, code): self._code = code def __str__(self): return self._mapping[self._code] def get_code(self): return self._code",
"return self._code class AllocationError(StackException): \"\"\"Class representing error in stack memory allocation.\"\"\" def __str__(self):",
"established', -11: 'Not connected', -12: 'Low level interface error', -13: 'Connection aborted', -14:",
"error', -13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal argument',",
"error codes.\"\"\" _mapping = { -1: 'Out of memory', -2: 'Buffer error', -3:",
"level interface error', -13: 'Connection aborted', -14: 'Connection reset', -15: 'Connection closed', -16:",
"of memory', -2: 'Buffer error', -3: 'Timeout', -4: 'Routing problem', -5: 'Operation in",
"lwip error codes.\"\"\" _mapping = { -1: 'Out of memory', -2: 'Buffer error',",
"'Not connected', -12: 'Low level interface error', -13: 'Connection aborted', -14: 'Connection reset',",
"-15: 'Connection closed', -16: 'Illegal argument', } def __init__(self, code): self._code = code",
"-6: 'Illegal value', -7: 'Operation would block', -8: 'Address in use', -9: 'Already",
"return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class representing error in stack",
"= code def __str__(self): return self._mapping[self._code] def get_code(self): return self._code class AllocationError(StackException): \"\"\"Class",
"aborted', -14: 'Connection reset', -15: 'Connection closed', -16: 'Illegal argument', } def __init__(self,",
"block', -8: 'Address in use', -9: 'Already connecting', -10: 'Connection already established', -11:"
] |
[
"form): application = form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args, **kwargs):",
"**kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self,",
"1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page +",
"'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1, total_pages),",
"8* 9 Next - and current is last --> Previous 1 ... 7",
"get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text or",
"1 ... 7 8* 9 ... Next - and current is penultimate -->",
"3* 4 ... Next - and current is somewhere in the middle -->",
"'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page,",
"f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page':",
"'page': 4}) if current_page == total_pages: pages.pop(-1) # Insert start \"...\" if current_page",
"'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if",
"+ 1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page })",
"super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,))",
"= { 'previous': { 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page - 1,",
"pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}',",
"and current is page 1 --> Previous 1* 2 3 4 ... Next",
"\"\"\" :return: Any of: - 1 page --> None (no pagination) - 6",
"'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def",
"pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page ==",
"if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data",
"{ 'text': self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name",
"except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self,",
"class SaveStateMixin: success_url_name = None def save_state(self, form): application = form.instance application.state_url_name =",
"3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page':",
"current_page, total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages,",
"(no pagination) - 6 pages or fewer --> Previous 1 2 3 4",
"8* 9 ... Next - and current is penultimate --> Previous 1 ...",
"'...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError:",
"import reverse from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ class",
"'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\" if current_page <=",
"f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages",
"--> Previous 1 2 3 4 5 6 Next - 7 pages or",
"total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'],",
"'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}',",
"must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for i",
"Next - and current is last --> Previous 1 ... 7 8 9*",
"back_text = None back_url = None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self,",
"2 --> Previous 1 2* 3 4 ... Next - and current is",
"get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def",
"9 ... Next - and current is penultimate --> Previous 1 ... 7",
"Previous 1 ... 7 8* 9 ... Next - and current is penultimate",
"data mixin for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return '' def",
"- and current is last --> Previous 1 ... 7 8 9* Next",
"def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self): raise",
"return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self, form): application = form.instance",
"fewer --> Previous 1 2 3 4 5 6 Next - 7 pages",
"current_page == total_pages: pages.pop(-1) # Insert start \"...\" if current_page > 3: pages.insert(1,",
"reverse from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ class BackContextMixin:",
"args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if",
"def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page':",
"{'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}',",
"{ 'previous': { 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}'",
"PaginationMixin: \"\"\" Pagination data mixin for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self):",
"self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page,",
"overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for i in range(1,",
"def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif",
"pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params):",
"if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) #",
"self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'), 'url':",
"args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for views \"\"\"",
"current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i})",
"'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page",
"- and current is page 1 --> Previous 1* 2 3 4 ...",
"= None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class",
"if current_page <= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis",
"... 7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params",
"pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2:",
"import urlencode from django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text = None",
"return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for",
"== total_pages: pages.pop(-1) # Insert start \"...\" if current_page > 3: pages.insert(1, {",
"import gettext_lazy as _ class BackContextMixin: back_text = None back_url = None def",
"is last --> Previous 1 ... 7 8 9* Next \"\"\" total_pages =",
"f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page':",
"4 ... Next - and current is page 2 --> Previous 1 2*",
"_ class BackContextMixin: back_text = None back_url = None def get_back_url(self): if hasattr(self,",
"class BackContextMixin: back_text = None back_url = None def get_back_url(self): if hasattr(self, 'back_url_name')",
"'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs):",
"ellipsis = '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1))",
"mixin for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self):",
"# Insert start \"...\" if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots',",
"get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination",
"current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0)",
"Previous 1 2* 3 4 ... Next - and current is page 3",
"current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert",
"<filename>frontend/web/core/view_mixins.py from django.urls import reverse from django.utils.http import urlencode from django.utils.translation import gettext_lazy",
">= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination",
"page 1 --> Previous 1* 2 3 4 ... Next - and current",
"get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages()",
"[] for i in range(1, total_pages + 1): if i == current_page: pages.append({",
"extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination = { 'previous':",
"total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1 < total_pages <=",
"'page': max(current_page - 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': {",
"extra_href_params ) elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'],",
"kwargs['back'] = { 'text': self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class",
"range(1, total_pages + 1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text':",
"3 --> Previous 1 2 3* 4 ... Next - and current is",
"7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params =",
"Previous 1* 2 3 4 ... Next - and current is page 2",
"1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page",
"4}) if current_page == total_pages: pages.pop(-1) # Insert start \"...\" if current_page >",
"int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.')",
"{ 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } }",
"{'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text':",
"\"...\" if current_page <= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text':",
"hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return",
":return: Any of: - 1 page --> None (no pagination) - 6 pages",
"django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text = None back_url = None",
"self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form, *args, **kwargs) self.save_state(form)",
"3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\"",
"... Next - and current is page 2 --> Previous 1 2* 3",
"1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1,",
"f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if",
"and current is penultimate --> Previous 1 ... 7 8* 9 Next -",
"None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,))",
"def save_state(self, form): application = form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form,",
"page --> None (no pagination) - 6 pages or fewer --> Previous 1",
"'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages",
"6 pages or fewer --> Previous 1 2 3 4 5 6 Next",
"return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for views \"\"\" ellipsis",
"'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self): \"\"\" :return: Any",
"1 2 3 4 5 6 Next - 7 pages or more -",
"previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page':",
"= self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self, form): application",
"--> Previous 1 ... 7 8* 9 Next - and current is last",
"pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4})",
"self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'), 'url': self.back_url }",
"2 3 4 ... Next - and current is page 2 --> Previous",
"current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4})",
"= urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination = { 'previous': {",
"hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self): \"\"\" :return: Any of: -",
"of: - 1 page --> None (no pagination) - 6 pages or fewer",
"1 2 3* 4 ... Next - and current is somewhere in the",
"total_pages + 1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page",
"getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self,",
"get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return 1",
"{ 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self): \"\"\" :return:",
"pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class':",
"next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href':",
"and current is page 3 --> Previous 1 2 3* 4 ... Next",
"pages def get_pagination(self): \"\"\" :return: Any of: - 1 page --> None (no",
"= self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs):",
"if 1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params )",
"_('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self):",
"previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ]",
"pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages'] =",
"'text': self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name =",
"7 pages or more - and current is page 1 --> Previous 1*",
"get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages =",
"Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages",
"1* 2 3 4 ... Next - and current is page 2 -->",
"Previous 1 ... 7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page =",
"else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page,",
"application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form, *args,",
"2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1) # Insert",
"{ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if",
"page 2 --> Previous 1 2* 3 4 ... Next - and current",
"self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination']",
"\"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and",
"for i in range(1, total_pages + 1): if i == current_page: pages.append({ 'class':",
"== current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page':",
"if current_page == total_pages: pages.pop(-1) # Insert start \"...\" if current_page > 3:",
"1 page --> None (no pagination) - 6 pages or fewer --> Previous",
"\"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page',",
"if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages:",
"current_page, total_pages, extra_href_params): pages = [] for i in range(1, total_pages + 1):",
"django.urls import reverse from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _",
"- and current is penultimate --> Previous 1 ... 7 8* 9 Next",
"somewhere in the middle --> Previous 1 ... 7 8* 9 ... Next",
"'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1: pages.pop(1)",
"min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1",
"= self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination =",
"- and current is page 3 --> Previous 1 2 3* 4 ...",
"def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for i in range(1, total_pages",
"pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1) # Insert start \"...\"",
"2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self):",
"total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages",
"2 3 4 5 6 Next - 7 pages or more - and",
"5 6 Next - 7 pages or more - and current is page",
"- 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page",
"None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin:",
"def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return",
"page 3 --> Previous 1 2 3* 4 ... Next - and current",
"--> Previous 1* 2 3 4 ... Next - and current is page",
"'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] =",
"as _ class BackContextMixin: back_text = None back_url = None def get_back_url(self): if",
"total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >=",
"def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\"",
"try: return int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must",
"pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self): \"\"\"",
"self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs)",
"def get_pagination(self): \"\"\" :return: Any of: - 1 page --> None (no pagination)",
"current_page <= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis })",
"get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self,",
"self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin",
"**kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'),",
"= '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except",
"\"\"\" Pagination data mixin for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return",
"4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page ==",
"gettext_lazy as _ class BackContextMixin: back_text = None back_url = None def get_back_url(self):",
"total_pages, extra_href_params): pages = [] for i in range(1, total_pages + 1): if",
"2 3* 4 ... Next - and current is somewhere in the middle",
"pages.pop(-1) # Insert start \"...\" if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item",
"hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self,",
"last --> Previous 1 ... 7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages()",
"from django.urls import reverse from django.utils.http import urlencode from django.utils.translation import gettext_lazy as",
"self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None",
"'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if",
"= self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'), 'url': self.back_url",
"Insert end \"...\" if current_page <= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item",
"current is page 2 --> Previous 1 2* 3 4 ... Next -",
"> 1: pagination = { 'previous': { 'page': max(current_page - 1, 1), 'href':",
"class PaginationMixin: \"\"\" Pagination data mixin for views \"\"\" ellipsis = '...' def",
"1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page +",
"pagination) - 6 pages or fewer --> Previous 1 2 3 4 5",
"i in range(1, total_pages + 1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item",
"} } if 1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages,",
"total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages",
"}, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href':",
"current is page 1 --> Previous 1* 2 3 4 ... Next -",
"SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name,",
"urlencode from django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text = None back_url",
"None (no pagination) - 6 pages or fewer --> Previous 1 2 3",
"} return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return",
"return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url =",
"Any of: - 1 page --> None (no pagination) - 6 pages or",
"Previous 1 2 3* 4 ... Next - and current is somewhere in",
"or more - and current is page 1 --> Previous 1* 2 3",
"3 4 ... Next - and current is page 2 --> Previous 1",
"extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, {",
"return pages def get_pagination(self): \"\"\" :return: Any of: - 1 page --> None",
"4 ... Next - and current is page 3 --> Previous 1 2",
"f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1, total_pages), 'href':",
"= [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item",
"return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = {",
"i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages = [",
"= form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid =",
"... 7 8* 9 Next - and current is last --> Previous 1",
"django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text =",
"1 --> Previous 1* 2 3 4 ... Next - and current is",
"elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url:",
"Next - 7 pages or more - and current is page 1 -->",
"in the middle --> Previous 1 ... 7 8* 9 ... Next -",
"super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self, form): application = form.instance application.state_url_name",
"f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page",
"and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def",
"is somewhere in the middle --> Previous 1 ... 7 8* 9 ...",
"is page 2 --> Previous 1 2* 3 4 ... Next - and",
"Previous 1 ... 7 8* 9 Next - and current is last -->",
"is page 1 --> Previous 1* 2 3 4 ... Next - and",
"args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for views \"\"\" ellipsis = '...'",
"def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = { 'text': self.back_text",
"save_state(self, form): application = form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args,",
"'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages =",
"None def save_state(self, form): application = form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self,",
"7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def",
"the middle --> Previous 1 ... 7 8* 9 ... Next - and",
"start \"...\" if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis",
"elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params )",
"hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page == 1:",
"pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1) # Insert start",
"get_pagination(self): \"\"\" :return: Any of: - 1 page --> None (no pagination) -",
") elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params",
"def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None",
"pagination = { 'previous': { 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page -",
"--> Previous 1 ... 7 8* 9 ... Next - and current is",
"reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for views",
"SaveStateMixin: success_url_name = None def save_state(self, form): application = form.instance application.state_url_name = self.success_url_name",
"or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def",
"pages or more - and current is page 1 --> Previous 1* 2",
"... Next - and current is somewhere in the middle --> Previous 1",
"i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}',",
"== 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1) #",
"success_url_name = None def save_state(self, form): application = form.instance application.state_url_name = self.success_url_name application.save()",
"9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if",
"self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1:",
"2* 3 4 ... Next - and current is page 3 --> Previous",
"'' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self):",
"class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return",
"'previous': { 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' },",
"reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url()",
"hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back']",
"max(current_page - 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page':",
"= [] for i in range(1, total_pages + 1): if i == current_page:",
"'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name)",
"> 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end",
"= self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form, *args, **kwargs)",
"current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination",
"<= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return",
"1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1,",
"3 4 ... Next - and current is page 3 --> Previous 1",
"return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review',",
"extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class",
"raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = []",
"3 4 5 6 Next - 7 pages or more - and current",
"} if 1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params",
"return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages = [ {'href':",
"current is page 3 --> Previous 1 2 3* 4 ... Next -",
"8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params())",
"- and current is page 2 --> Previous 1 2* 3 4 ...",
"= self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages(",
"1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif",
"'next': { 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' }",
"def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form, *args, **kwargs) self.save_state(form) return form_valid",
"middle --> Previous 1 ... 7 8* 9 ... Next - and current",
"= None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name,",
"... Next - and current is penultimate --> Previous 1 ... 7 8*",
"1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1 < total_pages",
"'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1 < total_pages <= 6:",
"self.ellipsis }) return pages def get_pagination(self): \"\"\" :return: Any of: - 1 page",
"'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page",
"from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text",
"pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs)",
"1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href':",
"<= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >= 7:",
"}) return pages def get_pagination(self): \"\"\" :return: Any of: - 1 page -->",
"Insert start \"...\" if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text':",
"'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page}, ] if current_page ==",
"f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1 < total_pages <= 6: pagination['pages']",
"if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page':",
"\"...\" if current_page > 3: pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis })",
"current_page, total_pages, previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href':",
"self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination = {",
"6 Next - 7 pages or more - and current is page 1",
"total_pages >= 7: pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return",
"'text': self.ellipsis }) return pages def get_pagination(self): \"\"\" :return: Any of: - 1",
"== 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if",
"1)) except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def",
"}) # Insert end \"...\" if current_page <= total_pages - 2: pages.insert(len(pages), {",
"current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages,",
"self.ellipsis }) # Insert end \"...\" if current_page <= total_pages - 2: pages.insert(len(pages),",
"= self.get_pagination_total_pages() current_page = self.get_current_page() extra_href_params = urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages >",
"total_pages, previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}',",
"Next - and current is page 2 --> Previous 1 2* 3 4",
"is page 3 --> Previous 1 2 3* 4 ... Next - and",
"... 7 8* 9 ... Next - and current is penultimate --> Previous",
"--> Previous 1 2 3* 4 ... Next - and current is somewhere",
"{ 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\" if current_page",
"self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin: success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page:",
"--> None (no pagination) - 6 pages or fewer --> Previous 1 2",
"= None def save_state(self, form): application = form.instance application.state_url_name = self.success_url_name application.save() def",
"application = form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid",
"for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try:",
"reverse(self.success_url_name, args=(self.object.pk,)) class PaginationMixin: \"\"\" Pagination data mixin for views \"\"\" ellipsis =",
"in range(1, total_pages + 1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active',",
"total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination()",
"and current is somewhere in the middle --> Previous 1 ... 7 8*",
"is penultimate --> Previous 1 ... 7 8* 9 Next - and current",
"pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name =",
"def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages",
"ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page,",
"1 ... 7 8* 9 Next - and current is last --> Previous",
"and current is page 2 --> Previous 1 2* 3 4 ... Next",
"None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'): return reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url",
"# Insert end \"...\" if current_page <= total_pages - 2: pages.insert(len(pages), { 'class':",
"- and current is somewhere in the middle --> Previous 1 ... 7",
"Next - and current is page 3 --> Previous 1 2 3* 4",
"- 1, 1)}&{extra_href_params}' }, 'next': { 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page",
"pages.insert(1, { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\" if",
"return int(self.request.GET.get('page', 1)) except ValueError: return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be",
"if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return reverse(self.back_url_name, args=(self.object.pk,)) elif hasattr(self, 'back_url_name'):",
"current is penultimate --> Previous 1 ... 7 8* 9 Next - and",
"'page': next_page}, ] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3})",
"end \"...\" if current_page <= total_pages - 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots',",
"f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1) # Insert start \"...\" if",
"... Next - and current is page 3 --> Previous 1 2 3*",
"total_pages)}&{extra_href_params}' } } if 1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page,",
"'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def get_pagination(self): \"\"\" :return: Any of:",
"self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self, form): application =",
"= { 'text': self.back_text or _('Back'), 'url': self.back_url } return super().get_context_data(**kwargs) class SuccessUrlObjectPkMixin:",
"more - and current is page 1 --> Previous 1* 2 3 4",
"current_page == 2: pages.pop(1) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == total_pages: pages.pop(-1)",
"if self.back_url: kwargs['back'] = { 'text': self.back_text or _('Back'), 'url': self.back_url } return",
"--> Previous 1 2* 3 4 ... Next - and current is page",
"{ 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page - 1, 1)}&{extra_href_params}' }, 'next':",
"current is somewhere in the middle --> Previous 1 ... 7 8* 9",
"f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1) pages.append({'href':",
"urlencode(self.get_extra_pagination_href_params()) if total_pages and total_pages > 1: pagination = { 'previous': { 'page':",
"- 6 pages or fewer --> Previous 1 2 3 4 5 6",
"hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\" if current_page <= total_pages -",
"Previous 1 2 3 4 5 6 Next - 7 pages or more",
"< total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages",
"application.save() def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form, *args, **kwargs) self.save_state(form) return",
"}) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return pages def get_dotted_pagination_pages(self, current_page, total_pages, previous_page,",
"1, total_pages)}&{extra_href_params}' } } if 1 < total_pages <= 6: pagination['pages'] = self.get_basic_pagination_pages(",
"4 5 6 Next - 7 pages or more - and current is",
"+ 1, total_pages)}&{extra_href_params}' } } if 1 < total_pages <= 6: pagination['pages'] =",
"--> Previous 1 ... 7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page",
"total_pages > 1: pagination = { 'previous': { 'page': max(current_page - 1, 1),",
"- 7 pages or more - and current is page 1 --> Previous",
"and total_pages > 1: pagination = { 'previous': { 'page': max(current_page - 1,",
"kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name = None def save_state(self, form):",
"Next - and current is somewhere in the middle --> Previous 1 ...",
"pages = [] for i in range(1, total_pages + 1): if i ==",
"current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination'] =",
"pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href': f'?page={i}&{extra_href_params}', 'page': i}) return",
"if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else: pages.append({'href':",
"from django.utils.translation import gettext_lazy as _ class BackContextMixin: back_text = None back_url =",
") return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin:",
"+ 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}' } } if 1 <",
"return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return super().get_context_data(**kwargs) class SaveStateMixin: success_url_name",
"'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page },",
"}, 'next': { 'page': min(current_page + 1, total_pages), 'href': f'?page={min(current_page + 1, total_pages)}&{extra_href_params}'",
"'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) # Insert end \"...\" if current_page <= total_pages",
"7 8* 9 ... Next - and current is penultimate --> Previous 1",
"back_url = None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None): return",
"9 Next - and current is last --> Previous 1 ... 7 8",
"- 2: pages.insert(len(pages), { 'class': 'hmcts-pagination__item hmcts-pagination__item--dots', 'text': self.ellipsis }) return pages def",
"total_pages: pages.pop(-1) # Insert start \"...\" if current_page > 3: pages.insert(1, { 'class':",
"4 ... Next - and current is somewhere in the middle --> Previous",
"views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return '' def get_current_page(self): try: return",
"or fewer --> Previous 1 2 3 4 5 6 Next - 7",
"Next - and current is penultimate --> Previous 1 ... 7 8* 9",
"total_pages and total_pages > 1: pagination = { 'previous': { 'page': max(current_page -",
"6: pagination['pages'] = self.get_basic_pagination_pages( current_page, total_pages, extra_href_params ) elif total_pages >= 7: pagination['pages']",
"pages or fewer --> Previous 1 2 3 4 5 6 Next -",
"] if current_page == 1: pages.pop(1) pages.pop(0) pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}',",
"1: pagination = { 'previous': { 'page': max(current_page - 1, 1), 'href': f'?page={max(current_page",
"pages.append({'href': f'?page=3&{extra_href_params}', 'page': 3}) pages.append({'href': f'?page=4&{extra_href_params}', 'page': 4}) if current_page == 2: pages.pop(1)",
"'text': self.ellipsis }) # Insert end \"...\" if current_page <= total_pages - 2:",
"None back_url = None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object', None):",
"and current is last --> Previous 1 ... 7 8 9* Next \"\"\"",
"NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for",
"- 1 page --> None (no pagination) - 6 pages or fewer -->",
"1 ... 7 8 9* Next \"\"\" total_pages = self.get_pagination_total_pages() current_page = self.get_current_page()",
"get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for i in range(1, total_pages +",
"penultimate --> Previous 1 ... 7 8* 9 Next - and current is",
"next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page},",
"return 1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages,",
"{'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}',",
"1 def get_pagination_total_pages(self): raise NotImplementedError('.get_pagination_total_pages() must be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params):",
"return '' def get_current_page(self): try: return int(self.request.GET.get('page', 1)) except ValueError: return 1 def",
"pagination['pages'] = self.get_dotted_pagination_pages( current_page, total_pages, pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self,",
"'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }, {'href': f'?page={next_page}&{extra_href_params}', 'page': next_page},",
"get_dotted_pagination_pages(self, current_page, total_pages, previous_page, next_page, extra_href_params): pages = [ {'href': f'?page=1&{extra_href_params}', 'page': 1},",
"pagination['previous']['page'], pagination['next']['page'], extra_href_params ) return pagination def get_context_data(self, **kwargs): kwargs['pagination'] = self.get_pagination() return",
"1): if i == current_page: pages.append({ 'class': 'hmcts-pagination__item hmcts-pagination__item--active', 'text': current_page }) else:",
"7 8* 9 Next - and current is last --> Previous 1 ...",
"reverse(self.back_url_name) def get_context_data(self, **kwargs): self.back_url = self.get_back_url() if self.back_url: kwargs['back'] = { 'text':",
"= None back_url = None def get_back_url(self): if hasattr(self, 'back_url_name') and getattr(self, 'object',",
"extra_href_params): pages = [] for i in range(1, total_pages + 1): if i",
"Pagination data mixin for views \"\"\" ellipsis = '...' def get_extra_pagination_href_params(self): return ''",
"form.instance application.state_url_name = self.success_url_name application.save() def form_valid(self, form, *args, **kwargs): form_valid = super().form_valid(form,",
"1 2* 3 4 ... Next - and current is page 3 -->",
"be overridden.') def get_basic_pagination_pages(self, current_page, total_pages, extra_href_params): pages = [] for i in",
"success_url_name = None def get_success_url(self): if self.object.has_viewed_review_page: return reverse('grant-applications:application-review', args=(self.object.pk,)) return reverse(self.success_url_name, args=(self.object.pk,))",
"current is last --> Previous 1 ... 7 8 9* Next \"\"\" total_pages",
"if total_pages and total_pages > 1: pagination = { 'previous': { 'page': max(current_page",
"BackContextMixin: back_text = None back_url = None def get_back_url(self): if hasattr(self, 'back_url_name') and",
"[ {'href': f'?page=1&{extra_href_params}', 'page': 1}, {'href': f'?page={previous_page}&{extra_href_params}', 'page': previous_page}, { 'class': 'hmcts-pagination__item hmcts-pagination__item--active',"
] |
[
"DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False app_config = { 'development': DevelopmentConfig,",
"<gh_stars>0 # config.py import os basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True",
"= '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False app_config",
"PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False",
"USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig):",
"class ProductionConfig(BaseConfig): DEBUG = False app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig }",
"+ os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME =",
"# 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py",
"os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS =",
"= True class ProductionConfig(BaseConfig): DEBUG = False app_config = { 'development': DevelopmentConfig, 'production':",
"'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME",
"or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False",
"'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD",
"= 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG",
"os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie'",
"= True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or",
"'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class",
"# FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True",
"class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI",
"SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt'",
"SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig):",
"= <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///'",
"DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')",
"= 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>'",
"SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir,",
"False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG =",
"BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI =",
"= os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS",
"os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' #",
"= False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG",
"os basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI",
"import os basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>'",
"basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI =",
"True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\",
"SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False # FLASK_APP=run.py USERNAME = 'ablie' PASSWORD =",
"'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT",
"'<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False app_config =",
"config.py import os basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY =",
"SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ #",
"True class ProductionConfig(BaseConfig): DEBUG = False app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig",
"class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False app_config = {",
"'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG =",
"\\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT = 'bcrypt' SQLALCHEMY_TRACK_MODIFICATIONS = False #",
"<KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' +",
"= os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY = <KEY>' SQLALCHEMY_DATABASE_URI = 'mysql://username:password@localhost/mitdb'",
"= 'mysql://username:password@localhost/mitdb' # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db')",
"DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False app_config = { 'development':",
"FLASK_APP=run.py USERNAME = 'ablie' PASSWORD = '<PASSWORD>' class DevelopmentConfig(BaseConfig): DEBUG = True class",
"# config.py import os basedir = os.path.abspath((os.path.dirname(__file__))) class BaseConfig(object): DEBUG = True SECRET_KEY",
"# SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\ # 'sqlite:///' + os.path.join(basedir, 'app.db') SECURITY_PASSWORD_SALT ="
] |
[
"glyph collection but no subsetted glyphs. For instance, a PDF can say “please",
"\"\"\"The AAT ``cidg`` table has almost the same structure as ``gidc``, just mapping",
"if the font is, say, a TrueType font. ``gidc`` is lossy for this",
"class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the same structure as ``gidc``,",
"use a font conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the",
"lossy for this purpose and is obsoleted by ``cidg``. For example, the first",
"PDF can say “please use a font conforming to Adobe-Japan-1”; the ``cidg`` mapping",
"of the reverse direction. It is useful for fonts that may be used",
"same structure as ``gidc``, just mapping CIDs to GlyphIDs instead of the reverse",
"coding: utf-8 from .otBase import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has",
"``gidc``, just mapping CIDs to GlyphIDs instead of the reverse direction. It is",
"``cidg`` mapping is necessary if the font is, say, a TrueType font. ``gidc``",
"fonts that may be used by a PDF renderer in lieu of a",
"can say “please use a font conforming to Adobe-Japan-1”; the ``cidg`` mapping is",
"font reference with a known glyph collection but no subsetted glyphs. For instance,",
"reverse direction. It is useful for fonts that may be used by a",
"is lossy for this purpose and is obsoleted by ``cidg``. For example, the",
"GlyphIDs instead of the reverse direction. It is useful for fonts that may",
"say “please use a font conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary",
"to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is, say, a",
"a TrueType font. ``gidc`` is lossy for this purpose and is obsoleted by",
"reference with a known glyph collection but no subsetted glyphs. For instance, a",
"a PDF renderer in lieu of a font reference with a known glyph",
"from .otBase import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the",
"is obsoleted by ``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple",
"instead of the reverse direction. It is useful for fonts that may be",
"lieu of a font reference with a known glyph collection but no subsetted",
"say, a TrueType font. ``gidc`` is lossy for this purpose and is obsoleted",
"For instance, a PDF can say “please use a font conforming to Adobe-Japan-1”;",
"a known glyph collection but no subsetted glyphs. For instance, a PDF can",
"and is obsoleted by ``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which",
"necessary if the font is, say, a TrueType font. ``gidc`` is lossy for",
"by ``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed",
"``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table. \"\"\"",
"TrueType font. ``gidc`` is lossy for this purpose and is obsoleted by ``cidg``.",
"a font conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font",
"for fonts that may be used by a PDF renderer in lieu of",
"is useful for fonts that may be used by a PDF renderer in",
"structure as ``gidc``, just mapping CIDs to GlyphIDs instead of the reverse direction.",
"mapping is necessary if the font is, say, a TrueType font. ``gidc`` is",
"example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6)",
"the reverse direction. It is useful for fonts that may be used by",
"font. ``gidc`` is lossy for this purpose and is obsoleted by ``cidg``. For",
"is, say, a TrueType font. ``gidc`` is lossy for this purpose and is",
"``gidc`` is lossy for this purpose and is obsoleted by ``cidg``. For example,",
"(which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table. \"\"\" pass",
"the ``cidg`` mapping is necessary if the font is, say, a TrueType font.",
"but no subsetted glyphs. For instance, a PDF can say “please use a",
"``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on",
"PDF renderer in lieu of a font reference with a known glyph collection",
"the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6) has",
"in lieu of a font reference with a known glyph collection but no",
"``cidg`` table has almost the same structure as ``gidc``, just mapping CIDs to",
"# coding: utf-8 from .otBase import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table",
"table has almost the same structure as ``gidc``, just mapping CIDs to GlyphIDs",
"useful for fonts that may be used by a PDF renderer in lieu",
"mapping CIDs to GlyphIDs instead of the reverse direction. It is useful for",
"conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is, say,",
"a PDF can say “please use a font conforming to Adobe-Japan-1”; the ``cidg``",
"that may be used by a PDF renderer in lieu of a font",
"“please use a font conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary if",
"font is, say, a TrueType font. ``gidc`` is lossy for this purpose and",
"a font reference with a known glyph collection but no subsetted glyphs. For",
"no subsetted glyphs. For instance, a PDF can say “please use a font",
"to GlyphIDs instead of the reverse direction. It is useful for fonts that",
"with a known glyph collection but no subsetted glyphs. For instance, a PDF",
"subsetted glyphs. For instance, a PDF can say “please use a font conforming",
"almost the same structure as ``gidc``, just mapping CIDs to GlyphIDs instead of",
"CIDs to GlyphIDs instead of the reverse direction. It is useful for fonts",
"renderer in lieu of a font reference with a known glyph collection but",
"font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg``",
".otBase import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the same",
"in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table.",
"the same structure as ``gidc``, just mapping CIDs to GlyphIDs instead of the",
"utf-8 from .otBase import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost",
"be used by a PDF renderer in lieu of a font reference with",
"first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS 10.12.6) has a",
"instance, a PDF can say “please use a font conforming to Adobe-Japan-1”; the",
"by a PDF renderer in lieu of a font reference with a known",
"the font is, say, a TrueType font. ``gidc`` is lossy for this purpose",
"AAT ``cidg`` table has almost the same structure as ``gidc``, just mapping CIDs",
"just mapping CIDs to GlyphIDs instead of the reverse direction. It is useful",
"direction. It is useful for fonts that may be used by a PDF",
"For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships pre-installed on MacOS",
"Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is, say, a TrueType",
"table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the same structure as ``gidc``, just",
"glyphs. For instance, a PDF can say “please use a font conforming to",
"for this purpose and is obsoleted by ``cidg``. For example, the first font",
"of a font reference with a known glyph collection but no subsetted glyphs.",
"known glyph collection but no subsetted glyphs. For instance, a PDF can say",
"as ``gidc``, just mapping CIDs to GlyphIDs instead of the reverse direction. It",
"this purpose and is obsoleted by ``cidg``. For example, the first font in",
"font conforming to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is,",
"import BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the same structure",
"used by a PDF renderer in lieu of a font reference with a",
"purpose and is obsoleted by ``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc``",
"BaseTTXConverter class table__c_i_d_g(BaseTTXConverter): \"\"\"The AAT ``cidg`` table has almost the same structure as",
"may be used by a PDF renderer in lieu of a font reference",
"collection but no subsetted glyphs. For instance, a PDF can say “please use",
"It is useful for fonts that may be used by a PDF renderer",
"is necessary if the font is, say, a TrueType font. ``gidc`` is lossy",
"obsoleted by ``cidg``. For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` (which Apple ships",
"has almost the same structure as ``gidc``, just mapping CIDs to GlyphIDs instead"
] |
[
"> len(palindrome): palindrome = initPalndrome #two pointers for even numbers characters initPalndrome =",
"the string def pointersfun(left,right): #we start from the middle of the string then",
"return s[left+1:right] # we store the result of the longestPalindrome palindrome = \"\"",
"function to find the longest palindrome from the string def pointersfun(left,right): #we start",
"of the string then go left and right to find out the longest",
"left and right to find out the longest Palindrome while (left >= 0",
"len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers for even numbers characters initPalndrome",
"-> str: # function to find the longest palindrome from the string def",
"initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers for",
"result of the longestPalindrome palindrome = \"\" # for loop for two cases",
"string then go left and right to find out the longest Palindrome while",
"the longestPalindrome palindrome = \"\" # for loop for two cases (odd number",
"odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome",
"range(len(s)): # for odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome):",
"find the longest palindrome from the string def pointersfun(left,right): #we start from the",
"(left >= 0 and right < len(s) and s[left]==s[right]): left-= 1 right+= 1",
"#we start from the middle of the string then go left and right",
"and right to find out the longest Palindrome while (left >= 0 and",
"# function to find the longest palindrome from the string def pointersfun(left,right): #we",
"variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome) s = input('enter",
"< len(s) and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] # we store",
"for two cases (odd number of characters string and even number of characters",
"for even numbers characters initPalndrome = pointersfun(i,i+1) # check which palindrome is the",
"> len(palindrome): palindrome = initPalndrome print (palindrome) s = input('enter a string:') longestPalindrome('self',s)",
"go left and right to find out the longest Palindrome while (left >=",
"for i in range(len(s)): # for odd numbers characters initPalndrome = pointersfun(i,i) if",
"palindrome from the string def pointersfun(left,right): #we start from the middle of the",
"and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] # we store the result",
"pointersfun(left,right): #we start from the middle of the string then go left and",
"the longest Palindrome while (left >= 0 and right < len(s) and s[left]==s[right]):",
"result variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome) s =",
"#two pointers for even numbers characters initPalndrome = pointersfun(i,i+1) # check which palindrome",
"in range(len(s)): # for odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) >",
"(odd number of characters string and even number of characters string) for i",
"= initPalndrome #two pointers for even numbers characters initPalndrome = pointersfun(i,i+1) # check",
"characters string and even number of characters string) for i in range(len(s)): #",
"of the longestPalindrome palindrome = \"\" # for loop for two cases (odd",
"class Solution: def longestPalindrome(self, s: str) -> str: # function to find the",
"longest palindrome from the string def pointersfun(left,right): #we start from the middle of",
"is the longest then store it in the result variable if len(initPalndrome) >",
"while (left >= 0 and right < len(s) and s[left]==s[right]): left-= 1 right+=",
"the middle of the string then go left and right to find out",
"characters initPalndrome = pointersfun(i,i+1) # check which palindrome is the longest then store",
"loop for two cases (odd number of characters string and even number of",
"= \"\" # for loop for two cases (odd number of characters string",
"s[left+1:right] # we store the result of the longestPalindrome palindrome = \"\" #",
"characters string) for i in range(len(s)): # for odd numbers characters initPalndrome =",
"numbers characters initPalndrome = pointersfun(i,i+1) # check which palindrome is the longest then",
"str: # function to find the longest palindrome from the string def pointersfun(left,right):",
"\"\" # for loop for two cases (odd number of characters string and",
"pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers for even numbers",
"middle of the string then go left and right to find out the",
"# check which palindrome is the longest then store it in the result",
"right+= 1 return s[left+1:right] # we store the result of the longestPalindrome palindrome",
"numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two",
"store the result of the longestPalindrome palindrome = \"\" # for loop for",
"the longest then store it in the result variable if len(initPalndrome) > len(palindrome):",
"1 right+= 1 return s[left+1:right] # we store the result of the longestPalindrome",
"and even number of characters string) for i in range(len(s)): # for odd",
"pointers for even numbers characters initPalndrome = pointersfun(i,i+1) # check which palindrome is",
"find out the longest Palindrome while (left >= 0 and right < len(s)",
"left-= 1 right+= 1 return s[left+1:right] # we store the result of the",
"s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] # we store the result of",
"of characters string and even number of characters string) for i in range(len(s)):",
"cases (odd number of characters string and even number of characters string) for",
"0 and right < len(s) and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right]",
"= pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers for even",
"# for loop for two cases (odd number of characters string and even",
"of characters string) for i in range(len(s)): # for odd numbers characters initPalndrome",
"Palindrome while (left >= 0 and right < len(s) and s[left]==s[right]): left-= 1",
"1 return s[left+1:right] # we store the result of the longestPalindrome palindrome =",
"to find out the longest Palindrome while (left >= 0 and right <",
"palindrome is the longest then store it in the result variable if len(initPalndrome)",
"then store it in the result variable if len(initPalndrome) > len(palindrome): palindrome =",
"which palindrome is the longest then store it in the result variable if",
"palindrome = \"\" # for loop for two cases (odd number of characters",
"number of characters string) for i in range(len(s)): # for odd numbers characters",
"for odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome =",
"<gh_stars>0 class Solution: def longestPalindrome(self, s: str) -> str: # function to find",
"the string then go left and right to find out the longest Palindrome",
"# for odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome",
"len(palindrome): palindrome = initPalndrome #two pointers for even numbers characters initPalndrome = pointersfun(i,i+1)",
"string and even number of characters string) for i in range(len(s)): # for",
"Solution: def longestPalindrome(self, s: str) -> str: # function to find the longest",
"start from the middle of the string then go left and right to",
"characters initPalndrome = pointersfun(i,i) if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers",
"even number of characters string) for i in range(len(s)): # for odd numbers",
"longest then store it in the result variable if len(initPalndrome) > len(palindrome): palindrome",
"the longest palindrome from the string def pointersfun(left,right): #we start from the middle",
"initPalndrome = pointersfun(i,i+1) # check which palindrome is the longest then store it",
"palindrome = initPalndrome #two pointers for even numbers characters initPalndrome = pointersfun(i,i+1) #",
"and right < len(s) and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] #",
"def longestPalindrome(self, s: str) -> str: # function to find the longest palindrome",
"right to find out the longest Palindrome while (left >= 0 and right",
"= pointersfun(i,i+1) # check which palindrome is the longest then store it in",
"longestPalindrome(self, s: str) -> str: # function to find the longest palindrome from",
"string def pointersfun(left,right): #we start from the middle of the string then go",
"i in range(len(s)): # for odd numbers characters initPalndrome = pointersfun(i,i) if len(initPalndrome)",
"string) for i in range(len(s)): # for odd numbers characters initPalndrome = pointersfun(i,i)",
"pointersfun(i,i+1) # check which palindrome is the longest then store it in the",
"len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome) s = input('enter a string:')",
"str) -> str: # function to find the longest palindrome from the string",
"from the middle of the string then go left and right to find",
"the result variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome) s",
"right < len(s) and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] # we",
"two cases (odd number of characters string and even number of characters string)",
"if len(initPalndrome) > len(palindrome): palindrome = initPalndrome #two pointers for even numbers characters",
"out the longest Palindrome while (left >= 0 and right < len(s) and",
"s: str) -> str: # function to find the longest palindrome from the",
"longestPalindrome palindrome = \"\" # for loop for two cases (odd number of",
"even numbers characters initPalndrome = pointersfun(i,i+1) # check which palindrome is the longest",
"for loop for two cases (odd number of characters string and even number",
"def pointersfun(left,right): #we start from the middle of the string then go left",
"initPalndrome #two pointers for even numbers characters initPalndrome = pointersfun(i,i+1) # check which",
"it in the result variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print",
"check which palindrome is the longest then store it in the result variable",
"if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome) s = input('enter a",
"from the string def pointersfun(left,right): #we start from the middle of the string",
"store it in the result variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome",
"we store the result of the longestPalindrome palindrome = \"\" # for loop",
"the result of the longestPalindrome palindrome = \"\" # for loop for two",
"then go left and right to find out the longest Palindrome while (left",
"# we store the result of the longestPalindrome palindrome = \"\" # for",
"in the result variable if len(initPalndrome) > len(palindrome): palindrome = initPalndrome print (palindrome)",
"len(s) and s[left]==s[right]): left-= 1 right+= 1 return s[left+1:right] # we store the",
">= 0 and right < len(s) and s[left]==s[right]): left-= 1 right+= 1 return",
"longest Palindrome while (left >= 0 and right < len(s) and s[left]==s[right]): left-=",
"number of characters string and even number of characters string) for i in",
"to find the longest palindrome from the string def pointersfun(left,right): #we start from"
] |
[
"self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point",
"1 + 1e-9: return None else: return None intersection_point = (x1 + (t",
"self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; # the crossing number counter",
"', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges",
"other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon,",
"1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges)",
"self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1])",
"result_polygon_points = [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not",
"= IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next",
"= (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1]",
"polygon width to maximize the floating point resolution max_x_point = max(p.pos[0] for p",
"= [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0 if intersection is None",
"PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1 for",
"return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0 if",
"2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges:",
"@staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in first_polygon.edges: for second_edge",
"ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon)",
"self.from_point = from_point self.to_point = to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t):",
"self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) +",
"(P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self,",
"point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1",
"'.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder() def",
"# next_vertex = self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1])",
"1e-9: return False divisor = (y2 - y1)*x0 - (x2 - x1)*y0 +",
"edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count)",
"edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first: \", ', '.join('(' +",
"range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1)",
"P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1]))",
"def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for",
"is_downward = y3 > y4 if is_upward: if t <= 1e-9 or t",
"self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY",
"= sum(0 if intersection is None else 1 for intersection in ray_intersections) #vertex_intersection_count",
"t <= 1e-9 or t > 1 - 1e-9 or u < 1e-9",
"- y3)) - ((y1 - y2) * (x1 - x3))) tu_divisor = ((y3",
">= 1 - 1e-9: return None intersection_point = (x1 + (t * (x2",
"\", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and abs(point[1]",
"!= intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed =",
"pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return",
"second_intersection is not None: first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point",
"t_dividend / tu_divisor u = u_dividend / tu_divisor is_upward = y3 < y4",
"return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point",
"## loop through all edges of the polygon #for i in range(len(self.points)): #",
"setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return",
"(next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return cn % 2 == 1",
"len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if",
"2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) # This has length of polygon",
"None t = t_dividend / tu_divisor u = u_dividend / tu_divisor is_upward =",
"## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt)",
"second_polygon): intersections = [] for first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection",
"ray_from_point = PolygonPoint((point[0], point[1])) # This has length of polygon width to maximize",
"self.processed = False def setNext(self, next_point): self.next = next_point def setPrev(self, prev_point): self.prev",
"for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def",
"self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self,",
"in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()]",
"polygon #for i in range(len(self.points)): # current_vertex = self.points[i] # next_vertex = self.points[(i",
"t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point =",
"first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True)",
"y4)) - ((y1 - y3) * (x3 - x4)) u_dividend = -(((x1 -",
"+ 1e-9: return None else: return None intersection_point = (x1 + (t *",
"GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in points_list] self.edges =",
"self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point)))",
"ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count =",
"t) def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2 = point return",
"self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return '(' + ','.join(str(p)",
"#return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon,",
"','.join(str(pt) for pt in edge_point) + ')' for edge_point in edge_points)) self.points =",
"> 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count +",
"elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def",
"assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and",
"', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside,",
"1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or",
"x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3 - y4))",
"August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1])",
"return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2 =",
"traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev",
"None else 1 for intersection in ray_intersections) #vertex_intersection_count = sum(a for a in",
"for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is",
"from_point, to_point): self.from_point = from_point self.to_point = to_point self.intersections = [] def insertIntersectionAt(self,",
"x4)) u_dividend = -(((x1 - x2) * (y1 - y3)) - ((y1 -",
"'.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn",
"== self.UNKNOWN or self == self.ENTRY or self == self.EXIT def getInverted(self): if(self",
"edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('(' +",
"of polygon width to maximize the floating point resolution max_x_point = max(p.pos[0] for",
"t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia # Last",
"and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): #",
"True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction)",
"Wikipedia # Last edit date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1 =",
"- 1e-9 or u < 1e-9 or u >= 1 - 1e-9: return",
"i in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i] next_point",
"def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point in self.points if point.intersection_type.isIntersection()]",
"is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if",
"August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1])",
"+ (t * (x2 - x1)), y1 + (t * (y2 - y1)),",
"vertex_intersections) ##if edge_intersection_count % 2 == 1 or vertex_intersection_count > 0: ## print()",
"for intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count % 2 == 1",
"edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge",
"second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection is not None: first_intersection_pos, t",
"return GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator):",
"dividend) if distance < 1e-9: return True return False class GreinerHormannPolygon: def __init__(self,",
"- current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]):",
"for intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed =",
"__createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point in self.points if point.intersection_type.isIntersection()] if",
"current_point = current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY",
"tu_divisor u = u_dividend / tu_divisor if t <= 1e-9 or t >",
"self.pos) + ')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point self.to_point",
"ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1 for intersection",
"self.points) - min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections =",
"intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point =",
"<= point[1]))): # vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) #",
">= 1 - 1e-9: return None elif is_downward: if t < 1e-9 or",
"import PolygonBooleanOperator from enum import Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0",
"- x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor / dividend) if distance",
"for intersection in ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections) ##if edge_intersection_count",
"second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def",
"in ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections) ##if edge_intersection_count % 2",
"= self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1]",
"% 2 == 1 or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count)",
"current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other",
"#print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point) + ')' for edge_point",
"enum import Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3",
"def __str__(self): return '(' + ','.join(str(p) for p in self.pos) + ')' class",
"[[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt",
"class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos self.next = None self.prev",
"if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def",
"https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia # Last edit date: 16",
"def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 =",
"in edge_points for point in edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges",
"if first_intersection is not None and second_intersection is not None: first_intersection_pos, t =",
"return self == self.UNKNOWN or self == self.ENTRY or self == self.EXIT def",
"# Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge):",
"second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None and",
"insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for",
"- y1)**2 + (x2 - x1)**2) if dividend <= 1e-9: return False divisor",
"##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] -",
"from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return",
"1e-9 or t >= 1 - 1e-9 or u <= -1e-9 or u",
"or self == self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self ==",
"range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point)",
"(ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections if",
"def __init__(self, pos, is_intersection=False): self.pos = pos self.next = None self.prev = None",
"= self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type =",
"- y2) * (x1 - x3))) tu_divisor = ((y3 - y4) * (x1",
"- (P2[0] - P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 =",
"1e-9 or u <= 1e-9 or u >= 1 + 1e-9: return None",
"in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in first_polygon.edges:",
"boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction =",
"else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported boolean",
"- 1e-9: return None intersection_point = (x1 + (t * (x2 - x1)),",
"Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self):",
"not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self,",
"self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i],",
"boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points))",
"= [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed",
"','.join(str(pt) for pt in self.points)) #print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point),",
"traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection in intersections) or",
"'.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\",",
"is_intersection=False): self.pos = pos self.next = None self.prev = None self.other_polygon_link = None",
"None self.prev = None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else",
"self == self.UNKNOWN or self == self.ENTRY or self == self.EXIT def getInverted(self):",
"% len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1]",
"## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in",
"-(((x1 - x2) * (y1 - y3)) - ((y1 - y2) * (x1",
"self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1",
"x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend",
"\", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for",
"current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD",
"point in edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first: \", ',",
"print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points))",
"def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator ==",
"= True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type",
"for edge_point in edge_points)) self.points = [point for edge in edge_points for point",
"1 - 1e-9: return None elif is_downward: if t < 1e-9 or t",
"current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed",
"- 1e-9 or u <= 1e-9 or u >= 1 + 1e-9: return",
"[] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return",
"False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in points_list]",
"== 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \",",
"< 0.00005: # print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points),",
"/ tu_divisor u = u_dividend / tu_divisor if t <= 1e-9 or t",
"intersection) is_point_inside = ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p)",
"__computePolygonWidth(self): return max(point.pos[0] for point in self.points) - min(point.pos[0] for point in self.points)",
"for a in vertex_intersections) ##if edge_intersection_count % 2 == 1 or vertex_intersection_count >",
"x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2",
"= TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection in intersections) or current_point",
"self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in self.intersections]",
"(self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1",
"(y2 - y1)), 0) return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1",
"second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point)",
"not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else: return",
"sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN",
"PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge",
"pos, is_intersection=False): self.pos = pos self.next = None self.prev = None self.other_polygon_link =",
"in self.points) - min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections",
"other_point def __str__(self): return '(' + ','.join(str(p) for p in self.pos) + ')'",
"in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections,",
"0) return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2",
"the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point =",
"is_point_inside = ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for",
"dividend <= 1e-9: return False divisor = (y2 - y1)*x0 - (x2 -",
"u_dividend = -(((x1 - x2) * (y1 - y3)) - ((y1 - y2)",
"UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN or self == self.ENTRY",
"__computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in first_polygon.edges: for second_edge in second_polygon.edges:",
"return False divisor = (y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1",
"boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points =",
"<reponame>ulrichji/HeightmapTileMaker from .polygon_boolean_operator import PolygonBooleanOperator from enum import Enum from math import sqrt",
"edge in edge_points for point in edge] #print('Points:', ','.join(str(pt) for pt in self.points))",
"self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for",
"= [PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list):",
"(intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia #",
"x1)), y1 + (t * (y2 - y1)), 0) return (intersection_point, t) def",
"class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos",
"[PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for i in",
"y1)), 0) return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos",
"self.to_point = to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def",
">= 1 - 1e-9 or u <= 1e-9 or u >= 1 +",
"P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2",
"= sqrt((y2 - y1)**2 + (x2 - x1)**2) if dividend <= 1e-9: return",
"(next_vertex.pos[1] <= point[1]))): # vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1])",
"## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points:",
"second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point)",
"intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and abs(point[1] - 0.20472) < 0.00005:",
"in ray_intersections if intersection) is_point_inside = ray_intersections_count % 2 == 1 return is_point_inside",
"+ 1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1]))",
"= PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self,",
"intersection.processed for intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed",
"current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS",
"# Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos)",
"[] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for",
"((y1 - y2) * (x1 - x3))) tu_divisor = ((y3 - y4) *",
"= t_dividend / tu_divisor u = u_dividend / tu_divisor is_upward = y3 <",
"2 == 1 or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ##",
"edge in self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections if intersection) is_point_inside",
"x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3)",
"math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self",
"return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link =",
"##if edge_intersection_count % 2 == 1 or vertex_intersection_count > 0: ## print() ##",
"1e-9 or t > 1 - 1e-9 or u < 1e-9 or u",
"#vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0 if intersection is",
"point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def",
"self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif",
"the crossing number counter ## loop through all edges of the polygon #for",
"= edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections)",
"self.next = None self.prev = None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if",
"y2) * (x3 - x4)) if abs(tu_divisor) <= 1e-9: return None t =",
"= self.points[i] # next_vertex = self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1]",
"edge_points)) self.points = [point for edge in edge_points for point in edge] #print('Points:',",
"/ tu_divisor if t <= 1e-9 or t > 1 - 1e-9 or",
"if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon,",
"intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True",
"and second_intersection is not None: first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection",
"if this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently",
"u <= 1e-9 or u >= 1 + 1e-9: return None else: return",
"current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt >",
"/ (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0]",
"self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False",
"first_intersection is not None and second_intersection is not None: first_intersection_pos, t = first_intersection",
"getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection",
"0; # the crossing number counter ## loop through all edges of the",
"u = u_dividend / tu_divisor is_upward = y3 < y4 is_downward = y3",
"x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor / dividend) if distance <",
"str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point,",
"other_polygon): if len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in",
"')' for edge_point in edge_points)) self.points = [point for edge in edge_points for",
"= ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p",
"vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return cn % 2",
"else 1 for intersection in ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections)",
"self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 -",
"None else: return None intersection_point = (x1 + (t * (x2 - x1)),",
"((x1 - x3) * (y3 - y4)) - ((y1 - y3) * (x3",
"current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): #",
"ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in",
"other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator",
"if dividend <= 1e-9: return False divisor = (y2 - y1)*x0 - (x2",
"(point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2",
"Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point",
"in vertex_intersections) ##if edge_intersection_count % 2 == 1 or vertex_intersection_count > 0: ##",
"if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point",
"<= 1e-9 or t > 1 - 1e-9 or u < 1e-9 or",
"cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point),",
"current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection",
"return True return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for",
"\", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges))",
"= None self.prev = None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection",
"or u >= 1 + 1e-9: return None else: return None intersection_point =",
"other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other:",
"vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count",
"edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point) +",
"points_list=[]): self.points = [PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def",
"< y4 is_downward = y3 > y4 if is_upward: if t <= 1e-9",
"def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for",
"y4 if is_upward: if t <= 1e-9 or t >= 1 - 1e-9",
"* (y1 - y3)) - ((y1 - y2) * (x1 - x3))) tu_divisor",
"= current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else",
"edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt)",
"<= 1e-9: return None t = t_dividend / tu_divisor u = u_dividend /",
"pt in self.points)) #print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) +",
"first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ',",
"This has length of polygon width to maximize the floating point resolution max_x_point",
"2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count",
"other_polygon, boolean_operator): intersections = [point for point in self.points if point.intersection_type.isIntersection()] if len(intersections)",
"self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self",
"- y2) * (x3 - x4)) if abs(tu_divisor) <= 1e-9: return None t",
"= from_point self.to_point = to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point,",
"__getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)])",
"edges of the polygon #for i in range(len(self.points)): # current_vertex = self.points[i] #",
"this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the",
"floating point resolution max_x_point = max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point",
"- P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1])",
"x3))) tu_divisor = ((y3 - y4) * (x1 - x2)) - ((y1 -",
"TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection in intersections) or current_point !=",
"u < 1e-9 or u >= 1 - 1e-9: return None intersection_point =",
"return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in",
"# print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def",
"point return ((P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0])",
"= y3 > y4 if is_upward: if t <= 1e-9 or t >=",
"= sum(a for a in vertex_intersections) ##if edge_intersection_count % 2 == 1 or",
"+ vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return cn %",
"TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos self.next",
"* (x1 - x3))) tu_divisor = ((y3 - y4) * (x1 - x2))",
"def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY return",
"[ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0 if intersection is None else",
"1 or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count",
"prev_point): self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next",
"print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \"",
"Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia # Last edit date:",
"+ ')' for edge_point in edge_points)) self.points = [point for edge in edge_points",
"return '(' + ','.join(str(p) for p in self.pos) + ')' class PolygonEdge: def",
"'(' + ','.join(str(p) for p in self.pos) + ')' class PolygonEdge: def __init__(self,",
"1e-9 or u >= 1 - 1e-9: return None intersection_point = (x1 +",
"for edge in edge_points for point in edge] #print('Points:', ','.join(str(pt) for pt in",
"(((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1]",
"boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other =",
"1 ray_from_point = PolygonPoint((point[0], point[1])) # This has length of polygon width to",
"= intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \",",
"ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and abs(point[1] -",
"points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for",
"pt in edge_point) + ')' for edge_point in edge_points)) self.points = [point for",
"#if abs(point[0] - 0.16535) < 0.00005 and abs(point[1] - 0.20472) < 0.00005: #",
"* (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])) def",
"point[1]))): # vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if",
"current_vertex.pos[0]): # cn += 1 #return cn % 2 == 1 ray_from_point =",
"return None else: return None intersection_point = (x1 + (t * (x2 -",
"self.other_polygon_link = other_point def __str__(self): return '(' + ','.join(str(p) for p in self.pos)",
"first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge)",
"= other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon()",
"result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction",
"-1e-9 or u >= 1 - 1e-9: return None elif is_downward: if t",
"distance < 1e-9: return True return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points",
"distance = abs(divisor / dividend) if distance < 1e-9: return True return False",
"self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for",
"has length of polygon width to maximize the floating point resolution max_x_point =",
"crossing number counter ## loop through all edges of the polygon #for i",
"if distance < 1e-9: return True return False class GreinerHormannPolygon: def __init__(self, points_list=[]):",
"0.20472) < 0.00005: # print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count,",
"cn % 2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) # This has length",
"self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False):",
"Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1",
"print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ',",
"1e-9 or u < 1e-9 or u >= 1 - 1e-9: return None",
"> point[1]) and (next_vertex.pos[1] <= point[1]))): # vt = (point[1] - current_vertex.pos[1]) /",
"for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge",
"0 while(any(not intersection.processed for intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if",
"y3) * (x3 - x4)) u_dividend = -(((x1 - x2) * (y1 -",
"return None intersection_point = (x1 + (t * (x2 - x1)), y1 +",
"IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next =",
"edge_point) + ')' for edge_point in edge_points)) self.points = [point for edge in",
"self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in first_polygon.edges: for",
"tu_divisor u = u_dividend / tu_divisor is_upward = y3 < y4 is_downward =",
"else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next = next_point def setPrev(self,",
"if is_upward: if t <= 1e-9 or t >= 1 - 1e-9 or",
"next_vertex = self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and",
"intersection is None else 1 for intersection in ray_intersections) #vertex_intersection_count = sum(a for",
"- (x2 - x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor / dividend)",
"and (next_vertex.pos[1] <= point[1]))): # vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] -",
"ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN or self == self.ENTRY or",
"% 2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) # This has length of",
"x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2 - x1)**2)",
"first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in",
"= other_point def __str__(self): return '(' + ','.join(str(p) for p in self.pos) +",
"in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self):",
"# the crossing number counter ## loop through all edges of the polygon",
"# Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia # Last edit",
"second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection is not None:",
"P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1",
"first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points)",
"traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self,",
"(x1 - x2)) - ((y1 - y2) * (x3 - x4)) if abs(tu_divisor)",
"pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is",
"i in range(len(self.points)): # current_vertex = self.points[i] # next_vertex = self.points[(i + 1)",
"= t_dividend / tu_divisor u = u_dividend / tu_divisor if t <= 1e-9",
"__setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) % len(self.points)]",
"t > 1 - 1e-9 or u < 1e-9 or u >= 1",
"[PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points",
"self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge",
"self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] >",
"in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point) + ')'",
"in edge_point) + ')' for edge_point in edge_points)) self.points = [point for edge",
"PolygonPoint((point[0], point[1])) # This has length of polygon width to maximize the floating",
"vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt",
"point = self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point)",
"first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0:",
"Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this",
"other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if",
"y4 is_downward = y3 > y4 if is_upward: if t <= 1e-9 or",
"- P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1])",
"u >= 1 - 1e-9: return None intersection_point = (x1 + (t *",
"in range(len(self.points)): # current_vertex = self.points[i] # next_vertex = self.points[(i + 1) %",
"boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not",
"point in self.points) - min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon):",
"tu_divisor is_upward = y3 < y4 is_downward = y3 > y4 if is_upward:",
"= (y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 + y2*x1 distance",
"- y4)) - ((y1 - y3) * (x3 - x4)) u_dividend = -(((x1",
"= first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos,",
"= self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in",
"<= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection():",
"* (x3 - x4)) if abs(tu_divisor) <= 1e-9: return None t = t_dividend",
"the floating point resolution max_x_point = max(p.pos[0] for p in self.points) ray_to_point =",
"len(self.points)] # if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] >",
"- x1)), y1 + (t * (y2 - y1)), 0) return (intersection_point, t)",
"def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in self.intersections] # Source:",
"y3)) - ((y1 - y2) * (x1 - x3))) tu_divisor = ((y3 -",
"##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\",",
"for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author:",
">= 1 + 1e-9: return None else: return None intersection_point = (x1 +",
"pos self.next = None self.prev = None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN",
"a in vertex_intersections) ##if edge_intersection_count % 2 == 1 or vertex_intersection_count > 0:",
"in edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first: \", ', '.join('('",
"point): #cn = 0; # the crossing number counter ## loop through all",
"'.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.edges =",
"point[1]) and (next_vertex.pos[1] <= point[1]))): # vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1]",
"first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point,",
"self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported",
"return None elif is_downward: if t < 1e-9 or t >= 1 -",
"# Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = []",
"self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; # the crossing number counter ##",
"edit date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2",
"= -(((x1 - x2) * (y1 - y3)) - ((y1 - y2) *",
"+ ')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0;",
"#for i in range(len(self.points)): # current_vertex = self.points[i] # next_vertex = self.points[(i +",
"= sum(1 for intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count % 2",
"< 1e-9 or u >= 1 - 1e-9: return None intersection_point = (x1",
"#cn = 0; # the crossing number counter ## loop through all edges",
"if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type class",
"PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos self.next = None self.prev =",
"= second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection is not None: first_intersection_pos,",
"= other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections",
"0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author:",
"vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon,",
"x1)), y1 + (t * (y2 - y1)), 0) return (intersection_point, t) #",
"point in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return",
"current_vertex = self.points[i] # next_vertex = self.points[(i + 1) % len(self.points)] # if",
"assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt",
"#print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first: \", ', '.join('(' + ',",
"#edge_intersection_count = sum(0 if intersection is None else 1 for intersection in ray_intersections)",
"__updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point",
"if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt",
"TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000): print(\"Fail\") return GreinerHormannPolygon(result_polygon_points)",
"other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3 -",
"x2) * (y1 - y3)) - ((y1 - y2) * (x1 - x3)))",
"(x1 - x3))) tu_divisor = ((y3 - y4) * (x1 - x2)) -",
"is_upward = y3 < y4 is_downward = y3 > y4 if is_upward: if",
"<= 1e-9: return False divisor = (y2 - y1)*x0 - (x2 - x1)*y0",
"boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1)",
"for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))]",
"def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in first_polygon.edges: for second_edge in",
"None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type",
"= current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT",
"self.ENTRY or self == self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self",
"__init__(self, pos, is_intersection=False): self.pos = pos self.next = None self.prev = None self.other_polygon_link",
"NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN or self ==",
"for first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection =",
"PolygonBooleanOperator from enum import Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1",
"(point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] +",
"Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1",
"sum(1 for intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count % 2 ==",
"current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type",
"(self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2",
"intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection",
"else: return None intersection_point = (x1 + (t * (x2 - x1)), y1",
"intersection_point = (x1 + (t * (x2 - x1)), y1 + (t *",
"- y3) * (x3 - x4)) u_dividend = -(((x1 - x2) * (y1",
"- x2)) - ((y1 - y2) * (x3 - x4)) if abs(tu_divisor) <=",
"= (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend =",
"self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0]",
"= y3 < y4 is_downward = y3 > y4 if is_upward: if t",
"def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\",",
"None and second_intersection is not None: first_intersection_pos, t = first_intersection second_intersection_pos, u =",
"< 0.00005 and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for pt in",
"is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next = next_point def",
"(t * (y2 - y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection #",
"None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self,",
"','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 ==",
"- 1e-9 or u <= -1e-9 or u >= 1 - 1e-9: return",
"'.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after:",
"self.points = [PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self,",
"in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None",
"- x3))) tu_divisor = ((y3 - y4) * (x1 - x2)) - ((y1",
"= current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else",
"= current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000): print(\"Fail\") return GreinerHormannPolygon(result_polygon_points) return GreinerHormannPolygon(result_polygon_points)",
"[point for edge in edge_points for point in edge] #print('Points:', ','.join(str(pt) for pt",
"next_point): self.next = next_point def setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction):",
"return self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2",
"u >= 1 - 1e-9: return None elif is_downward: if t < 1e-9",
"after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in",
"or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): # vt = (point[1] -",
"= PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u)",
"self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator)",
"', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder()",
"return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos,",
"self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges),",
"1e-9: return None elif is_downward: if t < 1e-9 or t >= 1",
"divisor = (y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 + y2*x1",
"y1)*x0 - (x2 - x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor /",
"point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return",
"GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self):",
"intersection # Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self,",
"intersection: intersection[1]) return [intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title:",
"+ ','.join(str(p) for p in self.pos) + ')' class PolygonEdge: def __init__(self, from_point,",
"= self.from_point.pos P1 = self.to_point.pos P2 = point return ((P1[0] - P0[0]) *",
"or u >= 1 - 1e-9: return None intersection_point = (x1 + (t",
"number counter ## loop through all edges of the polygon #for i in",
"# vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1]",
"if t <= 1e-9 or t > 1 - 1e-9 or u <",
"len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point)))",
"in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if",
"return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the",
"+ x2*y1 + y2*x1 distance = abs(divisor / dividend) if distance < 1e-9:",
"current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return cn",
"width to maximize the floating point resolution max_x_point = max(p.pos[0] for p in",
"(self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0],",
"or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count =",
"0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count",
"= (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) *",
"None intersection_point = (x1 + (t * (x2 - x1)), y1 + (t",
"(x3 - x4)) u_dividend = -(((x1 - x2) * (y1 - y3)) -",
"# Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersection(self, other_edge):",
"traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt",
"x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend",
"second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None",
"- x2) * (y1 - y3)) - ((y1 - y2) * (x1 -",
"self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class",
"1e-9 or t >= 1 - 1e-9 or u <= 1e-9 or u",
"pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 == 1 ##print(\"Edge",
"in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i] next_point =",
"u >= 1 + 1e-9: return None else: return None intersection_point = (x1",
"or t >= 1 - 1e-9 or u <= -1e-9 or u >=",
"abs(tu_divisor) <= 1e-9: return None t = t_dividend / tu_divisor u = u_dividend",
"intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0],",
"of the polygon #for i in range(len(self.points)): # current_vertex = self.points[i] # next_vertex",
"\", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\", point,",
"abs(point[0] - 0.16535) < 0.00005 and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt)",
"current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt *",
"= (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 +",
"#print('Points:', ', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for",
"for point in self.points) - min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon,",
"Title: Line–line intersection # Author: Wikipedia # Last edit date: 16 August 2019",
"def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0]",
"str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn =",
"self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only",
"for pt in self.points)) #print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point)))",
"1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ',",
"second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t)",
"point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self,",
"in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point",
"(t * (y2 - y1)), 0) return (intersection_point, t) def isPointLeft(point): P0 =",
"= prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction",
"getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point",
"(y3 - y4)) - ((y1 - y3) * (x3 - x4)) u_dividend =",
"def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2 = point return ((P1[0]",
"only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0]",
"', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.edges",
"')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; #",
"= 0; # the crossing number counter ## loop through all edges of",
"return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return '(' +",
"def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 =",
"return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported boolean operator",
"self == self.ENTRY or self == self.EXIT def getInverted(self): if(self == self.ENTRY): return",
"return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia",
"+= 1 #return cn % 2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) #",
"self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported boolean operator",
"- ((y1 - y3) * (x3 - x4)) u_dividend = -(((x1 - x2)",
"EXIT=3 def isIntersection(self): return self == self.UNKNOWN or self == self.ENTRY or self",
"(x1 + (t * (x2 - x1)), y1 + (t * (y2 -",
"IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point in self.points if",
"= u_dividend / tu_divisor if t <= 1e-9 or t > 1 -",
"import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self ==",
"date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 =",
"edge_point in edge_points)) self.points = [point for edge in edge_points for point in",
"= PolygonPoint((point[0], point[1])) # This has length of polygon width to maximize the",
"== 1 or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print()",
"t_dividend = ((x1 - x3) * (y3 - y4)) - ((y1 - y3)",
"in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections",
"or t >= 1 - 1e-9 or u <= 1e-9 or u >=",
"setNext(self, next_point): self.next = next_point def setPrev(self, prev_point): self.prev = prev_point def getNext(self,",
"* (x2 - x1)), y1 + (t * (y2 - y1)), 0) return",
"operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other",
"self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2 - x1)**2) if dividend <=",
"is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0 if intersection",
"supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if",
"TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return '('",
"len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in",
"is not None and second_intersection is not None: first_intersection_pos, t = first_intersection second_intersection_pos,",
"x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4",
"u_dividend / tu_divisor if t <= 1e-9 or t > 1 - 1e-9",
"def isIntersection(self): return self == self.UNKNOWN or self == self.ENTRY or self ==",
"# This has length of polygon width to maximize the floating point resolution",
"self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection:",
"# current_vertex = self.points[i] # next_vertex = self.points[(i + 1) % len(self.points)] #",
"- x4)) u_dividend = -(((x1 - x2) * (y1 - y3)) - ((y1",
"for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 == 1",
".polygon_boolean_operator import PolygonBooleanOperator from enum import Enum from math import sqrt class IntersectionType(Enum):",
"ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge)",
"return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos",
"= (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend =",
"% 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count)",
"isPointInside(self, point): #cn = 0; # the crossing number counter ## loop through",
"#vertex_intersection_count = sum(a for a in vertex_intersections) ##if edge_intersection_count % 2 == 1",
"intersection[1]) return [intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line",
"P2 = point return ((P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0]",
"> point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): # vt =",
"- y1)*x0 - (x2 - x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor",
"0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type",
"def setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD:",
"(t * (x2 - x1)), y1 + (t * (y2 - y1)), 0)",
"* (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 =",
"first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection",
"+ ')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ',",
"self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other",
"* (x1 - x2)) - ((y1 - y2) * (x3 - x4)) if",
"16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0],",
"__init__(self, from_point, to_point): self.from_point = from_point self.to_point = to_point self.intersections = [] def",
"for pt in edge_point) + ')' for edge_point in edge_points)) self.points = [point",
"= [point for edge in edge_points for point in edge] #print('Points:', ','.join(str(pt) for",
"sum(a for a in vertex_intersections) ##if edge_intersection_count % 2 == 1 or vertex_intersection_count",
"/ tu_divisor u = u_dividend / tu_divisor is_upward = y3 < y4 is_downward",
"(y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 + y2*x1 distance =",
"for i in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i]",
"prev_point def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction ==",
"# Last edit date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0],",
"self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point):",
"first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None current_intersection_type =",
"if intersection) is_point_inside = ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections =",
"tu_divisor = ((y3 - y4) * (x1 - x2)) - ((y1 - y2)",
"= second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point,",
"to maximize the floating point resolution max_x_point = max(p.pos[0] for p in self.points)",
"if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and",
"self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2 -",
"1 - 1e-9: return None intersection_point = (x1 + (t * (x2 -",
"- current_vertex.pos[0]): # cn += 1 #return cn % 2 == 1 ray_from_point",
"intersections = [] for first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection =",
"is_downward: if t < 1e-9 or t >= 1 - 1e-9 or u",
"point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point,",
"- x1)**2) if dividend <= 1e-9: return False divisor = (y2 - y1)*x0",
"edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; # the crossing",
"return max(point.pos[0] for point in self.points) - min(point.pos[0] for point in self.points) @staticmethod",
"first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection is not",
"self.UNKNOWN or self == self.ENTRY or self == self.EXIT def getInverted(self): if(self ==",
"== self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT): return",
"+ ')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point self.to_point =",
"2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3",
"*edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in",
"other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in",
"point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): # vt = (point[1]",
"\") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self,",
"','.join(str(p) for p in self.pos) + ')' class PolygonEdge: def __init__(self, from_point, to_point):",
"in self.points)) #print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')'",
"for edge in self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections if intersection)",
"t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in self.intersections] #",
"intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count % 2 == 1 return",
"for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \")",
"intersection # Author: Wikipedia # Last edit date: 16 August 2019 def computeIntersection(self,",
"computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0],",
"u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None current_intersection_type",
"abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for pt in self.points)) # print(is_point_inside,",
"in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon):",
"= PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for",
"* (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return cn % 2 ==",
"self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections =",
"in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 == 1 ##print(\"Edge cnt:\",",
"- y1)), 0) return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1 =",
"current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY",
"boolean_operator): intersections = [point for point in self.points if point.intersection_type.isIntersection()] if len(intersections) <=",
"edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside",
"dividend = sqrt((y2 - y1)**2 + (x2 - x1)**2) if dividend <= 1e-9:",
"to_point): self.from_point = from_point self.to_point = to_point self.intersections = [] def insertIntersectionAt(self, intersection_point,",
"is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and",
"- min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = []",
"')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point self.to_point = to_point",
"Last edit date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1])",
"t <= 1e-9 or t >= 1 - 1e-9 or u <= -1e-9",
"@staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return",
"in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if",
"x4)) if abs(tu_divisor) <= 1e-9: return None t = t_dividend / tu_divisor u",
"__getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self,",
"= pos self.next = None self.prev = None self.other_polygon_link = None self.intersection_type =",
"= to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self):",
"u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point)",
"True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type ==",
"Line–line intersection # Author: Wikipedia # Last edit date: 16 August 2019 def",
"if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next = next_point",
"y3 < y4 is_downward = y3 > y4 if is_upward: if t <=",
"< current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn += 1 #return",
"# print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point,",
"(P2[0] - P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0],",
"- P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point):",
"t = t_dividend / tu_divisor u = u_dividend / tu_divisor if t <=",
"self.to_point.pos P2 = point return ((P1[0] - P0[0]) * (P2[1] - P0[1]) -",
"= first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection is",
"<= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <=",
"= PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1",
"edge_points for point in edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first:",
"< 1e-9: return True return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points =",
"= point return ((P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] -",
"for edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point)",
"for i in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point",
"* (y3 - y4)) - ((y1 - y3) * (x3 - x4)) u_dividend",
"', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i",
"<= -1e-9 or u >= 1 - 1e-9: return None elif is_downward: if",
"1 - 1e-9 or u < 1e-9 or u >= 1 - 1e-9:",
"all edges of the polygon #for i in range(len(self.points)): # current_vertex = self.points[i]",
"def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) %",
"i in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point =",
"#intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:',",
"self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in self.points) - min(point.pos[0]",
"IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for",
"if len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points:",
"p in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point)",
"1e-9: return None intersection_point = (x1 + (t * (x2 - x1)), y1",
"else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point in self.points",
"1 - 1e-9 or u <= -1e-9 or u >= 1 - 1e-9:",
"% 2 == 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points]",
"== 1 ray_from_point = PolygonPoint((point[0], point[1])) # This has length of polygon width",
"##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \",",
"= next_point def setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction",
"vertex_intersections) #is_point_inside = intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\",",
"elif(self == self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint:",
"min(point.pos[0] for point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for",
"P0 = self.from_point.pos P1 = self.to_point.pos P2 = point return ((P1[0] - P0[0])",
"= [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1])",
"intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection in intersections)",
"the polygon #for i in range(len(self.points)): # current_vertex = self.points[i] # next_vertex =",
"(x3 - x4)) if abs(tu_divisor) <= 1e-9: return None t = t_dividend /",
"t >= 1 - 1e-9 or u <= 1e-9 or u >= 1",
"if abs(tu_divisor) <= 1e-9: return None t = t_dividend / tu_divisor u =",
"(next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] -",
"== self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum):",
"y2) * (x1 - x3))) tu_divisor = ((y3 - y4) * (x1 -",
"is None else 1 for intersection in ray_intersections) #vertex_intersection_count = sum(a for a",
"# Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0],",
"not None: first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos,",
"ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and abs(point[1] - 0.20472)",
"== self.ENTRY or self == self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT",
"None t = t_dividend / tu_divisor u = u_dividend / tu_divisor if t",
"x2)) - ((y1 - y2) * (x3 - x4)) if abs(tu_divisor) <= 1e-9:",
"edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2",
"len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon)",
"in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1]",
"if t <= 1e-9 or t >= 1 - 1e-9 or u <=",
"point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self,",
"= intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0 while(any(not intersection.processed for intersection in",
"def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return '(' + ','.join(str(p) for",
"= (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3 - y4)) -",
"second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:',",
"return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only",
"def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def",
"return None t = t_dividend / tu_divisor u = u_dividend / tu_divisor is_upward",
"or u <= -1e-9 or u >= 1 - 1e-9: return None elif",
"(P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0],",
"length of polygon width to maximize the floating point resolution max_x_point = max(p.pos[0]",
"[] for first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection",
"'.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \",",
"boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported",
"> y4 if is_upward: if t <= 1e-9 or t >= 1 -",
"= ((x1 - x3) * (y3 - y4)) - ((y1 - y3) *",
"sqrt((y2 - y1)**2 + (x2 - x1)**2) if dividend <= 1e-9: return False",
"1 - 1e-9 or u <= 1e-9 or u >= 1 + 1e-9:",
"ray_intersections_count = sum(1 for intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count %",
"1e-9 or u <= -1e-9 or u >= 1 - 1e-9: return None",
"for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' +",
"y4) * (x1 - x2)) - ((y1 - y2) * (x3 - x4))",
"def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints()",
"point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in self.points) - min(point.pos[0] for point",
"y1 + (t * (y2 - y1)), 0) return (intersection_point, t) # Source:",
"- 0.20472) < 0.00005: # print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count,",
"__tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION)",
"second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def",
"operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD",
"- ((y1 - y2) * (x3 - x4)) if abs(tu_divisor) <= 1e-9: return",
"or u < 1e-9 or u >= 1 - 1e-9: return None intersection_point",
"or u <= 1e-9 or u >= 1 + 1e-9: return None else:",
"u = u_dividend / tu_divisor if t <= 1e-9 or t > 1",
"in edge_points)) self.points = [point for edge in edge_points for point in edge]",
"def __setupPointsOrder(self): for i in range(len(self.points)): point = self.points[i] next_point = self.points[(i+1) %",
"prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in self.points)",
"> 1 - 1e-9 or u < 1e-9 or u >= 1 -",
"0.00005 and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for pt in self.points))",
"self.points = [point for edge in edge_points for point in edge] #print('Points:', ','.join(str(pt)",
"<= 1e-9 or u >= 1 + 1e-9: return None else: return None",
"+ (x2 - x1)**2) if dividend <= 1e-9: return False divisor = (y2",
"edge_intersection_count % 2 == 1 or vertex_intersection_count > 0: ## print() ## print(edge_intersection_count,",
"def setNext(self, next_point): self.next = next_point def setPrev(self, prev_point): self.prev = prev_point def",
"self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod",
"((y1 - y2) * (x3 - x4)) if abs(tu_divisor) <= 1e-9: return None",
"None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed =",
"for point in edge] #print('Points:', ','.join(str(pt) for pt in self.points)) #print(\"Edges first: \",",
"class PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point self.to_point = to_point self.intersections",
"y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection #",
"= u_dividend / tu_divisor is_upward = y3 < y4 is_downward = y3 >",
"<= 1e-9 or t >= 1 - 1e-9 or u <= -1e-9 or",
"#print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge",
"in self.points] #edge_intersection_count = sum(0 if intersection is None else 1 for intersection",
"boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator",
"y2*x1 distance = abs(divisor / dividend) if distance < 1e-9: return True return",
"max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray =",
"= 0 while(any(not intersection.processed for intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos)",
"or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link",
"def getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS:",
"self.points)) #print(\"Edges first: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for",
"for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points =",
"== PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt =",
"(x2 - x1)), y1 + (t * (y2 - y1)), 0) return (intersection_point,",
"self.next = next_point def setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction): if",
"< 1e-9 or t >= 1 - 1e-9 or u <= 1e-9 or",
"(y2 - y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line",
"self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge",
"[intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection #",
"vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in self.edges)) ##print(\"Is point",
"(x2 - x1)*y0 + x2*y1 + y2*x1 distance = abs(divisor / dividend) if",
"= TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt +=",
"point[1])) # This has length of polygon width to maximize the floating point",
"None elif is_downward: if t < 1e-9 or t >= 1 - 1e-9",
"vertex_intersection_count > 0: ## print() ## print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count",
"t < 1e-9 or t >= 1 - 1e-9 or u <= 1e-9",
"== IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000):",
"+ ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints()",
"ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon)",
"* (y2 - y1)), 0) return (intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos",
"1e-9: return None else: return None intersection_point = (x1 + (t * (x2",
"+ vertex_intersection_count ##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside =",
"self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for",
"+ ','.join(str(pt) for pt in edge_point) + ')' for edge_point in edge_points)) self.points",
"second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <=",
"__str__(self): return '(' + ','.join(str(p) for p in self.pos) + ')' class PolygonEdge:",
"##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(',",
"PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this:",
"TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1",
"point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))):",
"edge_intersection_count, \", pointint:\", vertex_intersection_count) ##print(\"Edges: \", ', '.join(', '.join((str(edge.from_point), str(edge.to_point))) for edge in",
"in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point),",
"self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections if intersection) is_point_inside = ray_intersections_count",
"= ((y3 - y4) * (x1 - x2)) - ((y1 - y2) *",
"for edge in self.edges)) ##print(\"Is point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point,",
"IntersectionType.NOT_AN_INTERSECTION self.processed = False def setNext(self, next_point): self.next = next_point def setPrev(self, prev_point):",
"return self.__createPolygonFromIntersections(other_polygon, boolean_operator) def __getEdgesFromPoints(self): #print('Points:', ', '.join(str(point) for point in self.points)) return",
"= self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0]",
"print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon,",
"t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in",
"next_point def setPrev(self, prev_point): self.prev = prev_point def getNext(self, traversal_direction): if traversal_direction ==",
"return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported boolean",
"16 August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0],",
"is_upward: if t <= 1e-9 or t >= 1 - 1e-9 or u",
"if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn +=",
"= (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections",
"y1 + (t * (y2 - y1)), 0) return (intersection_point, t) def isPointLeft(point):",
"intersections = [point for point in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0:",
"return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for i",
"')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('('",
"def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon,",
"= True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point =",
"self.pos = pos self.next = None self.prev = None self.other_polygon_link = None self.intersection_type",
"point resolution max_x_point = max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point +",
"(x2 - x1)**2) if dividend <= 1e-9: return False divisor = (y2 -",
"self == self.EXIT def getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT):",
"self.__getEdgesFromPoints() self.__setupPointsOrder() def remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list]",
"Wikipedia # Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 =",
"PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges)",
"current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if",
"isIntersection(self): return self == self.UNKNOWN or self == self.ENTRY or self == self.EXIT",
"IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN or self",
"only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos)",
"this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon",
"if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other =",
"(other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3 - y4)) - ((y1",
"this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return",
"else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000): print(\"Fail\") return",
"counter ## loop through all edges of the polygon #for i in range(len(self.points)):",
"print(edge_intersection_count, vertex_intersection_count) ## print() #intersection_count = edge_intersection_count + vertex_intersection_count ##print('Points: ', ','.join(str(pt) for",
"(self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2 - x1)**2) if dividend",
"#is_point_inside = intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count,",
"point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in self.points) - min(point.pos[0] for",
"def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator ==",
"P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])) def intersectsPoint(self, point): x0,y0",
"+ ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self,",
"edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon):",
"second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not",
"def isPointInside(self, point): #cn = 0; # the crossing number counter ## loop",
"if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else:",
"- 0.16535) < 0.00005 and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for",
"while(any(not intersection.processed for intersection in intersections) or current_point != intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection():",
"class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in points_list] self.edges",
"other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections =",
"- ((y1 - y2) * (x1 - x3))) tu_divisor = ((y3 - y4)",
"intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia",
"','.join('(' + ','.join(str(pt) for pt in edge_point) + ')' for edge_point in edge_points))",
"== PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this = self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not",
"other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3 - y4)) - ((y1 -",
"if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def",
"(intersection_point, t) def isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2 = point",
"the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other = other_polygon.isPointInside(self.points[0].pos) other_is_inside_this =",
"if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction =",
"edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ',",
"== TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return",
"p in self.pos) + ')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point =",
"def intersectsPoint(self, point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 =",
"is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator): intersections = [point for point in",
"linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self): return '(' + ','.join(str(p) for p",
"intersections, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points",
"return None current_intersection_type = self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type =",
"return [intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection",
"max_x_point = max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1]))",
"x1)**2) if dividend <= 1e-9: return False divisor = (y2 - y1)*x0 -",
"#return cn % 2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) # This has",
"1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count = sum(0",
"((P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1]",
"or t > 1 - 1e-9 or u < 1e-9 or u >=",
"# cn += 1 #return cn % 2 == 1 ray_from_point = PolygonPoint((point[0],",
"next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return",
"class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def isIntersection(self): return self == self.UNKNOWN or",
"point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 -",
"= None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed",
"- current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] < current_vertex.pos[1] + vt",
"None: first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True)",
"u_dividend / tu_divisor is_upward = y3 < y4 is_downward = y3 > y4",
"other_point): self.other_polygon_link = other_point def __str__(self): return '(' + ','.join(str(p) for p in",
"getInverted(self): if(self == self.ENTRY): return self.EXIT elif(self == self.EXIT): return self.ENTRY return enum_type",
"* (y2 - y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title:",
"/ dividend) if distance < 1e-9: return True return False class GreinerHormannPolygon: def",
"points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point) + ')' for edge_point in",
"cn += 1 #return cn % 2 == 1 ray_from_point = PolygonPoint((point[0], point[1]))",
"1 #return cn % 2 == 1 ray_from_point = PolygonPoint((point[0], point[1])) # This",
"self.__getFirstIntersectionType(other_polygon) for point in self.points: if point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted()",
"not None and second_intersection is not None: first_intersection_pos, t = first_intersection second_intersection_pos, u",
"and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for pt in self.points)) #",
"resolution max_x_point = max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point + 1,",
"((y3 - y4) * (x1 - x2)) - ((y1 - y2) * (x3",
"self.points] #edge_intersection_count = sum(0 if intersection is None else 1 for intersection in",
"current_point.processed = True current_point = current_point.other_polygon_link current_point.processed = True traversal_direction = TraversalDirection.FORWARD if",
"False divisor = (y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 +",
"is_inside_other = other_polygon.isPointInside(self.points[0].pos) return IntersectionType.EXIT if is_inside_other else IntersectionType.ENTRY def __createPolygonFromIntersections(self, other_polygon, boolean_operator):",
"for point in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator)",
"from enum import Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2",
"current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000): print(\"Fail\") return GreinerHormannPolygon(result_polygon_points) return",
"= (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 =",
"maximize the floating point resolution max_x_point = max(p.pos[0] for p in self.points) ray_to_point",
"in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point, ray.to_point, \" \") #return is_point_inside",
"second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return None current_intersection_type = self.__getFirstIntersectionType(other_polygon)",
"1 for intersection in ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections) ##if",
"GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections, boolean_operator): #",
"intersections[0]): result_polygon_points.append(current_point.pos) if current_point.intersection_type.isIntersection(): current_point.processed = True current_point = current_point.other_polygon_link current_point.processed = True",
"for p in self.points] #edge_intersection_count = sum(0 if intersection is None else 1",
"1e-9: return True return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point)",
"# if (((current_vertex.pos[1] <= point[1]) and (next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1])",
"self.from_point.pos P1 = self.to_point.pos P2 = point return ((P1[0] - P0[0]) * (P2[1]",
"return None t = t_dividend / tu_divisor u = u_dividend / tu_divisor if",
"elif is_downward: if t < 1e-9 or t >= 1 - 1e-9 or",
"PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction = TraversalDirection.FORWARD _cnt = 0",
"Last edit date: 16 August 2019 def computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1])",
"def __init__(self, from_point, to_point): self.from_point = from_point self.to_point = to_point self.intersections = []",
"supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) result_polygon_points = [] current_point = intersections[0] traversal_direction",
"1e-9: return None t = t_dividend / tu_divisor u = u_dividend / tu_divisor",
"u <= -1e-9 or u >= 1 - 1e-9: return None elif is_downward:",
"= (self.to_point.pos[0], self.to_point.pos[1]) dividend = sqrt((y2 - y1)**2 + (x2 - x1)**2) if",
"#print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge",
"== TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point):",
"y3 > y4 if is_upward: if t <= 1e-9 or t >= 1",
"in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia #",
"y1)**2 + (x2 - x1)**2) if dividend <= 1e-9: return False divisor =",
"from_point self.to_point = to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t))",
"# Title: Line–line intersection # Author: Wikipedia # Last edit date: 16 August",
"p in self.points] #edge_intersection_count = sum(0 if intersection is None else 1 for",
"or u >= 1 - 1e-9: return None elif is_downward: if t <",
"<= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): #",
"- y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection",
"abs(divisor / dividend) if distance < 1e-9: return True return False class GreinerHormannPolygon:",
"def __computePolygonWidth(self): return max(point.pos[0] for point in self.points) - min(point.pos[0] for point in",
"self.prev = None self.other_polygon_link = None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION",
"/ tu_divisor is_upward = y3 < y4 is_downward = y3 > y4 if",
"other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0], other_edge.from_point.pos[1])",
"str(edge.to_point))) + ')' for edge in self.edges)) self.edges = self.__getEdgesFromPoints() #print(\"Edges after: \",",
"import Enum from math import sqrt class IntersectionType(Enum): NOT_AN_INTERSECTION=0 UNKNOWN=1 ENTRY=2 EXIT=3 def",
"== self.EXIT): return self.ENTRY return enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def",
"sum(0 if intersection is None else 1 for intersection in ray_intersections) #vertex_intersection_count =",
"remakeFromEdges(self, edge_list): edge_points = [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('('",
"= False def setNext(self, next_point): self.next = next_point def setPrev(self, prev_point): self.prev =",
"point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005",
"(other_edge.from_point.pos[0], other_edge.from_point.pos[1]) x4,y4 = (other_edge.to_point.pos[0], other_edge.to_point.pos[1]) t_dividend = ((x1 - x3) * (y3",
"current_point.processed = True traversal_direction = TraversalDirection.FORWARD if current_point.intersection_type == IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point",
"# if point[1] < current_vertex.pos[1] + vt * (next_vertex.pos[0] - current_vertex.pos[0]): # cn",
"vt = (point[1] - current_vertex.pos[1]) / (next_vertex.pos[1] - current_vertex.pos[1]) # if point[1] <",
"= max(p.pos[0] for p in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray",
"intersection in ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections) ##if edge_intersection_count %",
"= abs(divisor / dividend) if distance < 1e-9: return True return False class",
"= self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def",
">= 1 - 1e-9 or u <= -1e-9 or u >= 1 -",
"- P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] -",
"or self == self.ENTRY or self == self.EXIT def getInverted(self): if(self == self.ENTRY):",
"from .polygon_boolean_operator import PolygonBooleanOperator from enum import Enum from math import sqrt class",
"= (x1 + (t * (x2 - x1)), y1 + (t * (y2",
"t_dividend / tu_divisor u = u_dividend / tu_divisor if t <= 1e-9 or",
"'.join(str(point) for point in self.points)) return [PolygonEdge(self.points[i], self.points[(i+1) % len(self.points)]) for i in",
"* (x3 - x4)) u_dividend = -(((x1 - x2) * (y1 - y3))",
"point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count",
"ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in self.edges) ray_intersections_count = sum(1 for intersection in",
"if t < 1e-9 or t >= 1 - 1e-9 or u <=",
"is not None: first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point =",
"__getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION)",
"date: 16 August 2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 =",
"P1 = self.to_point.pos P2 = point return ((P1[0] - P0[0]) * (P2[1] -",
"ray_intersections if intersection) is_point_inside = ray_intersections_count % 2 == 1 return is_point_inside #vertex_intersections",
"_cnt = 0 while(any(not intersection.processed for intersection in intersections) or current_point != intersections[0]):",
"== 1 return is_point_inside #vertex_intersections = [ray.intersectsPoint(p) for p in self.points] #edge_intersection_count =",
"and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon def",
"- x3) * (y3 - y4)) - ((y1 - y3) * (x3 -",
"through all edges of the polygon #for i in range(len(self.points)): # current_vertex =",
"for p in self.pos) + ')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point",
"TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link",
"0.16535) < 0.00005 and abs(point[1] - 0.20472) < 0.00005: # print(','.join(str(pt) for pt",
"= [] for first_edge in first_polygon.edges: for second_edge in second_polygon.edges: first_intersection = first_edge.computeIntersection(second_edge)",
"len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator):",
"(next_vertex.pos[1] > point[1])) or ((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): # vt",
"traversal_direction == TraversalDirection.BACKWARDS: return self.prev def linkToPoint(self, other_point): self.other_polygon_link = other_point def __str__(self):",
"% len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point",
"for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; # the",
"return ((P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) *",
"self.points[i] next_point = self.points[(i+1) % len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self):",
"max(point.pos[0] for point in self.points) - min(point.pos[0] for point in self.points) @staticmethod def",
"if intersection is None else 1 for intersection in ray_intersections) #vertex_intersection_count = sum(a",
"len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)): point =",
"True return False class GreinerHormannPolygon: def __init__(self, points_list=[]): self.points = [PolygonPoint(point) for point",
"t = t_dividend / tu_divisor u = u_dividend / tu_divisor is_upward = y3",
"tu_divisor if t <= 1e-9 or t > 1 - 1e-9 or u",
"(y1 - y3)) - ((y1 - y2) * (x1 - x3))) tu_divisor =",
"getNext(self, traversal_direction): if traversal_direction == TraversalDirection.FORWARD: return self.next elif traversal_direction == TraversalDirection.BACKWARDS: return",
"in self.edges)) self.__setupPointsOrder() def isPointInside(self, point): #cn = 0; # the crossing number",
"ray_intersections) #vertex_intersection_count = sum(a for a in vertex_intersections) ##if edge_intersection_count % 2 ==",
"isPointLeft(point): P0 = self.from_point.pos P1 = self.to_point.pos P2 = point return ((P1[0] -",
"= [point for point in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return",
"other_polygon, boolean_operator): # Currently the only supported boolean operator assert(boolean_operator == PolygonBooleanOperator.INTERSECTION) this_is_inside_other",
"IntersectionType.ENTRY else TraversalDirection.BACKWARDS current_point = current_point.getNext(traversal_direction) _cnt += 1 if(_cnt > 1000): print(\"Fail\")",
"self.points[i] # next_vertex = self.points[(i + 1) % len(self.points)] # if (((current_vertex.pos[1] <=",
"t >= 1 - 1e-9 or u <= -1e-9 or u >= 1",
"+ (t * (y2 - y1)), 0) return (intersection_point, t) # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection",
"% len(self.points)] prev_point = self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point",
"in self.edges) ray_intersections_count = sum(1 for intersection in ray_intersections if intersection) is_point_inside =",
"\", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges))",
"PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon):",
"PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point self.to_point = to_point self.intersections =",
"((current_vertex.pos[1] > point[1]) and (next_vertex.pos[1] <= point[1]))): # vt = (point[1] - current_vertex.pos[1])",
"point in self.points) @staticmethod def __computeEdgeIntersections(first_polygon, second_polygon): intersections = [] for first_edge in",
"first_intersection = first_edge.computeIntersection(second_edge) second_intersection = second_edge.computeIntersection(first_edge) if first_intersection is not None and second_intersection",
"- x4)) if abs(tu_divisor) <= 1e-9: return None t = t_dividend / tu_divisor",
"point inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535)",
"computeIntersectionForPointInPolygon(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3 = (other_edge.from_point.pos[0],",
"##print('Points: ', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count %",
"intersection_count % 2 == 1 ##print(\"Edge cnt:\", len(self.edges), \", edgeint:\", edge_intersection_count, \", pointint:\",",
"1e-9 or u >= 1 + 1e-9: return None else: return None intersection_point",
"is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator):",
"((y1 - y3) * (x3 - x4)) u_dividend = -(((x1 - x2) *",
"', ','.join(str(pt) for pt in self.points)) ##print('INts:', vertex_intersections) #is_point_inside = intersection_count % 2",
"self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection # Title: Line–line intersection # Author: Wikipedia # Last",
"[point for point in self.points if point.intersection_type.isIntersection()] if len(intersections) <= 0: return self.__getNonIntersectingPolygon(other_polygon,",
"range(len(self.points)): # current_vertex = self.points[i] # next_vertex = self.points[(i + 1) % len(self.points)]",
"is_intersection=True) second_intersection_point = PolygonPoint(second_intersection_pos, is_intersection=True) first_intersection_point.linkToPoint(second_intersection_point) second_intersection_point.linkToPoint(first_intersection_point) first_edge.insertIntersectionAt(first_intersection_point, t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges)",
"__init__(self, points_list=[]): self.points = [PolygonPoint(point) for point in points_list] self.edges = self.__getEdgesFromPoints() self.__setupPointsOrder()",
"x2*y1 + y2*x1 distance = abs(divisor / dividend) if distance < 1e-9: return",
"= self.points[i-1] point.setNext(next_point) point.setPrev(prev_point) def __computePolygonWidth(self): return max(point.pos[0] for point in self.points) -",
"enum_type class TraversalDirection(Enum): FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos =",
"+ 1, point[1])) ray = PolygonEdge(ray_from_point, ray_to_point) ray_intersections = (ray.computeIntersectionForPointInPolygon(edge) for edge in",
"linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def getPolygonPointsFromBoolean(self, other_polygon, boolean_operator): return self.__createPolygonFromIntersections(other_polygon, boolean_operator)",
"self.points[(i+1) % len(self.points)]) for i in range(len(self.points))] def __setupPointsOrder(self): for i in range(len(self.points)):",
"= self.isPointInside(other_polygon.points[0].pos) if not this_is_inside_other and not other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return",
"first_intersection_pos, t = first_intersection second_intersection_pos, u = second_intersection first_intersection_point = PolygonPoint(first_intersection_pos, is_intersection=True) second_intersection_point",
"+ y2*x1 distance = abs(divisor / dividend) if distance < 1e-9: return True",
"2019 def computeIntersection(self, other_edge): x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1]) x3,y3",
"- 1e-9: return None elif is_downward: if t < 1e-9 or t >=",
"= self.__getEdgesFromPoints() #print(\"Edges after: \", ', '.join('(' + ', '.join((str(edge.from_point), str(edge.to_point))) + ')'",
"loop through all edges of the polygon #for i in range(len(self.points)): # current_vertex",
"BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos self.next = None",
"self.intersections.sort(key=lambda intersection: intersection[1]) return [intersection[0] for intersection in self.intersections] # Source: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection #",
"\" \") #return is_point_inside @staticmethod def linkPolygons(first_polygon, second_polygon): GreinerHormannPolygon.__computeEdgeIntersections(first_polygon, second_polygon) first_polygon.__updateIntersectionTypes(second_polygon) second_polygon.__updateIntersectionTypes(first_polygon) def",
"+ (t * (y2 - y1)), 0) return (intersection_point, t) def isPointLeft(point): P0",
"inside:\", point, is_point_inside, \", ray:\", ray.from_point, ray.to_point, intersection_count) #if abs(point[0] - 0.16535) <",
"to_point self.intersections = [] def insertIntersectionAt(self, intersection_point, t): self.intersections.append((intersection_point, t)) def getIntersectionsAsPoints(self): self.intersections.sort(key=lambda",
"ray.to_point, intersection_count) #if abs(point[0] - 0.16535) < 0.00005 and abs(point[1] - 0.20472) <",
"t) second_edge.insertIntersectionAt(second_intersection_point, u) first_polygon.remakeFromEdges(first_polygon.edges) second_polygon.remakeFromEdges(second_polygon.edges) def __updateIntersectionTypes(self, other_polygon): if len(self.points) <= 0: return",
"other_is_inside_this: return GreinerHormannPolygon() if this_is_inside_other: return self else: return other_polygon def __tracePolygonPerimetersFromIntersections(self, intersections,",
"= [[edge.from_point, *edge.getIntersectionsAsPoints()] for edge in edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for",
"', '.join((str(edge.from_point), str(edge.to_point))) + ')' for edge in self.edges)) self.__setupPointsOrder() def isPointInside(self, point):",
"0.00005: # print(','.join(str(pt) for pt in self.points)) # print(is_point_inside, edge_intersection_count, vertex_intersection_count, len(self.points), ray.from_point,",
"point.intersection_type.isIntersection(): point.intersection_type = current_intersection_type current_intersection_type = current_intersection_type.getInverted() def __getFirstIntersectionType(self, other_polygon): is_inside_other = other_polygon.isPointInside(self.points[0].pos)",
"0: return self.__getNonIntersectingPolygon(other_polygon, boolean_operator) return self.__tracePolygonPerimetersFromIntersections(intersections, boolean_operator) def __getNonIntersectingPolygon(self, other_polygon, boolean_operator): # Currently",
"for p in self.points) ray_to_point = PolygonPoint((max_x_point + 1, point[1])) ray = PolygonEdge(ray_from_point,",
"- y4) * (x1 - x2)) - ((y1 - y2) * (x3 -",
"x3) * (y3 - y4)) - ((y1 - y3) * (x3 - x4))",
"FORWARD=1 BACKWARDS=2 class PolygonPoint: def __init__(self, pos, is_intersection=False): self.pos = pos self.next =",
"False def setNext(self, next_point): self.next = next_point def setPrev(self, prev_point): self.prev = prev_point",
"edge_list] #print(\"Edge points:\", ','.join('(' + ','.join(str(pt) for pt in edge_point) + ')' for",
"= None self.intersection_type = IntersectionType.UNKNOWN if is_intersection else IntersectionType.NOT_AN_INTERSECTION self.processed = False def",
"in self.pos) + ')' class PolygonEdge: def __init__(self, from_point, to_point): self.from_point = from_point",
"= self.to_point.pos P2 = point return ((P1[0] - P0[0]) * (P2[1] - P0[1])",
"point): x0,y0 = (point.pos[0], point.pos[1]) x1,y1 = (self.from_point.pos[0], self.from_point.pos[1]) x2,y2 = (self.to_point.pos[0], self.to_point.pos[1])"
] |
[
"import Body from typing import Optional class FormModel(BaseModel): first_name: str = None second_name:",
"<filename>app/routes/models/form_model.py<gh_stars>0 from pydantic import BaseModel from fastapi.param_functions import Body from typing import Optional",
"from fastapi.param_functions import Body from typing import Optional class FormModel(BaseModel): first_name: str =",
"pydantic import BaseModel from fastapi.param_functions import Body from typing import Optional class FormModel(BaseModel):",
"BaseModel from fastapi.param_functions import Body from typing import Optional class FormModel(BaseModel): first_name: str",
"Body from typing import Optional class FormModel(BaseModel): first_name: str = None second_name: str",
"import BaseModel from fastapi.param_functions import Body from typing import Optional class FormModel(BaseModel): first_name:",
"from pydantic import BaseModel from fastapi.param_functions import Body from typing import Optional class",
"fastapi.param_functions import Body from typing import Optional class FormModel(BaseModel): first_name: str = None"
] |
[] |
[
"params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json",
"offset \"wt\": \"json\", # format } if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"'",
"product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\",",
"if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response",
"query, # filter \"rows\": rows, # no of results per response \"sort\": \"title",
"yield data if __name__ == \"__main__\": res = _search() for item in res:",
"fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params =",
"in json: yield data if __name__ == \"__main__\": res = _search() for item",
"if response.status_code != 200: break json = response.json()['response'].get('docs', []) if not len(json): break",
"json = response.json()['response'].get('docs', []) if not len(json): break for data in json: yield",
"# sort \"start\": -rows, # offset \"wt\": \"json\", # format } if nsuid:",
"f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if",
"__name__ == \"__main__\": res = _search() for item in res: print(json.dumps(item, indent=4, sort_keys=True))",
"return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str",
"diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200",
"!= 200: break json = response.json()['response'].get('docs', []) if not len(json): break for data",
"AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code",
"= \"*\", nsuid: str = None, ) -> Iterator[dict]: ''' make query to",
"} if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows",
"api return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int,",
"-rows, # offset \"wt\": \"json\", # format } if nsuid: params[\"fq\"] += f'",
"system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\": rows, # no of results",
"= { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\":",
"= None, ) -> Iterator[dict]: ''' make query to noe api return a",
"while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200:",
"params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, # filter",
"import Iterator, Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str",
"break json = response.json()['response'].get('docs', []) if not len(json): break for data in json:",
"filter \"q\": query, # filter \"rows\": rows, # no of results per response",
"response.json()['response'].get('docs', []) if not len(json): break for data in json: yield data if",
"response.status_code != 200: break json = response.json()['response'].get('docs', []) if not len(json): break for",
"import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid:",
"response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json = response.json()['response'].get('docs', [])",
"no of results per response \"sort\": \"title asc\", # sort \"start\": -rows, #",
"typing import Iterator, Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query:",
"per response \"sort\": \"title asc\", # sort \"start\": -rows, # offset \"wt\": \"json\",",
"rows, # no of results per response \"sort\": \"title asc\", # sort \"start\":",
"sort \"start\": -rows, # offset \"wt\": \"json\", # format } if nsuid: params[\"fq\"]",
"AND system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\": rows, # no of",
"# filter \"q\": query, # filter \"rows\": rows, # no of results per",
"results per response \"sort\": \"title asc\", # sort \"start\": -rows, # offset \"wt\":",
"nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response =",
"image_url:str,image_url_h2x1_s:str ''' rows = 200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", #",
"\"rows\": rows, # no of results per response \"sort\": \"title asc\", # sort",
"# filter \"rows\": rows, # no of results per response \"sort\": \"title asc\",",
"+= f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params)",
"= response.json()['response'].get('docs', []) if not len(json): break for data in json: yield data",
"Iterator[dict]: ''' make query to noe api return a iterator of diction useful",
"data if __name__ == \"__main__\": res = _search() for item in res: print(json.dumps(item,",
"requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json = response.json()['response'].get('docs', []) if not",
"200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, #",
"params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL,",
"json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid: str =",
"<filename>NintendoOne/api/noe.py from typing import Iterator, Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def",
"_search( query: str = \"*\", nsuid: str = None, ) -> Iterator[dict]: '''",
"-> Iterator[dict]: ''' make query to noe api return a iterator of diction",
"nsuid: str = None, ) -> Iterator[dict]: ''' make query to noe api",
"noe api return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float,",
"None, ) -> Iterator[dict]: ''' make query to noe api return a iterator",
"def _search( query: str = \"*\", nsuid: str = None, ) -> Iterator[dict]:",
"\"json\", # format } if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True:",
"price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params = { \"fq\": \"type:GAME",
"of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows =",
"format } if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] +=",
"filter \"rows\": rows, # no of results per response \"sort\": \"title asc\", #",
"of results per response \"sort\": \"title asc\", # sort \"start\": -rows, # offset",
"SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid: str = None,",
"\"start\": -rows, # offset \"wt\": \"json\", # format } if nsuid: params[\"fq\"] +=",
"Iterator, Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str =",
"language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params = { \"fq\":",
"nsuid_txt:\"{nsuid}\"' while True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code !=",
"\"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\": rows, #",
"if __name__ == \"__main__\": res = _search() for item in res: print(json.dumps(item, indent=4,",
"Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\",",
"\"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\": rows, # no",
"from typing import Iterator, Optional import requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search(",
"str = \"*\", nsuid: str = None, ) -> Iterator[dict]: ''' make query",
") -> Iterator[dict]: ''' make query to noe api return a iterator of",
"query: str = \"*\", nsuid: str = None, ) -> Iterator[dict]: ''' make",
"make query to noe api return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[],",
"data in json: yield data if __name__ == \"__main__\": res = _search() for",
"= 200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query,",
"price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params = { \"fq\": \"type:GAME AND",
"{ \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\": query, # filter \"rows\": rows,",
"# format } if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while True: params[\"start\"]",
"== \"__main__\": res = _search() for item in res: print(json.dumps(item, indent=4, sort_keys=True)) input(\"continue?\")",
"iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows",
"a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str '''",
"if not len(json): break for data in json: yield data if __name__ ==",
"useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params",
"for data in json: yield data if __name__ == \"__main__\": res = _search()",
"''' rows = 200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter",
"# no of results per response \"sort\": \"title asc\", # sort \"start\": -rows,",
"[]) if not len(json): break for data in json: yield data if __name__",
"dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool, price_lowest_f:float,price_regular_f:float, product_code_txt[0],title:str,url:str,popularity:int, image_url:str,image_url_h2x1_s:str ''' rows = 200 params = {",
"# offset \"wt\": \"json\", # format } if nsuid: params[\"fq\"] += f' AND",
"= requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json = response.json()['response'].get('docs', []) if",
"\"*\", nsuid: str = None, ) -> Iterator[dict]: ''' make query to noe",
"\"title asc\", # sort \"start\": -rows, # offset \"wt\": \"json\", # format }",
"len(json): break for data in json: yield data if __name__ == \"__main__\": res",
"requests, json SEARCH_URL = \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid: str",
"asc\", # sort \"start\": -rows, # offset \"wt\": \"json\", # format } if",
"''' make query to noe api return a iterator of diction useful fields:",
"rows = 200 params = { \"fq\": \"type:GAME AND system_type:nintendoswitch\", # filter \"q\":",
"params=params) if response.status_code != 200: break json = response.json()['response'].get('docs', []) if not len(json):",
"\"wt\": \"json\", # format } if nsuid: params[\"fq\"] += f' AND nsuid_txt:\"{nsuid}\"' while",
"to noe api return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0], price_discount_percentage_f:float,price_has_discount_b:bool,",
"= \"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid: str = None, )",
"response \"sort\": \"title asc\", # sort \"start\": -rows, # offset \"wt\": \"json\", #",
"\"sort\": \"title asc\", # sort \"start\": -rows, # offset \"wt\": \"json\", # format",
"rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json = response.json()['response'].get('docs',",
"\"q\": query, # filter \"rows\": rows, # no of results per response \"sort\":",
"+= rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break json =",
"str = None, ) -> Iterator[dict]: ''' make query to noe api return",
"\"http://search.nintendo-europe.com/en/select\" def _search( query: str = \"*\", nsuid: str = None, ) ->",
"not len(json): break for data in json: yield data if __name__ == \"__main__\":",
"200: break json = response.json()['response'].get('docs', []) if not len(json): break for data in",
"break for data in json: yield data if __name__ == \"__main__\": res =",
"True: params[\"start\"] += rows response = requests.get(url=SEARCH_URL, params=params) if response.status_code != 200: break",
"json: yield data if __name__ == \"__main__\": res = _search() for item in",
"query to noe api return a iterator of diction useful fields: dates_released_dts[0],excerpt:str,game_categories_txt[], language_availability[],nsuid_txt[0],"
] |
[
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'), ]",
"2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'),",
"# Generated by Django 2.0.7 on 2018-07-23 08:52 from django.db import migrations class",
"class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'), ] operations = [",
"on 2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api',",
"Django 2.0.7 on 2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"by Django 2.0.7 on 2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration): dependencies",
"Generated by Django 2.0.7 on 2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration):",
"import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'), ] operations",
"08:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api',",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'),",
"migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'), ] operations =",
"Migration(migrations.Migration): dependencies = [ ('api', '0008_merge_20180723_0613'), ('api', '0006_auto_20180719_2243'), ] operations = [ ]",
"2.0.7 on 2018-07-23 08:52 from django.db import migrations class Migration(migrations.Migration): dependencies = ["
] |
[
"y[i]), color=(1, 1, 1)) return ax def count_presses(text): press_count = {} for idx,",
"func = partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join() for",
"CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase",
"in enumerate(text): if char not in press_count: press_count[char] = 1 else: press_count[char] +=",
"return ax def count_presses(text): press_count = {} for idx, char in enumerate(text): if",
"COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for",
"{} for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): zones[key] =",
"pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1 = text[idx",
"stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time()",
"[[presses_counts[item] if item in presses_counts else 0 for item in row] for row",
"pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2",
"colour import Color import copy import math import re import time from consts",
"+ 1 < len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1]",
"txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax def count_presses(text):",
"= default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2,",
"in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax def count_presses(text): press_count",
"return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] =",
"alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt in enumerate(n): ax.annotate(txt,",
"default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6],",
"default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1,",
"b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes,",
"COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8],",
"press_count): keys = [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2],",
"1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke = '' if idx",
"* stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" %",
"Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func,",
"(x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x = [i[0] for i",
"= [i[1] for i in [item for sublist in coords for item in",
"marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if",
"+ 1 == len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1]",
"zones = {} for idr, row in enumerate(QWERTY): for idk, key in enumerate(row):",
"idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords,",
"= { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС':",
"def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts else 0 for item",
"'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in",
"mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\"",
"- 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty): distances",
"is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]]",
"distance }) return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone }",
"{\"zone\": current_zone, \"count\": 1} stroke = '' if idx + 1 == len(sample):",
"x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda",
"enumerate(text): if idx + 1 == len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0]",
"y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance })",
"if idx + 1 == len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1",
"results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results: if stroke_distance is",
"# Or if you want different settings for the grids: major_ticks = np.arange(-20,",
"in enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk])",
"== 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 =",
"want different settings for the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks =",
"row_num, value): new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0]",
"Or if you want different settings for the grids: major_ticks = np.arange(-20, 210,",
"bs4 import BeautifulSoup from colour import Color import copy import math import re",
"f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist =",
"{distance_1[k] / 1000:.2f} м - меньше на {delta / 1000:.2f} м ({(1 -",
"red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b",
"(100 / max_value) * distance color_hue = int(round(color_hue)) r, g, b = colors[color_hue",
"# Or if you want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major',",
"in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)",
"def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper =",
"mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance",
"int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b,",
"\"distance\": distance }) else: char_1 = text[idx - 1] x1 = mapper[char_1]['x'] y1",
"\"pair\": pair, \"distance\": distance }) return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance,",
"= dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'],",
"current_zone: r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke",
"sublist]] n = [item for sublist in QWERTY for item in sublist] fig,",
"distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на {delta",
"char_1 = text[idx - 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 =",
"idr, row in enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk] == zone",
"'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], }",
"= Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results =",
"coords for item in sublist]] y = [i[1] for i in [item for",
"f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1 = text[idx - 1]",
"stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 =",
"= {} for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): zones[key]",
"press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts else 0 for item in",
"y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys,",
"BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ',",
"'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ':",
"if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] +=",
"(distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\")",
"manager = Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get()",
"item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in",
"total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if",
"color_hue = (100 / max_value) * distance color_hue = int(round(color_hue)) r, g, b",
"if item in presses_counts else 0 for item in row] for row in",
"strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes",
"= np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a",
"= default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 =",
"'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper",
"= {} num_workers = cpu_count() p = Pool(num_workers) manager = Manager() func =",
"want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12,",
"v in distance.items(): delta = v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k]",
"меньше на {delta / 1000:.2f} м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\")",
"stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] *",
"import time from consts import QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html):",
"+ value return new_coords def get_mapper(c, k): text_mapper = { item: { 'x':",
"210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True)",
"draw_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist in coords",
"QWERTY] def zone_distances(zone, press_count): keys = [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ':",
"zones[key] = THUMBS[idr][idk] strokes = {} stroke = '' for idx, char in",
"current_zone, \"count\": 1} stroke = '' if idx + 1 == len(sample): r_stroke",
"row] for row in QWERTY] def zone_distances(zone, press_count): keys = [] default_position =",
"} default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ':",
"'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time =",
"2: ', '').replace('Пользователь 1: ', '') for i in spans]).lower() return re.sub('[^а-я]+', '',",
"enumerate(k) for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper",
"ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') # Or if you",
"\"pair\": pair, \"distance\": distance }) if idx == 0: char_1 = default_keys[zone] x1",
"coords for item in sublist]] n = [item for sublist in QWERTY for",
"\"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return",
"1)) def get_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist",
"= ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for i in spans]).lower() return",
"return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for i in [item for",
"in enumerate(text): if idx + 1 == len(text): char_1 = char x1 =",
"THUMBS[idx][idy] } for idx, sublist in enumerate(k) for idy, item in enumerate(sublist) }",
"grids: major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks,",
"color_hue = int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r,",
"на {delta / 1000:.2f} м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая",
"print(\"--- %s seconds ---\" % (time.time() - start_time)) return { \"pairs\": pairs, \"distances\":",
"x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2",
"= default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance =",
"x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth",
"idx, char in enumerate(sample): current_zone = zones[char] stroke += char if idx +",
"char if idx + 1 < len(sample) and zones[sample[idx + 1]] != current_zone:",
"p.close() p.join() for stroke_distance in results: if stroke_distance is None: continue # stroke_distance",
"elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"]",
"Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b = pair[0],",
"+= delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на {delta / 1000:.2f}",
"idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def get_mapper(c,",
"= text[idx - 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char",
"coords[1][9], } start_time = time.time() mapper = get_mapper(coords, qwerty) pairs = {} num_workers",
"colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty):",
"num_workers = cpu_count() p = Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position,",
"coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9],",
"enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x =",
"+ 1]] != current_zone: r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] +=",
"= mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value)",
"partial import numpy as np from bs4 import BeautifulSoup from colour import Color",
"for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk]",
"'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k) for",
"for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones =",
"in press_count: press_count[char] = 1 else: press_count[char] += 1 return press_count def press_heatmap(presses_counts,",
"default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2 = mapper[char]['y']",
"(max_line_width / max_value) * distance color_hue = (100 / max_value) * distance color_hue",
"ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') # Or if you want",
"enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k): text_mapper =",
"({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum /",
"len(text) <= 1: return for idx, char in enumerate(text): if idx + 1",
"y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width /",
"/ 1000:.2f} м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась",
"linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ':",
"def distance_deltas(distance, distance_1): sum = 0 for k, v in distance.items(): delta =",
"row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red =",
"= f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return { \"pairs\": pairs, \"count\":",
"qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8],",
"press_count[char] = 1 else: press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY): return",
"= calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] })",
"if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs:",
"import re import time from consts import QWERTY, THUMBS, COORDS CACHE = {}",
"coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0,",
"new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k): text_mapper = { item: {",
"ax.grid(which='both') # Or if you want different settings for the grids: ax.grid(which='minor', alpha=0.2)",
"list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 =",
"= p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results: if stroke_distance is None:",
"1]] != current_zone: r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1",
"text[idx - 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2",
"+= 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2):",
"zone = stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance = 0 if",
"default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"]",
"alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]),",
"+= pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"]",
"get_mapper(c, k): text_mapper = { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy]",
"1)) return ax def count_presses(text): press_count = {} for idx, char in enumerate(text):",
"distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 =",
"calculateDistance(x1, y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair,",
"distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0,",
"x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance",
"for the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5)",
"<= 1: return for idx, char in enumerate(text): if idx + 1 ==",
"} def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper",
"for k, v in distance.items(): delta = v - distance_1[k] sum += delta",
"key in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1, y1",
"\"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '')",
"[i[0] for i in [item for sublist in coords for item in sublist]]",
"'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ':",
"'' for idx, char in enumerate(sample): current_zone = zones[char] stroke += char if",
"zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"]",
"fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш',",
"= 0 if len(text) <= 1: return for idx, char in enumerate(text): if",
"zone and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 =",
"= f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if idx == 0: char_1",
"= new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c)",
"default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6],",
"CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"]",
"finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx, cell",
"for idk, key in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0:",
"y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance",
"pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] *",
"'' if idx + 1 == len(sample): r_stroke = stroke[::-1] if stroke in",
"y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x = [i[0] for i in",
"math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def",
"= { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС':",
"i in [item for sublist in coords for item in sublist]] y =",
"in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke = '' for idx,",
"else: press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item",
"= char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2,",
"ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty): distances = {",
"stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() - start_time)) return { \"pairs\": pairs,",
"[i[1] for i in [item for sublist in coords for item in sublist]]",
"f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if idx == 0: char_1 =",
"f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return { \"pairs\": pairs, \"count\": count,",
"enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) >",
"item in row] for row in QWERTY] def zone_distances(zone, press_count): keys = []",
"\"distance\": distance }) return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone",
"process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ':",
"sum = 0 for k, v in distance.items(): delta = v - distance_1[k]",
"max_value) * distance color_hue = int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb",
"{ \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS,",
"idx + 1 < len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke =",
"= mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair =",
"distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({",
"1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty): distances =",
"text = stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance",
"'', lowercase) def generate_strokes(sample, QWERTY): zones = {} for idr, row in enumerate(QWERTY):",
"'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ':",
"return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c,",
"coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper =",
"import QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\")",
"pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1 = text[idx - 1] x1",
"coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time",
"< len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1] if stroke",
"if idx + 1 == len(sample): r_stroke = stroke[::-1] if stroke in strokes:",
"* stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() - start_time)) return { \"pairs\":",
"ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors =",
"20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) #",
"CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 -",
"finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx,",
"{\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in",
"'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr,",
"Or if you want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5)",
"'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, }",
"and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0],",
"QWERTY): x = [i[0] for i in [item for sublist in coords for",
"qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0],",
"= plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal',",
"y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or",
"{ 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7],",
"THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans =",
"return [[presses_counts[item] if item in presses_counts else 0 for item in row] for",
"i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax def",
"new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value",
"idx, char in enumerate(text): if char not in press_count: press_count[char] = 1 else:",
"pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}']",
"strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\"",
"{ 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7],",
"QWERTY): zones = {} for idr, row in enumerate(QWERTY): for idk, key in",
"CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist",
"* stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"]",
"item in sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5,",
"np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks,",
"= (100 / max_value) * distance color_hue = int(round(color_hue)) r, g, b =",
"> 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance",
"= char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 =",
"'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], }",
"0, 'ПБ': 0, 'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1],",
"if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist",
"1: ', '') for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample,",
"time from consts import QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup",
"in coords for item in sublist]] y = [i[1] for i in [item",
"from bs4 import BeautifulSoup from colour import Color import copy import math import",
"distance }) else: char_1 = text[idx - 1] x1 = mapper[char_1]['x'] y1 =",
"press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum =",
"enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke = '' for idx, char",
"for idx, char in enumerate(sample): current_zone = zones[char] stroke += char if idx",
"'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ':",
"default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({",
"coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper = get_mapper(coords, qwerty)",
"+= distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if idx",
"pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count,",
"distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]]",
"'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys = { 'ЛМ':",
"QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def",
"м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum",
"1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global",
"cpu_count from functools import partial import numpy as np from bs4 import BeautifulSoup",
"qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position",
"qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2],",
"None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] +=",
"major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True)",
"= default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2 =",
"strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke =",
"color=(1, 1, 1)) return ax def count_presses(text): press_count = {} for idx, char",
"char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1,",
"qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ':",
"from functools import partial import numpy as np from bs4 import BeautifulSoup from",
"mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y']",
"strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if",
"'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position =",
"ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i],",
"= time.time() mapper = get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count() p",
"value return new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx, row",
"if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1]",
"\"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True)",
"= cpu_count() p = Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position, default_keys,",
"p.join() for stroke_distance in results: if stroke_distance is None: continue # stroke_distance =",
"* stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]]",
"finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value):",
"return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if",
"{ 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k)",
"= colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def process_strokes(strokes, coords,",
"x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance",
"return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'],",
"in [item for sublist in coords for item in sublist]] n = [item",
"len(sample): r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke",
"item in sublist]] n = [item for sublist in QWERTY for item in",
"return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts else 0",
"= 1 else: press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item]",
"a corresponding grid ax.grid(which='both') # Or if you want different settings for the",
"= Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close()",
"= '' if idx + 1 == len(sample): r_stroke = stroke[::-1] if stroke",
"'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ':",
"stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"]",
"plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box')",
"\"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum",
"c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k) for idy,",
"enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0],",
"0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char",
"\"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY,",
"draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS,",
"pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else:",
"get_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist in coords",
"QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a,",
"+= distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1",
"char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2",
"== len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 =",
"return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0 for",
"idx == 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2",
"in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y']",
"{} stroke = '' for idx, char in enumerate(sample): current_zone = zones[char] stroke",
"in presses_counts else 0 for item in row] for row in QWERTY] def",
"you want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210,",
"default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2)",
"return for idx, char in enumerate(text): if idx + 1 == len(text): char_1",
"COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row",
"delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на {delta / 1000:.2f} м",
"color=(r, g, b, 1)) def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0,",
"pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\"",
"# print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for",
"zones[char] stroke += char if idx + 1 < len(sample) and zones[sample[idx +",
"in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones = {} for",
"def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2:",
"mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width",
"mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance color_hue = (100 / max_value)",
"value): new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] +",
"in row] for row in QWERTY] def zone_distances(zone, press_count): keys = [] default_position",
"\"count\": count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value,",
"if stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys,",
"enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax def count_presses(text): press_count =",
"in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return",
"qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3],",
"ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10)",
"in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num, value):",
"current_zone = zones[char] stroke += char if idx + 1 < len(sample) and",
"ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax def count_presses(text): press_count = {}",
"THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2,",
"default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6],",
"partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in",
"else: char_1 = text[idx - 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2",
"{sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone",
"0 if len(text) <= 1: return for idx, char in enumerate(text): if idx",
"in enumerate(k) for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return",
"import Color import copy import math import re import time from consts import",
"sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты",
"default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x']",
"spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for",
"mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance",
"[] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ':",
"Manager, cpu_count from functools import partial import numpy as np from bs4 import",
"+ (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return [[",
"different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48])",
"0 for item in row] for row in QWERTY] def zone_distances(zone, press_count): keys",
"distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if idx ==",
"'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], }",
"pair, distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1",
"enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x = [i[0]",
"stroke = '' if idx + 1 == len(sample): r_stroke = stroke[::-1] if",
"dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return",
"stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] =",
"+= pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds",
"mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance",
"def count_presses(text): press_count = {} for idx, char in enumerate(text): if char not",
"from colour import Color import copy import math import re import time from",
"'box') # Or if you want different settings for the grids: major_ticks =",
"pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y']",
"n = [item for sublist in QWERTY for item in sublist] fig, ax",
"distance }) if idx == 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1",
"QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans",
"the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt",
"+= char if idx + 1 < len(sample) and zones[sample[idx + 1]] !=",
"COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY): for idk, key in",
"i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0 for k, v in",
"cpu_count() p = Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper)",
"1, 1)) def get_keyboard(coords, QWERTY): x = [i[0] for i in [item for",
"you want different settings for the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks",
"the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks)",
"1)) def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС':",
"y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1,",
"total_distance = 0 if len(text) <= 1: return for idx, char in enumerate(text):",
"}) else: char_1 = text[idx - 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y']",
"= mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance +=",
"'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k) for idy, item",
"ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') #",
"item in presses_counts else 0 for item in row] for row in QWERTY]",
"Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join()",
"in results: if stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS,",
"pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif",
"+= distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return {",
"pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return { \"pairs\": pairs,",
"press_count = {} for idx, char in enumerate(text): if char not in press_count:",
"max_value) * distance color_hue = (100 / max_value) * distance color_hue = int(round(color_hue))",
"* 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys,",
"get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items():",
"import copy import math import re import time from consts import QWERTY, THUMBS,",
"strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] =",
"grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt in",
"COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\":",
"print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke):",
"default_keys, mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs",
"get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count() p = Pool(num_workers) manager =",
"in enumerate(sample): current_zone = zones[char] stroke += char if idx + 1 <",
"pairs = {} num_workers = cpu_count() p = Pool(num_workers) manager = Manager() func",
"{ 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0,",
"stroke = '' for idx, char in enumerate(sample): current_zone = zones[char] stroke +=",
"y1 = mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance",
"mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance color_hue =",
"row in QWERTY] def zone_distances(zone, press_count): keys = [] default_position = { 'ЛМ':",
"stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] +=",
"COORDS[1][9], } for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): if",
"= copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return",
"Pool, Manager, cpu_count from functools import partial import numpy as np from bs4",
"txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x",
"default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if",
"default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results:",
"ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') #",
"finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for",
"results: if stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position,",
"pairs.append({ \"pair\": pair, \"distance\": distance }) if idx == 0: char_1 = default_keys[zone]",
"total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return",
"max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors",
"def get_mapper(c, k): text_mapper = { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb':",
"in enumerate(QWERTY): for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {}",
"1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x']",
"strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke = ''",
"for idx, sublist in enumerate(k) for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper,",
"1} stroke = '' if idx + 1 == len(sample): r_stroke = stroke[::-1]",
"functools import partial import numpy as np from bs4 import BeautifulSoup from colour",
"stroke[\"count\"] pairs = [] total_distance = 0 if len(text) <= 1: return for",
"for sublist in coords for item in sublist]] y = [i[1] for i",
"sublist in QWERTY for item in sublist] fig, ax = plt.subplots() ax.scatter(x, y,",
"= default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2,",
"reverse=True) def distance_deltas(distance, distance_1): sum = 0 for k, v in distance.items(): delta",
"= (max_line_width / max_value) * distance color_hue = (100 / max_value) * distance",
"and zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1] if stroke in strokes:",
"count_presses(text): press_count = {} for idx, char in enumerate(text): if char not in",
"= [item for sublist in QWERTY for item in sublist] fig, ax =",
"COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance,",
"stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance = 0 if len(text) <=",
"= v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м -",
"shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] =",
"0, 'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2],",
"'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС':",
"'').replace('Пользователь 1: ', '') for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def",
"} start_time = time.time() mapper = get_mapper(coords, qwerty) pairs = {} num_workers =",
"enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num, value): new_coords",
"for item in sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5,",
"matplotlib.pyplot as plt from multiprocessing import Pool, Manager, cpu_count from functools import partial",
"pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) if idx == 0:",
"col_num, value): new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1]",
"+= 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\":",
"idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def shift_col(c,",
"== zone and len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2",
"sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0 for k,",
"= mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance +=",
"0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys = {",
"Color import copy import math import re import time from consts import QWERTY,",
"= [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3],",
"char in enumerate(text): if idx + 1 == len(text): char_1 = char x1",
"in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x =",
"pair, \"distance\": distance }) return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\":",
"= {} for idx, char in enumerate(text): if char not in press_count: press_count[char]",
"else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE",
"print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на {delta / 1000:.2f} м ({(1",
"- x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances):",
"м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count",
"return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones = {} for idr, row",
"дистанция уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text",
"minor=True) # And a corresponding grid ax.grid(which='both') # Or if you want different",
"idr, row in enumerate(QWERTY): for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes",
"{} num_workers = cpu_count() p = Pool(num_workers) manager = Manager() func = partial(count_stroke_distance,",
"''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for i in spans]).lower() return re.sub('[^а-я]+',",
"not in press_count: press_count[char] = 1 else: press_count[char] += 1 return press_count def",
"на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"]",
"mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs =",
"stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance = 0",
"for i in [item for sublist in coords for item in sublist]] y",
"def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count =",
"stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1",
"= mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance =",
"[] total_distance = 0 if len(text) <= 1: return for idx, char in",
"sublist in enumerate(k) for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False))",
"def get_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist in",
"math import re import time from consts import QWERTY, THUMBS, COORDS CACHE =",
"else 0 for item in row] for row in QWERTY] def zone_distances(zone, press_count):",
"48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def",
"'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ':",
"= f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1 = text[idx -",
"idx, sublist in enumerate(k) for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2,",
"/ v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\") def",
"= { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx,",
"for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke =",
"= { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС':",
"from consts import QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup =",
"new_coords def get_mapper(c, k): text_mapper = { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1],",
"count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair",
"CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 +",
"= np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks)",
"count = stroke[\"count\"] pairs = [] total_distance = 0 if len(text) <= 1:",
"5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both')",
"1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"]",
"for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def",
"for idx, char in enumerate(text): if idx + 1 == len(text): char_1 =",
"distance color_hue = (100 / max_value) * distance color_hue = int(round(color_hue)) r, g,",
"v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше",
"minor_ticks = np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And",
"ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x = [i[0] for",
"0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3],",
"'ПМ': coords[1][9], } start_time = time.time() mapper = get_mapper(coords, qwerty) pairs = {}",
"= {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase =",
"\"count\": 1} stroke = '' if idx + 1 == len(sample): r_stroke =",
"value): new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] +",
"in sublist]] n = [item for sublist in QWERTY for item in sublist]",
"distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1):",
"strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke]",
"consts import QWERTY, THUMBS, COORDS CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html,",
"copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords",
"calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return",
"p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results: if stroke_distance is None: continue",
"stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"]",
"210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid",
"current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE:",
"i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones = {}",
"print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for i",
"dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ']",
"for sublist in QWERTY for item in sublist] fig, ax = plt.subplots() ax.scatter(x,",
"count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"]",
"= mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth =",
"default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y']",
"y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk],",
"generate_strokes(sample, QWERTY): zones = {} for idr, row in enumerate(QWERTY): for idk, key",
"pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 =",
"%s seconds ---\" % (time.time() - start_time)) return { \"pairs\": pairs, \"distances\": distances",
"= list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1",
"color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you want",
"', '') for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY):",
"stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in",
"'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ':",
"= stroke[\"count\"] pairs = [] total_distance = 0 if len(text) <= 1: return",
"def generate_strokes(sample, QWERTY): zones = {} for idr, row in enumerate(QWERTY): for idk,",
"minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') # Or if",
"for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i,",
"numpy as np from bs4 import BeautifulSoup from colour import Color import copy",
"y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\":",
"x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2",
"colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1]",
"(y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'],",
"for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"]",
"plt from multiprocessing import Pool, Manager, cpu_count from functools import partial import numpy",
"= [] total_distance = 0 if len(text) <= 1: return for idx, char",
"+= 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke = '' if",
"f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2 -",
"!= current_zone: r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif",
"# And a corresponding grid ax.grid(which='both') # Or if you want different settings",
"distance_1): sum = 0 for k, v in distance.items(): delta = v -",
"COORDS CACHE = {} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span')",
"enumerate(sample): current_zone = zones[char] stroke += char if idx + 1 < len(sample)",
"dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'],",
"finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def",
"distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs:",
"+= stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]]",
"}) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0",
"= calculateDistance(x1, y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\":",
"pair, \"distance\": distance }) if idx == 0: char_1 = default_keys[zone] x1 =",
"]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]):",
"cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ',",
"for i in [item for sublist in coords for item in sublist]] n",
"x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return",
"zone_distances(zone, press_count): keys = [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС':",
"\"pair\": pair, \"distance\": distance }) else: char_1 = text[idx - 1] x1 =",
"idx + 1 == len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 =",
"BeautifulSoup from colour import Color import copy import math import re import time",
"= {\"zone\": current_zone, \"count\": 1} stroke = '' if idx + 1 ==",
"}) if idx == 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 =",
"v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position,",
"stroke += char if idx + 1 < len(sample) and zones[sample[idx + 1]]",
"for idy, item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def",
"in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else:",
"/ 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone =",
"qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1],",
"as plt from multiprocessing import Pool, Manager, cpu_count from functools import partial import",
"= mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair =",
"else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke = '' if idx +",
"strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} return strokes def",
"def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0,",
"in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke",
"CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'],",
"{ item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist",
"press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts else 0 for",
"re import time from consts import QWERTY, THUMBS, COORDS CACHE = {} def",
"finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c)",
"0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you want different settings",
"text_mapper = { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for",
"in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"]",
"char not in press_count: press_count[char] = 1 else: press_count[char] += 1 return press_count",
"in distance.items(): delta = v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k] /",
"coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8],",
"in sublist]] y = [i[1] for i in [item for sublist in coords",
"\"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance,",
"'ЛМ': 0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ':",
"{} def cleanhtml(raw_html): soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь",
"CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"]",
"= mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance color_hue",
"stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke)",
"{delta / 1000:.2f} м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция",
"pairs = [] total_distance = 0 if len(text) <= 1: return for idx,",
"mapper = get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count() p = Pool(num_workers)",
"'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ':",
"def zone_distances(zone, press_count): keys = [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1],",
"- (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f}",
"= char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2,",
"for stroke_distance in results: if stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS,",
"'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys =",
"mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1,",
"[item for sublist in QWERTY for item in sublist] fig, ax = plt.subplots()",
"indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for i in",
"r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in",
"shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] =",
"1 else: press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if",
"in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k): text_mapper",
"ax.set_aspect('equal', 'box') # Or if you want different settings for the grids: major_ticks",
"stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs = []",
"row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k):",
"x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2",
"+ 1 == len(sample): r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] +=",
"p = Pool(num_workers) manager = Manager() func = partial(count_stroke_distance, default_position, default_keys, mapper) results",
"stroke_distance in results: if stroke_distance is None: continue # stroke_distance = count_stroke_distance(COORDS, QWERTY,",
"'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ':",
"-12, 48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1))",
"= {\"zone\": current_zone, \"count\": 1} return strokes def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\"",
"pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s",
"finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx, cell in",
"distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) return { \"pairs\":",
"100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper,",
"start_time = time.time() mapper = get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count()",
"= THUMBS[idr][idk] strokes = {} stroke = '' for idx, char in enumerate(sample):",
"import partial import numpy as np from bs4 import BeautifulSoup from colour import",
"= BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1:",
"= { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС':",
"0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys",
"for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords,",
"= count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for",
"item in sublist]] y = [i[1] for i in [item for sublist in",
"ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you want different settings for",
"if char not in press_count: press_count[char] = 1 else: press_count[char] += 1 return",
"distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else: char_1 =",
"mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) *",
"new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k): text_mapper = {",
"} # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0]",
"{ 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7],",
"1: return for idx, char in enumerate(text): if idx + 1 == len(text):",
"COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY)",
"# stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] *",
"as np from bs4 import BeautifulSoup from colour import Color import copy import",
"0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0],",
"new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value",
"* distance color_hue = (100 / max_value) * distance color_hue = int(round(color_hue)) r,",
"/ max_value) * distance color_hue = (100 / max_value) * distance color_hue =",
"1, 1)) return ax def count_presses(text): press_count = {} for idx, char in",
"y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance",
"np.arange(-20, 210, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding",
"ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') # Or",
"len(QWERTY[idr][idk]) > 0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1]",
"= mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2 = mapper[char_2]['x'] y2 =",
"if you want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12,",
"= soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for i",
"grid ax.grid(which='both') # Or if you want different settings for the grids: ax.grid(which='minor',",
"ax.axis([-12, 210, -12, 48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1,",
"for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return ax",
"'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY): for",
"if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2 + (y2",
"sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на {delta /",
"idk, key in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1,",
"settings for the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20, 210,",
"if len(text) <= 1: return for idx, char in enumerate(text): if idx +",
"0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ': 0,",
"k, v in distance.items(): delta = v - distance_1[k] sum += delta print(f\"{k}:",
"soup = BeautifulSoup(raw_html, \"lxml\") spans = soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь",
"spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones = {} for idr,",
"COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9],",
"клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you want different settings for the",
"THUMBS[idr][idk] strokes = {} stroke = '' for idx, char in enumerate(sample): current_zone",
"pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() - start_time))",
"settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for",
"char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2)",
"i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0 for k, v in distance.items():",
"calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE:",
"def draw_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist in",
"for item in sublist]] n = [item for sublist in QWERTY for item",
"finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords =",
"import numpy as np from bs4 import BeautifulSoup from colour import Color import",
"c[idx][idy][1], 'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k) for idy, item in",
"i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) def get_keyboard(coords, QWERTY):",
"import BeautifulSoup from colour import Color import copy import math import re import",
"row in enumerate(QWERTY): for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes =",
"mapper) results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results: if stroke_distance",
"ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) ax.axis([-12, 210, -12, 48]) for i, txt in enumerate(n):",
"} for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk]",
"= default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 =",
"i in [item for sublist in coords for item in sublist]] n =",
"x = [i[0] for i in [item for sublist in coords for item",
"= int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g,",
"time.time() mapper = get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count() p =",
"import matplotlib.pyplot as plt from multiprocessing import Pool, Manager, cpu_count from functools import",
"= Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in pairs.items(): stroke_a, stroke_b =",
"def calculateDistance(x1,y1,x2,y2): global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in",
"QWERTY): return [[presses_counts[item] if item in presses_counts else 0 for item in row]",
"default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2)",
"', '').replace('Пользователь 1: ', '') for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase)",
"0 for k, v in distance.items(): delta = v - distance_1[k] sum +=",
"coords[1][3], 'ПУ': coords[1][6], 'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time()",
"strokes[stroke] = {\"zone\": current_zone, \"count\": 1} stroke = '' if idx + 1",
"get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for",
"strokes).get() p.close() p.join() for stroke_distance in results: if stroke_distance is None: continue #",
"210, -12, 48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1,",
"len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1] if stroke in",
"for row in QWERTY] def zone_distances(zone, press_count): keys = [] default_position = {",
"linewidth = (max_line_width / max_value) * distance color_hue = (100 / max_value) *",
"x2 = mapper[stroke_b]['x'] y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance",
"lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for i in spans]).lower()",
"pair, \"distance\": distance }) else: char_1 = text[idx - 1] x1 = mapper[char_1]['x']",
"if idx == 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1]",
"keys = [] default_position = { 'ЛМ': COORDS[1][0], 'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ':",
"k): text_mapper = { item: { 'x': c[idx][idy][0], 'y': c[idx][idy][1], 'thumb': THUMBS[idx][idy] }",
"enumerate(text): if char not in press_count: press_count[char] = 1 else: press_count[char] += 1",
"} for idx, sublist in enumerate(k) for idy, item in enumerate(sublist) } #",
"ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for i in [item",
"'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY): for idk, key",
"presses_counts else 0 for item in row] for row in QWERTY] def zone_distances(zone,",
"new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords):",
"- distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м - меньше на",
"return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2 - x1)**2",
"= {} stroke = '' for idx, char in enumerate(sample): current_zone = zones[char]",
"x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\":",
"1000:.2f} м - меньше на {delta / 1000:.2f} м ({(1 - (distance_1[k] /",
"distance.items(): delta = v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f}",
"QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in",
"'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0, 'ПМ':",
"idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke = ''",
"\"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax",
"'ПС': coords[1][7], 'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper = get_mapper(coords,",
"strokes = {} stroke = '' for idx, char in enumerate(sample): current_zone =",
"new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num, value): new_coords =",
"'thumb': THUMBS[idx][idy] } for idx, sublist in enumerate(k) for idy, item in enumerate(sublist)",
"char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2)",
"'ПБ': 0, 'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС':",
"char in enumerate(text): if char not in press_count: press_count[char] = 1 else: press_count[char]",
"in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] +=",
"in enumerate(row): if THUMBS[idr][idk] == zone and len(QWERTY[idr][idk]) > 0: x1, y1 =",
"fontsize=10) ax.set_aspect('equal', 'box') # Or if you want different settings for the grids:",
"sublist in coords for item in sublist]] y = [i[1] for i in",
"And a corresponding grid ax.grid(which='both') # Or if you want different settings for",
"ax def count_presses(text): press_count = {} for idx, char in enumerate(text): if char",
"x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance",
"= default_position[mapper[char]['thumb']][1] char_2 = char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance =",
"char_2 = char x2 = mapper[char_2]['x'] y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1,",
"- y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'],",
"for item in sublist]] y = [i[1] for i in [item for sublist",
"for idr, row in enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk] ==",
"y2 = mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair",
"- 1] x1 = mapper[char_1]['x'] y1 = mapper[char_1]['y'] char_2 = char x2 =",
"default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance in results: if",
"COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY): for idk,",
"= mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance color_hue = (100 /",
"1 == len(sample): r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1",
"1 == len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2",
"press_count: press_count[char] = 1 else: press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY):",
"pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"---",
"0: x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance =",
"48]) for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i]), color=(1, 1, 1)) return",
"for sublist in coords for item in sublist]] n = [item for sublist",
"zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY)",
"THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"] * stroke_distance[\"count\"] for pair in stroke_distance[\"pairs\"]:",
"1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts else",
"def shift_row(c, row_num, value): new_coords = copy.deepcopy(c) for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0]",
"[item for sublist in coords for item in sublist]] n = [item for",
"1 elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone,",
"text_mapper def draw_keyboard(coords, QWERTY): x = [i[0] for i in [item for sublist",
"item in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY):",
"qwerty) pairs = {} num_workers = cpu_count() p = Pool(num_workers) manager = Manager()",
"press_count[char] += 1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in",
"char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x']",
"b, 1)) def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ': 0,",
"y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'],",
"np from bs4 import BeautifulSoup from colour import Color import copy import math",
"= COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1, y1, x2, y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\":",
"'ПМ': 0, } default_keys = { 'ЛМ': qwerty[1][0], 'ЛБ': qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ':",
"re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones = {} for idr, row in",
"r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1))",
"return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs,",
"in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return CACHE[f\"{x2}{y2}{x1}{y1}\"] dist = math.sqrt((x2",
"seconds ---\" % (time.time() - start_time)) return { \"pairs\": pairs, \"distances\": distances }",
"in coords for item in sublist]] n = [item for sublist in QWERTY",
"pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"]",
"continue # stroke_distance = count_stroke_distance(COORDS, QWERTY, THUMBS, default_position, default_keys, stroke) distances[stroke_distance[\"zone\"]] += stroke_distance[\"total_distance\"]",
"stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x']",
"in [item for sublist in coords for item in sublist]] y = [i[1]",
"м - меньше на {delta / 1000:.2f} м ({(1 - (distance_1[k] / v))",
"in sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620, color=(0.5, 0.5, 0.5))",
"cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num,",
"QWERTY for item in sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\", s=620,",
"+= 1 return press_count def press_heatmap(presses_counts, QWERTY): return [[presses_counts[item] if item in presses_counts",
"= pair[0], pair[1] x1 = mapper[stroke_a]['x'] y1 = mapper[stroke_a]['y'] x2 = mapper[stroke_b]['x'] y2",
"enumerate(QWERTY): for idk, key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke",
"1 < len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke = stroke[::-1] if",
"= stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif r_stroke in strokes:",
"total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax =",
"= [i[0] for i in [item for sublist in coords for item in",
"multiprocessing import Pool, Manager, cpu_count from functools import partial import numpy as np",
"0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you want different",
"r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\": 1}",
"[item for sublist in coords for item in sublist]] y = [i[1] for",
"* distance color_hue = int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2],",
"sublist]] y = [i[1] for i in [item for sublist in coords for",
"in QWERTY for item in sublist] fig, ax = plt.subplots() ax.scatter(x, y, marker=\",\",",
"lowercase) def generate_strokes(sample, QWERTY): zones = {} for idr, row in enumerate(QWERTY): for",
"'ЛБ': COORDS[1][1], 'ЛС': COORDS[1][2], 'ЛУ': COORDS[1][3], 'ПУ': COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ':",
"char_2 = char x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1, y1,",
"new_coords[row_num][idx][0] + value return new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for",
"y2 = mapper[char_2]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair",
"sublist in coords for item in sublist]] n = [item for sublist in",
"qwerty[1][1], 'ЛС': qwerty[1][2], 'ЛУ': qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9],",
"total_distance += distance pair = f\"{char_1}{char_2}\" pairs.append({ \"pair\": pair, \"distance\": distance }) else:",
"pairs.append({ \"pair\": pair, \"distance\": distance }) return { \"pairs\": pairs, \"count\": count, \"total_distance\":",
"for pair, distance in pairs.items(): stroke_a, stroke_b = pair[0], pair[1] x1 = mapper[stroke_a]['x']",
"mapper[char]['y'] distance = calculateDistance(x1, y1, x2, y2) total_distance += distance pair = f\"{char_1}{char_2}\"",
"default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2 = mapper[char]['x'] y2 = mapper[char]['y'] distance = calculateDistance(x1,",
"'ПБ': coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper = get_mapper(coords, qwerty) pairs",
"= get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100))",
"= zones[char] stroke += char if idx + 1 < len(sample) and zones[sample[idx",
"color=(1, 1, 1)) def get_keyboard(coords, QWERTY): x = [i[0] for i in [item",
"s=620, color=(0.5, 0.5, 0.5)) ax.set_title('Координаты клавиш', fontsize=10) ax.set_aspect('equal', 'box') # Or if you",
"count, \"total_distance\": total_distance, \"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width):",
"return new_coords def get_mapper(c, k): text_mapper = { item: { 'x': c[idx][idy][0], 'y':",
"'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY): for idk, key in enumerate(row):",
"for idx, cell in enumerate(new_coords[row_num]): new_coords[row_num][idx][0] = new_coords[row_num][idx][0] + value return new_coords def",
"in QWERTY] def zone_distances(zone, press_count): keys = [] default_position = { 'ЛМ': COORDS[1][0],",
"(x[i], y[i]), color=(1, 1, 1)) return ax def count_presses(text): press_count = {} for",
"different settings for the grids: major_ticks = np.arange(-20, 210, 20) minor_ticks = np.arange(-20,",
"keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i: i[\"press_count\"],",
"= get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair, distance in",
"max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\")",
"= partial(count_stroke_distance, default_position, default_keys, mapper) results = p.map_async(func, strokes).get() p.close() p.join() for stroke_distance",
"global CACHE if f\"{x1}{y1}{x2}{y2}\" in CACHE: return CACHE[f\"{x1}{y1}{x2}{y2}\"] if f\"{x2}{y2}{x1}{y1}\" in CACHE: return",
"from multiprocessing import Pool, Manager, cpu_count from functools import partial import numpy as",
"/ max_value) * distance color_hue = int(round(color_hue)) r, g, b = colors[color_hue -",
"idx, char in enumerate(text): if idx + 1 == len(text): char_1 = char",
"уменшилась на {sum / 1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text =",
"= '' for idx, char in enumerate(sample): current_zone = zones[char] stroke += char",
"= copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return",
"= new_coords[idx][col_num][1] + value return new_coords def get_mapper(c, k): text_mapper = { item:",
"{} for idx, char in enumerate(text): if char not in press_count: press_count[char] =",
"QWERTY) mapper = get_mapper(COORDS, QWERTY) red = Color(\"green\") colors = list(red.range_to(Color(\"red\"),100)) for pair,",
"} default_position = { 'ЛМ': coords[1][0], 'ЛБ': coords[1][1], 'ЛС': coords[1][2], 'ЛУ': coords[1][3], 'ПУ':",
"g, b, 1)) def process_strokes(strokes, coords, qwerty): distances = { 'ЛМ': 0, 'ЛБ':",
"import math import re import time from consts import QWERTY, THUMBS, COORDS CACHE",
"finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num, value): new_coords",
"char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone] x2",
"distance color_hue = int(round(color_hue)) r, g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth,",
"if idx + 1 < len(sample) and zones[sample[idx + 1]] != current_zone: r_stroke",
"== len(sample): r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"] += 1 elif",
"in enumerate(sublist) } # print(json.dumps(text_mapper, indent=2, ensure_ascii=False)) return text_mapper def draw_keyboard(coords, QWERTY): x",
"copy import math import re import time from consts import QWERTY, THUMBS, COORDS",
"row in enumerate(QWERTY): for idk, key in enumerate(row): if THUMBS[idr][idk] == zone and",
"g, b = colors[color_hue - 1].rgb ax.plot([x1,x2],[y1,y2], linewidth=linewidth, color=(r, g, b, 1)) def",
"\"zone\": zone } def draw_stroke_lines(pairs, COORDS, QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS,",
"if you want different settings for the grids: major_ticks = np.arange(-20, 210, 20)",
"coords[1][8], 'ПМ': coords[1][9], } start_time = time.time() mapper = get_mapper(coords, qwerty) pairs =",
"def finger_heatmap(finger_distances): return [[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]]",
"= stroke[\"stroke\"] zone = stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance =",
"'') for i in spans]).lower() return re.sub('[^а-я]+', '', lowercase) def generate_strokes(sample, QWERTY): zones",
"import Pool, Manager, cpu_count from functools import partial import numpy as np from",
"f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in pairs: pairs[f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'] += pair[\"distance\"] * stroke_distance[\"count\"] else: pairs[pair[\"pair\"]] = pair[\"distance\"] *",
"- меньше на {delta / 1000:.2f} м ({(1 - (distance_1[k] / v)) *",
"= stroke[\"zone\"] count = stroke[\"count\"] pairs = [] total_distance = 0 if len(text)",
"1000:.2f} м ({(1 - (distance_1[k] / v)) * 100:.2f}%)\") print(f\"\\nОбщая дистанция уменшилась на",
"stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}' in",
"[[ finger_distances['ЛМ'], finger_distances['ЛБ'], finger_distances['ЛС'], finger_distances['ЛУ'], finger_distances['ПУ'], finger_distances['ПС'], finger_distances['ПБ'], finger_distances['ПМ'] ]] def shift_row(c, row_num,",
"= math.sqrt((x2 - x1)**2 + (y2 - y1)**2) CACHE[f\"{x1}{y1}{x2}{y2}\"] = dist return dist",
"len(text): char_1 = char x1 = default_position[mapper[char]['thumb']][0] y1 = default_position[mapper[char]['thumb']][1] char_2 = default_keys[zone]",
"\"distance\": distance }) if idx == 0: char_1 = default_keys[zone] x1 = default_position[mapper[char]['thumb']][0]",
"copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1] = new_coords[idx][col_num][1] + value return new_coords",
"in stroke_distance[\"pairs\"]: if pair[\"pair\"] in pairs: pairs[pair[\"pair\"]] += pair[\"distance\"] * stroke_distance[\"count\"] elif f'{pair[\"pair\"][1]}{pair[\"pair\"][0]}'",
"y2 = mapper[stroke_b]['y'] linewidth = (max_line_width / max_value) * distance color_hue = (100",
"= 0 for k, v in distance.items(): delta = v - distance_1[k] sum",
"1000:.2f} м\") def count_stroke_distance(default_position, default_keys, mapper, stroke): text = stroke[\"stroke\"] zone = stroke[\"zone\"]",
"x1, y1 = default_position[zone][0], default_position[zone][1] x2, y2 = COORDS[idr][idk][0], COORDS[idr][idk][1] distance = calculateDistance(x1,",
"distance_deltas(distance, distance_1): sum = 0 for k, v in distance.items(): delta = v",
"y2) keys.append({ \"symbol\": QWERTY[idr][idk], \"distance\": distance, \"press_count\": press_count[QWERTY[idr][idk]] }) return sorted(keys, key=lambda i:",
"key in enumerate(row): zones[key] = THUMBS[idr][idk] strokes = {} stroke = '' for",
"y = [i[1] for i in [item for sublist in coords for item",
"= pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() - start_time)) return",
"for idx, char in enumerate(text): if char not in press_count: press_count[char] = 1",
"idx + 1 == len(sample): r_stroke = stroke[::-1] if stroke in strokes: strokes[stroke][\"count\"]",
"return new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx, row in",
"COORDS[1][6], 'ПС': COORDS[1][7], 'ПБ': COORDS[1][8], 'ПМ': COORDS[1][9], } for idr, row in enumerate(QWERTY):",
"elif r_stroke in strokes: strokes[r_stroke][\"count\"] += 1 else: strokes[stroke] = {\"zone\": current_zone, \"count\":",
"0, 'ЛБ': 0, 'ЛС': 0, 'ЛУ': 0, 'ПУ': 0, 'ПС': 0, 'ПБ': 0,",
"}) return { \"pairs\": pairs, \"count\": count, \"total_distance\": total_distance, \"zone\": zone } def",
"else: pairs[pair[\"pair\"]] = pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() -",
"corresponding grid ax.grid(which='both') # Or if you want different settings for the grids:",
"for item in row] for row in QWERTY] def zone_distances(zone, press_count): keys =",
"+ value return new_coords def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx,",
"soup.find_all('span') lowercase = ''.join([i.text.replace('Пользователь 2: ', '').replace('Пользователь 1: ', '') for i in",
"qwerty[1][3], 'ПУ': qwerty[1][6], 'ПС': qwerty[1][7], 'ПБ': qwerty[1][8], 'ПМ': qwerty[1][9], } default_position = {",
"key=lambda i: i[\"press_count\"], reverse=True) def distance_deltas(distance, distance_1): sum = 0 for k, v",
"char in enumerate(sample): current_zone = zones[char] stroke += char if idx + 1",
"/ 1000:.2f} м - меньше на {delta / 1000:.2f} м ({(1 - (distance_1[k]",
"delta = v - distance_1[k] sum += delta print(f\"{k}: {distance_1[k] / 1000:.2f} м",
"pair[\"distance\"] * stroke_distance[\"count\"] print(\"--- %s seconds ---\" % (time.time() - start_time)) return {",
"def shift_col(c, col_num, value): new_coords = copy.deepcopy(c) for idx, row in enumerate(new_coords): new_coords[idx][col_num][1]",
"value return new_coords def get_mapper(c, k): text_mapper = { item: { 'x': c[idx][idy][0],",
"QWERTY, row_count, max_value, max_line_width): ax = get_keyboard(COORDS, QWERTY) mapper = get_mapper(COORDS, QWERTY) red",
"= get_mapper(coords, qwerty) pairs = {} num_workers = cpu_count() p = Pool(num_workers) manager"
] |
[
"saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file from set url to set",
"raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns true if file at",
"self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file from set url",
"link, saveTo): self._link = link self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType",
"except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns true if file",
"import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen =",
"import hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise",
"\".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 =",
"self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns true if",
"file at remote URL is different than file located at local destination else",
"hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew",
"CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns true if file at remote",
"false Raises CannotRetrieveFileException Returns bool ''' import hashlib import urllib import os try:",
"afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile:",
"csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 =",
"def __init__(self, link, saveTo): self._link = link self._saveTo = saveTo def getFile(self): '''(NoneType)",
"saveTo): self._link = link self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves",
"at local destination else returns false Raises CannotRetrieveFileException Returns bool ''' import hashlib",
"+ \".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2",
"hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2",
"hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew == csumOriginal) class",
"file located at local destination else returns false Raises CannotRetrieveFileException Returns bool '''",
"= hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf)",
"def getFile(self): '''(NoneType) -> NoneType Retrieves file from set url to set local",
"csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew == csumOriginal) class CannotRetrieveFileException(Exception):",
"try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with",
"= hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 = afile.read()",
"from set url to set local destination Raises CannotRetrieveFileException Returns NoneType ''' import",
"class remoteGet: def __init__(self, link, saveTo): self._link = link self._saveTo = saveTo def",
"destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise",
"Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def",
"try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns",
"Retrieves file from set url to set local destination Raises CannotRetrieveFileException Returns NoneType",
"def isNew(self): '''(NoneType) -> bool returns true if file at remote URL is",
"remote URL is different than file located at local destination else returns false",
"hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest()",
"local destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except:",
"raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile:",
"CannotRetrieveFileException Returns bool ''' import hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo",
"located at local destination else returns false Raises CannotRetrieveFileException Returns bool ''' import",
"destination else returns false Raises CannotRetrieveFileException Returns bool ''' import hashlib import urllib",
"= hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew == csumOriginal) class CannotRetrieveFileException(Exception): pass",
"if file at remote URL is different than file located at local destination",
"= saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file from set url to",
"except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as",
"= afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew ==",
"__init__(self, link, saveTo): self._link = link self._saveTo = saveTo def getFile(self): '''(NoneType) ->",
"urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool returns true",
"getFile(self): '''(NoneType) -> NoneType Retrieves file from set url to set local destination",
"urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo",
"''' import hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except:",
"afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew == csumOriginal)",
"''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType)",
"at remote URL is different than file located at local destination else returns",
"\".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb')",
"CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo)",
"= hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal =",
"= link self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file from",
"link self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file from set",
"else returns false Raises CannotRetrieveFileException Returns bool ''' import hashlib import urllib import",
"self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo +",
"self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile: buf =",
"open(self._saveTo + \".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest()",
"afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not",
"'''(NoneType) -> NoneType Retrieves file from set url to set local destination Raises",
"Returns bool ''' import hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo +",
"-> NoneType Retrieves file from set url to set local destination Raises CannotRetrieveFileException",
"hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal",
"-> bool returns true if file at remote URL is different than file",
"hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link,",
"'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5()",
"urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen",
"NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self):",
"self._link = link self._saveTo = saveTo def getFile(self): '''(NoneType) -> NoneType Retrieves file",
"bool returns true if file at remote URL is different than file located",
"NoneType Retrieves file from set url to set local destination Raises CannotRetrieveFileException Returns",
"true if file at remote URL is different than file located at local",
"Raises CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link,",
"local destination else returns false Raises CannotRetrieveFileException Returns bool ''' import hashlib import",
"URL is different than file located at local destination else returns false Raises",
"to set local destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link,",
"open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo +",
"+ \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\",",
"Raises CannotRetrieveFileException Returns bool ''' import hashlib import urllib import os try: urllib.request.urlretrieve(self._link,",
"import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo)",
"os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\") except: raise CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5()",
"file from set url to set local destination Raises CannotRetrieveFileException Returns NoneType '''",
"as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return",
"import urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) ->",
"set url to set local destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib",
"returns false Raises CannotRetrieveFileException Returns bool ''' import hashlib import urllib import os",
"different than file located at local destination else returns false Raises CannotRetrieveFileException Returns",
"hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile: buf = afile.read()",
"set local destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib try: urllib.request.urlretrieve(self._link, self._saveTo)",
"remoteGet: def __init__(self, link, saveTo): self._link = link self._saveTo = saveTo def getFile(self):",
"urllib try: urllib.request.urlretrieve(self._link, self._saveTo) except: raise CannotRetrieveFileException(self._link, self._saveTo) def isNew(self): '''(NoneType) -> bool",
"hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2)",
"as afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with",
"= afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb') as",
"CannotRetrieveFileException(self._link, self._saveTo) hashgen = hashlib.md5() with open(self._saveTo + \".TMP\", 'rb') as afile: buf",
"url to set local destination Raises CannotRetrieveFileException Returns NoneType ''' import urllib try:",
"with open(self._saveTo, 'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo",
"afile: buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo,",
"isNew(self): '''(NoneType) -> bool returns true if file at remote URL is different",
"with open(self._saveTo + \".TMP\", 'rb') as afile: buf = afile.read() hashgen.update(buf) csumNew =",
"buf = afile.read() hashgen.update(buf) csumNew = hashgen.hexdigest() hashgen2 = hashlib.md5() with open(self._saveTo, 'rb')",
"'rb') as afile: buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\")",
"than file located at local destination else returns false Raises CannotRetrieveFileException Returns bool",
"buf2 = afile.read() hashgen2.update(buf2) csumOriginal = hashgen2.hexdigest() os.remove(self._saveTo + \".TMP\") return not (csumNew",
"bool ''' import hashlib import urllib import os try: urllib.request.urlretrieve(self._link, self._saveTo + \".TMP\")",
"'''(NoneType) -> bool returns true if file at remote URL is different than",
"returns true if file at remote URL is different than file located at",
"self._saveTo) def isNew(self): '''(NoneType) -> bool returns true if file at remote URL",
"is different than file located at local destination else returns false Raises CannotRetrieveFileException"
] |
[
"__str__(self): return \"node: {} system: {} release: {} arch: {}\".format(self.node, self.system, self.release, self.processor)",
"self.version = platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture",
"extend me \"\"\" def __init__(self): self.system = platform.system() self.node = platform.node() self.release =",
"= platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node: {} system: {} release:",
"\"\"\" def __init__(self): self.system = platform.system() self.node = platform.node() self.release = platform.release() self.version",
"= platform.system() self.node = platform.node() self.release = platform.release() self.version = platform.version() self.machine =",
"self.architecture = platform.architecture() def __str__(self): return \"node: {} system: {} release: {} arch:",
"platform.architecture() def __str__(self): return \"node: {} system: {} release: {} arch: {}\".format(self.node, self.system,",
"@author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend me \"\"\" def __init__(self):",
"self.machine = platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def",
"platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node: {} system:",
"platform class SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system = platform.system() self.node",
"= platform.node() self.release = platform.release() self.version = platform.version() self.machine = platform.machine() self.processor =",
"\"\"\" import platform class SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system =",
"def __init__(self): self.system = platform.system() self.node = platform.node() self.release = platform.release() self.version =",
"platform.release() self.version = platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform = platform.platform()",
"sysinfo.py obtain system informations @author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend",
"SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system = platform.system() self.node = platform.node()",
"obtain system informations @author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend me",
"platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture = platform.architecture()",
"def __str__(self): return \"node: {} system: {} release: {} arch: {}\".format(self.node, self.system, self.release,",
"class SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system = platform.system() self.node =",
"= platform.release() self.version = platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform =",
"= platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self):",
"K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system",
"platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self): return",
"= platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node: {}",
"me \"\"\" def __init__(self): self.system = platform.system() self.node = platform.node() self.release = platform.release()",
"__init__(self): self.system = platform.system() self.node = platform.node() self.release = platform.release() self.version = platform.version()",
"system informations @author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend me \"\"\"",
"platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node: {} system: {} release: {}",
"= platform.architecture() def __str__(self): return \"node: {} system: {} release: {} arch: {}\".format(self.node,",
"\"\"\" extend me \"\"\" def __init__(self): self.system = platform.system() self.node = platform.node() self.release",
"platform.system() self.node = platform.node() self.release = platform.release() self.version = platform.version() self.machine = platform.machine()",
"platform.node() self.release = platform.release() self.version = platform.version() self.machine = platform.machine() self.processor = platform.processor()",
"= platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform = platform.platform() self.architecture =",
"self.processor = platform.processor() self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node:",
"self.node = platform.node() self.release = platform.release() self.version = platform.version() self.machine = platform.machine() self.processor",
"informations @author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\" extend me \"\"\" def",
"self.system = platform.system() self.node = platform.node() self.release = platform.release() self.version = platform.version() self.machine",
"self.platform = platform.platform() self.architecture = platform.architecture() def __str__(self): return \"node: {} system: {}",
"import platform class SysInfo(): \"\"\" extend me \"\"\" def __init__(self): self.system = platform.system()",
"\"\"\" sysinfo.py obtain system informations @author: K.Edeline \"\"\" import platform class SysInfo(): \"\"\"",
"self.release = platform.release() self.version = platform.version() self.machine = platform.machine() self.processor = platform.processor() self.platform"
] |
[
"= models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE',",
"'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ]",
"from django.db import models # Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions",
"TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user",
"# Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe =",
"django.db import models # Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions",
"tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE",
"on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'),",
"user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'),",
"models # Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe",
"models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and interactive",
"'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES,",
"'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE',",
"on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value",
"class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user =",
"('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type', max_length=9,",
"model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, )",
"import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE )",
"('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self):",
"'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\"",
"choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe}",
"\"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User',",
"user, and interactive values\"\"\" return f'clothe: {self.clothe} | user: {self.user} | value: {self.value}'",
") INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value =",
"models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [",
"INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField(",
"interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE,",
"InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey(",
"type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return",
"\"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe} | user: {self.user} |",
"'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def",
"= models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES =",
"import models # Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\"",
"def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe} | user:",
"__str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe} | user: {self.user}",
"models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike')",
"('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, )",
"] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe,",
"[ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction type',",
"from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey( 'clothes.ClothesModel',",
"value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user,",
"\"\"\"Interactions model\"\"\" # Django from django.db import models # Utils from tclothes.utils.baseModels import",
"= models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and",
"clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe} | user: {self.user} | value:",
"model\"\"\" # Django from django.db import models # Utils from tclothes.utils.baseModels import TClothesModel",
"Django from django.db import models # Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel):",
"'dislike') ] value = models.CharField( 'Interaction type', max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return",
"clothe = models.ForeignKey( 'clothes.ClothesModel', on_delete=models.CASCADE ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES",
"max_length=9, choices=INTERACTIVE_VALUES, ) def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe:",
") user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, ) INTERACTIVE_VALUES = [ ('LIKE', 'like'), ('SUPERLIKE',",
"Utils from tclothes.utils.baseModels import TClothesModel class InteractionsModel(TClothesModel): \"\"\"Interactions interactions model.\"\"\" clothe = models.ForeignKey(",
"= [ ('LIKE', 'like'), ('SUPERLIKE', 'superlike'), ('DISLIKE', 'dislike') ] value = models.CharField( 'Interaction",
") def __str__(self): \"\"\"Return clothe, user, and interactive values\"\"\" return f'clothe: {self.clothe} |",
"# Django from django.db import models # Utils from tclothes.utils.baseModels import TClothesModel class"
] |
[
"np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T",
"% (query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if",
"in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 =",
"assigned nearest features qreq - QueryRequest object Output: qaid2_chipmatch - dict of (",
"np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not matching",
"if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs,",
"return qaid2_nnfilt #============================ # 4) Conversion from featurematches to chipmatches qfx2 -> aid2",
"the feature match / score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V,",
"matches based on config and weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns))",
"qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are",
"invalided by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid",
"qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the",
"difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs,",
"= (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation",
"mapping query annnotation-ids to a nearest neighbor tuple (indexes, dists). indexes and dist",
"chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches",
"database feature indexes * qfx2_dist - ranked list of query feature indexes to",
"{} for qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch = qaid2_chipmatch[qaid]",
"# Check the diaglen sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm,",
"= ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2 + (y_m.max() -",
"not QUIET: # nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats =",
"as sver # Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as",
"end_ = log_prog('Assign NN: ', len(qaids)) for count, qaid in enumerate(qaids): mark_(count) #",
"feature indexes } * qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm) =",
"np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid)",
"time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids",
"(qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as much as",
"# Find a transform from chip2 to chip1 (the old way was 1",
"# hack of a fix qaid2_qres = {} failed_qaids = [] for qaid",
"= 0 #Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk =",
"filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris =",
"object qreq list qaids dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr",
"Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call a",
"nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx",
"# qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns)",
"Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score =",
"weight if thresh is not None and thresh != 'None': thresh = float(thresh)",
"+ (y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx",
"qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================",
"Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq)",
"to each nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns,",
"qaid2_nns - dict of assigned nearest features (only indexes are used here) qaid2_nnfilt",
"(aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im not even sure if the",
"query feature indexes to database feature indexes } * qaid2_norm_weight - mapping from",
"assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return",
"= ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) #",
"of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index #",
"elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif",
"qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification:",
"and matches correspond to the assigned nearest features qreq - QueryRequest object Output:",
"= qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres # Retain original score",
"printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi #",
"# Helpers #================= #def compare(qreq, qreq_): # qaid = 1 # qvecs_list =",
"by nid' % nName_all_invalid) print('[mf] * %d are newly invalided by nid' %",
"to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid,",
"1) Assign nearest neighbors: ' + cfgstr_) num_neighbors = K + Knorm #",
"% nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as",
"as vr2 import utool from functools import partial #profile = utool.profile print, print_,",
"nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid]",
"for yourself or another chip in the same image cant_match_self = not cant_match_sameimg",
"cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter",
"= topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup =",
"return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {}",
"np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T",
"score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1] # Choose the appropriate scoring",
"qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are invalid by thresh' % ((True",
"(qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with its nearest",
"appropriate scoring mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method ==",
"remove if there is a speed issue) def print_(msg, count=0): \"\"\" temp print_.",
"K is the number of approximate nearest neighbors. cdef: dict qaid2_nns object ibs",
"(fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk():",
"qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self,",
"% nName_all_invalid) print('[mf] * %d are newly invalided by nid' % nName_new_invalid) ####",
"mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score,",
"is not None and thresh != 'None': thresh = float(thresh) # corrects for",
"matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) =",
"import linalg as ltool from vtool import spatial_verification as sver # Hotspotter from",
"FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] =",
"corresponding feature * valid - a valid bit for a corresponding feature REALIZATIONS:",
"qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts),",
"Apply gravity vector weight to the score qfx2_score *= qfx2_gvweight # Remove Impossible",
"print('[mf] * %d assignments are invalid by thresh' % ((True - qfx2_valid).sum())) if",
"= defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile",
"else: # Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid",
"qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] * made %d feat matches'",
"diaglen sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank,",
"the inliers to the homography homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo:",
"sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent",
"qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring",
"matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def spatial_verification(ibs,",
"len(qreq.data_index.dx2_data) # Filter matches based on config and weights mark_, end_ = log_prog('Filter",
"as possible or abstract it away from __future__ import absolute_import, division, print_function #",
"aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute",
"checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function",
"annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of",
"for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid",
"assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape ==",
"- qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by gid' % nImg_all_invalid) print('[mf]",
"= nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors:",
"#================= START_AFTER = 2 # specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #=================",
"are newly invalided by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if",
"= topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs =",
"qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step",
"nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d desc from %d",
"a dict mapping query annnotation-ids to a nearest neighbor tuple (indexes, dists). indexes",
"indexes and dist have the shape (nDesc x K) where nDesc is the",
"sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm)",
"homography homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid]",
"in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs,",
"float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t",
"print('[mf] * %d assignments are invalid by nid' % nName_all_invalid) print('[mf] * %d",
"query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch",
"qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] *",
"a list of failed qaids cdef: object qreq list qaids dict qaid2_qres list",
"# nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' +",
"nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent",
"= np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into an interator valid_lists",
"# Vsmany - Append query feature matches to database aids if not is_vsone:",
"aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts =",
"also this is where the filter weights and thershold are applied to the",
"np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into an interator valid_lists =",
"2 # TODO: paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype =",
"_apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) #",
"qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0])",
"if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True -",
"numpy as np from vtool import keypoint as ktool from vtool import linalg",
"ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as vr2 import utool from functools",
"or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t",
"progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) #",
"elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif",
"# corrects for thresh being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed =",
"a hack \"\"\" if NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg) count",
"= _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors,",
"from featurematches to chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk):",
"from chip2 to chip1 (the old way was 1 to 2) for qaid",
"(qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric score",
"qfx2_dist - ranked list of query feature indexes to database feature indexes }",
"double tau \"\"\" #================= # Globals #================= START_AFTER = 2 # specialized progress",
"topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw **",
"Essientally nearest neighbors are converted into weighted assignments \"\"\" # Config K =",
"weight * qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt",
"sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh",
"np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ =",
"# Globals #================= START_AFTER = 2 # specialized progress func log_prog = partial(utool.log_progress,",
"QueryException(msg) return ex #============================ # 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids,",
"if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' % (query_type,)) # Return var",
"thresh is not None and thresh != 'None': thresh = float(thresh) # corrects",
"in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid]",
"from vtool import keypoint as ktool from vtool import linalg as ltool from",
"here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the scores and matches correspond",
"else: for qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note",
"min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff",
"nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2]",
"to chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches =",
"ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid",
"ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef",
"dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to determine feature",
"ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef",
"aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs,",
"(qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid",
"not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step",
"each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx]",
"[len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) #",
"0 mark_, end_ = log_prog('Assign NN: ', len(qaids)) for count, qaid in enumerate(qaids):",
"print('[mf] * Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog",
"Return the inliers to the homography homog_inliers, H, aff_inliers, Aff = sv_tup if",
"qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename",
"len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d desc from %d chips to",
"six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw = sign,",
"(query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if is_vsone:",
"query annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number",
"anymore if score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1] # Choose the",
"qfx2_dist) # record number of query and result desc nTotalNN += qfx2_dx.size nTotalDesc",
"topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() -",
"a transform from chip2 to chip1 (the old way was 1 to 2)",
"where nDesc is the number of descriptors in the annotation, and K is",
"= sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal =",
"\"\"\" Try and load the result structures for each query. returns a list",
"21.9 % time of this function cfgstr = qreq.get_cfgstr2() # hack of a",
"####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True",
"hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid,",
"{} # dbg info (can remove if there is a speed issue) def",
"- a (qfx2_fs, qfx2_valid) tuple SCALARS * dx - the index into the",
"qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are",
"fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers)",
"(nDesc x K) where nDesc is the number of descriptors in the annotation,",
"Plain Nearest Neighbors Input: ibs - an IBEIS Controller qaids - query annotation-ids",
"thresh, weight = filt_cfg.get_stw(filt) # stw = sign, thresh, weight if thresh is",
"qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids) == 1",
"####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum()",
"- prefix mapping query chip feature index to TUPLES: * nns - a",
"len(qfx2_desc) == 0: # Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32)",
"before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) #",
"nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of query and result",
"fs - a score of a corresponding feature * valid - a valid",
"isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights <= sign * thresh qfx2_valid",
"if VERBOSE: print('[mf] * %d assignments are invalid by thresh' % ((True -",
"qfx2_passed = sign * qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed)",
"chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im not even",
"nearest neighbors. cdef: dict qaid2_nns object ibs object qreq \"\"\" # Neareset neighbor",
"(nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm,",
"%r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank =",
"six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs",
"from six.moves import zip, range import six from collections import defaultdict import sys",
"for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt)",
"Filter matches based on config and weights mark_, end_ = log_prog('Filter NN: ',",
"scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight =",
"ex = QueryException(msg) return ex #============================ # 1) Nearest Neighbors #============================ @profile def",
"Vsone - Append database feature matches to query aids else: for qfx, aid,",
"NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont have",
"else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for",
"easy way to access keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) #",
"- dict of (featmatch_scores, featmatch_mask) where the scores and matches correspond to the",
"qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by nid' % nName_all_invalid) print('[mf] *",
"\"\"\" # TODO: Remove ibs control as much as possible or abstract it",
"are 1, far are 0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau #",
"doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially",
"#def compare(qreq, qreq_): # qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids",
"FIX TAKES 21.9 % time of this function cfgstr = qreq.get_cfgstr2() # hack",
"weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone =",
"ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance",
"qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg",
"ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into",
"Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) #",
"*= qfx2_gvweight # Remove Impossible Votes: # dont vote for yourself or another",
"by gid' % nImg_all_invalid) print('[mf] * %d are newly invalided by gid' %",
"filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are invalid",
"= qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,))",
"the number of descriptors in the annotation, and K is the number of",
"-> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO:",
"aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal +=",
"qaid2_nns - maping from query chip index to nns { * qfx2_dx -",
"aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if",
"qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist",
"in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append",
"list of query feature indexes to database feature indexes } * qaid2_norm_weight -",
"\"\"\" #================= # matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping",
"enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid]",
"spatially verify the top __NUM_RERANK__ results for topx in range(nRerank): aid = topx2_aid[topx]",
"Knorm # number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func",
"Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks)",
"nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS * dx - the index into",
"qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from featurematches",
"= qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid",
"topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__ results for topx",
"y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2 + (y_m.max()",
"if isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights <= sign * thresh",
"qreq): \"\"\" testing function returns unfiltered nearest neighbors this does check that you",
"to determine feature validity and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights =",
"qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid",
"verified something # Rebuild the feature match / score arrays to be consistent",
"qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres except",
"the result structures for each query. returns a list of failed qaids cdef:",
"qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid)",
"= 0 if dbginfo: qaid2_svtups = {} # dbg info (can remove if",
"Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE #",
"applied to the matches. Essientally nearest neighbors are converted into weighted assignments \"\"\"",
"progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_):",
"= dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) #",
"checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t,",
"print_function # Python from six.moves import zip, range import six from collections import",
"# assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx",
"tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #=================",
"verification: off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch,",
"into the database of features * dist - the distance to a corresponding",
"= sign, thresh, weight if thresh is not None and thresh != 'None':",
"qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as much as possible or abstract",
"%d are newly invalided by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg)",
"%d are newly invalided by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename)",
"and load the result structures for each query. returns a list of failed",
"(the old way was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch =",
"qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from featurematches to chipmatches qfx2 ->",
"K = nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ =",
"thresh = float(thresh) # corrects for thresh being strings sometimes if isinstance(thresh, (int,",
"is where the filter weights and thershold are applied to the matches. Essientally",
"{} nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs,",
"homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] =",
"ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func #",
"long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2]",
"num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx",
"qnid ####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid *",
"aid2_fs, aid2_fk) = chipmatch # HACK: Im not even sure if the 'w'",
"= (x_m.max() - x_m.min()) ** 2 + (y_m.max() - y_m.min()) ** 2 return",
"chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method,",
"or abstract it away from __future__ import absolute_import, division, print_function # Python from",
"Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef",
"the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm,",
"qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for nnfilter",
"sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0",
"== 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda':",
"qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified",
"= hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ = {aid:",
"temp print_. Using count in this way is a hack \"\"\" if NOT_QUIET:",
"ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {} # Internal",
"= nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr()",
"verify the top __NUM_RERANK__ results for topx in range(nRerank): aid = topx2_aid[topx] fm",
"except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile def",
"chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return",
"index to nns { * qfx2_dx - ranked list of query feature indexes",
"= np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based",
"failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid,",
"as ltool from vtool import spatial_verification as sver # Hotspotter from ibeis.model.hots import",
"aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers]",
"and result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf]",
"print('[mf] * %d are newly invalided by self' % nChip_new_invalid) #### qfx2_valid =",
"of descriptors in the annotation, and K is the number of approximate nearest",
"{aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_",
"TODO: Sorting the valid lists by aid might help the speed of this",
"= sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV",
"six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres # Retain",
"Approx nearest neighbor func # Call a tighter (hopefully cythonized) nearest neighbor function",
"from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import",
"#============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert",
"where keys are query-annotation-id vsmany/vsone counts here. also this is where the filter",
"over chips with nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for",
"of this function cfgstr = qreq.get_cfgstr2() # hack of a fix qaid2_qres =",
"qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists by aid might",
"aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd =",
"#============================ # 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if",
"2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in",
"* nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid)",
"return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta,",
"qaids dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() #",
"chips to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ #",
"chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2",
"cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except",
"# Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as hsexcept from",
"into weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone",
"#========================== # 3) Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights,",
"features qreq - QueryRequest object Output: qaid2_chipmatch - dict of ( Notes: The",
"hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2",
"NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s: qaid=%r has no descriptors!' +",
"nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def",
"%d assignments are invalid by nid' % nName_all_invalid) print('[mf] * %d are newly",
"query chip index to nns { * qfx2_dx - ranked list of query",
"= qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors",
"\"\"\" if NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg) count += 1",
"dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches",
"qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\"",
"{} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to",
"are not matching yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count,",
"returns unfiltered nearest neighbors this does check that you are not matching yourself",
"qfx2_dist \"\"\" # Output qaid2_nns = {} # Internal statistics reporting nTotalNN, nTotalDesc",
"aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs",
"1)) # Pack valid feature matches into an interator valid_lists = [qfx2[qfx2_valid] for",
"if there is a speed issue) def print_(msg, count=0): \"\"\" temp print_. Using",
"neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks =",
"cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True -",
"are 0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau # Apply gravity vector",
"assignments are invalid by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori =",
"of assigned nearest features (only indexes are used here) qaid2_nnfilt - dict of",
"old way was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid]",
"- a dict mapping query annnotation-ids to a nearest neighbor tuple (indexes, dists).",
"= utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo: aid2_svtup",
"qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score,",
"'Please delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================ #",
"= qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape,",
"= {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename =",
"mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get",
"== qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) #",
"aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of assigned",
"nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf]",
"delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================ # 1)",
"corrects for thresh being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign",
"def print_(msg, count=0): \"\"\" temp print_. Using count in this way is a",
"(qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by self'",
"@profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize # Convert",
"keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list",
"= topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max()",
"unfiltered nearest neighbors this does check that you are not matching yourself \"\"\"",
"aid2_fk = new_fmfsfk() # Iterate over chips with nearest neighbors mark_, end_ =",
"def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs - an IBEIS",
"qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches'",
"* thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score +=",
"((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d",
"* assigned %d desc from %d chips to %r nearest neighbors' % (nTotalDesc,",
"# tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query')",
"feature matches into an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid,",
"Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight",
"weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)):",
"def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch ->",
"77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return",
"qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to determine feature validity",
"nName_all_invalid) print('[mf] * %d are newly invalided by nid' % nName_new_invalid) #### qfx2_valid",
"nFeatMatches += 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid =",
"dist have the shape (nDesc x K) where nDesc is the number of",
"# Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone'",
"nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__ results for topx in range(nRerank):",
"filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if",
"the number of approximate nearest neighbors. cdef: dict qaid2_nns object ibs object qreq",
"dlensqrd = (x_m.max() - x_m.min()) ** 2 + (y_m.max() - y_m.min()) ** 2",
"= aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d",
"cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} #",
"Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t",
"@profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch #",
"K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting:",
"verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh",
"0: # Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist =",
"qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t,",
"np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns",
"+= 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET:",
"fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone -",
"scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV",
"= qreq.cfg.agg_cfg.score_method # Create the result structures for each query. qaid2_qres = {}",
"qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest neighbors this",
"scoring mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl':",
"chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq,",
"of this # code. Also, consolidating fm, fs, and fk into one vector",
"#============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize #",
"chipmatch end_() if NOT_QUIET: print('[mf] * made %d feat matches' % nFeatMatches) return",
"qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification,",
"%d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches'",
"qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of assigned nearest features (only indexes",
"= qres # Retain original score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\"",
"chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output container if",
"database of features * dist - the distance to a corresponding feature *",
"Append database feature matches to query aids else: for qfx, aid, fx, fs,",
"Building chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches =",
"score of a corresponding feature * valid - a valid bit for a",
"cdef int MARK_AFTER cdef double tau \"\"\" #================= # Globals #================= START_AFTER =",
"= np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename =",
"= 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list =",
"{}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def",
"for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone",
"a score of a corresponding feature * valid - a valid bit for",
"#cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time of this function",
"', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _)",
"dist - the distance to a corresponding feature * fs - a score",
"elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method",
"if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate",
"# Apply gravity vector weight to the score qfx2_score *= qfx2_gvweight # Remove",
"VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum()",
"Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups",
"function for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long",
"', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) =",
"= 2 # TODO: paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype",
"# Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data)",
"\"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 %",
"#============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs -",
"= {aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches}",
"topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use extent of matching",
"# Create the result structures for each query. qaid2_qres = {} for qaid",
"nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid",
"filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3)",
"dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get",
"invalid by gid' % nImg_all_invalid) print('[mf] * %d are newly invalided by gid'",
"= new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check",
"5) Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return",
"#### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid' %",
"We dont have an easy way to access keypoints from nearest neighbors yet",
"= ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation",
"Impossible Votes: # dont vote for yourself or another chip in the same",
"to database feature indexes * qfx2_dist - ranked list of query feature indexes",
"number of approximate nearest neighbors. cdef: dict qaid2_nns object ibs object qreq \"\"\"",
"aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx,",
"nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns,",
"qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid =",
"of coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method)",
"try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres",
"this does check that you are not matching yourself \"\"\" qaid2_nnfilt = {}",
"#if not QUIET: # nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats",
"thresh being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights",
"qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm,",
"qaid2_ denotes a mapping where keys are query-annotation-id vsmany/vsone counts here. also this",
"abstract it away from __future__ import absolute_import, division, print_function # Python from six.moves",
"aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns,",
"prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh",
"speed of this # code. Also, consolidating fm, fs, and fk into one",
"difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] =",
"IBEIS Controller qaids - query annotation-ids qreq - a QueryRequest object Output: qaid2_nnds",
"= {} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight",
"not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification: off') return",
"qfx2_oris) # Normalize into a weight (close orientations are 1, far are 0)",
"nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in",
"@profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial",
"_weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for",
"THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms",
"feature indexes to database feature indexes } * qaid2_norm_weight - mapping from qaid",
"dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find",
"indexes to database feature indexes * qfx2_dist - ranked list of query feature",
"qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg =",
"% nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch,",
"list qaids dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr()",
"(int, float)): qfx2_passed = sign * qfx2_weights <= sign * thresh qfx2_valid =",
"in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1",
"nTotalNN, nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign NN: ', len(qaids)) for",
"if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score",
"return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list",
"score_method = score_method[:-1] # Choose the appropriate scoring mechanism if score_method == 'csum':",
"weight (close orientations are 1, far are 0) qfx2_gvweight = (np.tau - qfx2_oridist)",
"np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid]",
"the database of features * dist - the distance to a corresponding feature",
"aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] * made",
"Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes",
"\"\"\" helper for spatial verification, computes the squared diagonal length of matching chips",
"qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper",
"end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) #",
"# dont vote for yourself or another chip in the same image cant_match_self",
"{aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches} #",
"dtype=np.bool) # Check that you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip",
"aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of",
"query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' % (query_type,))",
"qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by gid' % nImg_all_invalid) print('[mf] *",
"Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid]",
"this # code. Also, consolidating fm, fs, and fk into one vector will",
"+ cfgstr_) num_neighbors = K + Knorm # number of nearest neighbors qdesc_list",
"= ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] *",
"scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a query result",
"chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else:",
"qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert",
"- an IBEIS Controller qaids - query annotation-ids qreq - a QueryRequest object",
"there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints",
"print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal))",
"nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf]",
"qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg",
"= qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are invalid by thresh' %",
"qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper",
"where the filter weights and thershold are applied to the matches. Essientally nearest",
"= np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not",
"object ibs object qreq \"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K",
"super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s: qaid=%r has",
"self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid)",
"hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid)",
"msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s: qaid=%r",
"0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k",
"neighbors are converted into weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type",
"+= len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d desc from %d chips",
"linalg as ltool from vtool import spatial_verification as sver # Hotspotter from ibeis.model.hots",
"_spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg",
"> minMatches} # Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size",
"qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] =",
"# Internal statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign",
"{} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta",
"* %d assignments are invalid by nid' % nName_all_invalid) print('[mf] * %d are",
"(qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by gid'",
"mark_, end_ = log_prog('Assign NN: ', len(qaids)) for count, qaid in enumerate(qaids): mark_(count)",
"score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load the result",
"qfx2_passed) if not weight == 0: qfx2_score += weight * qfx2_weights return qfx2_score,",
"qdesc_list[count] # Check that we can query this annotation if len(qfx2_desc) == 0:",
"query this annotation if len(qfx2_desc) == 0: # Assign empty nearest neighbors qfx2_dx",
"Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2)",
"handled anymore if score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1] # Choose",
"% nChip_all_invalid) print('[mf] * %d are newly invalided by self' % nChip_new_invalid) ####",
"Vsmany - Append query feature matches to database aids if not is_vsone: aid2_fm,",
"Neighbors Input: ibs - an IBEIS Controller qaids - query annotation-ids qreq -",
"qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring method:' + score_method) return",
"utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2",
"* (True - qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by nid' %",
"aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2",
"feature match / score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V)",
"+ Knorm # number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors",
"@profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg =",
"qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid):",
"method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise",
"# FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts)",
"for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method,",
"index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index]",
"+ sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh =",
"container if dbginfo: aid2_svtup = {} # dbg info (can remove if there",
"_apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments",
"check that you are not matching yourself \"\"\" qaid2_nnfilt = {} K =",
"nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid,",
"by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts =",
"by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid =",
"qaid2_nns = {} # Internal statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_,",
"score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) =",
"- dict of assigned nearest features (only indexes are used here) qaid2_nnfilt -",
"#### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid)",
"= ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize",
"% ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def",
"qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d desc from",
"weight == 0: qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid @profile def",
"VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum()",
"= (fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def",
"25 == 0: sys.stdout.write(msg) count += 1 # Find a transform from chip2",
"sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch,",
"if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch",
"np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to determine",
"testing function returns unfiltered nearest neighbors this does check that you are not",
"%d desc from %d chips to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN))",
"import keypoint as ktool from vtool import linalg as ltool from vtool import",
"num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup =",
"* Marking %d assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score,",
"query-annotation-id vsmany/vsone counts here. also this is where the filter weights and thershold",
"if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid]",
"thresh, weight if thresh is not None and thresh != 'None': thresh =",
"assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type",
"* Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified",
"chipw ** 2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for",
"= aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) **",
"H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers,",
"matches correspond to the assigned nearest features qreq - QueryRequest object Output: qaid2_chipmatch",
"% (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal))",
"the annotation, and K is the number of approximate nearest neighbors. cdef: dict",
"= qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq)",
"qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch",
"ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import coverage_image",
"might help the speed of this # code. Also, consolidating fm, fs, and",
"HACK: Im not even sure if the 'w' suffix is correctly handled anymore",
"nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc",
"aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if",
"(qfx2_fs, qfx2_valid) tuple SCALARS * dx - the index into the database of",
"as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import",
"fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape",
"reduce # the amount of appends. match_iter = zip(*valid_lists) # Vsmany - Append",
"(qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist)",
"qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings",
"match / score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if",
"Globals #================= START_AFTER = 2 # specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER)",
"# 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest",
"qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from featurematches to",
"if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid",
"range import six from collections import defaultdict import sys # Scientific import numpy",
"#============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors: '",
"* %d are newly invalided by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid,",
"= np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid' % ((True -",
"not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid =",
"2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else:",
"Iterate over chips with nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns))",
"qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats",
"Check that you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid",
"# Python from six.moves import zip, range import six from collections import defaultdict",
"cfgstr = qreq.get_cfgstr2() # hack of a fix qaid2_qres = {} failed_qaids =",
"qaid, chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid,",
"qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call a tighter (hopefully cythonized) nearest",
"ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2]",
"Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx)",
"# Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query chip index to",
"qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists by aid might help",
"qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid !=",
"(nQKpts, 1)) # Pack valid feature matches into an interator valid_lists = [qfx2[qfx2_valid]",
"sign * qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not",
"are invalid by self' % nChip_all_invalid) print('[mf] * %d are newly invalided by",
"nearest neighbor tuple (indexes, dists). indexes and dist have the shape (nDesc x",
"# qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert",
"indexes } * qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid]",
"# Choose the appropriate scoring mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch)",
"based on config and weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for",
"for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid]",
"return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} #",
"cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG",
"end of coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq,",
"- ranked list of query feature indexes to database feature indexes } *",
"aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\"",
"descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of query and result desc",
"for a corresponding feature REALIZATIONS: qaid2_nns - maping from query chip index to",
"topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd",
"score_method.startswith('coverage'): # Method num is at the end of coverage method = int(score_method.replace('coverage',",
"assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ ==",
"tx in range(nRerank)] else: # Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2",
"vector weight to the score qfx2_score *= qfx2_gvweight # Remove Impossible Votes: #",
"(x_m.max() - x_m.min()) ** 2 + (y_m.max() - y_m.min()) ** 2 return dlensqrd",
"to a nearest neighbor tuple (indexes, dists). indexes and dist have the shape",
"hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {}",
"# Vsone - Append database feature matches to query aids else: for qfx,",
"qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d assignments are",
"each query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): # For each query's",
"= qreq.get_cfgstr2() # hack of a fix qaid2_qres = {} failed_qaids = []",
"cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: ' + cfgstr_) num_neighbors",
"QUIET: # nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = '",
"Pack valid feature matches into an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in",
"that we can query this annotation if len(qfx2_desc) == 0: # Assign empty",
"NN: ', len(qaids)) for count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc =",
"and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight",
"count % 25 == 0: sys.stdout.write(msg) count += 1 # Find a transform",
"of a fix qaid2_qres = {} failed_qaids = [] for qaid in qaids:",
"Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K",
"= ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing the",
"is a speed issue) def print_(msg, count=0): \"\"\" temp print_. Using count in",
"filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles)",
"(chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph ** 2",
"# qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) #",
"#================= PREFIXES: qaid2_XXX - prefix mapping query chip index to qfx2_XXX - prefix",
"= sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV =",
"qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im not",
"if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True -",
"# Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch",
"(nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if",
"= qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K,",
"vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid,",
"qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient",
"qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) !=",
"topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd",
"- the index into the database of features * dist - the distance",
"qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta):",
"DEBUG=False) np.tau = 2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not",
"a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 =",
"something # Rebuild the feature match / score arrays to be consistent chipmatchSV",
"nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for nnfilter in nnfilter_list:",
"gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid)",
"six from collections import defaultdict import sys # Scientific import numpy as np",
"len(fk) > minMatches} # Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape =",
"access keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient",
"dbg info (can remove if there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V",
"aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk",
"qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres # Retain original score method",
"and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #=================",
"aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num",
"{} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not",
"score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid]",
"aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype)",
"minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk)",
"topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult",
"qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO:",
"nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something",
"@profile def try_load_resdict(qreq): \"\"\" Try and load the result structures for each query.",
"Using count in this way is a hack \"\"\" if NOT_QUIET: if count",
"neighbor func # Call a tighter (hopefully cythonized) nearest neighbor function qaid2_nns =",
"matches. Essientally nearest neighbors are converted into weighted assignments \"\"\" # Config K",
"@profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape,",
"a numeric score score and valid flag for each feature match qfx2_score, qfx2_valid",
"shape for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch",
"= nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: ' + cfgstr_) num_neighbors =",
"= defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt,",
"list of query feature indexes to database feature indexes * qfx2_dist - ranked",
"# 77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid)",
"Check the diaglen sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid,",
"import six from collections import defaultdict import sys # Scientific import numpy as",
"%s' % (query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone",
"print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch",
"Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) =",
"= ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid = ((True",
"topx in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2",
"qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights",
"import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as vr2 import",
"even sure if the 'w' suffix is correctly handled anymore if score_method.find('w') ==",
"qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres') cfgstr",
"for aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape for",
"qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert",
"are newly invalided by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if",
"def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize # Convert to",
"each nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq)",
"# verified something # Rebuild the feature match / score arrays to be",
"#Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() #",
"NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= #",
"* %d are newly invalided by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid,",
"ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2 + (y_m.max() - y_m.min())",
"kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is",
"\"\"\" Plain Nearest Neighbors Input: ibs - an IBEIS Controller qaids - query",
"in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists by",
"#============================ # 4) Conversion from featurematches to chipmatches qfx2 -> aid2 #============================ @profile",
"def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN",
"%d are newly invalided by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip)",
"reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign NN: ', len(qaids))",
"0: qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns,",
"filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K =",
"paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype =",
"sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights <= sign *",
"into a weight (close orientations are 1, far are 0) qfx2_gvweight = (np.tau",
"no descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return",
"if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris",
"Method num is at the end of coverage method = int(score_method.replace('coverage', '0')) aid2_score",
"= sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh =",
"TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs,",
"defaultdict import sys # Scientific import numpy as np from vtool import keypoint",
"this annotation if len(qfx2_desc) == 0: # Assign empty nearest neighbors qfx2_dx =",
"of matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph)",
"continue # Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc,",
"if not weight == 0: qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid",
"= (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by",
"%r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest",
"qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not matching yourself qfx2_aid",
"%d feat matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification #============================",
"code. Also, consolidating fm, fs, and fk into one vector will reduce #",
"' + cfgstr_) num_neighbors = K + Knorm # number of nearest neighbors",
"feature index to TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt",
"consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] =",
"qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid",
"and valid flag for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights,",
"qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:,",
"#============================ # 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET:",
"kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau \"\"\" #================= #",
"= nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest neighbor # TODO FIX",
"qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _)",
"len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) =",
"topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo:",
"= qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET:",
"dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method",
"not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx, fs, fk",
"NEEDS FIX TAKES 21.9 % time of this function cfgstr = qreq.get_cfgstr2() #",
"topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh,",
"qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn =",
"= qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time of",
"the appropriate scoring mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method",
"!= id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) #",
"- a valid bit for a corresponding feature REALIZATIONS: qaid2_nns - maping from",
"startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_): # qaid = 1 #",
"of a corresponding feature * valid - a valid bit for a corresponding",
"vsmany/vsone counts here. also this is where the filter weights and thershold are",
"{} # dbg info (can remove if there is a speed issue) aid2_fm_V,",
"qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx,",
"= fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') #",
"numeric score score and valid flag for each feature match qfx2_score, qfx2_valid =",
"list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES",
"filt_cfg.get_stw(filt) # stw = sign, thresh, weight if thresh is not None and",
"assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips",
"score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method",
"dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step",
"maping from query chip index to nns { * qfx2_dx - ranked list",
"(Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE)",
"sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup",
"for each query. returns a list of failed qaids cdef: object qreq list",
"in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw =",
"you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid",
"aids else: for qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) #",
"cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result structures for each",
"qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting",
"score and valid flag for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx,",
"sign, thresh, weight = filt_cfg.get_stw(filt) # stw = sign, thresh, weight if thresh",
"aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid",
"from %d chips to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns",
"# Check that we can query this annotation if len(qfx2_desc) == 0: #",
"% (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid),",
"filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor",
"qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches = [len(fm) for fm in",
"0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {} #",
"VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t",
"fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is",
"'None': thresh = float(thresh) # corrects for thresh being strings sometimes if isinstance(thresh,",
"= ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on config and",
"Also, consolidating fm, fs, and fk into one vector will reduce # the",
"* dx - the index into the database of features * dist -",
"qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if",
"- qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by self' % nChip_all_invalid) print('[mf]",
"helper for spatial verification, computes the squared diagonal length of matching chips \"\"\"",
"= log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark",
"# HACK: Im not even sure if the 'w' suffix is correctly handled",
"(qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns",
"ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid",
"6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create",
"!= qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def",
"# 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg",
"dont vote for yourself or another chip in the same image cant_match_self =",
"is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if",
"distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close orientations are",
"assignments are invalid by gid' % nImg_all_invalid) print('[mf] * %d are newly invalided",
"(featmatch_scores, featmatch_mask) where the scores and matches correspond to the assigned nearest features",
"by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d",
"'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method",
"qreq - a QueryRequest object Output: qaid2_nnds - a dict mapping query annnotation-ids",
"dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with its",
"new_fmfsfk() # Iterate over chips with nearest neighbors mark_, end_ = log_prog('Build Chipmatch:",
"sv_tup is None: print_('o') # sv failure else: # Return the inliers to",
"appends. match_iter = zip(*valid_lists) # Vsmany - Append query feature matches to database",
"coding: utf-8 -*- \"\"\" #================= # matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX",
"= {} failed_qaids = [] for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid,",
"** 2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx",
"correctly handled anymore if score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1] #",
"keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m,",
"var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids) ==",
"query annnotation-ids to a nearest neighbor tuple (indexes, dists). indexes and dist have",
"count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx =",
"= aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats for",
"the squared diagonal length of matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid))",
"nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo:",
"== 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs,",
"from functools import partial #profile = utool.profile print, print_, printDBG, rrr, profile =",
"2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE =",
"len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild",
"__init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s:",
"from query chip index to nns { * qfx2_dx - ranked list of",
"_fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if",
"in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres #",
"= list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2",
"@profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs - an",
"QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step",
"len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs)",
"qfx2_desc = qdesc_list[count] # Check that we can query this annotation if len(qfx2_desc)",
"consolidating fm, fs, and fk into one vector will reduce # the amount",
"sys # Scientific import numpy as np from vtool import keypoint as ktool",
"to database feature indexes } * qaid2_norm_weight - mapping from qaid to (qfx2_normweight,",
"new_fmfsfk() for qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note",
"from collections import defaultdict import sys # Scientific import numpy as np from",
"a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs,",
"its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of query and",
"the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close",
"fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for",
"qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX",
"import nn_filters from ibeis.model.hots import voting_rules2 as vr2 import utool from functools import",
"= ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing the homography topx2_dlen_sqrd =",
"sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch, {}) if",
"six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring",
"dtype=np.bool) # Apply the filter weightings to determine feature validity and scores for",
"range(nRerank)] else: # Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx]",
"query aids else: for qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx))",
"are invalid by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx]",
"ibs object qreq \"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K =",
"chipmatch #if not QUIET: # nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] #",
"profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi # tauday.com NOT_QUIET",
"count=0): \"\"\" temp print_. Using count in this way is a hack \"\"\"",
"self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s: qaid=%r has no",
"dict of assigned nearest features (only indexes are used here) qaid2_nnfilt - dict",
"zip(*valid_lists) # Vsmany - Append query feature matches to database aids if not",
"= qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: #",
"qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time of this function cfgstr =",
"to qfx2_XXX - prefix mapping query chip feature index to TUPLES: * nns",
"and thershold are applied to the matches. Essientally nearest neighbors are converted into",
"= (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs =",
"qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid =",
"dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2]",
"distance to a corresponding feature * fs - a score of a corresponding",
"as ktool from vtool import linalg as ltool from vtool import spatial_verification as",
"score_method[:-1] # Choose the appropriate scoring mechanism if score_method == 'csum': aid2_score =",
"is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_()",
"print_. Using count in this way is a hack \"\"\" if NOT_QUIET: if",
"import absolute_import, division, print_function # Python from six.moves import zip, range import six",
"feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches' %",
"if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd =",
"the index into the database of features * dist - the distance to",
"if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk in",
"- qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly",
"aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk) >",
"fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers)",
"import utool from functools import partial #profile = utool.profile print, print_, printDBG, rrr,",
"ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef",
"defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns",
"qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) #",
"for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid =",
"build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of assigned nearest features (only",
"This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm)",
"squared diagonal length of matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def",
"cdef double tau \"\"\" #================= # Globals #================= START_AFTER = 2 # specialized",
"qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx,",
"# utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches to query aids else:",
"qfx2_gvweight # Remove Impossible Votes: # dont vote for yourself or another chip",
"chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches = 0",
"#============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch",
"- mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove",
"qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid =",
"to the assigned nearest features qreq - QueryRequest object Output: qaid2_chipmatch - dict",
"to chip1 (the old way was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch):",
"# assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index =",
"def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors cdef:",
"nearest features (only indexes are used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask)",
"qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric score score and valid",
"in range(nRerank)] else: # Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 =",
"qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== #",
"qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx",
"end_() if NOT_QUIET: print('[mf] * assigned %d desc from %d chips to %r",
"2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list)",
"Return var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids)",
"topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing the homography topx2_dlen_sqrd",
"info (can remove if there is a speed issue) def print_(msg, count=0): \"\"\"",
"fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for",
"= qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check",
"vr2 import utool from functools import partial #profile = utool.profile print, print_, printDBG,",
"_) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid =",
"cdef: dict qaid2_nns object ibs object qreq \"\"\" # Neareset neighbor configuration nn_cfg",
"# Apply the filter weightings to determine feature validity and scores for filt,",
"VERBOSE: print('[mf] * %d assignments are invalid by thresh' % ((True - qfx2_valid).sum()))",
"a mapping where keys are query-annotation-id vsmany/vsone counts here. also this is where",
"sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0",
"nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score",
"chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph **",
"qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid' % ((True",
"neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func,",
"structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch",
"= qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K),",
"interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] #",
"scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None: print_('o') #",
"Conversion from featurematches to chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs,",
"dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS",
"fk in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape for aid, fm",
"fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ =",
"- query annotation-ids qreq - a QueryRequest object Output: qaid2_nnds - a dict",
"nImg_all_invalid) print('[mf] * %d are newly invalided by gid' % nImg_new_invalid) #### qfx2_valid",
"is None: print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo",
"utool from functools import partial #profile = utool.profile print, print_, printDBG, rrr, profile",
"ranked list of query feature indexes to database feature indexes } * qaid2_norm_weight",
"descriptors in the annotation, and K is the number of approximate nearest neighbors.",
"empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64)",
"filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter",
"in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore:",
"qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights,",
"# Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs,",
"qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset",
"') if filt_cfg.gravity_weighting: # We dont have an easy way to access keypoints",
"from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as",
"qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf] Step",
"#print(inliers) print_('.') # verified something # Rebuild the feature match / score arrays",
"determine feature validity and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid]",
"nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign",
"strings sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights <= sign",
"qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_)",
"= qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return",
"Normalize into a weight (close orientations are 1, far are 0) qfx2_gvweight =",
"identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest neighbors this does check that",
"(indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with",
"ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau \"\"\" #================= # Globals",
"qaid, chipmatch, score_method, qreq) # Create a query result structure qres = hots_query_result.QueryResult(qaid,",
"matches into an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx,",
"ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters",
"function cfgstr = qreq.get_cfgstr2() # hack of a fix qaid2_qres = {} failed_qaids",
"Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2)",
"inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris)",
"away from __future__ import absolute_import, division, print_function # Python from six.moves import zip,",
"Helpers #================= #def compare(qreq, qreq_): # qaid = 1 # qvecs_list = qreq_.get_internal_qvecs()",
"the shape (nDesc x K) where nDesc is the number of descriptors in",
"ibs - an IBEIS Controller qaids - query annotation-ids qreq - a QueryRequest",
"num_neighbors, checks=checks) # Associate query annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx,",
"dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine",
"qreq list qaids dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids #cfgstr =",
"qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch,",
"qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the scores and matches correspond to",
"Check that we can query this annotation if len(qfx2_desc) == 0: # Assign",
"aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs)",
"in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1",
"sure if the 'w' suffix is correctly handled anymore if score_method.find('w') == len(score_method)",
"- dict of ( Notes: The prefix qaid2_ denotes a mapping where keys",
"chip feature index to TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple *",
"= _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__",
"nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list)",
"- y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)]",
"failure else: # Return the inliers to the homography homog_inliers, H, aff_inliers, Aff",
"qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time",
"validity and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh,",
"\"\"\" testing function returns unfiltered nearest neighbors this does check that you are",
"return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial",
"one vector will reduce # the amount of appends. match_iter = zip(*valid_lists) #",
"_nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors cdef: list",
"#================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef",
"- x_m.min()) ** 2 + (y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd",
"output container if dbginfo: aid2_svtup = {} # dbg info (can remove if",
"else: # Return the inliers to the homography homog_inliers, H, aff_inliers, Aff =",
"object Output: qaid2_nnds - a dict mapping query annnotation-ids to a nearest neighbor",
"aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers)",
"%d assignments are invalid by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori",
"#print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank",
"_precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes the",
"thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score += weight",
"nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign NN: ', len(qaids)) for count,",
"= [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format",
"#### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid)",
"structures for each query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): # For",
"chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' %",
"= ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func",
"# TODO: paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE",
"return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent):",
"print('[mf] * %d assignments are invalid by self' % nChip_all_invalid) print('[mf] * %d",
"qreq.cfg.agg_cfg.score_method # Create the result structures for each query. qaid2_qres = {} for",
"an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)]",
"-*- coding: utf-8 -*- \"\"\" #================= # matching_functions: # Module Concepts #================= PREFIXES:",
"= {aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches}",
"# Iterate over chips with nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ',",
"dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not matching yourself",
"qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres",
"+= weight * qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq):",
"result structures for each query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): #",
"4) Conversion from featurematches to chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm,",
"of appends. match_iter = zip(*valid_lists) # Vsmany - Append query feature matches to",
"def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh",
"annotation, and K is the number of approximate nearest neighbors. cdef: dict qaid2_nns",
"qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:,",
"Create the result structures for each query. qaid2_qres = {} for qaid in",
"Notes: The prefix qaid2_ denotes a mapping where keys are query-annotation-id vsmany/vsone counts",
"('QUERY ERROR IN %s: qaid=%r has no descriptors!' + 'Please delete it.') %",
"len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild the feature match",
"# TODO: Sorting the valid lists by aid might help the speed of",
"Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step",
"else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg",
"+ chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)]",
"qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result structures for",
"[nnfilter] weight to each nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms =",
"are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid",
"returns a list of failed qaids cdef: object qreq list qaids dict qaid2_qres",
"match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE:",
"qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert",
"if sv_tup is None: print_('o') # sv failure else: # Return the inliers",
"Internal statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign NN:",
"structures for each query. returns a list of failed qaids cdef: object qreq",
"and K is the number of approximate nearest neighbors. cdef: dict qaid2_nns object",
"== 0: qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs,",
"qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We",
"aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats for filt,",
"Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh =",
"= utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython",
"index into the database of features * dist - the distance to a",
"weight to each nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs,",
"sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method =",
"'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method == 'topk':",
"ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau \"\"\" #=================",
"nRerank = min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo: aid2_svtup = {}",
"qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename",
"- Append query feature matches to database aids if not is_vsone: aid2_fm, aid2_fs,",
"qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for nnfilter in",
"qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return",
"utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef",
"use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV",
"1 # Find a transform from chip2 to chip1 (the old way was",
"if len(qfx2_desc) == 0: # Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors),",
"1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: #",
"- qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d assignments",
"((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME:",
"START_AFTER = 2 # specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= #",
"long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t,",
"fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_,",
"1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2 + (y_m.max() - y_m.min()) **",
"= new_fmfsfk() for qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) #",
"qfx2_dx[:, 0:K] # Get a numeric score score and valid flag for each",
"count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] # Check that",
"# dbg info (can remove if there is a speed issue) aid2_fm_V, aid2_fs_V,",
"qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx)",
"def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of assigned nearest features",
"#============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm,",
"chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if",
"qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf]",
"off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq,",
"if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] *",
"if dbginfo: aid2_svtup = {} # dbg info (can remove if there is",
"= {} filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] #",
"a fix qaid2_qres = {} failed_qaids = [] for qaid in qaids: try:",
"in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape,",
"topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the top",
"tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS * dx - the",
"- the distance to a corresponding feature * fs - a score of",
"orientations are 1, far are 0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau",
"= new_fmfsfk() # Iterate over chips with nearest neighbors mark_, end_ = log_prog('Build",
"aid2_fk): minMatches = 2 # TODO: paramaterize # Convert to numpy fm_dtype =",
"ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close orientations are 1, far are",
"((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d",
"vector will reduce # the amount of appends. match_iter = zip(*valid_lists) # Vsmany",
"annotation-ids qreq - a QueryRequest object Output: qaid2_nnds - a dict mapping query",
"Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d",
"the score qfx2_score *= qfx2_gvweight # Remove Impossible Votes: # dont vote for",
"neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)):",
"FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist =",
"# Approx nearest neighbor func # Call a tighter (hopefully cythonized) nearest neighbor",
"invalid by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts",
"qfx2_dx - ranked list of query feature indexes to database feature indexes *",
"vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num is at the",
"np.tau # Apply gravity vector weight to the score qfx2_score *= qfx2_gvweight #",
"print('[mf] Step 6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method",
"yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)):",
"# For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score",
"# print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature",
"utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata",
"= qdesc_list[count] # Check that we can query this annotation if len(qfx2_desc) ==",
"qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) #",
"minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs)",
"qaids - query annotation-ids qreq - a QueryRequest object Output: qaid2_nnds - a",
"= aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh,",
"minMatches} # Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size //",
"ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid = ((True -",
"help the speed of this # code. Also, consolidating fm, fs, and fk",
"chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres')",
"dict of ( Notes: The prefix qaid2_ denotes a mapping where keys are",
"we can query this annotation if len(qfx2_desc) == 0: # Assign empty nearest",
"nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest neighbor # TODO",
"qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid",
"Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate",
"####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True",
"chips with nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count,",
"and fk into one vector will reduce # the amount of appends. match_iter",
"of failed qaids cdef: object qreq list qaids dict qaid2_qres list failed_qaids \"\"\"",
"as np from vtool import keypoint as ktool from vtool import linalg as",
"Remove ibs control as much as possible or abstract it away from __future__",
"def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK:",
"featmatch_mask) where the scores and matches correspond to the assigned nearest features qreq",
"chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result",
"qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist",
"if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification: off')",
"dbginfo: qaid2_svtups = {} # dbg info (can remove if there is a",
"feature validity and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign,",
"number of query and result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_()",
"qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles) #========================== @profile",
"filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres') cfgstr =",
"!= qgid ####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid",
"# We dont have an easy way to access keypoints from nearest neighbors",
"Marking %d assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid)",
"2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================",
"feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx",
"TODO: Remove ibs control as much as possible or abstract it away from",
"qfx2_dist) continue # Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) =",
"For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score =",
"= qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method",
"counts here. also this is where the filter weights and thershold are applied",
"to database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx,",
"fm, fs, and fk into one vector will reduce # the amount of",
"+= 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0]",
"Choose the appropriate scoring mechanism if score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif",
"match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch",
"# number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func =",
"voting_rules2 as vr2 import utool from functools import partial #profile = utool.profile print,",
"Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors),",
"qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as",
"count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score",
"@profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict of assigned nearest",
"dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6)",
"nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if",
"the diaglen sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts,",
"if filt_cfg.gravity_weighting: # We dont have an easy way to access keypoints from",
"min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None: print_('o') # sv failure else:",
"(qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by nid'",
"qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid)",
"def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' +",
"# 4) Conversion from featurematches to chipmatches qfx2 -> aid2 #============================ @profile def",
"The prefix qaid2_ denotes a mapping where keys are query-annotation-id vsmany/vsone counts here.",
"qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with its nearest descriptors",
"tau \"\"\" #================= # Globals #================= START_AFTER = 2 # specialized progress func",
"qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ ==",
"qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num is at the end",
"qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' +",
"qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get",
"qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS * dx -",
"= aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw = sign, thresh, weight",
"class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY",
"= qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring",
"correspond to the assigned nearest features qreq - QueryRequest object Output: qaid2_chipmatch -",
"dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup",
"= qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call a tighter (hopefully cythonized)",
"defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def",
"== qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg)",
"Controller qaids - query annotation-ids qreq - a QueryRequest object Output: qaid2_nnds -",
"+= qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d desc",
"qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score += weight *",
"for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K]",
"query and result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET:",
"nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest",
"# Rebuild the feature match / score arrays to be consistent chipmatchSV =",
"load the result structures for each query. returns a list of failed qaids",
"= qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time of this function cfgstr",
"#================= # matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query",
"# Output qaid2_nns = {} # Internal statistics reporting nTotalNN, nTotalDesc = 0,",
"configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks",
"assignments are invalid by nid' % nName_all_invalid) print('[mf] * %d are newly invalided",
"_fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf]",
"nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid",
"sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {}",
"sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV = 0",
"np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to determine feature validity and scores",
"sv failure else: # Return the inliers to the homography homog_inliers, H, aff_inliers,",
"qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T",
"Create a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm,",
"* %d assignments are invalid by self' % nChip_all_invalid) print('[mf] * %d are",
"ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {} # Internal statistics reporting nTotalNN,",
"%d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return",
"qreq) elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda')",
"aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d feat",
"Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query chip index to qfx2_XXX",
"qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack",
"{} K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid]",
"= K + Knorm # number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) #",
"for qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the",
"0: sys.stdout.write(msg) count += 1 # Find a transform from chip2 to chip1",
"feature matches to query aids else: for qfx, aid, fx, fs, fk in",
"chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV",
"K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET:",
"x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min()) ** 2 +",
"of (featmatch_scores, featmatch_mask) where the scores and matches correspond to the assigned nearest",
"* %d are newly invalided by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid,",
"num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker",
"2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm =",
"aid2_fk = new_fmfsfk() for qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx))",
"query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk)",
"utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET",
"min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo: aid2_svtup = {} # dbg",
"annotation if len(qfx2_desc) == 0: # Assign empty nearest neighbors qfx2_dx = np.empty((0,",
"{} filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply",
"gravity vector weight to the score qfx2_score *= qfx2_gvweight # Remove Impossible Votes:",
"# assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist",
"another chip in the same image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG",
"def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest neighbors this does check",
"1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid]",
"qaid2_svtups = {} # dbg info (can remove if there is a speed",
"fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk",
"1: score_method = score_method[:-1] # Choose the appropriate scoring mechanism if score_method ==",
"FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert",
"\"\"\" # Output qaid2_nns = {} # Internal statistics reporting nTotalNN, nTotalDesc =",
"PREFIXES: qaid2_XXX - prefix mapping query chip index to qfx2_XXX - prefix mapping",
"index to TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt -",
"log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_): # qaid",
"filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] =",
"of features * dist - the distance to a corresponding feature * fs",
"nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {} # dbg info (can remove",
"result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) =",
"nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score =",
"aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid]",
"new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs,",
"qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists",
"ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal",
"Output: qaid2_nnds - a dict mapping query annnotation-ids to a nearest neighbor tuple",
"> minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if",
"== 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): #",
"= ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE:",
"valid bit for a corresponding feature REALIZATIONS: qaid2_nns - maping from query chip",
"for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid]",
"the scores and matches correspond to the assigned nearest features qreq - QueryRequest",
"featurematches to chipmatches qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches",
"aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.')",
"hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_",
"= sign * qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if",
"for each query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch): # For each",
"from vtool import linalg as ltool from vtool import spatial_verification as sver #",
"# Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm",
"was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore =",
"#================= # Globals #================= START_AFTER = 2 # specialized progress func log_prog =",
"* Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV,",
"valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO:",
"for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN,",
"# qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs,",
"chip1 (the old way was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch",
"nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with its nearest descriptors qaid2_nns[qaid] =",
"np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t,",
"Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx]",
"except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism",
"qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats for filt, qaid2_meta in",
"collections import defaultdict import sys # Scientific import numpy as np from vtool",
"filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not",
"of query feature indexes to database feature indexes } * qaid2_norm_weight - mapping",
"is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s'",
"% (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor weights #============================",
"computes the squared diagonal length of matching chips \"\"\" if use_chip_extent: topx2_chipsize =",
"dont have an easy way to access keypoints from nearest neighbors yet aid_list",
"print_('.') # verified something # Rebuild the feature match / score arrays to",
"= _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n')",
"if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts,",
"assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid ==",
"0 #Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk()",
"= (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by",
"topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1,",
"progress qfx2_desc = qdesc_list[count] # Check that we can query this annotation if",
"cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET:",
"aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs) >",
"= utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t",
"amount of appends. match_iter = zip(*valid_lists) # Vsmany - Append query feature matches",
"# 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET:",
"exceptions as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots",
"to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as much",
"= qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) #",
"in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) =",
"ibeis.model.hots import voting_rules2 as vr2 import utool from functools import partial #profile =",
"ex #============================ # 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\"",
"for count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] # Check",
"func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_): #",
"aid2_svtup = {} # dbg info (can remove if there is a speed",
"are newly invalided by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf]",
"= _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET:",
"import hots_query_result from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import coverage_image from",
"score score and valid flag for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid,",
"vtool import spatial_verification as sver # Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots",
"filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) #",
"Scientific import numpy as np from vtool import keypoint as ktool from vtool",
"mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts",
"time of this function cfgstr = qreq.get_cfgstr2() # hack of a fix qaid2_qres",
"thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid)",
"1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into an",
"coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring method:' + score_method)",
"spatial verification, computes the squared diagonal length of matching chips \"\"\" if use_chip_extent:",
"qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq)",
"# Precompute output container if dbginfo: aid2_svtup = {} # dbg info (can",
"be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid]",
"aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch =",
"= sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] =",
"neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest",
"aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches = [len(fm) for",
"1 # qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids)",
"if NOT_QUIET: print('[mf] * assigned %d desc from %d chips to %r nearest",
"kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2,",
"assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist =",
"ltool from vtool import spatial_verification as sver # Hotspotter from ibeis.model.hots import hots_query_result",
"tuple (indexes, dists). indexes and dist have the shape (nDesc x K) where",
"# Return var qaid2_chipmatch = {} nFeatMatches = 0 #Vsone if is_vsone: assert",
"checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest",
"** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd",
"it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================ # 1) Nearest",
"at the end of coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid,",
"neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {}",
"not matching yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count, qaid",
"aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize # Convert to numpy fm_dtype",
"+ qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def",
"original score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load the",
"in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final",
"return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns -",
"= ('QUERY ERROR IN %s: qaid=%r has no descriptors!' + 'Please delete it.')",
"= ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE:",
"+= 1 # Find a transform from chip2 to chip1 (the old way",
"is the number of approximate nearest neighbors. cdef: dict qaid2_nns object ibs object",
"nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs - an IBEIS Controller",
"nearest neighbor func # Call a tighter (hopefully cythonized) nearest neighbor function qaid2_nns",
"% (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================ # 1) Nearest Neighbors",
"assigned %d desc from %d chips to %r nearest neighbors' % (nTotalDesc, len(qaids),",
"yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts =",
"= [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting",
"aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a query result structure",
"chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num is at the end of",
"nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid",
"range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx]",
"dbg info (can remove if there is a speed issue) def print_(msg, count=0):",
"qaid2_qres[qaid] = qres # Retain original score method return qaid2_qres @profile def try_load_resdict(qreq):",
"qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor",
"= utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi # tauday.com NOT_QUIET =",
"neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor weights",
"weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr())",
"failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile",
"the valid lists by aid might help the speed of this # code.",
"- qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq):",
"= nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta",
"qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq,",
"num is at the end of coverage method = int(score_method.replace('coverage', '0')) aid2_score =",
"query feature matches to database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk =",
"nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid =",
"2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step",
"Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid",
"- qfx2_oridist) / np.tau # Apply gravity vector weight to the score qfx2_score",
"qfx2_oridist) / np.tau # Apply gravity vector weight to the score qfx2_score *=",
"aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx,",
"print_(msg, count=0): \"\"\" temp print_. Using count in this way is a hack",
"return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo)",
"score_method = qreq.cfg.agg_cfg.score_method # Create the result structures for each query. qaid2_qres =",
"compare(qreq, qreq_): # qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids =",
"x K) where nDesc is the number of descriptors in the annotation, and",
"vote for yourself or another chip in the same image cant_match_self = not",
"not weight == 0: qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid @profile",
"ranked list of query feature indexes to database feature indexes * qfx2_dist -",
"'topk') elif score_method.startswith('coverage'): # Method num is at the end of coverage method",
"log_prog('Assign NN: ', len(qaids)) for count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc",
"Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return",
"qfx, aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference",
"y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return",
"neighbors: ' + cfgstr_) num_neighbors = K + Knorm # number of nearest",
"if NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method",
"+ 'Please delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================",
"matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat matches' % (nFeatMatchSV,",
"Votes: # dont vote for yourself or another chip in the same image",
"specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq,",
"assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ =",
"feature matches to database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk()",
"# Retain original score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and",
"= vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs,",
"mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count)",
"qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec ==",
"#================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t",
"nearest features qreq - QueryRequest object Output: qaid2_chipmatch - dict of ( Notes:",
"= qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] =",
"= [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches)))",
"way is a hack \"\"\" if NOT_QUIET: if count % 25 == 0:",
"mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs",
"np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid",
"Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch =",
"= topx2_kpts[topx] fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm,",
"failed qaids cdef: object qreq list qaids dict qaid2_qres list failed_qaids \"\"\" qaids",
"* qfx2_dx - ranked list of query feature indexes to database feature indexes",
"import spatial_verification as sver # Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import",
"aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize",
"int MARK_AFTER cdef double tau \"\"\" #================= # Globals #================= START_AFTER = 2",
"by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid =",
"= fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET:",
"nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned %d",
"_spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: '",
"has no descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg)",
"fk into one vector will reduce # the amount of appends. match_iter =",
"qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time",
"qreq, 'topk') elif score_method.startswith('coverage'): # Method num is at the end of coverage",
"prefix mapping query chip feature index to TUPLES: * nns - a (qfx2_dx,",
"** 2 + (y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx)",
"#============================ # 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain",
"the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid]",
"Apply the filter weightings to determine feature validity and scores for filt, aid2_weights",
"qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight ==",
"== len(qreq.data_index.dx2_data) # Filter matches based on config and weights mark_, end_ =",
"# Call a tighter (hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids,",
"fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches",
"= qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles) #==========================",
"(np.tau - qfx2_oridist) / np.tau # Apply gravity vector weight to the score",
"self' % nChip_all_invalid) print('[mf] * %d are newly invalided by self' % nChip_new_invalid)",
"ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as vr2",
"six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r'",
"to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME:",
"kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:,",
"4) Building chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch = {} nFeatMatches",
"x_m.min()) ** 2 + (y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd =",
"TAKES 21.9 % time of this function cfgstr = qreq.get_cfgstr2() # hack of",
"use_chip_extent) # spatially verify the top __NUM_RERANK__ results for topx in range(nRerank): aid",
"failed_qaids \"\"\" qaids = qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9",
"feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV",
"nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes the squared diagonal length of",
"weights and thershold are applied to the matches. Essientally nearest neighbors are converted",
"'0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring",
"qaid2_nnds - a dict mapping query annnotation-ids to a nearest neighbor tuple (indexes,",
"this way is a hack \"\"\" if NOT_QUIET: if count % 25 ==",
"_) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature",
"qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by self' % nChip_all_invalid) print('[mf] *",
"qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors cdef: list qaids,",
"can query this annotation if len(qfx2_desc) == 0: # Assign empty nearest neighbors",
"qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone:",
"= score_method[:-1] # Choose the appropriate scoring mechanism if score_method == 'csum': aid2_score",
"config and weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid",
"Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont have an easy",
"image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid",
"qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply",
"will reduce # the amount of appends. match_iter = zip(*valid_lists) # Vsmany -",
"= 2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE",
"= {} nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm,",
"absolute_import, division, print_function # Python from six.moves import zip, range import six from",
"matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid]",
"six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk",
"arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] =",
"NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg) count += 1 # Find",
"filt_cfg.gravity_weighting: # We dont have an easy way to access keypoints from nearest",
"' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches to query",
"match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone",
"orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close orientations",
"np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid' % ((True - qfx2_valid).sum()))",
"Step 5) Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else:",
"np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid]",
"len(fm) if sv_tup is None: print_('o') # sv failure else: # Return the",
"qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method,",
"qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load the result structures for each",
"indexes to database feature indexes } * qaid2_norm_weight - mapping from qaid to",
"qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum()",
"np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape",
"_fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches = [len(fm)",
"print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont have an",
"Input: qaid2_nns - dict of assigned nearest features (only indexes are used here)",
"nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor",
"(aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist)",
"FIXME: This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm in",
"= fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff",
"<filename>_broken/old/matching_functions.py # -*- coding: utf-8 -*- \"\"\" #================= # matching_functions: # Module Concepts",
"'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score,",
"import defaultdict import sys # Scientific import numpy as np from vtool import",
"are applied to the matches. Essientally nearest neighbors are converted into weighted assignments",
"# Scientific import numpy as np from vtool import keypoint as ktool from",
"== 0: # Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist",
"= np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not matching yourself qfx2_aid =",
"= {} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] #",
"qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1))",
"not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid",
"desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau",
"-*- \"\"\" #================= # matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX - prefix",
"# TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight",
"' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh",
"sys.stdout.write(msg) count += 1 # Find a transform from chip2 to chip1 (the",
"Find a transform from chip2 to chip1 (the old way was 1 to",
"print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist =",
"prefix qaid2_ denotes a mapping where keys are query-annotation-id vsmany/vsone counts here. also",
"== 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips with nearest",
"print('[mf] * Homog verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return",
"defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq):",
"flag for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid",
"of approximate nearest neighbors. cdef: dict qaid2_nns object ibs object qreq \"\"\" #",
"6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf]",
"'[mf]', DEBUG=False) np.tau = 2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and",
"if NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return",
"np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double",
"as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt",
"k+1th qaid2_qres[qaid] = qres # Retain original score method return qaid2_qres @profile def",
"query annotation-ids qreq - a QueryRequest object Output: qaid2_nnds - a dict mapping",
"= qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) #",
"Sorting the valid lists by aid might help the speed of this #",
"qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs,",
"a speed issue) def print_(msg, count=0): \"\"\" temp print_. Using count in this",
"qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors",
"* %d assignments are invalid by gid' % nImg_all_invalid) print('[mf] * %d are",
"= hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for",
"feature * valid - a valid bit for a corresponding feature REALIZATIONS: qaid2_nns",
"nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num is",
"= np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors",
"qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4)",
"cfgstr_) num_neighbors = K + Knorm # number of nearest neighbors qdesc_list =",
"fs = aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh,",
"Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs",
"fix qaid2_qres = {} failed_qaids = [] for qaid in qaids: try: qres",
"rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi # tauday.com",
"qfx2_valid) tuple SCALARS * dx - the index into the database of features",
"qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {}",
"if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid",
"aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype)",
"(ibs.get_dbname(), qaid) ex = QueryException(msg) return ex #============================ # 1) Nearest Neighbors #============================",
"#================= #def compare(qreq, qreq_): # qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() #",
"np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception):",
"length of matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw,",
"ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter",
"+= len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild the feature",
"= ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close orientations are 1, far",
"def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR IN %s: qaid=%r has no descriptors!'",
"in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid,",
"tighter (hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks)",
"' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile",
"Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk)",
"%d assignments are invalid by self' % nChip_all_invalid) print('[mf] * %d are newly",
"for aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk,",
"# specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def",
"Get a numeric score score and valid flag for each feature match qfx2_score,",
"return filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles) #========================== @profile def",
"= utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau =",
"end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) #",
"def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {}",
"hack of a fix qaid2_qres = {} failed_qaids = [] for qaid in",
"# Apply [nnfilter] weight to each nearest neighbor # TODO FIX THIS! qaid2_norm_weight,",
"Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots",
"qaids, qreq): \"\"\" Plain Nearest Neighbors Input: ibs - an IBEIS Controller qaids",
"np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from",
"the speed of this # code. Also, consolidating fm, fs, and fk into",
"(qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile",
"count += 1 # Find a transform from chip2 to chip1 (the old",
"= vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq)",
"@profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch",
"# Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a",
"return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use extent",
"if score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1] # Choose the appropriate",
"ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs,",
"index to qfx2_XXX - prefix mapping query chip feature index to TUPLES: *",
"= QueryException(msg) return ex #============================ # 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs,",
"or another chip in the same image cant_match_self = not cant_match_sameimg if cant_match_self:",
"0 if dbginfo: qaid2_svtups = {} # dbg info (can remove if there",
"np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup",
"nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not",
"= qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] * made %d feat",
"= np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to",
"matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid,",
"a (qfx2_fs, qfx2_valid) tuple SCALARS * dx - the index into the database",
"_nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks):",
"is a hack \"\"\" if NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg)",
"Precompute output container if dbginfo: aid2_svtup = {} # dbg info (can remove",
"it away from __future__ import absolute_import, division, print_function # Python from six.moves import",
"# qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) #",
"len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on config and weights mark_, end_",
"end_() if NOT_QUIET: print('[mf] * made %d feat matches' % nFeatMatches) return qaid2_chipmatch",
"print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches",
"* dist - the distance to a corresponding feature * fs - a",
"= np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris",
"K) where nDesc is the number of descriptors in the annotation, and K",
"to TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt - a",
"NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _)",
"np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue",
"qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list,",
"len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid]",
"are used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the scores and",
"% 25 == 0: sys.stdout.write(msg) count += 1 # Find a transform from",
"aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output",
"qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert",
"invalid by self' % nChip_all_invalid) print('[mf] * %d are newly invalided by self'",
"/ np.tau # Apply gravity vector weight to the score qfx2_score *= qfx2_gvweight",
"= aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid] fk =",
"to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup",
"in this way is a hack \"\"\" if NOT_QUIET: if count % 25",
"for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each",
"this is where the filter weights and thershold are applied to the matches.",
"# TODO: Remove ibs control as much as possible or abstract it away",
"if count % 25 == 0: sys.stdout.write(msg) count += 1 # Find a",
"_) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric score score",
"filter weights and thershold are applied to the matches. Essientally nearest neighbors are",
"print('[mf] * %d are newly invalided by nid' % nName_new_invalid) #### qfx2_valid =",
"QueryRequest object Output: qaid2_chipmatch - dict of ( Notes: The prefix qaid2_ denotes",
"dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] =",
"chipmatch # HACK: Im not even sure if the 'w' suffix is correctly",
"= log_prog('Assign NN: ', len(qaids)) for count, qaid in enumerate(qaids): mark_(count) # progress",
"+= len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something #",
"nChip_all_invalid) print('[mf] * %d are newly invalided by self' % nChip_new_invalid) #### qfx2_valid",
"way to access keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME:",
"= qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ #",
"= chipmatch # HACK: Im not even sure if the 'w' suffix is",
"qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #========================== # 3)",
"Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if",
"(can remove if there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk()",
"in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid,",
"cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if",
"= chipw ** 2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx)",
"qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight (close orientations are 1,",
"use_chip_extent): \"\"\" helper for spatial verification, computes the squared diagonal length of matching",
"# Assign empty nearest neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0,",
"+ # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches to query aids",
"things like k+1th qaid2_qres[qaid] = qres # Retain original score method return qaid2_qres",
"# record number of query and result desc nTotalNN += qfx2_dx.size nTotalDesc +=",
"#profile = utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau",
"* qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight",
"print('[mf] * made %d feat matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5)",
"== qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] #",
"nearest neighbors: ' + cfgstr_) num_neighbors = K + Knorm # number of",
"', len(qaids)) for count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count]",
"= np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score += weight * qfx2_weights",
"chip in the same image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip",
"kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data)",
"log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress",
"sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers",
"Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) #",
"nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {} # dbg",
"desc_t cdef int MARK_AFTER cdef double tau \"\"\" #================= # Globals #================= START_AFTER",
"bit for a corresponding feature REALIZATIONS: qaid2_nns - maping from query chip index",
"float(thresh) # corrects for thresh being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed",
"nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild the",
"sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV +=",
"qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_",
"qfx2_k,)] # TODO: Sorting the valid lists by aid might help the speed",
"# index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] #",
"inliers to the homography homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid]",
"(qfx2_dx, qfx2_dist) # record number of query and result desc nTotalNN += qfx2_dx.size",
"matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def",
"converted into weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type",
"* qfx2_dist - ranked list of query feature indexes to database feature indexes",
"qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid =",
"matches to database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for",
"= qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec",
"fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None:",
"aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET: print('[mf]",
"list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2]",
"assignments are invalid by self' % nChip_all_invalid) print('[mf] * %d are newly invalided",
"denotes a mapping where keys are query-annotation-id vsmany/vsone counts here. also this is",
"qgid ####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid *",
"invalided by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid",
"result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] *",
"return ex #============================ # 1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq):",
"qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors #",
"= qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4) Building",
"is at the end of coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs,",
"features * dist - the distance to a corresponding feature * fs -",
"from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as vr2 import utool from",
"# assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_",
"have an easy way to access keypoints from nearest neighbors yet aid_list =",
"import partial #profile = utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]',",
"query. returns a list of failed qaids cdef: object qreq list qaids dict",
"# FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist",
"import voting_rules2 as vr2 import utool from functools import partial #profile = utool.profile",
"= (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from featurematches to chipmatches",
"cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG",
"ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau \"\"\" #================= # Globals #=================",
"worker function for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns",
"homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the",
"nid' % nName_all_invalid) print('[mf] * %d are newly invalided by nid' % nName_new_invalid)",
"verification, computes the squared diagonal length of matching chips \"\"\" if use_chip_extent: topx2_chipsize",
"= [] for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) #",
"query chip index to qfx2_XXX - prefix mapping query chip feature index to",
"chipmatch qres.filt2_meta = {} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] =",
"record number of query and result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc)",
"if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True",
"len(fs) > minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk)",
"= ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches to",
"= {} # dbg info (can remove if there is a speed issue)",
"ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on config and weights",
"(hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return",
"for aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs,",
"\"\"\" Input: qaid2_nns - dict of assigned nearest features (only indexes are used",
"sver # Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions as hsexcept",
"(close orientations are 1, far are 0) qfx2_gvweight = (np.tau - qfx2_oridist) /",
"here. also this is where the filter weights and thershold are applied to",
"qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg",
"# FIXME: This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm",
"\"\"\" # Config K = qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type ==",
"K + Knorm # number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get",
"database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid,",
"(only indexes are used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the",
"filt2_weights = {} filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter]",
"score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im not even sure",
"six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return",
"nDesc is the number of descriptors in the annotation, and K is the",
"qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are invalid by thresh'",
"object Output: qaid2_chipmatch - dict of ( Notes: The prefix qaid2_ denotes a",
"nn_filters from ibeis.model.hots import voting_rules2 as vr2 import utool from functools import partial",
"diagonal length of matching chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx):",
"new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the",
"Rebuild the feature match / score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V,",
"# Create a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score",
"fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ = {aid:",
"qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) #",
"partial #profile = utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False)",
"qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc",
"(aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) #",
"qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that",
"= topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph ** 2 return dlen_sqrd",
"dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch,",
"neighbors: ') if filt_cfg.gravity_weighting: # We dont have an easy way to access",
"if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: ' +",
"aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw = sign, thresh, weight if",
"# Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs,",
"mark_(count) # progress qfx2_desc = qdesc_list[count] # Check that we can query this",
"way was 1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore",
"for spatial verification, computes the squared diagonal length of matching chips \"\"\" if",
"np from vtool import keypoint as ktool from vtool import linalg as ltool",
"Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors Input:",
"qaid2_XXX - prefix mapping query chip index to qfx2_XXX - prefix mapping query",
"utf-8 -*- \"\"\" #================= # matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX -",
"number of descriptors in the annotation, and K is the number of approximate",
"kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing",
"qfx2 -> aid2 #============================ @profile def _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 #",
"= (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx,",
"(True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by gid' % nImg_all_invalid)",
"the filter weights and thershold are applied to the matches. Essientally nearest neighbors",
"you are not matching yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for",
"sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5)",
"!= 'None': thresh = float(thresh) # corrects for thresh being strings sometimes if",
"\"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx,",
"corresponding feature REALIZATIONS: qaid2_nns - maping from query chip index to nns {",
"aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score,",
"# Method num is at the end of coverage method = int(score_method.replace('coverage', '0'))",
"- a (qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS",
"3) Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score",
"descriptors # assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert",
"dict mapping query annnotation-ids to a nearest neighbor tuple (indexes, dists). indexes and",
"# Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx =",
"to a corresponding feature * fs - a score of a corresponding feature",
"qres # Retain original score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try",
"= qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches",
"- maping from query chip index to nns { * qfx2_dx - ranked",
"(indexes, dists). indexes and dist have the shape (nDesc x K) where nDesc",
"final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a query",
"\"\"\" #================= # Globals #================= START_AFTER = 2 # specialized progress func log_prog",
"0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau # Apply gravity vector weight",
"/ score arrays to be consistent chipmatchSV = _fix_fmfsfk(aid2_fm_V, aid2_fs_V, aid2_fk_V) if dbginfo:",
"neighbors. cdef: dict qaid2_nns object ibs object qreq \"\"\" # Neareset neighbor configuration",
"aid2_fk) = chipmatch # HACK: Im not even sure if the 'w' suffix",
"utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef",
"= len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx]",
"np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {} #",
"= {} for qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch =",
"(aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list)",
"# matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query chip",
"sign, thresh, weight if thresh is not None and thresh != 'None': thresh",
"database feature indexes } * qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm)",
"# Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen",
"this function cfgstr = qreq.get_cfgstr2() # hack of a fix qaid2_qres = {}",
"\"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd",
"Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo else qaid2_chipmatch else: return _spatial_verification(ibs,",
"NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method =",
"chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid",
"= not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf]",
"= topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]])",
"lists by aid might help the speed of this # code. Also, consolidating",
"scores and matches correspond to the assigned nearest features qreq - QueryRequest object",
"info (can remove if there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V =",
"aid2_fs_V, aid2_fk_V) if dbginfo: qaid2_svtups[qaid] = aid2_svtup qaid2_chipmatchSV[qaid] = chipmatchSV print_('\\n') if NOT_QUIET:",
"dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5)",
"dlen_sqrd = chipw ** 2 + chiph ** 2 return dlen_sqrd topx2_dlen_sqrd =",
"ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns =",
"are invalid by nid' % nName_all_invalid) print('[mf] * %d are newly invalided by",
"# code. Also, consolidating fm, fs, and fk into one vector will reduce",
"each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs,",
"return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list)",
"is None: print_('o') # sv failure else: # Return the inliers to the",
"end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest",
"dbginfo: aid2_svtup = {} # dbg info (can remove if there is a",
"nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + #",
"matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx =",
"of ( Notes: The prefix qaid2_ denotes a mapping where keys are query-annotation-id",
"= [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use extent of matching keypoints",
"'borda') elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk')",
"# progress qfx2_desc = qdesc_list[count] # Check that we can query this annotation",
"the amount of appends. match_iter = zip(*valid_lists) # Vsmany - Append query feature",
"chipmatch, score_method, qreq) # Create a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr)",
"qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\"",
"= query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' %",
"qreq): \"\"\" Input: qaid2_nns - dict of assigned nearest features (only indexes are",
"feature REALIZATIONS: qaid2_nns - maping from query chip index to nns { *",
"aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if",
"qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as much as possible",
"[kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================",
"checks=checks) # Associate query annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist)",
"weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors:",
"a weight (close orientations are 1, far are 0) qfx2_gvweight = (np.tau -",
"of query and result desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if",
"fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches",
"if dbginfo: qaid2_svtups = {} # dbg info (can remove if there is",
"issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts",
"print('[mf] * %d are newly invalided by gid' % nImg_new_invalid) #### qfx2_valid =",
"{} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things",
"# 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if NOT_QUIET: print('[mf]",
"ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef",
"to the score qfx2_score *= qfx2_gvweight # Remove Impossible Votes: # dont vote",
"weight = filt_cfg.get_stw(filt) # stw = sign, thresh, weight if thresh is not",
"-> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result structures",
"made %d feat matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification",
"invalided by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking",
"% time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres,",
"{ * qfx2_dx - ranked list of query feature indexes to database feature",
"print('[mf] Step 1) Assign nearest neighbors: ' + cfgstr_) num_neighbors = K +",
"= qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum() nImg_new_invalid",
"NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch",
"for qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] #",
"# assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_",
"= not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE:",
"dict qaid2_nns object ibs object qreq \"\"\" # Neareset neighbor configuration nn_cfg =",
"= nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1)",
"chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph ** 2 return",
"newly invalided by nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] *",
"id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index",
"qaid2_chipmatch - dict of ( Notes: The prefix qaid2_ denotes a mapping where",
"Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query chip index to qfx2_XXX -",
"MARK_AFTER cdef double tau \"\"\" #================= # Globals #================= START_AFTER = 2 #",
"( Notes: The prefix qaid2_ denotes a mapping where keys are query-annotation-id vsmany/vsone",
"utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database feature matches to query aids else: for",
"qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ #",
"= chipmatch qres.filt2_meta = {} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt]",
"qfx2_score *= qfx2_gvweight # Remove Impossible Votes: # dont vote for yourself or",
"function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns def _nearest_neighbors(nn_func, qaids,",
"numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This",
"Output qaid2_nns = {} # Internal statistics reporting nTotalNN, nTotalDesc = 0, 0",
"a valid bit for a corresponding feature REALIZATIONS: qaid2_nns - maping from query",
"aid2_fs[aid] fk = aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd,",
"a tighter (hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors,",
"= (np.tau - qfx2_oridist) / np.tau # Apply gravity vector weight to the",
"= chipmatch end_() if NOT_QUIET: print('[mf] * made %d feat matches' % nFeatMatches)",
"# stw = sign, thresh, weight if thresh is not None and thresh",
"Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq): if NOT_QUIET: print('[mf] Step 6)",
"aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch = (aid2_fm_,",
"is the number of descriptors in the annotation, and K is the number",
"are query-annotation-id vsmany/vsone counts here. also this is where the filter weights and",
"NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: ' + cfgstr_)",
"valid lists by aid might help the speed of this # code. Also,",
"by self' % nChip_all_invalid) print('[mf] * %d are newly invalided by self' %",
"zip, range import six from collections import defaultdict import sys # Scientific import",
"neighbors qfx2_dx = np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] =",
"= sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff =",
"qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid]",
"Step 1) Assign nearest neighbors: ' + cfgstr_) num_neighbors = K + Knorm",
"return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load the result structures for",
"query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4)",
"in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] # Check that we can",
"qaid2_nns #============================ # 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq): if",
"yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip)",
"and thresh != 'None': thresh = float(thresh) # corrects for thresh being strings",
"utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo: aid2_svtup =",
"hots_query_result from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots",
"% nImg_all_invalid) print('[mf] * %d are newly invalided by gid' % nImg_new_invalid) ####",
"same image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid !=",
"qreq): qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg",
"len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs,",
"feature * fs - a score of a corresponding feature * valid -",
"dict of (featmatch_scores, featmatch_mask) where the scores and matches correspond to the assigned",
"count in this way is a hack \"\"\" if NOT_QUIET: if count %",
"is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1",
"= not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors:",
"= chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1] nRerank = min(len(topx2_aid), nShortlist) # Precompute output container",
"aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] *",
"= score_chipmatch(ibs, qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk)",
"= qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K",
"score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'):",
"3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont have an easy way",
"* (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by gid' %",
"there is a speed issue) def print_(msg, count=0): \"\"\" temp print_. Using count",
"id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist)",
"IN %s: qaid=%r has no descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid)",
"qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False):",
"a corresponding feature * valid - a valid bit for a corresponding feature",
"= _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d",
"aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx, fs, fk in match_iter:",
"nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter]",
"verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] * Homog verified %d/%d feat",
"in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_)",
"fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ = {aid: np.array(fm, fm_dtype)",
"# Get a numeric score score and valid flag for each feature match",
"nearest neighbors are converted into weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K",
"nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid =",
"ERROR IN %s: qaid=%r has no descriptors!' + 'Please delete it.') % (ibs.get_dbname(),",
"Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori, qfx2_oris) # Normalize into a weight",
"[qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the",
"Nearest Neighbors Input: ibs - an IBEIS Controller qaids - query annotation-ids qreq",
"feature indexes * qfx2_dist - ranked list of query feature indexes to database",
"Remove Impossible Votes: # dont vote for yourself or another chip in the",
"coverage_image from ibeis.model.hots import nn_filters from ibeis.model.hots import voting_rules2 as vr2 import utool",
"NOT_QUIET: print('[mf] * assigned %d desc from %d chips to %r nearest neighbors'",
"msg = ('QUERY ERROR IN %s: qaid=%r has no descriptors!' + 'Please delete",
"# Pack valid feature matches into an interator valid_lists = [qfx2[qfx2_valid] for qfx2",
"uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER",
"filt2_weights, filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid,",
"Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris)",
"= _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches =",
"to query aids else: for qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx,",
"annnotation-ids to a nearest neighbor tuple (indexes, dists). indexes and dist have the",
"np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score += weight * qfx2_weights return",
"progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric",
"= hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta =",
"qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters()",
"if the 'w' suffix is correctly handled anymore if score_method.find('w') == len(score_method) -",
"qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True",
"an IBEIS Controller qaids - query annotation-ids qreq - a QueryRequest object Output:",
"gid' % nImg_all_invalid) print('[mf] * %d are newly invalided by gid' % nImg_new_invalid)",
"# things like k+1th qaid2_qres[qaid] = qres # Retain original score method return",
"yourself or another chip in the same image cant_match_self = not cant_match_sameimg if",
"= filt_cfg.get_stw(filt) # stw = sign, thresh, weight if thresh is not None",
"weightings to determine feature validity and scores for filt, aid2_weights in six.iteritems(filt2_weights): qfx2_weights",
"# assert np.all(qvecs_list[0] == qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid",
"%d chips to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================",
"function returns unfiltered nearest neighbors this does check that you are not matching",
"* qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt =",
"(qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS * dx",
"aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :]",
"(True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by self' % nChip_all_invalid)",
"qaid, chipmatch, prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch",
"nns - a (qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple",
"= {} K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) =",
"results for topx in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd =",
"aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid2_chipmatch[qaid] = chipmatch",
"matches to query aids else: for qfx, aid, fx, fs, fk in match_iter:",
"division, print_function # Python from six.moves import zip, range import six from collections",
"Call a tighter (hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list,",
"mapping query chip feature index to TUPLES: * nns - a (qfx2_dx, qfx2_dist)",
"1 to 2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs,",
"enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] #",
"fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers) if NOT_QUIET: #print(inliers) print_('.') # verified",
"matching_functions: # Module Concepts #================= PREFIXES: qaid2_XXX - prefix mapping query chip index",
"neighbors this does check that you are not matching yourself \"\"\" qaid2_nnfilt =",
"indexes are used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the scores",
"to nns { * qfx2_dx - ranked list of query feature indexes to",
"np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\"",
"qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im not even sure if",
"qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid = utool.util_dict.keys_sorted_by_value(aid2_prescore)[::-1]",
"#========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid =",
"np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or",
"feat matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def",
"= {aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches}",
"qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if",
"% nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid",
"import zip, range import six from collections import defaultdict import sys # Scientific",
"have the shape (nDesc x K) where nDesc is the number of descriptors",
"Im not even sure if the 'w' suffix is correctly handled anymore if",
"transform from chip2 to chip1 (the old way was 1 to 2) for",
"in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape for aid, fm in",
"used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where the scores and matches",
"count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs,",
"aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) #",
"corresponding feature * fs - a score of a corresponding feature * valid",
"% nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid",
"def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg",
"- QueryRequest object Output: qaid2_chipmatch - dict of ( Notes: The prefix qaid2_",
"{aid: np.array(fs, fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_",
"def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes",
"print('[mf] Step 4) Building chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch =",
"chip index to nns { * qfx2_dx - ranked list of query feature",
"else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights =",
"nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups =",
"issue) def print_(msg, count=0): \"\"\" temp print_. Using count in this way is",
"fm = aid2_fm[aid] x_m, y_m = ktool.get_xys(kpts2[fm[:, 1]]) dlensqrd = (x_m.max() - x_m.min())",
"cdef: object qreq list qaids dict qaid2_qres list failed_qaids \"\"\" qaids = qreq.qaids",
"query chip feature index to TUPLES: * nns - a (qfx2_dx, qfx2_dist) tuple",
"ibs control as much as possible or abstract it away from __future__ import",
"qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output",
"kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m =",
"= np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion",
"= sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers =",
"= np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature",
"# Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create",
"possible or abstract it away from __future__ import absolute_import, division, print_function # Python",
"0:K] # Get a numeric score score and valid flag for each feature",
"# Find Neareset Neighbors nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors,",
"= np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid = ibs.get_annot_gids(qaid) qfx2_notsameimg =",
"# Use extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid =",
"chip index to qfx2_XXX - prefix mapping query chip feature index to TUPLES:",
"Append query feature matches to database aids if not is_vsone: aid2_fm, aid2_fs, aid2_fk",
"np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {} # Internal statistics reporting",
"qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors cdef: list qaids, qdesc_list",
"\"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm =",
"for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2, 2) chipmatch =",
"** 2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: #",
"#============================ # 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg =",
"from ibeis.model.hots import exceptions as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import",
"if thresh is not None and thresh != 'None': thresh = float(thresh) #",
"topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes the squared diagonal length",
"that you are not matching yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K",
"np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx]",
"* valid - a valid bit for a corresponding feature REALIZATIONS: qaid2_nns -",
"score qfx2_score *= qfx2_gvweight # Remove Impossible Votes: # dont vote for yourself",
"else qaid2_chipmatch else: return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq,",
"qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts,",
"vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif",
"((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf] * %d",
"ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int MARK_AFTER cdef double tau \"\"\"",
"# Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename",
"Assign nearest neighbors: ' + cfgstr_) num_neighbors = K + Knorm # number",
"# Get descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call",
"qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg =",
"= 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {}",
"chips \"\"\" if use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx]",
"import sys # Scientific import numpy as np from vtool import keypoint as",
"(qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists by aid",
"tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile def",
"return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch,",
"None and thresh != 'None': thresh = float(thresh) # corrects for thresh being",
"the 'w' suffix is correctly handled anymore if score_method.find('w') == len(score_method) - 1:",
"import exceptions as hsexcept from ibeis.model.hots import coverage_image from ibeis.model.hots import nn_filters from",
"qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def",
"return _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg =",
"if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True -",
"a QueryRequest object Output: qaid2_nnds - a dict mapping query annnotation-ids to a",
"database feature matches to query aids else: for qfx, aid, fx, fs, fk",
"QueryRequest object Output: qaid2_nnds - a dict mapping query annnotation-ids to a nearest",
"qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf]",
"nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: '",
"qfx2_score += weight * qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights,",
"= qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control as much as possible or",
"Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm = nn_cfg.Knorm checks",
"neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts",
"cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid =",
"> minMatches} aid2_fk_ = {aid: np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if",
"topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx] kpts2 = topx2_kpts[topx] fs = aid2_fs[aid]",
"[chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use extent of matching keypoints def",
"invalid by nid' % nName_all_invalid) print('[mf] * %d are newly invalided by nid'",
"failed_qaids = [] for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir())",
"is correctly handled anymore if score_method.find('w') == len(score_method) - 1: score_method = score_method[:-1]",
"<= sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0:",
"num_neighbors = K + Knorm # number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids)",
"the filter weightings to determine feature validity and scores for filt, aid2_weights in",
"(True - qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by nid' % nName_all_invalid)",
"= qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0] ==",
"#Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk) qaid = qreq.qaids[0] qaid2_chipmatch[qaid] =",
"if there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query",
"# dbg info (can remove if there is a speed issue) def print_(msg,",
"filt2_meta #========================== # 3) Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx,",
"qreq.get_cfgstr2() # hack of a fix qaid2_qres = {} failed_qaids = [] for",
"not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ')",
"from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list =",
"if len(fk) > minMatches} # Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape",
"NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild the feature match / score",
"is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over",
"aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list)",
"_fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk): minMatches = 2 # TODO: paramaterize # Convert to numpy",
"qreq) # Create a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score =",
"} * qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\"",
"return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in range(nRerank)] return topx2_dlen_sqrd #============================ #",
"// 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm",
"qaid2_chipmatch, qreq, dbginfo=dbginfo) @profile def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf]",
"int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown",
"Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont have an easy way to",
"for tx in range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile",
"#printDBG('[mf] * Marking %d assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] =",
"= (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are invalid by",
"the result structures for each query. qaid2_qres = {} for qaid in six.iterkeys(qaid2_chipmatch):",
"\"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t",
"== 'borda': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method ==",
"topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch, filt2_meta, qreq):",
"# -*- coding: utf-8 -*- \"\"\" #================= # matching_functions: # Module Concepts #=================",
"qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:,",
"qres.filt2_meta = {} # dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid]",
"* %d assignments are invalid by thresh' % ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting:",
"= vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'topk') elif score_method.startswith('coverage'): # Method num is at",
"qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid]",
"len(qaids)) for count, qaid in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] #",
"vtool import keypoint as ktool from vtool import linalg as ltool from vtool",
"'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' % (query_type,)) # Return",
"return qaid2_nns #============================ # 2) Nearest Neighbor weights #============================ def weight_neighbors(ibs, qaid2_nns, qreq):",
"prefix mapping query chip index to qfx2_XXX - prefix mapping query chip feature",
"enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE)",
"= np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class",
"far are 0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau # Apply gravity",
"dx - the index into the database of features * dist - the",
"to the matches. Essientally nearest neighbors are converted into weighted assignments \"\"\" #",
"sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh",
"qaid in six.iterkeys(qaid2_chipmatch): # For each query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform",
"Step 6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method #",
"1) Nearest Neighbors #============================ @profile def nearest_neighbors(ibs, qaids, qreq): \"\"\" Plain Nearest Neighbors",
"where the scores and matches correspond to the assigned nearest features qreq -",
"approximate nearest neighbors. cdef: dict qaid2_nns object ibs object qreq \"\"\" # Neareset",
"newly invalided by gid' % nImg_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename:",
"- a QueryRequest object Output: qaid2_nnds - a dict mapping query annnotation-ids to",
"weight to the score qfx2_score *= qfx2_gvweight # Remove Impossible Votes: # dont",
"failed_qaids #============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None):",
"qaid = qreq.qaids[0] qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] * made %d",
"qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\"",
"qaid=%r has no descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid) ex =",
"try_load_resdict(qreq): \"\"\" Try and load the result structures for each query. returns a",
"aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips with nearest neighbors mark_, end_",
"- qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments",
"#============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or",
"qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score =",
"the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify",
"* fs - a score of a corresponding feature * valid - a",
"hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================ @profile def score_chipmatch(ibs,",
"2) for qaid in six.iterkeys(qaid2_chipmatch): chipmatch = qaid2_chipmatch[qaid] aid2_prescore = score_chipmatch(ibs, qaid, chipmatch,",
"aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes the squared",
"partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_): # qaid = 1",
"valid - a valid bit for a corresponding feature REALIZATIONS: qaid2_nns - maping",
"qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None:",
"qreq): \"\"\" Plain Nearest Neighbors Input: ibs - an IBEIS Controller qaids -",
"in the same image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip =",
"qfx2_weights return qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {}",
"ktool from vtool import linalg as ltool from vtool import spatial_verification as sver",
"= (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function",
"on config and weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count,",
"is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx, fs, fk in",
"fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches +=",
"if not is_vsone: aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() for qfx, aid, fx, fs,",
"qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw = sign, thresh,",
"Step 4) Building chipmatches %s' % (query_type,)) # Return var qaid2_chipmatch = {}",
"len(score_method) - 1: score_method = score_method[:-1] # Choose the appropriate scoring mechanism if",
"0, 0 mark_, end_ = log_prog('Assign NN: ', len(qaids)) for count, qaid in",
"tuple SCALARS * dx - the index into the database of features *",
"# progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a",
"(nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2) Nearest Neighbor weights #============================ def",
"qfx2_aid != qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt",
"qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered",
"qfx2_XXX - prefix mapping query chip feature index to TUPLES: * nns -",
"= qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn",
"float64_t ctypedef np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t",
"a nearest neighbor tuple (indexes, dists). indexes and dist have the shape (nDesc",
"qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" # Output qaid2_nns = {} # Internal statistics",
"np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches",
"np.unique(qreq.data_index.dx2_aid) # FIXME: Highly inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris =",
"# qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg):",
"= hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow",
"Associate query annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record",
"qreq_): # qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids()",
"matching yourself \"\"\" qaid2_nnfilt = {} K = qreq.cfg.nn_cfg.K for count, qaid in",
"* np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE",
"does check that you are not matching yourself \"\"\" qaid2_nnfilt = {} K",
"= zip(*valid_lists) # Vsmany - Append query feature matches to database aids if",
"fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches +=",
"fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff +=",
"# Associate query annotation with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) #",
"QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg = ('QUERY ERROR",
"0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Check that you",
"2 + (y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for",
"qfx2_score, qfx2_valid @profile def filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs",
"== qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape #",
"qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th qaid2_qres[qaid] = qres # Retain original",
"= {} # Internal statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_",
"into one vector will reduce # the amount of appends. match_iter = zip(*valid_lists)",
"+= len(fm) if sv_tup is None: print_('o') # sv failure else: # Return",
"func # Call a tighter (hopefully cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func,",
"def _spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification:",
"qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool)",
"a (qfx2_dx, qfx2_dist) tuple * nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS *",
"NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf] *",
"if NOT_QUIET: #print(inliers) print_('.') # verified something # Rebuild the feature match /",
"xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None: print_('o')",
"qaid2_nnfilt #============================ # 4) Conversion from featurematches to chipmatches qfx2 -> aid2 #============================",
"# Mark progress (qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts =",
"== 'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches %s' % (query_type,)) #",
"six.itervalues(aid2_fm)] # print('nFeats_in_matches_stats = ' + # utool.dict_str(utool.mystats(nFeats_in_matches))) # Vsone - Append database",
"slow aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm)",
"= qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial",
"# qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException, self).__init__(msg) def NoDescriptorsException(ibs, qaid): msg",
"feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if",
"np.uint8_t uint8_t ctypedef np.uint8_t desc_t ctypedef ktool.KPTS_T kpts_t ctypedef ktool.DESC_T desc_t cdef int",
"* (True - qfx2_notsamechip)).sum() print('[mf] * %d assignments are invalid by self' %",
"= sv_cfg.use_chip_extent min_nInliers = sv_cfg.min_nInliers qaid2_chipmatchSV = {} nFeatSVTotal = 0 nFeatMatchSV =",
"nntup = (indexes, dists) (qfx2_dx, qfx2_dist) = nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query",
"np.tau = 2 * np.pi # tauday.com NOT_QUIET = utool.NOT_QUIET and not utool.get_flag('--quiet-query')",
"list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2 +",
"nn_cfg.get_cfgstr() print('[mf] Step 1) Assign nearest neighbors: ' + cfgstr_) num_neighbors = K",
"{} failed_qaids = [] for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr)",
"dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None: print_('o') # sv failure",
"being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign * qfx2_weights <=",
"@profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest neighbors this does",
"a corresponding feature * fs - a score of a corresponding feature *",
"= np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the filter weightings to determine feature validity and",
"if NOT_QUIET: print('[mf] Step 3) Filter neighbors: ') if filt_cfg.gravity_weighting: # We dont",
"qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr())",
"with its nearest descriptors qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of query",
"= min(len(topx2_aid), nShortlist) # Precompute output container if dbginfo: aid2_svtup = {} #",
"qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into an interator",
"coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else:",
"Chipmatch: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # Mark progress (qfx2_dx,",
"Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts) # Get the orientation distance qfx2_oridist = ltool.rowwise_oridist(qfx2_nnori,",
"nTotalDesc np.ndarray[desc_t, ndim=2] qfx2_desc np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx",
"thershold are applied to the matches. Essientally nearest neighbors are converted into weighted",
"[] for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4",
"Input: ibs - an IBEIS Controller qaids - query annotation-ids qreq - a",
"if NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg) count += 1 #",
"np.array(fk, fk_dtype) for aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure",
"np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ !=",
"if NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches' % (nFeatMatchSVAff, nFeatSVTotal)) print('[mf]",
"== len(score_method) - 1: score_method = score_method[:-1] # Choose the appropriate scoring mechanism",
"and weights mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in",
"= np.empty((0, num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist)",
"elif score_method.startswith('coverage'): # Method num is at the end of coverage method =",
"# sv failure else: # Return the inliers to the homography homog_inliers, H,",
"qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index]",
"qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result structures for each query. qaid2_qres",
"# spatially verify the top __NUM_RERANK__ results for topx in range(nRerank): aid =",
"filt2_meta = {} for nnfilter in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter]",
"to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return qaid2_nns #============================ # 2)",
"nid' % nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments",
"print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 * np.pi",
"1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips with nearest neighbors",
"qreq.cfg.sv_cfg print('[mf] Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist",
"a corresponding feature REALIZATIONS: qaid2_nns - maping from query chip index to nns",
"aid2_fk) qaid2_chipmatch[qaid] = chipmatch #if not QUIET: # nFeats_in_matches = [len(fm) for fm",
"assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on config and weights mark_,",
"are converted into weighted assignments \"\"\" # Config K = qreq.cfg.nn_cfg.K query_type =",
"2 return dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use",
"score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a query result structure qres =",
"Step 5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist",
"qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) #",
"from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" # TODO: Remove ibs control",
"nName_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamename) #printDBG('[mf] * Marking %d assignments as invalid'",
"from vtool import spatial_verification as sver # Hotspotter from ibeis.model.hots import hots_query_result from",
"score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk) = chipmatch # HACK: Im",
"descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid) ex = QueryException(msg) return ex",
"filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool) # Apply the",
"fs, and fk into one vector will reduce # the amount of appends.",
"qaid) ex = QueryException(msg) return ex #============================ # 1) Nearest Neighbors #============================ @profile",
"aid might help the speed of this # code. Also, consolidating fm, fs,",
"the assigned nearest features qreq - QueryRequest object Output: qaid2_chipmatch - dict of",
"not None and thresh != 'None': thresh = float(thresh) # corrects for thresh",
"shape (nDesc x K) where nDesc is the number of descriptors in the",
"valid flag for each feature match qfx2_score, qfx2_valid = _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg)",
"len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips with",
"Scoring Mechanism #============================ @profile def score_chipmatch(ibs, qaid, chipmatch, score_method, qreq=None): (aid2_fm, aid2_fs, aid2_fk)",
"= float(thresh) # corrects for thresh being strings sometimes if isinstance(thresh, (int, float)):",
"None: print_('o') # sv failure else: # Return the inliers to the homography",
"fs_dtype) for aid, fs in six.iteritems(aid2_fs) if len(fs) > minMatches} aid2_fk_ = {aid:",
"5) Spatial verification: ' + sv_cfg.get_cfgstr()) prescore_method = sv_cfg.prescore_method nShortlist = sv_cfg.nShortlist xy_thresh",
"verified %d/%d feat matches' % (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else:",
"__NUM_RERANK__ results for topx in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd",
"qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() # qdesc_list",
"print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns,",
"qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if",
"qreq.cfg.filt_cfg cant_match_sameimg = not filt_cfg.can_match_sameimg cant_match_samename = not filt_cfg.can_match_samename K = qreq.cfg.nn_cfg.K if",
"assert np.all(qfx2_dx_ == qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_",
"ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid != qnid ####DBG if VERBOSE: nName_all_invalid = ((True -",
"aid2_weights in six.iteritems(filt2_weights): qfx2_weights = aid2_weights[qaid] sign, thresh, weight = filt_cfg.get_stw(filt) # stw",
"qaid2_qres = {} failed_qaids = [] for qaid in qaids: try: qres =",
"= partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #================= #def compare(qreq, qreq_): # qaid =",
"chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs",
"= qfx2_dx[:, 0:K] # Get a numeric score score and valid flag for",
"qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq):",
"- 1: score_method = score_method[:-1] # Choose the appropriate scoring mechanism if score_method",
"K = qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx",
"hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE # FIXME: This is slow aid2_fm_ = {aid: np.array(fm,",
"\"\"\" Helper worker function for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks",
"def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm = aid2_fm[aid] x_m, y_m",
"of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm =",
"aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input: qaid2_nns - dict",
"return qaid2_nns def _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks): \"\"\" Helper worker function for",
"= ibs.get_annot_gids(qaid) qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid = ((True",
"qfx2_fs, qfx2_k,)] # TODO: Sorting the valid lists by aid might help the",
"log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx,",
"for qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the",
"and dist have the shape (nDesc x K) where nDesc is the number",
"# Remove Impossible Votes: # dont vote for yourself or another chip in",
"assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx ==",
"aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__ results for",
"= nn_func(qfx2_desc, num_neighbors, checks=checks) # Associate query annotation with its nearest descriptors qaid2_nns[qaid]",
"qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid !=",
"by aid might help the speed of this # code. Also, consolidating fm,",
"six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape for aid, fm in six.iteritems(aid2_fm_):",
"remove if there is a speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() #",
"qreq - QueryRequest object Output: qaid2_chipmatch - dict of ( Notes: The prefix",
"utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t",
"aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk =",
"valid feature matches into an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx,",
"def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk = defaultdict(list) return aid2_fm,",
"= chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches' %",
"aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method == 'borda': aid2_score, nid2_score",
"%s: qaid=%r has no descriptors!' + 'Please delete it.') % (ibs.get_dbname(), qaid) ex",
"minMatches = 2 # TODO: paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE",
"from __future__ import absolute_import, division, print_function # Python from six.moves import zip, range",
"ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before doing the homography",
"= vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score =",
"!= qnid ####DBG if VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid",
"REALIZATIONS: qaid2_nns - maping from query chip index to nns { * qfx2_dx",
"% time of this function cfgstr = qreq.get_cfgstr2() # hack of a fix",
"aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring method:'",
"neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] =",
"vr2.score_chipmatch_pos(ibs, qaid, chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs,",
"query feature indexes to database feature indexes * qfx2_dist - ranked list of",
"nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call a tighter (hopefully",
"aid2_fm, aid2_fs, aid2_fk = new_fmfsfk() # Iterate over chips with nearest neighbors mark_,",
"filter_neighbors(ibs, qaid2_nns, filt2_weights, qreq): qaid2_nnfilt = {} # Configs filt_cfg = qreq.cfg.filt_cfg cant_match_sameimg",
"# Ensure shape for aid, fm in six.iteritems(aid2_fm_): fm.shape = (fm.size // 2,",
"= (qfx2_dx, qfx2_dist) # record number of query and result desc nTotalNN +=",
"nFeatMatches = 0 #Vsone if is_vsone: assert len(qreq.qaids) == 1 aid2_fm, aid2_fs, aid2_fk",
"topx2_aid, topx2_kpts, nRerank, use_chip_extent): \"\"\" helper for spatial verification, computes the squared diagonal",
"stw = sign, thresh, weight if thresh is not None and thresh !=",
"(can remove if there is a speed issue) def print_(msg, count=0): \"\"\" temp",
"_precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__ results",
"# assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx) # qfx2_dx.shape",
"= 2 # specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers",
"method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load the result structures",
"aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch,",
"_weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list =",
"dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank,",
"functools import partial #profile = utool.profile print, print_, printDBG, rrr, profile = utool.inject(__name__,",
"qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup = (indexes, dists)",
"checks): \"\"\" Helper worker function for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors,",
"2 # specialized progress func log_prog = partial(utool.log_progress, startafter=START_AFTER) #================= # Helpers #=================",
"nFeatSVTotal += len(fm) if sv_tup is None: print_('o') # sv failure else: #",
"for tx in range(nRerank)] else: # Use extent of matching keypoints def kpts_dlen_sqrd(tx):",
"None: print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch, {}) if dbginfo else",
"in the annotation, and K is the number of approximate nearest neighbors. cdef:",
"# the amount of appends. match_iter = zip(*valid_lists) # Vsmany - Append query",
"= qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:, 0:K]",
"inefficient kpts_list = ibs.get_annot_kpts(aid_list) dx2_kpts = np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) ==",
"nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq,",
"qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric score score and valid flag",
"- Append database feature matches to query aids else: for qfx, aid, fx,",
"use_chip_extent: topx2_chipsize = list(ibs.get_annot_chipsizes(topx2_aid)) def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw",
"= qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K] # Get a numeric score score and",
"statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_ = log_prog('Assign NN: ',",
"* qaid2_norm_weight - mapping from qaid to (qfx2_normweight, qfx2_selnorm) = qaid2_nnfilt[qaid] \"\"\" #",
"dists). indexes and dist have the shape (nDesc x K) where nDesc is",
"cdef: list qaids, qdesc_list long num_neighbors, checks dict qaid2_nns long nTotalNN, nTotalDesc np.ndarray[desc_t,",
"fm.shape = (fm.size // 2, 2) chipmatch = (aid2_fm_, aid2_fs_, aid2_fk_) return chipmatch",
"six.moves import zip, range import six from collections import defaultdict import sys #",
"mapping where keys are query-annotation-id vsmany/vsone counts here. also this is where the",
"cythonized) nearest neighbor function qaid2_nns = _nearest_neighbors(nn_func, qaids, qdesc_list, num_neighbors, checks) return qaid2_nns",
"Apply [nnfilter] weight to each nearest neighbor # TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms",
"= defaultdict(list) return aid2_fm, aid2_fs, aid2_fk @profile def build_chipmatches(qaid2_nns, qaid2_nnfilt, qreq): \"\"\" Input:",
"# NEEDS FIX TAKES 21.9 % time of this function cfgstr = qreq.get_cfgstr2()",
"def chip_dlen_sqrd(tx): (chipw, chiph) = topx2_chipsize[tx] dlen_sqrd = chipw ** 2 + chiph",
"qaid2_nns, qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if",
"1, far are 0) qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau # Apply",
"qfx2_notsamechip = qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid",
"are invalid by gid' % nImg_all_invalid) print('[mf] * %d are newly invalided by",
"qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score = aid2_score (qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta",
"keys are query-annotation-id vsmany/vsone counts here. also this is where the filter weights",
"nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum() print('[mf]",
"the same image cant_match_self = not cant_match_sameimg if cant_match_self: ####DBG qfx2_notsamechip = qfx2_aid",
"* nnfilt - a (qfx2_fs, qfx2_valid) tuple SCALARS * dx - the index",
"qreq \"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K Knorm",
"dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue # Find Neareset Neighbors nntup = (indexes,",
"Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on",
"(y_m.max() - y_m.min()) ** 2 return dlensqrd topx2_dlen_sqrd = [kpts_dlen_sqrd(tx) for tx in",
"# Filter matches based on config and weights mark_, end_ = log_prog('Filter NN:",
"neighbor tuple (indexes, dists). indexes and dist have the shape (nDesc x K)",
"the end of coverage method = int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch,",
"# Return the inliers to the homography homog_inliers, H, aff_inliers, Aff = sv_tup",
"the distance to a corresponding feature * fs - a score of a",
"Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not",
"for thresh being strings sometimes if isinstance(thresh, (int, float)): qfx2_passed = sign *",
"qfx2_gvweight = (np.tau - qfx2_oridist) / np.tau # Apply gravity vector weight to",
"if NOT_QUIET: print('[mf] * made %d feat matches' % nFeatMatches) return qaid2_chipmatch #============================",
"mark_, end_ = log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count)",
"qaid): msg = ('QUERY ERROR IN %s: qaid=%r has no descriptors!' + 'Please",
"fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk) nFeatMatches += 1 chipmatch = _fix_fmfsfk(aid2_fm,",
"== qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] #",
"(K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into",
"in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx = qfx2_dx[:, 0:K]",
"= chipmatch #if not QUIET: # nFeats_in_matches = [len(fm) for fm in six.itervalues(aid2_fm)]",
"len(qfx2_dx) # Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx",
"or sv_cfg.xy_thresh is None: print('[mf] Step 5) Spatial verification: off') return (qaid2_chipmatch, {})",
"ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if sv_tup is None: print_('o') # sv",
"float)): qfx2_passed = sign * qfx2_weights <= sign * thresh qfx2_valid = np.logical_and(qfx2_valid,",
"extent of matching keypoints def kpts_dlen_sqrd(tx): kpts2 = topx2_kpts[tx] aid = topx2_aid[tx] fm",
"__future__ import absolute_import, division, print_function # Python from six.moves import zip, range import",
"like k+1th qaid2_qres[qaid] = qres # Retain original score method return qaid2_qres @profile",
"= 0, 0 mark_, end_ = log_prog('Assign NN: ', len(qaids)) for count, qaid",
"not even sure if the 'w' suffix is correctly handled anymore if score_method.find('w')",
"= coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring method:' +",
"num_neighbors, checks): \"\"\" Helper worker function for nearest_neighbors cdef: list qaids, qdesc_list long",
"nn_cfg.K Knorm = nn_cfg.Knorm checks = nn_cfg.checks if NOT_QUIET: cfgstr_ = nn_cfg.get_cfgstr() print('[mf]",
"prescore_method, qreq) #print('Prescore: %r' % (aid2_prescore,)) (aid2_fm, aid2_fs, aid2_fk) = chipmatch topx2_aid =",
"@profile def _weight_neighbors(ibs, qaid2_nns, qreq): nnfilter_list = qreq.cfg.filt_cfg.get_active_filters() filt2_weights = {} filt2_meta =",
"qfx2_notsameimg = qfx2_gid != qgid ####DBG if VERBOSE: nImg_all_invalid = ((True - qfx2_notsameimg)).sum()",
"to access keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid) # FIXME: Highly",
"not utool.get_flag('--quiet-query') VERBOSE = utool.VERBOSE or utool.get_flag('--verbose-query') #================= # Cython Metadata #================= \"\"\"",
"speed issue) def print_(msg, count=0): \"\"\" temp print_. Using count in this way",
"enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] # Check that we can query",
"aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk) nFeatMatches += 1 #Vsone if is_vsone: chipmatch = _fix_fmfsfk(aid2_fm, aid2_fs, aid2_fk)",
"aid, fk in six.iteritems(aid2_fk) if len(fk) > minMatches} # Ensure shape for aid,",
"features (only indexes are used here) qaid2_nnfilt - dict of (featmatch_scores, featmatch_mask) where",
"qreq): if NOT_QUIET: print('[mf] Step 6) Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr()",
"np.vstack(kpts_list) dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on",
"# 3) Neighbor scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg):",
"np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm) > minMatches} aid2_fs_ =",
"invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile",
"desc from %d chips to %r nearest neighbors' % (nTotalDesc, len(qaids), nTotalNN)) return",
"'w' suffix is correctly handled anymore if score_method.find('w') == len(score_method) - 1: score_method",
"= qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) #",
"- qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments",
"in nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest neighbor",
"== qfx2_dx) # assert np.all(qfx2_dist_ == qfx2_dist) # index = np.where(qfx2_dx_ != qfx2_dx)",
"suffix is correctly handled anymore if score_method.find('w') == len(score_method) - 1: score_method =",
"'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid,",
"# Check that you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip =",
"((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns,",
"return qaid2_chipmatch #============================ # 5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False):",
"print('[mf] * assigned %d desc from %d chips to %r nearest neighbors' %",
"np.logical_and(qfx2_valid, qfx2_notsameimg) if cant_match_samename: qfx2_nid = ibs.get_annot_nids(qfx2_aid) qnid = ibs.get_annot_nids(qaid) qfx2_notsamename = qfx2_nid",
"{} # Internal statistics reporting nTotalNN, nTotalDesc = 0, 0 mark_, end_ =",
"list of failed qaids cdef: object qreq list qaids dict qaid2_qres list failed_qaids",
"range(nRerank)] return topx2_dlen_sqrd #============================ # 6) QueryResult Format #============================ @profile def chipmatch_to_resdict(ibs, qaid2_chipmatch,",
"# qaid = 1 # qvecs_list = qreq_.get_internal_qvecs() # qaids = qreq.get_internal_qaids() #",
"mapping query chip index to qfx2_XXX - prefix mapping query chip feature index",
"if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs, qaid2_nns, qreq) else: return {} @profile def _weight_neighbors(ibs, qaid2_nns,",
"VERBOSE: nName_all_invalid = ((True - qfx2_notsamename)).sum() nName_new_invalid = (qfx2_valid * (True - qfx2_notsamename)).sum()",
"0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {} # dbg info (can",
"= qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the result structures for each query.",
"match_iter = zip(*valid_lists) # Vsmany - Append query feature matches to database aids",
"5) Spatial Verification #============================ def spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if",
"score_method == 'csum': aid2_score = vr2.score_chipmatch_csum(chipmatch) elif score_method == 'pl': aid2_score, nid2_score =",
"for qaid in qaids: try: qres = hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 %",
"= qreq.cfg.nn_cfg.K query_type = qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf]",
"sizes before doing the homography topx2_dlen_sqrd = _precompute_topx2_dlen_sqrd(ibs, aid2_fm, topx2_aid, topx2_kpts, nRerank, use_chip_extent)",
"= {} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo:",
"import numpy as np from vtool import keypoint as ktool from vtool import",
"spatial_verification(ibs, qaid2_chipmatch, qreq, dbginfo=False): sv_cfg = qreq.cfg.sv_cfg if not sv_cfg.sv_on or sv_cfg.xy_thresh is",
"chipmatch, qreq, method=method) else: raise Exception('[mf] unknown scoring method:' + score_method) return aid2_score",
"(qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build feature matches qfx2_nndx =",
"desc nTotalNN += qfx2_dx.size nTotalDesc += len(qfx2_desc) end_() if NOT_QUIET: print('[mf] * assigned",
"Output: qaid2_chipmatch - dict of ( Notes: The prefix qaid2_ denotes a mapping",
"qreq.data_index.dx2_fx) # qfx2_dx_, qfx2_dist_ = qaid2_nns_[qaid] # qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert",
"qaid2_nns object ibs object qreq \"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg",
"# qfx2_dx, qfx2_dist = qaid2_nns[qaid] # assert id(qaid2_nns) != id(qaid2_nns_) # assert np.all(qfx2_dx_",
"= log_prog('Filter NN: ', len(qaid2_nns)) for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress",
"nShortlist) # Precompute output container if dbginfo: aid2_svtup = {} # dbg info",
"- ranked list of query feature indexes to database feature indexes * qfx2_dist",
"(qfx2_score, qfx2_valid) return qaid2_nnfilt #============================ # 4) Conversion from featurematches to chipmatches qfx2",
"qaid2_chipmatch[qaid] = chipmatch end_() if NOT_QUIET: print('[mf] * made %d feat matches' %",
"NOT_QUIET: print('[mf] * made %d feat matches' % nFeatMatches) return qaid2_chipmatch #============================ #",
"% ((True - qfx2_valid).sum())) if filt_cfg.gravity_weighting: qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) #",
"each query. returns a list of failed qaids cdef: object qreq list qaids",
"Try and load the result structures for each query. returns a list of",
"= qreq.cfg.nn_cfg.K for count, qaid in enumerate(six.iterkeys(qaid2_nns)): (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx =",
"the top __NUM_RERANK__ results for topx in range(nRerank): aid = topx2_aid[topx] fm =",
"print_('o') # sv failure else: # Return the inliers to the homography homog_inliers,",
"the homography homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] = sv_tup",
"= aid2_fk[aid] sv_tup = sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal",
"# Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype = hots_query_result.FK_DTYPE",
"def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape, dtype=hots_query_result.FS_DTYPE) qfx2_valid = np.ones(qfx2_nndx.shape, dtype=np.bool)",
"with nearest neighbors mark_, end_ = log_prog('Build Chipmatch: ', len(qaid2_nns)) for count, qaid",
"speed issue) aid2_fm_V, aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid)",
"vtool import linalg as ltool from vtool import spatial_verification as sver # Hotspotter",
"keypoint as ktool from vtool import linalg as ltool from vtool import spatial_verification",
"spatial_verification as sver # Hotspotter from ibeis.model.hots import hots_query_result from ibeis.model.hots import exceptions",
"object qreq \"\"\" # Neareset neighbor configuration nn_cfg = qreq.cfg.nn_cfg K = nn_cfg.K",
"# Normalize into a weight (close orientations are 1, far are 0) qfx2_gvweight",
"assigned nearest features (only indexes are used here) qaid2_nnfilt - dict of (featmatch_scores,",
"indexes * qfx2_dist - ranked list of query feature indexes to database feature",
"print, print_, printDBG, rrr, profile = utool.inject(__name__, '[mf]', DEBUG=False) np.tau = 2 *",
":] aid2_fs_V[aid] = fs[homog_inliers] aid2_fk_V[aid] = fk[homog_inliers] nFeatMatchSV += len(homog_inliers) nFeatMatchSVAff += len(aff_inliers)",
"Retain original score method return qaid2_qres @profile def try_load_resdict(qreq): \"\"\" Try and load",
"from ibeis.model.hots import voting_rules2 as vr2 import utool from functools import partial #profile",
"= 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups = {} # dbg info",
"into an interator valid_lists = [qfx2[qfx2_valid] for qfx2 in (qfx2_qfx, qfx2_aid, qfx2_fx, qfx2_fs,",
"hack \"\"\" if NOT_QUIET: if count % 25 == 0: sys.stdout.write(msg) count +=",
"Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a",
"aid2_fs_, aid2_fk_) return chipmatch def new_fmfsfk(): aid2_fm = defaultdict(list) aid2_fs = defaultdict(list) aid2_fk",
"fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs) aid2_fk[aid].append(fk)",
"chip2 to chip1 (the old way was 1 to 2) for qaid in",
"# dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like",
"= qfx2_aid != qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid =",
"!= qaid if VERBOSE: nChip_all_invalid = ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid *",
"score_method, qreq) # Create a query result structure qres = hots_query_result.QueryResult(qaid, cfgstr) qres.aid2_score",
"result structures for each query. returns a list of failed qaids cdef: object",
"feature indexes to database feature indexes * qfx2_dist - ranked list of query",
"scoring (Voting Profiles) #========================== @profile def _apply_filter_scores(qaid, qfx2_nndx, filt2_weights, filt_cfg): qfx2_score = np.ones(qfx2_nndx.shape,",
"(qres.aid2_fm, qres.aid2_fs, qres.aid2_fk) = chipmatch qres.filt2_meta = {} # dbgstats for filt, qaid2_meta",
"chipmatchSV print_('\\n') if NOT_QUIET: print('[mf] * Affine verified %d/%d feat matches' % (nFeatMatchSVAff,",
"== 0: sys.stdout.write(msg) count += 1 # Find a transform from chip2 to",
"% (nFeatMatchSV, nFeatSVTotal)) if dbginfo: return qaid2_chipmatchSV, qaid2_svtups else: return qaid2_chipmatchSV def _precompute_topx2_dlen_sqrd(ibs,",
"Build feature matches qfx2_nndx = qfx2_dx[:, 0:K] qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx]",
"query's chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs, qaid,",
"qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) # record number of query and result desc nTotalNN",
"control as much as possible or abstract it away from __future__ import absolute_import,",
"qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_() return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing",
"= hots_query_result.QueryResult(qaid, cfgstr) qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError:",
"chipmatch, qreq, 'borda') elif score_method == 'topk': aid2_score, nid2_score = vr2.score_chipmatch_pos(ibs, qaid, chipmatch,",
"qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_fx = qreq.data_index.dx2_fx[qfx2_nndx] qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T qfx2_k =",
"qaid in enumerate(qaids): mark_(count) # progress qfx2_desc = qdesc_list[count] # Check that we",
"- a score of a corresponding feature * valid - a valid bit",
"for topx in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid] dlen_sqrd = topx2_dlen_sqrd[topx]",
"= int(score_method.replace('coverage', '0')) aid2_score = coverage_image.score_chipmatch_coverage(ibs, qaid, chipmatch, qreq, method=method) else: raise Exception('[mf]",
"= ((True - qfx2_notsamechip)).sum() nChip_new_invalid = (qfx2_valid * (True - qfx2_notsamechip)).sum() print('[mf] *",
"top __NUM_RERANK__ results for topx in range(nRerank): aid = topx2_aid[topx] fm = aid2_fm[aid]",
"xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent = sv_cfg.use_chip_extent min_nInliers",
"nns { * qfx2_dx - ranked list of query feature indexes to database",
"sv_tup if dbginfo: aid2_svtup[aid] = sv_tup aid2_fm_V[aid] = fm[homog_inliers, :] aid2_fs_V[aid] = fs[homog_inliers]",
"qaids = qreq.get_internal_qaids() # qdesc_list = qreq_.get_annot_desc(qaids) # Get descriptors # assert np.all(qvecs_list[0]",
"of query feature indexes to database feature indexes * qfx2_dist - ranked list",
"# Cython Metadata #================= \"\"\" ctypedef np.float32_t float32_t ctypedef np.float64_t float64_t ctypedef np.uint8_t",
"= sv_cfg.nShortlist xy_thresh = sv_cfg.xy_thresh scale_thresh = sv_cfg.scale_thresh ori_thresh = sv_cfg.ori_thresh use_chip_extent =",
"qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx) # qfx2_dx_,",
"nearest neighbors this does check that you are not matching yourself \"\"\" qaid2_nnfilt",
"that you are not matching yourself qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] qfx2_notsamechip = qfx2_aid !=",
"fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference aid2_fs[qaid].append(fs) aid2_fk[qaid].append(fk)",
"SCALARS * dx - the index into the database of features * dist",
"qreq): if NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on:",
"NOT_QUIET: print('[mf] Step 2) Weight neighbors: ' + qreq.cfg.filt_cfg.get_cfgstr()) if qreq.cfg.filt_cfg.filt_on: return _weight_neighbors(ibs,",
"%d assignments are invalid by gid' % nImg_all_invalid) print('[mf] * %d are newly",
"np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) # assert np.all(qreq_.indexer.dx2_fx == qreq.data_index.dx2_fx)",
"number of nearest neighbors qdesc_list = ibs.get_annot_desc(qaids) # Get descriptors nn_func = qreq.data_index.flann.nn_index",
"an easy way to access keypoints from nearest neighbors yet aid_list = np.unique(qreq.data_index.dx2_aid)",
"aid2_fs_V, aid2_fk_V = new_fmfsfk() # Query Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid)",
"thresh != 'None': thresh = float(thresh) # corrects for thresh being strings sometimes",
"nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg: qfx2_gid = ibs.get_annot_gids(qfx2_aid) qgid =",
"return qaid2_nnfilt @profile def identity_filter(qaid2_nns, qreq): \"\"\" testing function returns unfiltered nearest neighbors",
"as much as possible or abstract it away from __future__ import absolute_import, division,",
"sign * thresh qfx2_valid = np.logical_and(qfx2_valid, qfx2_passed) if not weight == 0: qfx2_score",
"topx2_kpts, nRerank, use_chip_extent) # spatially verify the top __NUM_RERANK__ results for topx in",
"qreq.cfg.agg_cfg.query_type is_vsone = query_type == 'vsone' if NOT_QUIET: print('[mf] Step 4) Building chipmatches",
"the matches. Essientally nearest neighbors are converted into weighted assignments \"\"\" # Config",
"= sver.spatial_verification(kpts1, kpts2, fm, xy_thresh, scale_thresh, ori_thresh, dlen_sqrd, min_nInliers) nFeatSVTotal += len(fm) if",
"def try_load_resdict(qreq): \"\"\" Try and load the result structures for each query. returns",
"TODO: paramaterize # Convert to numpy fm_dtype = hots_query_result.FM_DTYPE fs_dtype = hots_query_result.FS_DTYPE fk_dtype",
"hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError: failed_qaids.append(qaid) return qaid2_qres, failed_qaids #============================ # Scoring Mechanism #============================",
"Helper worker function for nearest_neighbors cdef: list qaids, qdesc_list long num_neighbors, checks dict",
"qreq.qaids #cfgstr = qreq.get_cfgstr() # NEEDS FIX TAKES 21.9 % time of this",
"newly invalided by self' % nChip_new_invalid) #### qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) if cant_match_sameimg:",
"qfx2_nnori = dx2_oris[qfx2_nndx] qfx2_kpts = ibs.get_annot_kpts(qaid) # FIXME: Highly inefficient qfx2_oris = ktool.get_oris(qfx2_kpts)",
"to the homography homog_inliers, H, aff_inliers, Aff = sv_tup if dbginfo: aid2_svtup[aid] =",
"aid2_fm_ = {aid: np.array(fm, fm_dtype) for aid, fm in six.iteritems(aid2_fm) if len(fm) >",
"print('[mf] * %d assignments are invalid by gid' % nImg_all_invalid) print('[mf] * %d",
"dlen_sqrd topx2_dlen_sqrd = [chip_dlen_sqrd(tx) for tx in range(nRerank)] else: # Use extent of",
"= score_chipmatch(ibs, qaid, chipmatch, score_method, qreq) # Create a query result structure qres",
"chipmatch chipmatch = qaid2_chipmatch[qaid] # Perform final scoring aid2_score = score_chipmatch(ibs, qaid, chipmatch,",
"score_method == 'pl': aid2_score, nid2_score = vr2.score_chipmatch_PL(ibs, qaid, chipmatch, qreq) elif score_method ==",
"qfx, aid, fx, fs, fk in match_iter: aid2_fm[qaid].append((fx, qfx)) # Note the difference",
"\"\"\" temp print_. Using count in this way is a hack \"\"\" if",
"dx2_oris = ktool.get_oris(dx2_kpts) assert len(dx2_oris) == len(qreq.data_index.dx2_data) # Filter matches based on config",
"Convert chipmatch -> qres') cfgstr = qreq.get_cfgstr() score_method = qreq.cfg.agg_cfg.score_method # Create the",
"== qdesc_list[0]) # assert np.all(qreq_.indexer.dx2_vec == qreq.data_index.dx2_data) # assert np.all(qreq_.indexer.dx2_rowid == qreq.data_index.dx2_aid) #",
"descriptors nn_func = qreq.data_index.flann.nn_index # Approx nearest neighbor func # Call a tighter",
"filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are invalid by",
"nnfilter_list: nn_filter_fn = nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest neighbor #",
"num_neighbors), dtype=np.int32) qfx2_dist = np.empty((0, num_neighbors), dtype=np.float64) qaid2_nns[qaid] = (qfx2_dx, qfx2_dist) continue #",
"- prefix mapping query chip index to qfx2_XXX - prefix mapping query chip",
"ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist np.ndarray[int32_t, ndim=2] qfx2_dx np.ndarray[float64_t, ndim=2] qfx2_dist \"\"\" #",
"* made %d feat matches' % nFeatMatches) return qaid2_chipmatch #============================ # 5) Spatial",
"= ((True - qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] *",
"Keypoints kpts1 = ibs.get_annot_kpts(qaid) topx2_kpts = ibs.get_annot_kpts(topx2_aid) # Check the diaglen sizes before",
"qaids cdef: object qreq list qaids dict qaid2_qres list failed_qaids \"\"\" qaids =",
"(qfx2_dx, _) = qaid2_nns[qaid] (qfx2_fs, qfx2_valid) = qaid2_nnfilt[qaid] nQKpts = len(qfx2_dx) # Build",
"qres.load(qreq.get_qresdir()) # 77.4 % time qaid2_qres[qaid] = qres except hsexcept.HotsCacheMissError: failed_qaids.append(qaid) except hsexcept.HotsNeedsRecomputeError:",
"- qfx2_notsamename)).sum() print('[mf] * %d assignments are invalid by nid' % nName_all_invalid) print('[mf]",
"%d assignments as invalid' % ((True - qfx2_valid).sum())) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) end_()",
"filter weightings to determine feature validity and scores for filt, aid2_weights in six.iteritems(filt2_weights):",
"nn_filters.NN_FILTER_FUNC_DICT[nnfilter] # Apply [nnfilter] weight to each nearest neighbor # TODO FIX THIS!",
"aid, fx, fs, fk in match_iter: aid2_fm[aid].append((qfx, fx)) # Note the difference aid2_fs[aid].append(fs)",
"qfx2_dx.shape == qfx2_dx.shape # qfx2_dx_[index] # qfx2_dx[index] class QueryException(Exception): def __init__(self, msg): super(QueryException,",
"{} nFeatSVTotal = 0 nFeatMatchSV = 0 nFeatMatchSVAff = 0 if dbginfo: qaid2_svtups",
"!= qaid qfx2_valid = np.logical_and(qfx2_valid, qfx2_notsamechip) qaid2_nnfilt[qaid] = (qfx2_score, qfx2_valid) return qaid2_nnfilt #============================",
"much as possible or abstract it away from __future__ import absolute_import, division, print_function",
"qfx2_nndx, filt2_weights, filt_cfg) qfx2_aid = qreq.data_index.dx2_aid[qfx2_nndx] if VERBOSE: print('[mf] * %d assignments are",
"Python from six.moves import zip, range import six from collections import defaultdict import",
"#================= # Helpers #================= #def compare(qreq, qreq_): # qaid = 1 # qvecs_list",
"for count, qaid in enumerate(six.iterkeys(qaid2_nns)): mark_(count) # progress (qfx2_dx, _) = qaid2_nns[qaid] qfx2_nndx",
"nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter] = qaid2_selnorms return filt2_weights, filt2_meta #==========================",
"qfx2_notsameimg)).sum() nImg_new_invalid = (qfx2_valid * (True - qfx2_notsameimg)).sum() print('[mf] * %d assignments are",
"dbgstats for filt, qaid2_meta in six.iteritems(filt2_meta): qres.filt2_meta[filt] = qaid2_meta[qaid] # things like k+1th",
"if len(fm) > minMatches} aid2_fs_ = {aid: np.array(fs, fs_dtype) for aid, fs in",
"TODO FIX THIS! qaid2_norm_weight, qaid2_selnorms = nn_filter_fn(ibs, qaid2_nns, qreq) filt2_weights[nnfilter] = qaid2_norm_weight filt2_meta[nnfilter]"
] |
[
"into sequences of tokens and labels. Returns: tuple: sentences, labels \"\"\" temp_df =",
"of the dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx:",
"Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if train:",
"idx item from the dataset. Returns: tuple: sentences, labels \"\"\" if self.transform is",
"the dataloaders needed for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset,",
"return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed for",
"def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that accepts a sentence as",
"Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform",
"\"\"\" This module contains preprocessing code to prepare data for training and inference.",
"tokenize and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see",
"test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir,",
"from types import SimpleNamespace import pandas as pd import torch import torchtext from",
"tuple of sentence_indices, sentences_labels, else just a list of sentence_indices. Defaults to True.",
"path where the model configuration file is located.', required=True) args = parser.parse_args() main(args)",
"padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else:",
"batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility",
"@staticmethod def _collate_fn(batch: tuple, train: bool = True) -> tuple: \"\"\"Custom collate function",
"= [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return",
"$ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from collections import Counter",
"to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab =",
"label_dict[k] = i i += 1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple,",
"import Counter import os from types import SimpleNamespace import pandas as pd import",
"\"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize the preprocessor and generate vocabulary",
"sentence: list) -> torch.tensor: \"\"\"Transform function that accepts a sentence as a string",
"the transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in New York",
"module contains preprocessing code to prepare data for training and inference. Examples: $",
"sequences of tokens and labels. Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID',",
"all the dataloaders needed for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\"",
"optional): If train=True, expects tuple of sentence_indices, sentences_labels, else just a list of",
"= 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return",
"argparse from collections import Counter import os from types import SimpleNamespace import pandas",
"labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle data",
"str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args):",
"open(config, 'r') as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict =",
"yaml file. \"\"\" with open(config, 'r') as f: config = yaml.safe_load(f) self.config =",
"= os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset =",
"x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if",
"the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict()))",
"preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence))",
"etc.). Defaults to None. \"\"\" self.df = df self.transform = transform self.sentences, self.labels",
"test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset",
"\"\"\"Retrieves the idx item from the dataset, potentially transformed. Args: idx (int): idx",
"else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains",
"== '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the model",
"any arbitrary list of string sentences and return indices that can be fed",
"the preprocessor and generate vocabulary and label dictionary based on the training set.",
"indices = [] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence:",
"item from the dataset. Returns: tuple: sentences, labels \"\"\" if self.transform is None:",
"tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv')",
"self.transform = transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data",
"configs/baseline.yaml \"\"\" import argparse from collections import Counter import os from types import",
"torch.tensor: Label indices. \"\"\" labels = [] for label in label_sequence: labels.append(self.label_dict[label]) return",
"see if there is a way to reuse the CoNLL2003Dataset class + dataloaders",
"Label indices. \"\"\" labels = [] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels)",
"= self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels =",
"a string or tokenized list and returns vocabulary indices. Args: sentence (list): Tokenized",
"string. Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list)",
"function that accepts a sequence of labels and returns label indices. Args: label_sequence",
"isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def",
"labels and returns label indices. Args: label_sequence (list): Sequence of string labels. Returns:",
"indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if there is",
"temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels",
"if self.transform is None: return self.sentences[idx], self.labels[idx] # TODO: probably should wrap this",
"\"\"\" self.df = df self.transform = transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self)",
"'__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the model configuration",
"return self.sentences[idx], self.labels[idx] # TODO: probably should wrap this in a for-loop indices",
"inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from collections",
"training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path =",
"= CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset,",
"sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that",
"\"\"\"Transform function that accepts a sequence of labels and returns label indices. Args:",
"string sentences and return indices that can be fed into the model. Args:",
"# for guaranteed consistency with the way that we're preparing training data preprocessed",
"main(args): # contains vocab and label_dict embedded in the transform function preprocessor =",
"torch.tensor: \"\"\"Transform function that accepts a sequence of labels and returns label indices.",
"1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool = True) ->",
"variable length sequences into padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR just",
"label dictionary. Returns: tuple: vocab, label_dict \"\"\" # load train data to build",
"Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at train and inference time. \"\"\"",
"indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at train and",
"class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\" def __init__(self, df:",
"def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences of tokens and labels. Returns:",
"labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens)",
"-> tuple: \"\"\"Generates all the dataloaders needed for model training. Returns: tuple: train_dataloader,",
"\"\"\"Initializes the dataset and prepares sequences of tokens and labels. Args: df (pd.DataFrame):",
"sentence (str): Sentence string. Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ') def",
"'--config', type=str, help='File path where the model configuration file is located.', required=True) args",
"= self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences of tokens and",
"sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list of string sentences and return",
"can be fed into the model. Args: sentences (list): List of sentences to",
"CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame,",
"dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes",
"+ dataloaders # for guaranteed consistency with the way that we're preparing training",
"sentences_labels OR just sentences_indices (a list). train (bool, optional): If train=True, expects tuple",
"else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed",
"data into sequences of tokens and labels. Returns: tuple: sentences, labels \"\"\" temp_df",
"= torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader,",
"a way to reuse the CoNLL2003Dataset class + dataloaders # for guaranteed consistency",
"the length of the dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences) def",
"def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label dictionary. Returns: tuple: vocab,",
"else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices =",
"needed for model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir,",
"there is a way to reuse the CoNLL2003Dataset class + dataloaders # for",
"sentence (list): Tokenized list or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if",
"torch.tensor: \"\"\"Transform function that accepts a sentence as a string or tokenized list",
"York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(",
"dataloaders needed for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset,",
"or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence =",
"set. Args: config (str): File path to the configuration yaml file. \"\"\" with",
"a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object):",
"sentence_indices, sentences_labels OR just sentences_indices (a list). train (bool, optional): If train=True, expects",
"if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False)",
"sentences (list): List of sentences to tokenize and retrieve indices for. Returns: tuple:",
"the CoNLL2003Dataset class + dataloaders # for guaranteed consistency with the way that",
"val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader",
"item from the dataset, potentially transformed. Args: idx (int): idx item from the",
"label indices. Args: label_sequence (list): Sequence of string labels. Returns: torch.tensor: Label indices.",
"function to tokenize sentences. Args: sentence (str): Sentence string. Returns: list: Tokenized sentence.",
"config (str): File path to the configuration yaml file. \"\"\" with open(config, 'r')",
"tuple: \"\"\"Generate vocabulary object and label dictionary. Returns: tuple: vocab, label_dict \"\"\" #",
"Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized',",
"idx: int) -> tuple: \"\"\"Retrieves the idx item from the dataset, potentially transformed.",
"(sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels",
"transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences",
"in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser =",
"None: return self.sentences[idx], self.labels[idx] # TODO: probably should wrap this in a for-loop",
"Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader =",
"preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): #",
"True) -> tuple: \"\"\"Custom collate function that combines variable length sequences into padded",
"indices. Args: sentence (list): Tokenized list or sentence string. Returns: torch.tensor: Vocabulary indices.",
"# contains vocab and label_dict embedded in the transform function preprocessor = Preprocessor(args.config)",
"sentence = self._tokenize(sentence) indices = [] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices)",
"to prepare data for training and inference. Examples: $ python preprocess.py \\ --config",
"pandas as pd import torch import torchtext from torch.nn.utils.rnn import pad_sequence import yaml",
"\"\"\"Groups data into sequences of tokens and labels. Returns: tuple: sentences, labels \"\"\"",
"__len__(self) -> int: \"\"\"Retrieve the length of the dataset. Returns: int: Dataset length.",
"\"\"\" with open(config, 'r') as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab,",
"Args: df (pd.DataFrame): DF containing training examples. transform (list, optional): List of transforms",
"label_dict embedded in the transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives",
"self.labels[idx] # TODO: probably should wrap this in a for-loop indices = self.transform[0](self.sentences[idx])",
"data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab",
"in a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class",
"dataset. Returns: tuple: sentences, labels \"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx]",
"way to reuse the CoNLL2003Dataset class + dataloaders # for guaranteed consistency with",
"for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset =",
"val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path =",
"function that combines variable length sequences into padded batches. Args: batch (tuple): sentence_indices,",
"transforms (e.g. index lookups, etc.). Defaults to None. \"\"\" self.df = df self.transform",
"preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list of string sentences and",
"'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return",
"for k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and",
"Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {} i = 0 for k",
"label_sequence (list): Sequence of string labels. Returns: torch.tensor: Label indices. \"\"\" labels =",
"(tuple): sentence_indices, sentences_labels OR just sentences_indices (a list). train (bool, optional): If train=True,",
"f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label =",
"Args: idx (int): idx item from the dataset. Returns: tuple: sentences, labels \"\"\"",
"train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens = [len(x) for",
"CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list = None) -> None:",
"{v: k for k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary",
"dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int) ->",
"sentence_indices, sentences_labels, else just a list of sentence_indices. Defaults to True. Returns: tuple:",
"return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at train",
"as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label",
"sentences_labels, else just a list of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded,",
"sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed for model training.",
"df: pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes the dataset and prepares",
"sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens",
"SimpleNamespace import pandas as pd import torch import torchtext from torch.nn.utils.rnn import pad_sequence",
"str) -> list: \"\"\"Utility function to tokenize sentences. Args: sentence (str): Sentence string.",
"sentences and return indices that can be fed into the model. Args: sentences",
"and label_dict embedded in the transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME>",
"= CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self)",
"tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices,",
"create label dictionary label_dict = {} i = 0 for k in train_df['NER_Tag_Normalized'].unique():",
"__init__(self, df: pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes the dataset and",
"CoNLL2003Dataset class + dataloaders # for guaranteed consistency with the way that we're",
"get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed for model training. Returns: tuple:",
"= [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset =",
"path to the configuration yaml file. \"\"\" with open(config, 'r') as f: config",
"list of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True,",
"batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded",
"transform: list = None) -> None: \"\"\"Initializes the dataset and prepares sequences of",
"torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) ->",
"test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed for model training.",
"New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser()",
"\"\"\"Preprocess any arbitrary list of string sentences and return indices that can be",
"for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if there is a",
"val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader =",
"labels. Args: df (pd.DataFrame): DF containing training examples. transform (list, optional): List of",
"import SimpleNamespace import pandas as pd import torch import torchtext from torch.nn.utils.rnn import",
"of sentences to tokenize and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\"",
"should wrap this in a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return",
"(sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch",
"-> list: \"\"\"Utility function to tokenize sentences. Args: sentence (str): Sentence string. Returns:",
"'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels]",
"get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed for model training. Returns: tuple:",
"\\ --config configs/baseline.yaml \"\"\" import argparse from collections import Counter import os from",
"config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v:",
"sequences into padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a",
"just a list of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded",
"padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple:",
"vocabulary indices. Args: sentence (list): Tokenized list or sentence string. Returns: torch.tensor: Vocabulary",
"self.df = df self.transform = transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) ->",
"Tokenized list or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str):",
"File path to the configuration yaml file. \"\"\" with open(config, 'r') as f:",
"Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self)",
"sentences, labels \"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx] # TODO: probably",
"data preparation at train and inference time. \"\"\" def __init__(self, config: str) ->",
"[self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path),",
"and return indices that can be fed into the model. Args: sentences (list):",
"list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def",
"temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int: \"\"\"Retrieve the",
"as a string or tokenized list and returns vocabulary indices. Args: sentence (list):",
"be fed into the model. Args: sentences (list): List of sentences to tokenize",
"= True) -> tuple: \"\"\"Custom collate function that combines variable length sequences into",
"containing training examples. transform (list, optional): List of transforms (e.g. index lookups, etc.).",
"accepts a sequence of labels and returns label indices. Args: label_sequence (list): Sequence",
"= self._create_vocabs() self.idx_to_label = {v: k for k, v in self.label_dict.items()} def _create_vocabs(self)",
"as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences,",
"to contain the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list =",
"\"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices = [] for token in",
"vocabulary and label dictionary based on the training set. Args: config (str): File",
"idx item from the dataset, potentially transformed. Args: idx (int): idx item from",
"help='File path where the model configuration file is located.', required=True) args = parser.parse_args()",
"train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create",
"the way that we're preparing training data preprocessed = [] if isinstance(sentences, str):",
"for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor:",
"data for training and inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\"",
"in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function",
"config: str) -> None: \"\"\"Initialize the preprocessor and generate vocabulary and label dictionary",
"embedded in the transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in",
"examples. transform (list, optional): List of transforms (e.g. index lookups, etc.). Defaults to",
"load train data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create",
"return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts a",
"__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the",
"retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if there",
"(e.g. index lookups, etc.). Defaults to None. \"\"\" self.df = df self.transform =",
"def main(args): # contains vocab and label_dict embedded in the transform function preprocessor",
"return len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx item from",
"sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and",
"transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders",
"parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the model configuration file",
"parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\" def __init__(self,",
"def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list of string sentences",
"to tokenize and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO:",
"of tokens and labels. Args: df (pd.DataFrame): DF containing training examples. transform (list,",
"in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return vocab, label_dict @staticmethod def",
"with open(config, 'r') as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict",
"sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence)",
"the dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int)",
"in the transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in New",
"the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list = None) ->",
"train (bool, optional): If train=True, expects tuple of sentence_indices, sentences_labels, else just a",
"sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function",
"time. \"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize the preprocessor and generate",
"return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function to",
"vocab and label_dict embedded in the transform function preprocessor = Preprocessor(args.config) sample_sentence =",
"torchtext from torch.nn.utils.rnn import pad_sequence import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset):",
"length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx",
"= self._tokenize(sentence) indices = [] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def",
"test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn,",
"the model. Args: sentences (list): List of sentences to tokenize and retrieve indices",
"Returns: tuple: vocab, label_dict \"\"\" # load train data to build the dictionaries",
"\"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist()",
"labels def __len__(self) -> int: \"\"\"Retrieve the length of the dataset. Returns: int:",
"int) -> tuple: \"\"\"Retrieves the idx item from the dataset, potentially transformed. Args:",
"This module contains preprocessing code to prepare data for training and inference. Examples:",
"list: Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor:",
"self._tokenize(sentence) indices = [] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self,",
"str) -> None: \"\"\"Initialize the preprocessor and generate vocabulary and label dictionary based",
"\"\"\"Custom collate function that combines variable length sequences into padded batches. Args: batch",
"torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader =",
"val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize sentences.",
"(list, optional): List of transforms (e.g. index lookups, etc.). Defaults to None. \"\"\"",
"dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) #",
"bool = True) -> tuple: \"\"\"Custom collate function that combines variable length sequences",
"vocab, label_dict \"\"\" # load train data to build the dictionaries train_df =",
"import pandas as pd import torch import torchtext from torch.nn.utils.rnn import pad_sequence import",
"self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label dictionary. Returns: tuple:",
"\"\"\"Initialize the preprocessor and generate vocabulary and label dictionary based on the training",
"= transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into",
"Args: sentence (str): Sentence string. Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ')",
"sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded",
"prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str,",
"the datasets needed for model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path",
"collate function that combines variable length sequences into padded batches. Args: batch (tuple):",
"with the way that we're preparing training data preprocessed = [] if isinstance(sentences,",
"-> int: \"\"\"Retrieve the length of the dataset. Returns: int: Dataset length. \"\"\"",
"= preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File",
"test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates",
"Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if there is a way",
"if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where",
"val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset",
"preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and label_dict embedded in",
"# TODO: see if there is a way to reuse the CoNLL2003Dataset class",
"batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a list). train (bool, optional): If",
"val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return",
"tokenize sentences. Args: sentence (str): Sentence string. Returns: list: Tokenized sentence. \"\"\" return",
"\"\"\" # load train data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv'))",
"val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size,",
"_create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label dictionary. Returns: tuple: vocab, label_dict",
"\"\"\" import argparse from collections import Counter import os from types import SimpleNamespace",
"preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from collections import Counter import os",
"code to prepare data for training and inference. Examples: $ python preprocess.py \\",
"torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader,",
"in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label dictionary. Returns:",
"sample_sentence = '<NAME> lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__",
"string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices",
"Args: sentences (list): List of sentences to tokenize and retrieve indices for. Returns:",
"Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels",
"labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list",
"return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list of",
"Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices = [] for",
"sequence of labels and returns label indices. Args: label_sequence (list): Sequence of string",
"list: \"\"\"Utility function to tokenize sentences. Args: sentence (str): Sentence string. Returns: list:",
"-> tuple: \"\"\"Groups data into sequences of tokens and labels. Returns: tuple: sentences,",
"test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize sentences. Args:",
"_transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that accepts a sentence as a",
"# create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict =",
"train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform",
"Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the",
"for training and inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import",
"create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {}",
"from collections import Counter import os from types import SimpleNamespace import pandas as",
"import pad_sequence import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to",
"labels \"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx] # TODO: probably should",
"[] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) ->",
"(sentences_padded, sentence_lens) \"\"\" # TODO: see if there is a way to reuse",
"import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the",
"dataset to contain the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list",
"Returns: int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int) -> tuple:",
"to the configuration yaml file. \"\"\" with open(config, 'r') as f: config =",
"if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens = [len(x)",
"pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens),",
"os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path),",
"transform function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in New York City.'",
"os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence,",
"sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels =",
"of sentence_indices, sentences_labels, else just a list of sentence_indices. Defaults to True. Returns:",
"transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple:",
"from the dataset, potentially transformed. Args: idx (int): idx item from the dataset.",
"return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates",
"expects tuple of sentence_indices, sentences_labels, else just a list of sentence_indices. Defaults to",
"batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset,",
"or tokenized list and returns vocabulary indices. Args: sentence (list): Tokenized list or",
"prepare data for training and inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml",
"from torch.nn.utils.rnn import pad_sequence import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom",
"import os from types import SimpleNamespace import pandas as pd import torch import",
"list and returns vocabulary indices. Args: sentence (list): Tokenized list or sentence string.",
"training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader",
"datasets needed for model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path =",
"self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle",
"tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list))",
"k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label",
"guaranteed consistency with the way that we're preparing training data preprocessed = []",
"Defaults to None. \"\"\" self.df = df self.transform = transform self.sentences, self.labels =",
"'<NAME> lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__':",
"k for k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object",
"val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed for model",
"(sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all",
"this in a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels",
"of string sentences and return indices that can be fed into the model.",
"\"\"\" def __init__(self, df: pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes the",
"and returns vocabulary indices. Args: sentence (list): Tokenized list or sentence string. Returns:",
"label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess",
"= pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label",
"collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size,",
"= torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader",
"sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences",
"as pd import torch import torchtext from torch.nn.utils.rnn import pad_sequence import yaml from",
"i i += 1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool",
"self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for k,",
"dataset, potentially transformed. Args: idx (int): idx item from the dataset. Returns: tuple:",
"collections import Counter import os from types import SimpleNamespace import pandas as pd",
"__getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx item from the dataset, potentially",
"= argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the model configuration file is",
"contains preprocessing code to prepare data for training and inference. Examples: $ python",
"the configuration yaml file. \"\"\" with open(config, 'r') as f: config = yaml.safe_load(f)",
"return indices that can be fed into the model. Args: sentences (list): List",
"preparation at train and inference time. \"\"\" def __init__(self, config: str) -> None:",
"str): sentence = self._tokenize(sentence) indices = [] for token in sentence: indices.append(self.vocab[token]) return",
"of transforms (e.g. index lookups, etc.). Defaults to None. \"\"\" self.df = df",
"List of transforms (e.g. index lookups, etc.). Defaults to None. \"\"\" self.df =",
"labels. Returns: torch.tensor: Label indices. \"\"\" labels = [] for label in label_sequence:",
"test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list:",
"dataset and prepares sequences of tokens and labels. Args: df (pd.DataFrame): DF containing",
"training examples. transform (list, optional): List of transforms (e.g. index lookups, etc.). Defaults",
"a sequence of labels and returns label indices. Args: label_sequence (list): Sequence of",
"tuple, train: bool = True) -> tuple: \"\"\"Custom collate function that combines variable",
"list = None) -> None: \"\"\"Initializes the dataset and prepares sequences of tokens",
"to reuse the CoNLL2003Dataset class + dataloaders # for guaranteed consistency with the",
"for guaranteed consistency with the way that we're preparing training data preprocessed =",
"file. \"\"\" with open(config, 'r') as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config)",
"temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int: \"\"\"Retrieve the length of the",
"sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded,",
"(list): Tokenized list or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence,",
"and labels. Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token',",
"if train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else:",
"object and label dictionary. Returns: tuple: vocab, label_dict \"\"\" # load train data",
"that combines variable length sequences into padded batches. Args: batch (tuple): sentence_indices, sentences_labels",
"labels = [] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences:",
"-> tuple: \"\"\"Custom collate function that combines variable length sequences into padded batches.",
"vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {} i",
"(bool, optional): If train=True, expects tuple of sentence_indices, sentences_labels, else just a list",
"-> tuple: \"\"\"Preprocess any arbitrary list of string sentences and return indices that",
"_prepare_data(self) -> tuple: \"\"\"Groups data into sequences of tokens and labels. Returns: tuple:",
"= torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str)",
"train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return",
"(sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed for model",
"sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and label_dict embedded",
"\"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx] # TODO: probably should wrap",
"and inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from",
"transform (list, optional): List of transforms (e.g. index lookups, etc.). Defaults to None.",
"labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch)",
"Args: label_sequence (list): Sequence of string labels. Returns: torch.tensor: Label indices. \"\"\" labels",
"_collate_fn(batch: tuple, train: bool = True) -> tuple: \"\"\"Custom collate function that combines",
"sentence_lens) \"\"\" # TODO: see if there is a way to reuse the",
"dictionary based on the training set. Args: config (str): File path to the",
"import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\" def",
"List of sentences to tokenize and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens)",
"training data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in",
"pd import torch import torchtext from torch.nn.utils.rnn import pad_sequence import yaml from yaml",
"return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed",
"from the dataset. Returns: tuple: sentences, labels \"\"\" if self.transform is None: return",
"class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at train and inference time.",
"self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for k, v in self.label_dict.items()}",
"torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts a sequence",
"self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences of tokens",
"labels class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at train and inference",
"sequences of tokens and labels. Args: df (pd.DataFrame): DF containing training examples. transform",
"self._create_vocabs() self.idx_to_label = {v: k for k, v in self.label_dict.items()} def _create_vocabs(self) ->",
"-> tuple: \"\"\"Retrieves the idx item from the dataset, potentially transformed. Args: idx",
"= self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation",
"train=True, else (sentences_padded, sentence_lens). \"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices",
"\"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform:",
"yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003",
"tuple: \"\"\"Groups data into sequences of tokens and labels. Returns: tuple: sentences, labels",
"and returns label indices. Args: label_sequence (list): Sequence of string labels. Returns: torch.tensor:",
"+= 1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool = True)",
"'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict",
"dataloaders # for guaranteed consistency with the way that we're preparing training data",
"fed into the model. Args: sentences (list): List of sentences to tokenize and",
"\"\"\"Preproccessor class to handle data preparation at train and inference time. \"\"\" def",
"labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences =",
"label_dict @staticmethod def _collate_fn(batch: tuple, train: bool = True) -> tuple: \"\"\"Custom collate",
"= os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform =",
"if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return",
"zip(*batch) else: sentence_indices = batch sentence_lens = [len(x) for x in sentence_indices] #",
"batch sentence_lens = [len(x) for x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded",
"contains vocab and label_dict embedded in the transform function preprocessor = Preprocessor(args.config) sample_sentence",
"based on the training set. Args: config (str): File path to the configuration",
"pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self)",
"sentences. Args: sentence (str): Sentence string. Returns: list: Tokenized sentence. \"\"\" return sentence.split('",
"self.sentences[idx], self.labels[idx] # TODO: probably should wrap this in a for-loop indices =",
"import torchtext from torch.nn.utils.rnn import pad_sequence import yaml from yaml import parser class",
"yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset. \"\"\"",
"= yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k",
"Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list) ->",
"Returns: tuple: sentences, labels \"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx] #",
"train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset,",
"list) -> torch.tensor: \"\"\"Transform function that accepts a sequence of labels and returns",
"\"\"\"Generate vocabulary object and label dictionary. Returns: tuple: vocab, label_dict \"\"\" # load",
"return sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that accepts",
"label dictionary based on the training set. Args: config (str): File path to",
"_transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts a sequence of labels",
"a list of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if",
"function preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in New York City.' prepared_sentence",
"= i i += 1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train:",
"the dataset. Returns: tuple: sentences, labels \"\"\" if self.transform is None: return self.sentences[idx],",
"import torch import torchtext from torch.nn.utils.rnn import pad_sequence import yaml from yaml import",
"inference time. \"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize the preprocessor and",
"val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def",
"that can be fed into the model. Args: sentences (list): List of sentences",
"else just a list of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens),",
"idx (int): idx item from the dataset. Returns: tuple: sentences, labels \"\"\" if",
"(int): idx item from the dataset. Returns: tuple: sentences, labels \"\"\" if self.transform",
"self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform)",
"(list): Sequence of string labels. Returns: torch.tensor: Label indices. \"\"\" labels = []",
"= [] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list)",
"= [len(x) for x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices,",
"\"\"\"Retrieve the length of the dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences)",
"generate vocabulary and label dictionary based on the training set. Args: config (str):",
"preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path",
"= {} i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i",
"int: \"\"\"Retrieve the length of the dataset. Returns: int: Dataset length. \"\"\" return",
"collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function",
"tuple: vocab, label_dict \"\"\" # load train data to build the dictionaries train_df",
"os from types import SimpleNamespace import pandas as pd import torch import torchtext",
"torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary list of string",
"TODO: see if there is a way to reuse the CoNLL2003Dataset class +",
"CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) ->",
"transformed. Args: idx (int): idx item from the dataset. Returns: tuple: sentences, labels",
"Sequence of string labels. Returns: torch.tensor: Label indices. \"\"\" labels = [] for",
"i += 1 return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool =",
"\"\"\"Generates all the dataloaders needed for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader",
"\"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv')",
"= torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {} i = 0",
"def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed for model training. Returns:",
"0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return vocab,",
"just sentences_indices (a list). train (bool, optional): If train=True, expects tuple of sentence_indices,",
"'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform)",
"[] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) ->",
"df (pd.DataFrame): DF containing training examples. transform (list, optional): List of transforms (e.g.",
"If train=True, expects tuple of sentence_indices, sentences_labels, else just a list of sentence_indices.",
"') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that accepts a sentence",
"def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts a sequence of",
"-> torch.tensor: \"\"\"Transform function that accepts a sequence of labels and returns label",
"vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {} i =",
"isinstance(sentence, str): sentence = self._tokenize(sentence) indices = [] for token in sentence: indices.append(self.vocab[token])",
"os.path.join(self.config.data_dir, 'validation.csv') test_file_path = os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path),",
"consistency with the way that we're preparing training data preprocessed = [] if",
"def _collate_fn(batch: tuple, train: bool = True) -> tuple: \"\"\"Custom collate function that",
"-> None: \"\"\"Initializes the dataset and prepares sequences of tokens and labels. Args:",
"optional): List of transforms (e.g. index lookups, etc.). Defaults to None. \"\"\" self.df",
"that accepts a sequence of labels and returns label indices. Args: label_sequence (list):",
"if there is a way to reuse the CoNLL2003Dataset class + dataloaders #",
"and prepares sequences of tokens and labels. Args: df (pd.DataFrame): DF containing training",
"in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and label_dict",
"list). train (bool, optional): If train=True, expects tuple of sentence_indices, sentences_labels, else just",
"yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for",
"'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform)",
"OR just sentences_indices (a list). train (bool, optional): If train=True, expects tuple of",
"Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a list). train (bool, optional):",
"sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens = [len(x) for x",
"\"\"\"Generates all the datasets needed for model training. Returns: tuple: train_dataset, val_dataset, test_dataset",
"length of the dataset. Returns: int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self,",
"Counter import os from types import SimpleNamespace import pandas as pd import torch",
"i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1",
"that accepts a sentence as a string or tokenized list and returns vocabulary",
"labels. Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list),",
"= SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for k, v",
"of sentence_indices. Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else",
"[] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed,",
"that we're preparing training data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else:",
"labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets",
"label_dict = {} i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i",
"and label dictionary. Returns: tuple: vocab, label_dict \"\"\" # load train data to",
"Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir,",
"pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary",
"[len(x) for x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True,",
"CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset,",
"\"\"\"Utility function to tokenize sentences. Args: sentence (str): Sentence string. Returns: list: Tokenized",
"= pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded,",
"string or tokenized list and returns vocabulary indices. Args: sentence (list): Tokenized list",
"df self.transform = transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups",
"types import SimpleNamespace import pandas as pd import torch import torchtext from torch.nn.utils.rnn",
"def _tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize sentences. Args: sentence (str):",
"training set. Args: config (str): File path to the configuration yaml file. \"\"\"",
"= self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset,",
"to None. \"\"\" self.df = df self.transform = transform self.sentences, self.labels = self._prepare_data()",
"list) -> torch.tensor: \"\"\"Transform function that accepts a sentence as a string or",
"function that accepts a sentence as a string or tokenized list and returns",
"accepts a sentence as a string or tokenized list and returns vocabulary indices.",
"sentence as a string or tokenized list and returns vocabulary indices. Args: sentence",
"\"\"\" return len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx item",
"the dataset, potentially transformed. Args: idx (int): idx item from the dataset. Returns:",
"length sequences into padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices",
"list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) ->",
"@staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize sentences. Args: sentence",
"(list): List of sentences to tokenize and retrieve indices for. Returns: tuple: (sentences_padded,",
"of tokens and labels. Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'],",
"# vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded =",
"indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices = [] for token",
"sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens = [len(x) for x in",
"for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor",
"sentence_indices = batch sentence_lens = [len(x) for x in sentence_indices] # vocab['<pad>'] =",
"train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn)",
"on the training set. Args: config (str): File path to the configuration yaml",
"TODO: probably should wrap this in a for-loop indices = self.transform[0](self.sentences[idx]) labels =",
"returns label indices. Args: label_sequence (list): Sequence of string labels. Returns: torch.tensor: Label",
"to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\"",
"model. Args: sentences (list): List of sentences to tokenize and retrieve indices for.",
"-> None: \"\"\"Initialize the preprocessor and generate vocabulary and label dictionary based on",
"torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices = []",
"indices. \"\"\" labels = [] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def",
"sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return",
"CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the",
"def __init__(self, df: pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes the dataset",
"test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence:",
"tuple: sentences, labels \"\"\" if self.transform is None: return self.sentences[idx], self.labels[idx] # TODO:",
"tuple: \"\"\"Generates all the datasets needed for model training. Returns: tuple: train_dataset, val_dataset,",
"tokens and labels. Args: df (pd.DataFrame): DF containing training examples. transform (list, optional):",
"train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path = os.path.join(self.config.data_dir, 'validation.csv') test_file_path",
"(a list). train (bool, optional): If train=True, expects tuple of sentence_indices, sentences_labels, else",
"= Preprocessor(args.config) sample_sentence = '<NAME> lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence)",
"data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence in sentences:",
"= 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True,",
"in sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train:",
"vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels,",
"potentially transformed. Args: idx (int): idx item from the dataset. Returns: tuple: sentences,",
"= temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int: \"\"\"Retrieve",
"return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and label_dict embedded in the",
"train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded,",
"self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size,",
"(str): File path to the configuration yaml file. \"\"\" with open(config, 'r') as",
"train_dataloader, val_dataloader, test_dataloader @staticmethod def _tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize",
"-> torch.tensor: \"\"\"Transform function that accepts a sentence as a string or tokenized",
"\"\"\" # TODO: see if there is a way to reuse the CoNLL2003Dataset",
"to tokenize sentences. Args: sentence (str): Sentence string. Returns: list: Tokenized sentence. \"\"\"",
"Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence = self._tokenize(sentence) indices =",
"else: sentence_indices = batch sentence_lens = [len(x) for x in sentence_indices] # vocab['<pad>']",
"= os.path.join(self.config.data_dir, 'test.csv') transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset =",
"indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts",
"we're preparing training data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for",
"\"\"\" return sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that",
"train=False) def main(args): # contains vocab and label_dict embedded in the transform function",
"train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return vocab, label_dict @staticmethod def _collate_fn(batch:",
"is a way to reuse the CoNLL2003Dataset class + dataloaders # for guaranteed",
"list) -> tuple: \"\"\"Preprocess any arbitrary list of string sentences and return indices",
"= self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to",
"labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int: \"\"\"Retrieve the length",
"-> tuple: \"\"\"Generate vocabulary object and label dictionary. Returns: tuple: vocab, label_dict \"\"\"",
"{} i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i +=",
"tuple: \"\"\"Custom collate function that combines variable length sequences into padded batches. Args:",
"all the datasets needed for model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\"",
"= None) -> None: \"\"\"Initializes the dataset and prepares sequences of tokens and",
"dictionary. Returns: tuple: vocab, label_dict \"\"\" # load train data to build the",
"self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences of",
"train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all the dataloaders needed for",
"train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader(",
"sentence.split(' ') def _transform_sentence(self, sentence: list) -> torch.tensor: \"\"\"Transform function that accepts a",
"list or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\" if isinstance(sentence, str): sentence",
"wrap this in a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices,",
"train: bool = True) -> tuple: \"\"\"Custom collate function that combines variable length",
"indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class",
"collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod def",
"test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader = torch.utils.data.DataLoader(",
"returns vocabulary indices. Args: sentence (list): Tokenized list or sentence string. Returns: torch.tensor:",
"tuple: \"\"\"Preprocess any arbitrary list of string sentences and return indices that can",
"Preprocessor(args.config) sample_sentence = '<NAME> lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if",
"label_dict \"\"\" # load train data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir,",
"in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any",
"class + dataloaders # for guaranteed consistency with the way that we're preparing",
"None: \"\"\"Initializes the dataset and prepares sequences of tokens and labels. Args: df",
"train=True, expects tuple of sentence_indices, sentences_labels, else just a list of sentence_indices. Defaults",
"len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx item from the",
"'r') as f: config = yaml.safe_load(f) self.config = SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs()",
"for x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1)",
"# TODO: probably should wrap this in a for-loop indices = self.transform[0](self.sentences[idx]) labels",
"for sentence in sentences: preprocessed.append(self._transform_sentence(sentence)) return self._collate_fn(preprocessed, train=False) def main(args): # contains vocab",
"preprocessor and generate vocabulary and label dictionary based on the training set. Args:",
"= df self.transform = transform self.sentences, self.labels = self._prepare_data() def _prepare_data(self) -> tuple:",
"tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if there is a way to",
"def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves the idx item from the dataset,",
"into padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a list).",
"sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) -> tuple: \"\"\"Generates all the",
"at train and inference time. \"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize",
"way that we're preparing training data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences))",
"argparse.ArgumentParser() parser.add_argument( '--config', type=str, help='File path where the model configuration file is located.',",
"for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return vocab, label_dict",
"def get_train_datasets(self) -> tuple: \"\"\"Generates all the datasets needed for model training. Returns:",
"= batch sentence_lens = [len(x) for x in sentence_indices] # vocab['<pad>'] = 1",
"and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" # TODO: see if",
"type=str, help='File path where the model configuration file is located.', required=True) args =",
"import argparse from collections import Counter import os from types import SimpleNamespace import",
"batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def get_train_datasets(self) ->",
"k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] = i i += 1 return vocab, label_dict @staticmethod",
"__init__(self, config: str) -> None: \"\"\"Initialize the preprocessor and generate vocabulary and label",
"torch import torchtext from torch.nn.utils.rnn import pad_sequence import yaml from yaml import parser",
"from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain the CoNLL2003 dataset.",
"-> tuple: \"\"\"Generates all the datasets needed for model training. Returns: tuple: train_dataset,",
"None: \"\"\"Initialize the preprocessor and generate vocabulary and label dictionary based on the",
"sentences, labels def __len__(self) -> int: \"\"\"Retrieve the length of the dataset. Returns:",
"sentences to tokenize and retrieve indices for. Returns: tuple: (sentences_padded, sentence_lens) \"\"\" #",
"contain the CoNLL2003 dataset. \"\"\" def __init__(self, df: pd.DataFrame, transform: list = None)",
"and labels. Args: df (pd.DataFrame): DF containing training examples. transform (list, optional): List",
"train and inference time. \"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize the",
"None) -> None: \"\"\"Initializes the dataset and prepares sequences of tokens and labels.",
"\"\"\" labels = [] for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self,",
"None. \"\"\" self.df = df self.transform = transform self.sentences, self.labels = self._prepare_data() def",
"Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from collections import",
"_tokenize(sentence: str) -> list: \"\"\"Utility function to tokenize sentences. Args: sentence (str): Sentence",
"(pd.DataFrame): DF containing training examples. transform (list, optional): List of transforms (e.g. index",
"True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens). \"\"\" if",
"= [] for token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list)",
"--config configs/baseline.yaml \"\"\" import argparse from collections import Counter import os from types",
"Args: sentence (list): Tokenized list or sentence string. Returns: torch.tensor: Vocabulary indices. \"\"\"",
"token in sentence: indices.append(self.vocab[token]) return torch.tensor(indices) def _transform_labels(self, label_sequence: list) -> torch.tensor: \"\"\"Transform",
"arbitrary list of string sentences and return indices that can be fed into",
"probably should wrap this in a for-loop indices = self.transform[0](self.sentences[idx]) labels = self.transform[1](self.labels[idx])",
"Args: config (str): File path to the configuration yaml file. \"\"\" with open(config,",
"python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse from collections import Counter import",
"= CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset def get_train_dataloaders(self) -> tuple: \"\"\"Generates all",
"def __len__(self) -> int: \"\"\"Retrieve the length of the dataset. Returns: int: Dataset",
"configuration yaml file. \"\"\" with open(config, 'r') as f: config = yaml.safe_load(f) self.config",
"if isinstance(sentence, str): sentence = self._tokenize(sentence) indices = [] for token in sentence:",
"\"\"\"Transform function that accepts a sentence as a string or tokenized list and",
"v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate vocabulary object and label dictionary.",
"padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a list). train",
"1 sentences_padded = pad_sequence(sentence_indices, batch_first=True, padding_value=1) if train: labels_padded = pad_sequence(sentence_labels, batch_first=True, padding_value=-1)",
"model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv') val_file_path",
"for label in label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple:",
"build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary vocab = torchtext.vocab.Vocab(",
"preprocessor = Preprocessor(args.config) sample_sentence = '<NAME> lives in New York City.' prepared_sentence =",
"vocabulary object and label dictionary. Returns: tuple: vocab, label_dict \"\"\" # load train",
"def __init__(self, config: str) -> None: \"\"\"Initialize the preprocessor and generate vocabulary and",
"DF containing training examples. transform (list, optional): List of transforms (e.g. index lookups,",
"training and inference. Examples: $ python preprocess.py \\ --config configs/baseline.yaml \"\"\" import argparse",
"sentences_indices (a list). train (bool, optional): If train=True, expects tuple of sentence_indices, sentences_labels,",
"for model training. Returns: tuple: train_dataset, val_dataset, test_dataset \"\"\" train_file_path = os.path.join(self.config.data_dir, 'train.csv')",
"needed for model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset",
"train data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) # create vocabulary",
"a sentence as a string or tokenized list and returns vocabulary indices. Args:",
"(str): Sentence string. Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self,",
"lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser",
"= zip(*batch) else: sentence_indices = batch sentence_lens = [len(x) for x in sentence_indices]",
"dictionary label_dict = {} i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k] =",
"self.transform[1](self.labels[idx]) return indices, labels class Preprocessor(object): \"\"\"Preproccessor class to handle data preparation at",
"\"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True)",
"tuple: \"\"\"Generates all the dataloaders needed for model training. Returns: tuple: train_dataloader, val_dataloader,",
"index lookups, etc.). Defaults to None. \"\"\" self.df = df self.transform = transform",
"torchtext.vocab.Vocab( Counter(train_df['Token'].value_counts().to_dict())) # create label dictionary label_dict = {} i = 0 for",
"reuse the CoNLL2003Dataset class + dataloaders # for guaranteed consistency with the way",
"and label dictionary based on the training set. Args: config (str): File path",
"train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn, shuffle=True) val_dataloader",
"self.idx_to_label = {v: k for k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple:",
"model training. Returns: tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets()",
"label_sequence: labels.append(self.label_dict[label]) return torch.tensor(labels) def preprocess(self, sentences: list) -> tuple: \"\"\"Preprocess any arbitrary",
"into the model. Args: sentences (list): List of sentences to tokenize and retrieve",
"shuffle=True) val_dataloader = torch.utils.data.DataLoader( val_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn)",
"transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset = CoNLL2003Dataset(pd.read_csv(test_file_path), transform) return train_dataset, val_dataset, test_dataset",
"string labels. Returns: torch.tensor: Label indices. \"\"\" labels = [] for label in",
"SimpleNamespace(**config) self.vocab, self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for k, v in",
"self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg( Sentence=('Token', list), Labels=('NER_Tag_Normalized', list)) sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist()",
"\"\"\" if train: sentence_indices, sentence_labels = zip(*batch) else: sentence_indices = batch sentence_lens =",
"sentences = temp_df['Sentence'].values.tolist() labels = temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int:",
"label dictionary label_dict = {} i = 0 for k in train_df['NER_Tag_Normalized'].unique(): label_dict[k]",
"int: Dataset length. \"\"\" return len(self.sentences) def __getitem__(self, idx: int) -> tuple: \"\"\"Retrieves",
"the training set. Args: config (str): File path to the configuration yaml file.",
"prepares sequences of tokens and labels. Args: df (pd.DataFrame): DF containing training examples.",
"handle data preparation at train and inference time. \"\"\" def __init__(self, config: str)",
"tokens and labels. Returns: tuple: sentences, labels \"\"\" temp_df = self.df.groupby(['Article_ID', 'Sentence_ID'], as_index=False).agg(",
"transform = [self._transform_sentence, self._transform_labels] train_dataset = CoNLL2003Dataset(pd.read_csv(train_file_path), transform) val_dataset = CoNLL2003Dataset(pd.read_csv(val_file_path), transform) test_dataset",
"self._prepare_data() def _prepare_data(self) -> tuple: \"\"\"Groups data into sequences of tokens and labels.",
"indices. Args: label_sequence (list): Sequence of string labels. Returns: torch.tensor: Label indices. \"\"\"",
"Sentence string. Returns: list: Tokenized sentence. \"\"\" return sentence.split(' ') def _transform_sentence(self, sentence:",
"return sentences, labels def __len__(self) -> int: \"\"\"Retrieve the length of the dataset.",
"is None: return self.sentences[idx], self.labels[idx] # TODO: probably should wrap this in a",
"= pad_sequence(sentence_labels, batch_first=True, padding_value=-1) return (sentences_padded, sentence_lens), labels_padded else: return (sentences_padded, sentence_lens) def",
"= temp_df['Labels'].values.tolist() return sentences, labels def __len__(self) -> int: \"\"\"Retrieve the length of",
"tuple: train_dataloader, val_dataloader, test_dataloader \"\"\" train_dataset, val_dataset, test_dataset = self.get_train_datasets() train_dataloader = torch.utils.data.DataLoader(",
"tuple: \"\"\"Retrieves the idx item from the dataset, potentially transformed. Args: idx (int):",
"sentence_lens = [len(x) for x in sentence_indices] # vocab['<pad>'] = 1 sentences_padded =",
"Defaults to True. Returns: tuple: (sentences_padded, sentence_lens), labels_padded if train=True, else (sentences_padded, sentence_lens).",
"= '<NAME> lives in New York City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ ==",
"self._collate_fn(preprocessed, train=False) def main(args): # contains vocab and label_dict embedded in the transform",
"self.transform is None: return self.sentences[idx], self.labels[idx] # TODO: probably should wrap this in",
"preparing training data preprocessed = [] if isinstance(sentences, str): preprocessed.append(self._transform_sentence(sentences)) else: for sentence",
"pd.DataFrame, transform: list = None) -> None: \"\"\"Initializes the dataset and prepares sequences",
"of labels and returns label indices. Args: label_sequence (list): Sequence of string labels.",
"= {v: k for k, v in self.label_dict.items()} def _create_vocabs(self) -> tuple: \"\"\"Generate",
"label_sequence: list) -> torch.tensor: \"\"\"Transform function that accepts a sequence of labels and",
"batches. Args: batch (tuple): sentence_indices, sentences_labels OR just sentences_indices (a list). train (bool,",
"of string labels. Returns: torch.tensor: Label indices. \"\"\" labels = [] for label",
"self.label_dict = self._create_vocabs() self.idx_to_label = {v: k for k, v in self.label_dict.items()} def",
"vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool = True) -> tuple: \"\"\"Custom",
"list of string sentences and return indices that can be fed into the",
"preprocessing code to prepare data for training and inference. Examples: $ python preprocess.py",
"the dataset and prepares sequences of tokens and labels. Args: df (pd.DataFrame): DF",
"Returns: torch.tensor: Label indices. \"\"\" labels = [] for label in label_sequence: labels.append(self.label_dict[label])",
"class to handle data preparation at train and inference time. \"\"\" def __init__(self,",
"pad_sequence import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset to contain",
"torch.nn.utils.rnn import pad_sequence import yaml from yaml import parser class CoNLL2003Dataset(torch.utils.data.Dataset): \"\"\"Custom dataset",
"return vocab, label_dict @staticmethod def _collate_fn(batch: tuple, train: bool = True) -> tuple:",
"batch_size=self.config.batch_size, collate_fn=self._collate_fn) test_dataloader = torch.utils.data.DataLoader( test_dataset, batch_size=self.config.batch_size, collate_fn=self._collate_fn) return train_dataloader, val_dataloader, test_dataloader @staticmethod",
"City.' prepared_sentence = preprocessor.preprocess(sample_sentence) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--config',",
"parser.add_argument( '--config', type=str, help='File path where the model configuration file is located.', required=True)",
"and inference time. \"\"\" def __init__(self, config: str) -> None: \"\"\"Initialize the preprocessor",
"the idx item from the dataset, potentially transformed. Args: idx (int): idx item",
"combines variable length sequences into padded batches. Args: batch (tuple): sentence_indices, sentences_labels OR",
"tokenized list and returns vocabulary indices. Args: sentence (list): Tokenized list or sentence",
"lookups, etc.). Defaults to None. \"\"\" self.df = df self.transform = transform self.sentences,",
"and generate vocabulary and label dictionary based on the training set. Args: config",
"# load train data to build the dictionaries train_df = pd.read_csv(os.path.join(self.config.data_dir, 'train.csv')) #",
"to handle data preparation at train and inference time. \"\"\" def __init__(self, config:",
"indices that can be fed into the model. Args: sentences (list): List of",
"# create label dictionary label_dict = {} i = 0 for k in"
] |
[
"= gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert",
"0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set())",
"D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G",
"13): G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1)",
"gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) ==",
"test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph()",
"gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0,",
"D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self):",
"False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert",
"gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0)",
"[1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0)",
"def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError):",
"def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self):",
"gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert",
"assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5)",
"G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G =",
"gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError):",
"G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G",
"set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3)",
"def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self):",
"gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert",
"assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G,",
"gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self):",
"gp.is_k_forcing_set(G, [1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2,",
"def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError):",
"gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G,",
"2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) ==",
"test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G) assert",
"pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G",
"= gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph()",
"in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def",
"= gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G,",
"test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G",
"assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0],",
"gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def",
"gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5)",
"def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G =",
"True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def",
"3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def",
"gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0,",
"assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def",
"= gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G =",
"gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self):",
"set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set())",
"gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) == True def",
"12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G",
"G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert",
"== False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def",
"assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert",
"False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self):",
"[0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) ==",
"= gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G,",
"[0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self):",
"test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G =",
"1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1,",
"assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G",
"test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError):",
"test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i",
"False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G = gp.star_graph(i) D =",
"gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G,",
"G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert",
"[0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False",
"pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1],",
"gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert",
"== None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G",
"test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2)",
"assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert",
"G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) ==",
"False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert",
"test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G",
"gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self):",
"G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G",
"assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1])",
"gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G,",
"gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert",
"G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G",
"def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4",
"assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0])",
"with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G",
"import pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1,",
"gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2)",
"test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self):",
"= gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5)",
"True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G",
"= gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G =",
"test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G",
"[1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) ==",
"test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order()",
"= gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G,",
"as gp import pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2)",
"1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0)",
"== False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def",
"False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self):",
"1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G",
"pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2)",
"G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2)",
"G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def",
"with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError):",
"G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G,",
"gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G,",
"with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G =",
"== True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G = gp.star_graph(i) assert",
"== False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3)",
"== 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def",
"gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G,",
"with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert",
"= gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert",
"= gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for",
"gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G =",
"gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self):",
"- 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self):",
"= gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5)",
"gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def",
"True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self):",
"for i in range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G,",
"[1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12):",
"def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G)",
"G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set())",
"== True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True",
"gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) == False",
"== False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) ==",
"def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G",
"gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G,",
"G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3)",
"assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G,",
"def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self):",
"[0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def",
"test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self):",
"False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True",
"0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with",
"def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G",
"gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0,",
"== 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def",
"G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G =",
"== False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False",
"gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G,",
"== True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def",
"i in range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1],",
"gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def",
"True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def",
"G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3)",
"assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G)",
"gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1,",
"gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5)",
"gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) ==",
"assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def",
"gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3])",
"[0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False",
"= gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4)",
"gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self):",
"gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0])",
"assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2,",
"gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2",
"gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self):",
"None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G =",
"G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6)",
"def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for",
"def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G,",
"test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G =",
"def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self):",
"= gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G = gp.empty_graph(5) assert gp.connected_zero_forcing_number(G) ==",
"4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self):",
"== 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def",
"= gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) == True",
"gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) ==",
"== False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True",
"gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) ==",
"G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3)",
"test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G",
"def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self):",
"test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G",
"gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1],",
"G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2)",
"2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True",
"== True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) ==",
"def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G",
"pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G =",
"0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with",
"== True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def",
"test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G =",
"[0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) ==",
"- 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G =",
"== True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False",
"assert gp.is_k_forcing_set(G, [1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in",
"= gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0)",
"[0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0],",
"gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def",
"assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0])",
"def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G",
"pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G =",
"= gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2)",
"G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2)",
"G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G",
"def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) ==",
"G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2)",
"G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0]) == False def test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G =",
"0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0,",
"G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G =",
"def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G = gp.empty_graph(5)",
"def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def",
"== False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G = gp.star_graph(i) D",
"== G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5",
"TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def",
"G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G =",
"G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G,",
"def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G",
"test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3)",
"1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) ==",
"G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert",
"G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self):",
"gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def",
"= gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert",
"[1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False",
"== False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) ==",
"with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G =",
"pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2)",
"with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G =",
"def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def",
"G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in",
"gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13):",
"1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1],",
"range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self):",
"def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError):",
"assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set())",
"[1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3, 13): G = gp.star_graph(i)",
"True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G)",
"[1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1])",
"gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D - 1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i",
"def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G =",
"grinpy as gp import pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G =",
"def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G =",
"assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert",
"= gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2)",
"test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError):",
"1) == True def test_zero_forcing_number_of_star_is_order_minus_2(self): for i in range(2, 12): G = gp.star_graph(i)",
"True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False",
"1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G",
"in range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D",
"test_endpoint_is_connected_forcing_set_of_path(self): G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G = gp.empty_graph(5) assert",
"gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2)",
"gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3,",
"test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G =",
"= gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G,",
"gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G = gp.empty_graph(5) assert gp.connected_zero_forcing_number(G) == None",
"assert gp.is_zero_forcing_vertex(G, 1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G,",
"def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def",
"== True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self):",
"= gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with",
"def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G =",
"assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert",
"gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert",
"assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) ==",
"0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2,",
"range(3, 13): G = gp.star_graph(i) D = gp.max_degree(G) assert gp.is_k_forcing_set(G, [1], D -",
"3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2)",
"G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2)",
"gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G = gp.star_graph(3)",
"gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1,",
"4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G =",
"== False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def",
"pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G)",
"test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with",
"= gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0)",
"1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def",
"[1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) ==",
"0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True",
"5) assert gp.connected_zero_forcing_number(G) == 4 def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G,",
"2 def test_zero_forcing_number_of_petersen_graph_is_5(self): G = gp.petersen_graph() assert gp.zero_forcing_number(G) == 5 def test_2_forcing_number_of_petersen_graph_is_2(self): G",
"test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G",
"test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph()",
"gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G,",
"gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0],",
"gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) ==",
"with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(TypeError): G",
"def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G",
"test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G",
"test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G =",
"0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None def test_endpoint_is_connected_forcing_set_of_path(self): G",
"def test_non_int_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with",
"2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G = gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0],",
"G = gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) ==",
"gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) ==",
"1.5) def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self):",
"gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G,",
"gp import pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G,",
"gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2)",
"= gp.star_graph(2) gp.connected_k_forcing_number(G, 0) def test_total_zero_forcing_num_of_trivial_graph_is_None(self): G = gp.trivial_graph() assert gp.total_zero_forcing_number(G) == None",
"gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) ==",
"import grinpy as gp import pytest class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G",
"set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) == False def test_center_of_S3_is_3_forcing_vertex(self): G =",
"test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G =",
"assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0])",
"test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self):",
"test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G) == 4 def",
"0, [0], 2) == False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1])",
"False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def",
"[2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2",
"= gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G = gp.star_graph(2) assert gp.is_k_forcing_vertex(G,",
"5 def test_2_forcing_number_of_petersen_graph_is_2(self): G = gp.petersen_graph() assert gp.k_forcing_number(G, 2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self):",
"pytest.raises(TypeError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2)",
"True def test_center_of_star_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self):",
"= gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1, set()) ==",
"= gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert",
"gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert gp.is_zero_forcing_set(G,",
"G = gp.path_graph(2) assert gp.is_connected_zero_forcing_set(G, [0]) def test_connected_zero_forcing_num_of_disconnected_graph_is_None(self): G = gp.empty_graph(5) assert gp.connected_zero_forcing_number(G)",
"G = gp.path_graph(5) assert gp.total_zero_forcing_number(G) == 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3,",
"= gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True def test_leaf_is_not_zero_forcing_set_of_S3(self): G = gp.star_graph(3) assert",
"for i in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() -",
"[0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self): G = gp.path_graph(6) assert gp.is_total_zero_forcing_set(G, [2, 3]) ==",
"i in range(2, 12): G = gp.star_graph(i) assert gp.zero_forcing_number(G) == G.order() - 2",
"== 2 def test_connected_zero_forcing_number_of_monster_is_4(self): G = gp.star_graph(3) G.add_edge(3, 4) G.add_edge(3, 5) assert gp.connected_zero_forcing_number(G)",
"False def test_leaf_of_star_is_zero_forcing_active_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [1]) == True def test_center_of_star_is_not_zero_forcing_active_set(self):",
"= gp.star_graph(3) assert gp.is_zero_forcing_set(G, [1]) == False def test_leaf_is_max_degree_minus_one_forcing_set_for_star(self): for i in range(3,",
"= gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5) def test_0_value_for_k_raises_ValueError_in_is_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2)",
"with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 0) def test_integral_float_for_k_works(self): G =",
"def test_0_value_for_k_raises_error_in_is_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.is_connected_k_forcing_set(G, [0], 0) def test_non_int_value_for_k_raises_error_in_min_connected_k_forcing(self): with",
"set()) == False def test_leaf_is_zero_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_zero_forcing_set(G, [0]) == True",
"= gp.star_graph(3) assert gp.is_k_forcing_vertex(G, 0, [0], 3) == True def test_center_of_S3_is_not_2_forcing_vertex(self): G =",
"False assert gp.is_zero_forcing_vertex(G, 1, set()) == False assert gp.is_zero_forcing_vertex(G, 2, set()) == False",
"gp.is_k_forcing_vertex(G, 1, [1], 1.0) == True def test_leaf_is_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G,",
"class TestZeroForcing: def test_non_integral_value_for_k_raises_TypeError_in_is_k_forcing(self): with pytest.raises(TypeError): G = gp.star_graph(2) gp.is_k_forcing_vertex(G, 1, [1], 1.5)",
"test_no_vertex_is_zero_forcing_vertex_for_empty_set(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, set()) == False assert gp.is_zero_forcing_vertex(G, 1,",
"1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 0) def test_non_int_value_for_k_raises_error_in_connected_k_forcing_num(self): with",
"assert gp.is_total_zero_forcing_set(G, [2, 3]) == True def test_total_zero_forcing_number_of_path_is_2(self): G = gp.path_graph(5) assert gp.total_zero_forcing_number(G)",
"1, [1]) == True def test_center_is_not_zero_forcing_vertex_for_star(self): G = gp.star_graph(2) assert gp.is_zero_forcing_vertex(G, 0, [0])",
"2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False def test_pair_of_adjacent_nodes_is_total_forcing_set_of_path(self):",
"2) == 2 def test_leaf_is_not_total_forcing_set_of_path(self): G = gp.path_graph(3) assert gp.is_total_zero_forcing_set(G, [0]) == False",
"= gp.star_graph(2) assert gp.is_zero_forcing_active_set(G, [0]) == False def test_empy_set_is_not_zero_forcing_active_set(self): G = gp.star_graph(2) assert",
"pytest.raises(TypeError): G = gp.star_graph(2) gp.connected_k_forcing_number(G, 1.5) def test_0_value_for_k_raises_error_in_connected_k_forcing_num(self): with pytest.raises(ValueError): G = gp.star_graph(2)",
"G = gp.star_graph(2) gp.min_connected_k_forcing_set(G, 1.5) def test_0_value_for_k_raises_error_in_min_connected_k_forcing(self): with pytest.raises(ValueError): G = gp.star_graph(2) gp.min_connected_k_forcing_set(G,"
] |
[
"data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of",
"= [ result for result in data_list if result > data_first_std_deviation_start and result",
"data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for",
"DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end],",
"0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\"))",
"import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median",
"for result in data_list if result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation",
"name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start,",
"y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\",",
"result for result in data_list if result > data_third_std_deviation_start and result < data_third_std_deviation_end]",
"within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean],",
"in data_list if result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [",
"result < data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of this data",
"- \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start,",
"data_list_of_data_within_3_std_deviation = [ result for result in data_list if result > data_third_std_deviation_start and",
"print(\"{}% of data for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig =",
"if result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for",
"{}.\".format(data_mode)) print(\"{}% of data for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}%",
"this data is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of data",
"- \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation",
"scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0,",
"mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3\"))",
"fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\"))",
"data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list)",
"this data is {}.\".format(data_mode)) print(\"{}% of data for data lies within 1 standard",
"- \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in data_list if",
"pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean",
"data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list if result > data_second_std_deviation_start and",
"standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0,",
"y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17], mode=\"lines\",",
"data is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of this data",
"within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 2",
"result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result",
"lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean,",
"as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean =",
"data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in data_list if result > data_first_std_deviation_start",
"fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0,",
"{}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode))",
"result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in",
"data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean",
"statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end =",
"1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 2 standard",
"statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start,",
"data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end =",
"result in data_list if result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation =",
"> data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in",
"data_list_of_data_within_1_std_deviation = [ result for result in data_list if result > data_first_std_deviation_start and",
"if result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this data is",
"data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean -",
"as go import pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list =",
"0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION",
"deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list)))",
"0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD",
"data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result",
"pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list)",
"(2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [",
"data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies",
"1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[",
"name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3\")) fig.show()",
"\\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end",
"[result for result in data_list if result > data_second_std_deviation_start and result < data_second_std_deviation_end]",
"deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17],",
"y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\",",
"result in data_list if result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation =",
"statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean",
"1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[",
"deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list)))",
"0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION",
"data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD",
"< data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in data_list if result >",
"data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation)",
"import plotly.figure_factory as ff import plotly.graph_objects as go import pandas as pd import",
"name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end,",
"= pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode",
"for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data",
"lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within",
"= dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation",
"for result in data_list if result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean",
"len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\",",
"show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17],",
"score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list)",
"print(\"{}% of data for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of",
"mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end],",
"data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17],",
"{}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of data for data lies",
"data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean -",
"print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of data for data lies within",
"data for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for",
"print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode",
"print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}%",
"pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode =",
"[ result for result in data_list if result > data_first_std_deviation_start and result <",
"data_list if result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result",
"data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median))",
"for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data",
"\\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in data_list if result",
"for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"],",
"ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start],",
"plotly.graph_objects as go import pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list",
"plotly.figure_factory as ff import plotly.graph_objects as go import pandas as pd import statistics",
"data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation,",
"in data_list if result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result",
"if result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result",
"data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean",
"data is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of data for",
"y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION",
"0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end,",
"data is {}.\".format(data_mode)) print(\"{}% of data for data lies within 1 standard deviation\".format(",
"len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}%",
"data for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for",
"0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD",
"go import pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading",
"in data_list if result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this",
"= [result for result in data_list if result > data_second_std_deviation_start and result <",
"2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 3 standard",
"fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\",",
"name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[",
"fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0,",
"result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean))",
"< data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list if result > data_second_std_deviation_start",
"data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in data_list",
"data_list if result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this data",
"[ result for result in data_list if result > data_third_std_deviation_start and result <",
"statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\",
"standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 2 standard deviations\".format(",
"data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\",
"= statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean -",
"data_first_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17],",
"mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\"))",
"and result < data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of this",
"standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 3 standard deviations\".format(",
"data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\")) fig.add_trace(go.Scatter(x=[data_third_std_deviation_end, data_third_std_deviation_end], y=[ 0, 0.17],",
"data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False)",
"is {}.\".format(data_mode)) print(\"{}% of data for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list)))",
"fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0,",
"data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in data_list if result > data_third_std_deviation_start",
"[\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start, data_first_std_deviation_start], y=[",
"data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in data_list",
"data for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading",
"statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median =",
"data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end",
"import plotly.graph_objects as go import pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\")",
"> data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list",
"is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of data for data",
"within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 3",
"of data for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list],",
"and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list if result",
"of this data is {}.\".format(data_median)) print(\"Mode of this data is {}.\".format(data_mode)) print(\"{}% of",
"of data for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data",
"this data is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of this",
"\\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation =",
"data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\",
"for result in data_list if result > data_second_std_deviation_start and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation",
"0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION",
"mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2\"))",
"DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_second_std_deviation_start, data_second_std_deviation_start],",
"data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result",
"import pandas as pd import statistics dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list()",
"= statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end",
"< data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median of this data is",
"dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation =",
"= data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation) data_third_std_deviation_start, data_third_std_deviation_end = data_mean - \\ (3*data_std_deviation),",
"and result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in data_list if",
"(3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in data_list if result >",
"is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of this data is",
"= data_mean - \\ (3*data_std_deviation), data_mean+(3*data_std_deviation) data_list_of_data_within_1_std_deviation = [ result for result in",
"as ff import plotly.graph_objects as go import pandas as pd import statistics dataframe",
"len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within 3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig",
"result < data_second_std_deviation_end] data_list_of_data_within_3_std_deviation = [ result for result in data_list if result",
"= [ result for result in data_list if result > data_third_std_deviation_start and result",
"of data for data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data",
"dataframe = pd.read_csv(\"StudentsPerformance.csv\") data_list = dataframe[\"reading score\"].to_list() data_mean = statistics.mean(data_list) data_median = statistics.median(data_list)",
"ff import plotly.graph_objects as go import pandas as pd import statistics dataframe =",
"lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies within",
"data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation), data_mean+(2*data_std_deviation)",
"data_list if result > data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for",
"data_list_of_data_within_2_std_deviation = [result for result in data_list if result > data_second_std_deviation_start and result",
"data_mean = statistics.mean(data_list) data_median = statistics.median(data_list) data_mode = statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start,",
"3 standard deviations\".format( len(data_list_of_data_within_3_std_deviation)*100.0/len(data_list))) fig = ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[",
"of this data is {}.\".format(data_mean)) print(\"Median of this data is {}.\".format(data_median)) print(\"Mode of",
"print(\"{}% of data for data lies within 2 standard deviations\".format( len(data_list_of_data_within_2_std_deviation)*100.0/len(data_list))) print(\"{}% of",
"= statistics.mode(data_list) data_std_deviation = statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation",
"result in data_list if result > data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of",
"result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list if result >",
"= ff.create_distplot([data_list], [\"reading scores\"], show_hist=False) fig.add_trace(go.Scatter(x=[data_mean, data_mean], y=[ 0, 0.17], mode=\"lines\", name=\"MEAN\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_start,",
"result for result in data_list if result > data_first_std_deviation_start and result < data_first_std_deviation_end]",
"data lies within 1 standard deviation\".format( len(data_list_of_data_within_1_std_deviation)*100.0/len(data_list))) print(\"{}% of data for data lies",
"of this data is {}.\".format(data_mode)) print(\"{}% of data for data lies within 1",
"= statistics.stdev(data_list) data_first_std_deviation_start, data_first_std_deviation_end = data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end =",
"= data_mean - \\ data_std_deviation, data_mean+data_std_deviation data_second_std_deviation_start, data_second_std_deviation_end = data_mean - \\ (2*data_std_deviation),",
"> data_third_std_deviation_start and result < data_third_std_deviation_end] print(\"Mean of this data is {}.\".format(data_mean)) print(\"Median",
"data_first_std_deviation_start and result < data_first_std_deviation_end] data_list_of_data_within_2_std_deviation = [result for result in data_list if",
"0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1\")) fig.add_trace(go.Scatter(x=[data_first_std_deviation_end, data_first_std_deviation_end], y=[ 0, 0.17], mode=\"lines\", name=\"STANDARD"
] |
[
"conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta,",
"genero self.dni = dni self.peso = peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento",
"pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes",
"celular: str genero: str dni: str peso: float talla: float fecha_nacimiento: str def",
"informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente,",
"peso: float talla: float fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero, dni,",
"obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion):",
"mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento,",
"paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=(",
"pow class Paciente: nombre: str apellido: str celular: str genero: str dni: str",
"pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes",
"conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def",
"self.nombre = nombre self.apellido = apellido self.celular = celular self.genero = genero self.dni",
"paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc = peso /",
"= consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado",
"id_paciente )) def calcular_imc(self, peso, talla): imc = peso / pow(talla, 2) return",
"= celular self.genero = genero self.dni = dni self.peso = peso self.talla =",
"paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente,",
"valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion)",
"str apellido: str celular: str genero: str dni: str peso: float talla: float",
"database import conexion, consulta from math import pow class Paciente: nombre: str apellido:",
"conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=(",
"peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes",
"valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self,",
"= genero self.dni = dni self.peso = peso self.talla = talla self.fecha_nacimiento =",
"conexion, consulta from math import pow class Paciente: nombre: str apellido: str celular:",
"paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado):",
"def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular,",
"= talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta,",
"= apellido self.celular = celular self.genero = genero self.dni = dni self.peso =",
"paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso,",
"pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente']",
"paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente,",
"genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular =",
"def __init__(self, nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre",
"= conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta,",
"consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado ))",
"float fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento):",
"apellido self.celular = celular self.genero = genero self.dni = dni self.peso = peso",
"str dni: str peso: float talla: float fecha_nacimiento: str def __init__(self, nombre, apellido,",
"math import pow class Paciente: nombre: str apellido: str celular: str genero: str",
"self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return",
"return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido,",
"import pow class Paciente: nombre: str apellido: str celular: str genero: str dni:",
"apellido: str celular: str genero: str dni: str peso: float talla: float fecha_nacimiento:",
"mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento,",
"float talla: float fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero, dni, peso,",
"pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular,",
"<filename>models/entidad_paciente.py from database import conexion, consulta from math import pow class Paciente: nombre:",
")) def calcular_imc(self, peso, talla): imc = peso / pow(talla, 2) return round(imc,2)",
"id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla,",
"talla: float fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero, dni, peso, talla,",
"talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=())",
"= dni self.peso = peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self):",
"class Paciente: nombre: str apellido: str celular: str genero: str dni: str peso:",
"str genero: str dni: str peso: float talla: float fecha_nacimiento: str def __init__(self,",
"self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes =",
"self.peso = peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta =",
"celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular",
"consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta =",
"paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente']",
"return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return",
"nombre self.apellido = apellido self.celular = celular self.genero = genero self.dni = dni",
"def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero,",
"valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre,",
"paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc = peso / pow(talla,",
"valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def",
"self.apellido = apellido self.celular = celular self.genero = genero self.dni = dni self.peso",
"apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido",
"nombre: str apellido: str celular: str genero: str dni: str peso: float talla:",
"str peso: float talla: float fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero,",
"from math import pow class Paciente: nombre: str apellido: str celular: str genero:",
"= nombre self.apellido = apellido self.celular = celular self.genero = genero self.dni =",
"conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente ))",
"= conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes =",
"Paciente: nombre: str apellido: str celular: str genero: str dni: str peso: float",
"paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc",
"mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta",
"paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc =",
"str celular: str genero: str dni: str peso: float talla: float fecha_nacimiento: str",
"fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def",
"from database import conexion, consulta from math import pow class Paciente: nombre: str",
"id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc = peso / pow(talla, 2)",
")) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido,",
"= consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado,",
"actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero,",
"= consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado): mi_consulta",
"paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self,",
"__init__(self, nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido",
"paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni,",
"= peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente']",
"paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla):",
"dni: str peso: float talla: float fecha_nacimiento: str def __init__(self, nombre, apellido, celular,",
"= fecha_nacimiento def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes",
"import conexion, consulta from math import pow class Paciente: nombre: str apellido: str",
"fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular = celular self.genero = genero",
"id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla,",
"self.celular = celular self.genero = genero self.dni = dni self.peso = peso self.talla",
"genero: str dni: str peso: float talla: float fecha_nacimiento: str def __init__(self, nombre,",
"def obtener_paciente(self): mi_consulta = consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self,",
"dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular = celular",
"self.dni = dni self.peso = peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def",
"dni self.peso = peso self.talla = talla self.fecha_nacimiento = fecha_nacimiento def obtener_paciente(self): mi_consulta",
"paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta",
"paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta,",
"peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular = celular self.genero",
"consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente",
"str def __init__(self, nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre =",
"self.genero = genero self.dni = dni self.peso = peso self.talla = talla self.fecha_nacimiento",
"id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre,",
"def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def",
"nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre = nombre self.apellido =",
"paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado )) def actualizar_paciente(self, paciente, id_paciente, id_empleado): mi_consulta =",
"paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso,",
"fecha_nacimiento: str def __init__(self, nombre, apellido, celular, genero, dni, peso, talla, fecha_nacimiento): self.nombre",
"= consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta =",
"paciente.peso, paciente.talla, paciente.fecha_nacimiento, id_empleado, id_paciente )) def calcular_imc(self, peso, talla): imc = peso",
"talla, fecha_nacimiento): self.nombre = nombre self.apellido = apellido self.celular = celular self.genero =",
"buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self,",
"nuevo_paciente(self, paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['registrar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni,",
"mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente'] pacientes = conexion.leer_datos(consulta=mi_consulta, valores=informacion) return pacientes def nuevo_paciente(self, paciente, id_empleado):",
"id_paciente, id_empleado): mi_consulta = consulta.CONSULTAS_PACIENTE['editar_paciente'] conexion.crud_datos(consulta=mi_consulta, valores=( paciente.nombre, paciente.apellido, paciente.celular, paciente.genero, paciente.dni, paciente.peso,",
"consulta from math import pow class Paciente: nombre: str apellido: str celular: str",
"celular self.genero = genero self.dni = dni self.peso = peso self.talla = talla",
"consulta.CONSULTAS_PACIENTE['buscar_paciente'] pacientes = conexion.obtener_datos(consulta=mi_consulta, valores=()) return pacientes def buscar_paciente(self, informacion): mi_consulta = consulta.CONSULTAS_PACIENTE['leer_paciente']"
] |
[
"crazyflie import uav_trajectory import time import tf #from crazyflie_driver.msg import Hover from std_msgs.msg",
"duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2",
":', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0)",
"+ '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\",",
"cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end cf.startTrajectory(0, timescale=1.0, reverse=True)",
"time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end",
"\"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use",
"- default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default 0.4 ##",
"2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default 1.25",
"cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay",
"cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\")",
"0.2) # reduce z wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0)",
"get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params",
"z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default",
"reduce z wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0)",
"time import tf #from crazyflie_driver.msg import Hover from std_msgs.msg import Empty from crazyflie_driver.srv",
"rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2",
"'/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1)",
"import absolute_import, division, unicode_literals, print_function import rospy import crazyflie import uav_trajectory import time",
"0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger",
"0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight",
"# reduce z wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\",",
"cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller",
"= uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0,",
"rospy import crazyflie import uav_trajectory import time import tf #from crazyflie_driver.msg import Hover",
"update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce",
"# reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble",
"from __future__ import absolute_import, division, unicode_literals, print_function import rospy import crazyflie import uav_trajectory",
"default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1)",
"0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0)",
"GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found",
"cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5)",
"std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from threading",
"## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\",",
"import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from threading import",
"import rospy import crazyflie import uav_trajectory import time import tf #from crazyflie_driver.msg import",
"z wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\",",
"uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1)",
"#cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 =",
"- https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function import rospy import crazyflie",
"import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1'",
"__future__ import absolute_import, division, unicode_literals, print_function import rospy import crazyflie import uav_trajectory import",
"reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2)",
"0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ########",
"default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2)",
"division, unicode_literals, print_function import rospy import crazyflie import uav_trajectory import time import tf",
"python # source - https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function import",
"UpdateParams from crazyflie_driver.msg import GenericLogData from threading import Thread import tty, termios import",
"import Hover from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import",
"1.0) # reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z",
"# Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\",",
"0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\")",
"#from crazyflie_driver.msg import Hover from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from",
"Hover from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData",
"'__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix",
"3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :',",
"cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight =",
"traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional",
"prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\")",
"#cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\",",
"unicode_literals, print_function import rospy import crazyflie import uav_trajectory import time import tf #from",
"Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06)",
"reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble -",
"source - https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function import rospy import",
"timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end cf.startTrajectory(0, timescale=1.0, reverse=True) time.sleep(1.2)",
"sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf",
"- default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\",",
"from threading import Thread import tty, termios import sys if __name__ == '__main__':",
"0.06) # reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z",
"duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration *",
"Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from threading import Thread",
"2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0)",
"= 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration",
"* 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end cf.startTrajectory(0,",
"time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\")",
"wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default 0.4",
"traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0)",
"1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4,",
"# 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0)",
"default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default 0.4 ## reset",
"2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1",
"time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end cf.startTrajectory(0, timescale=1.0, reverse=True) time.sleep(1.2) cf.stop()",
"== '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\")",
"import time import tf #from crazyflie_driver.msg import Hover from std_msgs.msg import Empty from",
"import tf #from crazyflie_driver.msg import Hover from std_msgs.msg import Empty from crazyflie_driver.srv import",
"GenericLogData from threading import Thread import tty, termios import sys if __name__ ==",
"crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from threading import Thread import tty,",
"timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at",
"from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from",
"tty, termios import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix",
"- default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\",",
"wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default 0.05",
"from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg import GenericLogData from threading import Thread import",
"mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1 =",
"from crazyflie_driver.msg import GenericLogData from threading import Thread import tty, termios import sys",
"traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0,",
"traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1,",
"cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use",
"if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf =",
"termios import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix =",
"__name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\",",
"= uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2)",
"#rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params')",
"= '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\",",
"# source - https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function import rospy",
"rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges) prefix = '/cf1' cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix +",
"import Thread import tty, termios import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges',",
"2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1) #additional delay at end cf.startTrajectory(0, timescale=1.0,",
"cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default",
"import UpdateParams from crazyflie_driver.msg import GenericLogData from threading import Thread import tty, termios",
"controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory()",
"cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5)",
"EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) #",
"rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) #",
"cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble",
"import GenericLogData from threading import Thread import tty, termios import sys if __name__",
"traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials),",
"traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1,",
"tf #from crazyflie_driver.msg import Hover from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams",
"0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default 0.4 ## reset kalman",
"Thread import tty, termios import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData,",
"service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z",
"reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble -",
"traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration *",
"'/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0)",
"rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF",
"#time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration)",
"z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble - default",
"crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2) #",
"######## cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration",
"1) cf.setParam(\"stabilizer/estimator\", 2) # Use EKF cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble -",
"uav_trajectory.Trajectory() traj2.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/sine.csv\") print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0,",
"absolute_import, division, unicode_literals, print_function import rospy import crazyflie import uav_trajectory import time import",
"len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration * 1.5) time.sleep(1)",
"#cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce",
"crazyflie_driver.msg import GenericLogData from threading import Thread import tty, termios import sys if",
"1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) #",
"= crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\", 2)",
"wobble - default 0.4 ## reset kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0)",
"0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration * 2.0) cf.startTrajectory(1, timescale=1.5) time.sleep(traj2.duration",
"print_function import rospy import crazyflie import uav_trajectory import time import tf #from crazyflie_driver.msg",
"crazyflie_driver.msg import Hover from std_msgs.msg import Empty from crazyflie_driver.srv import UpdateParams from crazyflie_driver.msg",
"#!/usr/bin/env python # source - https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function",
"cf.setParam(\"ctrlMel/kp_z\", 1.0) # reduce z wobble - default 1.25 #cf.setParam(\"ctrlMel/ki_z\", 0.06) # reduce",
"import crazyflie import uav_trajectory import time import tf #from crazyflie_driver.msg import Hover from",
"uav_trajectory import time import tf #from crazyflie_driver.msg import Hover from std_msgs.msg import Empty",
"print('traj2 duration :', traj2.duration) cf.uploadTrajectory(0, 0, traj1) cf.uploadTrajectory(1, len(traj1.polynomials), traj2) cf.startTrajectory(0, timescale=1.0) time.sleep(traj1.duration",
"# reduce z wobble - default 0.05 #cf.setParam(\"ctrlMel/kd_z\", 0.2) # reduce z wobble",
"https://github.com/whoenig/crazyflie_ros/commit/b048c1f2fd3ee34f899fa0e2f6c58a4885a39405#diff-970be3522034ff436332d391db26982a from __future__ import absolute_import, division, unicode_literals, print_function import rospy import crazyflie import",
"threading import Thread import tty, termios import sys if __name__ == '__main__': rospy.init_node('test_high_level')",
"import tty, termios import sys if __name__ == '__main__': rospy.init_node('test_high_level') #rospy.Subscriber('/cf1/log_ranges', GenericLogData, get_ranges)",
"import uav_trajectory import time import tf #from crazyflie_driver.msg import Hover from std_msgs.msg import",
"kalman cf.setParam(\"kalman/initialX\", 0) cf.setParam(\"kalman/initialY\", 0) cf.setParam(\"kalman/initialZ\", 0) cf.setParam(\"kalman/resetEstimation\", 1) ######## cf.setParam(\"stabilizer/controller\", 2) #",
"cf = crazyflie.Crazyflie(\"/cf1\", \"world\") rospy.wait_for_service(prefix + '/update_params') rospy.loginfo(\"found update_params service\") cf.setParam(\"commander/enHighLevel\", 1) cf.setParam(\"stabilizer/estimator\",",
"cf.setParam(\"stabilizer/controller\", 2) # 2=Use mellinger controller time.sleep(1.0) rospy.loginfo(\"launching\") #cf.takeoff(targetHeight = 0.4, duration =",
"= 0.4, duration = 3.0) #time.sleep(5.0) traj1 = uav_trajectory.Trajectory() traj1.loadcsv(\"/home/user/catkin_ws/src/crazyflie_ros/crazyflie_demo/scripts/takeoff.csv\") traj2 = uav_trajectory.Trajectory()"
] |
[
"val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): #",
"return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return",
"CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL",
"= response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) #",
"json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"]",
"\"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID }",
"Authentication Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url",
"expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def",
"getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def",
"play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6",
"}, \"position_ms\": 0 } # Auth Step 6: Use the access token to",
"= \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4: Requests",
"= requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint",
"= \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def",
"def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if",
"url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args)",
"SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, #",
"defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all the steps, parameters,",
"Step 4: Requests refresh and access tokens auth_token = request.args['code'] code_payload = {",
"Auth Step 5: Tokens are Returned to Application response_data = json.loads(post_request.text) session['access_token'] =",
"authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code'",
"print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])}",
"CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL",
"\"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\"",
"\"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side",
"= { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\":",
"Auth Step 4: Requests refresh and access tokens auth_token = request.args['code'] code_payload =",
"# Auth Step 4: Requests refresh and access tokens auth_token = request.args['code'] code_payload",
"6: Use the access token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request",
"@app.route(\"/\") def index(): # Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for",
"@app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": {",
"Flask(__name__) app.secret_key = \"super secret key\" # Authentication Steps, paramaters, and responses are",
"= getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def",
"Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\"",
"Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL =",
"'' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\":",
"'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint,",
"requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint =",
"access tokens auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\":",
"see all the steps, parameters, and expected response. # Client Keys CLIENT_ID =",
"auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4:",
"4: Requests refresh and access tokens auth_token = request.args['code'] code_payload = { \"grant_type\":",
"= response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type =",
"\"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT =",
"# print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body = {",
"SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters",
"\"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL,",
"data=code_payload) # Auth Step 5: Tokens are Returned to Application response_data = json.loads(post_request.text)",
"response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) #",
"urllib.parse import quote app = Flask(__name__) app.secret_key = \"super secret key\" # Authentication",
"post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned to Application",
"body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0 }",
"responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all the",
"authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if __name__ == \"__main__\": app.run(debug=True, port=PORT)",
"authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 },",
"expected response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify",
"# \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): #",
"def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if __name__ == \"__main__\":",
"@app.route(\"/callback\") def callback(): # Auth Step 4: Requests refresh and access tokens auth_token",
"REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool",
"paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see",
"parameters, and expected response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\"",
"callback(): # Auth Step 4: Requests refresh and access tokens auth_token = request.args['code']",
"refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token)",
"session import requests import json from urllib.parse import quote app = Flask(__name__) app.secret_key",
"STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\":",
"return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request =",
"tokens auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI,",
"Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to",
"5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\"",
"\"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4: Requests refresh",
"from urllib.parse import quote app = Flask(__name__) app.secret_key = \"super secret key\" #",
"code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET,",
"Requests refresh and access tokens auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\",",
"= requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned to Application response_data",
"response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"]",
"token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return",
"refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if __name__",
"\"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload)",
"{ \"position\": 6 }, \"position_ms\": 0 } # Auth Step 6: Use the",
"} @app.route(\"/\") def index(): # Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val))",
"CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private",
"in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth",
"return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4: Requests refresh and access",
"= \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return",
"6 }, \"position_ms\": 0 } # Auth Step 6: Use the access token",
"are Returned to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"]",
"# Auth Step 6: Use the access token to access Spotify API play_endpoint",
"SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth Step 1: Authorization url_args",
"Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return",
"'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are",
"= \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT",
"{ \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request",
"pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next():",
"are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all the steps,",
"steps, parameters, and expected response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET =",
"= getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\")",
"5: Tokens are Returned to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token']",
"next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return",
"'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5:",
"url to see all the steps, parameters, and expected response. # Client Keys",
"REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step",
"= response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return ''",
"{ \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str,",
"response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in)",
"# print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body",
"pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea')",
"url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4: Requests refresh and",
"= 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool =",
"Step 6: Use the access token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL)",
"Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url",
"API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code'",
"def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code))",
"\"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url)",
"access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] #",
"print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if __name__ ==",
"} # Auth Step 6: Use the access token to access Spotify API",
"response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token",
"# Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in",
"# \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth Step 1:",
"\"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header =",
"SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index():",
"requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\":",
"response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify URLS",
"# print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL)",
"play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header",
"CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned",
"this url to see all the steps, parameters, and expected response. # Client",
"= \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI",
"\"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()",
"\"offset\": { \"position\": 6 }, \"position_ms\": 0 } # Auth Step 6: Use",
"to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] =",
"print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader()",
"app = Flask(__name__) app.secret_key = \"super secret key\" # Authentication Steps, paramaters, and",
"@app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header)",
"redirect, session import requests import json from urllib.parse import quote app = Flask(__name__)",
"to see all the steps, parameters, and expected response. # Client Keys CLIENT_ID",
"= request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID,",
"pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header",
"'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header",
"session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type",
"\"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth Step 1: Authorization",
"Flask, request, redirect, session import requests import json from urllib.parse import quote app",
"https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all the steps, parameters, and expected",
"import quote app = Flask(__name__) app.secret_key = \"super secret key\" # Authentication Steps,",
"import json from urllib.parse import quote app = Flask(__name__) app.secret_key = \"super secret",
"Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public",
"SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL",
"= 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE =",
"= True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\":",
"session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in",
"access token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header,",
"data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint =",
"print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request",
"\"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0 } # Auth Step",
"Visit this url to see all the steps, parameters, and expected response. #",
"= \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\",",
"= \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header",
"json from urllib.parse import quote app = Flask(__name__) app.secret_key = \"super secret key\"",
"\"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL =",
"\"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth",
"import json from flask import Flask, request, redirect, session import requests import json",
"API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\"",
"Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE =",
"\"position\": 6 }, \"position_ms\": 0 } # Auth Step 6: Use the access",
"secret key\" # Authentication Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ #",
"\"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL,",
"the steps, parameters, and expected response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET",
"\"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI =",
"def index(): # Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key,",
"{ \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0 } # Auth",
"headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL)",
"play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\")",
"import requests import json from urllib.parse import quote app = Flask(__name__) app.secret_key =",
"quote(val)) for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\")",
"print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body =",
"# Visit this url to see all the steps, parameters, and expected response.",
"= { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0 } #",
"Step 5: Tokens are Returned to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"]",
"# Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE",
"= \"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL =",
"@app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header)",
"= { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, }",
"# Authentication Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this",
"session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token",
"\"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\"",
"\"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0 } # Auth Step 6:",
"= response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in =",
"\"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader():",
"\"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\"",
"str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE,",
"\"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def",
"Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"]",
"headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer",
"= getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\":",
"from flask import Flask, request, redirect, session import requests import json from urllib.parse",
"# Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION",
"app.secret_key = \"super secret key\" # Authentication Steps, paramaters, and responses are defined",
"flask import Flask, request, redirect, session import requests import json from urllib.parse import",
"playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters",
"= \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str =",
"user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = {",
"requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader()",
"# Auth Step 5: Tokens are Returned to Application response_data = json.loads(post_request.text) session['access_token']",
"at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all the steps, parameters, and",
"import Flask, request, redirect, session import requests import json from urllib.parse import quote",
"key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback():",
"= response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token)",
"return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\",",
"\"position_ms\": 0 } # Auth Step 6: Use the access token to access",
"authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code'",
"pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return 'pause_request.status_code' @app.route(\"/next\") def next(): authorization_header = getAuthorizationHeader()",
"= \"super secret key\" # Authentication Steps, paramaters, and responses are defined at",
"\"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID",
"= str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\":",
"\"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause():",
"= \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL",
"# print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header =",
"\"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth",
"} post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned to",
"= requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def getAuthorizationHeader(): authorization_header =",
"SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000",
"pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint, headers=authorization_header) print((pause_request.status_code)) return",
"response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"]",
"return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request =",
"response_data[\"token_type\"] expires_in = response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\")",
"and expected response. # Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" #",
"URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\"",
"= \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL =",
"SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str",
"json from flask import Flask, request, redirect, session import requests import json from",
"REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\")",
"# Client Keys CLIENT_ID = \"\" CLIENT_SECRET = \"\" # Spotify URLS SPOTIFY_AUTH_URL",
"STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth Step",
"index(): # Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val",
"= json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token =",
"getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\": 6 }, \"position_ms\": 0",
"auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step",
"token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body))",
"print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\":",
"True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE,",
"to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) #",
"getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken():",
"def next(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json()))",
"\"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, # \"show_dialog\": SHOW_DIALOG_str, \"client_id\":",
"request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret':",
"= \"{}/me/player/devices\".format(SPOTIFY_API_URL) pause_request = requests.get(pause_profile_endpoint, headers=authorization_header) print((pause_request.json())) return 'pause_request.status_code' def refreshAccessToken(): print('yea') def",
"Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()])",
"Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION =",
"for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL, url_args) return redirect(auth_url) @app.route(\"/callback\") def",
"= Flask(__name__) app.secret_key = \"super secret key\" # Authentication Steps, paramaters, and responses",
"Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url = \"{}/?{}\".format(SPOTIFY_AUTH_URL,",
"headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint",
"requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned to Application response_data =",
"CLIENT_ID } @app.route(\"/\") def index(): # Auth Step 1: Authorization url_args = \"&\".join([\"{}={}\".format(key,",
"Returned to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in']",
"= \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION) #",
"\"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request =",
"response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token = response_data[\"refresh_token\"] token_type = response_data[\"token_type\"] expires_in = response_data[\"expires_in\"]",
"Auth Step 6: Use the access token to access Spotify API play_endpoint =",
"and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit this url to see all",
"SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL = \"https://api.spotify.com\" API_VERSION = \"v1\" SPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION)",
"\"client_id\": CLIENT_ID } @app.route(\"/\") def index(): # Auth Step 1: Authorization url_args =",
"auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI, \"scope\": SCOPE, # \"state\": STATE, #",
"def play(): authorization_header = getAuthorizationHeader() body = { \"context_uri\": \"spotify:playlist:5XCRfaXW22GIQIZrUrw2gc\", \"offset\": { \"position\":",
"= \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming",
"access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json())",
"\"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\":",
"CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens",
"the access token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request = requests.put(play_endpoint,",
"refresh and access tokens auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\":",
"key\" # Authentication Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/ # Visit",
"and access tokens auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token),",
"= requests.put(play_endpoint, headers=authorization_header, data=json.dumps(body)) # print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header =",
"all the steps, parameters, and expected response. # Client Keys CLIENT_ID = \"\"",
"PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE",
"'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request = requests.put(pause_profile_endpoint,",
"print(play_request.json()) return 'play_request.status_code' @app.route(\"/pause\") def pause(): authorization_header = getAuthorizationHeader() pause_profile_endpoint = \"{}/me/player/pause\".format(SPOTIFY_API_URL) pause_request",
"\"super secret key\" # Authentication Steps, paramaters, and responses are defined at https://developer.spotify.com/web-api/authorization-guide/",
"response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play(): authorization_header",
"SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { \"response_type\": \"code\", \"redirect_uri\": REDIRECT_URI,",
"= response_data[\"expires_in\"] # print(access_token) # print(refresh_token) # print(expires_in) return '' @app.route(\"/play\") def play():",
"Tokens are Returned to Application response_data = json.loads(post_request.text) session['access_token'] = response_data[\"access_token\"] session['refresh_token'] =",
"requests import json from urllib.parse import quote app = Flask(__name__) app.secret_key = \"super",
"auth_token = request.args['code'] code_payload = { \"grant_type\": \"authorization_code\", \"code\": str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id':",
"quote app = Flask(__name__) app.secret_key = \"super secret key\" # Authentication Steps, paramaters,",
"request, redirect, session import requests import json from urllib.parse import quote app =",
"0 } # Auth Step 6: Use the access token to access Spotify",
"Use the access token to access Spotify API play_endpoint = \"{}/me/player/play\".format(SPOTIFY_API_URL) play_request =",
"= response_data[\"access_token\"] session['refresh_token'] = response_data[\"refresh_token\"] session['expires_in'] = response_data[\"expires_in\"] access_token = response_data[\"access_token\"] refresh_token =",
"redirect(auth_url) @app.route(\"/callback\") def callback(): # Auth Step 4: Requests refresh and access tokens",
"API_VERSION) # Server-side Parameters CLIENT_SIDE_URL = \"http://localhost\" PORT = 5000 REDIRECT_URI = 'http://localhost:5000/callback'",
"getAuthorizationHeader(): authorization_header = {\"Authorization\": \"Bearer {}\".format(session['access_token'])} return authorization_header if __name__ == \"__main__\": app.run(debug=True,",
"streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters =",
"1: Authorization url_args = \"&\".join([\"{}={}\".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url =",
"def callback(): # Auth Step 4: Requests refresh and access tokens auth_token =",
"'http://localhost:5000/callback' SCOPE = \"playlist-modify-public playlist-modify-private streaming user-read-playback-state\" STATE = \"\" SHOW_DIALOG_bool = True",
"str(auth_token), \"redirect_uri\": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) #",
"= \"\" # Spotify URLS SPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\" SPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\" SPOTIFY_API_BASE_URL ="
] |
[
"from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns",
"api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w ]+)/$', api_views.search_external), url(r'^api/', include(router.urls)), )",
"from rest_framework import routers from books.api import views as api_views from books import",
"views as api_views from books import views router = routers.DefaultRouter() # TODO: Nest",
"router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w ]+)/$', api_views.search_external), url(r'^api/', include(router.urls)),",
"import views router = routers.DefaultRouter() # TODO: Nest API endpoints # # from",
"routers.DefaultRouter() # TODO: Nest API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books',",
"# # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers',",
"django.conf.urls import patterns, include, url from rest_framework import routers from books.api import views",
"import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns(",
"api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w ]+)/$', api_views.search_external), url(r'^api/',",
"import patterns, include, url from rest_framework import routers from books.api import views as",
"api_views from books import views router = routers.DefaultRouter() # TODO: Nest API endpoints",
"api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w ]+)/$',",
"include, url from rest_framework import routers from books.api import views as api_views from",
"ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '',",
"router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w ]+)/$', api_views.search_external),",
"import routers from books.api import views as api_views from books import views router",
"# TODO: Nest API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet)",
"= routers.DefaultRouter() # TODO: Nest API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter",
"# from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet)",
"Nest API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet)",
"url from rest_framework import routers from books.api import views as api_views from books",
"from books.api import views as api_views from books import views router = routers.DefaultRouter()",
"endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet)",
"rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns =",
"TODO: Nest API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions',",
"from books import views router = routers.DefaultRouter() # TODO: Nest API endpoints #",
"routers from books.api import views as api_views from books import views router =",
"router = routers.DefaultRouter() # TODO: Nest API endpoints # # from rest_framework_extensions.routers import",
"rest_framework import routers from books.api import views as api_views from books import views",
"API endpoints # # from rest_framework_extensions.routers import ExtendedSimpleRouter router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors',",
"books import views router = routers.DefaultRouter() # TODO: Nest API endpoints # #",
"from django.conf.urls import patterns, include, url from rest_framework import routers from books.api import",
"patterns, include, url from rest_framework import routers from books.api import views as api_views",
"as api_views from books import views router = routers.DefaultRouter() # TODO: Nest API",
"router.register(r'books', api_views.BookViewSet) router.register(r'editions', api_views.EditionViewSet) router.register(r'authors', api_views.AuthorViewSet) router.register(r'publishers', api_views.PublisherViewSet) urlpatterns = patterns( '', url(r'^api/search/external/(?P<q>[\\w",
"views router = routers.DefaultRouter() # TODO: Nest API endpoints # # from rest_framework_extensions.routers",
"books.api import views as api_views from books import views router = routers.DefaultRouter() #",
"import views as api_views from books import views router = routers.DefaultRouter() # TODO:"
] |
[
"response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location =",
"bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price =",
"=jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask",
", request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names()",
"from flask import Flask , request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def",
"float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price",
"location = float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response",
"def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response",
"@app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk'])",
"#response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk'])",
"util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server from Home",
"render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath =",
"#}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server from Home proce",
"Flask , request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response =",
"total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names()",
"util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk",
"= int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath)",
"float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price)",
"def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft'])",
"#response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python",
"import Flask , request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response",
", jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*')",
"= float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({",
"= util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\":",
"app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def",
"estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server",
"= float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html',",
"= util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location'])",
"render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server from Home proce prediction...\") app.run()",
"response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if",
"bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return",
"util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting",
"return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath",
"flask import Flask , request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names():",
"util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST'])",
"request , jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response)",
"import util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response)",
"return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server from Home proce prediction...\")",
"@app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price():",
"jsonify,render_template import util app=Flask(__name__) @app.route('/') def get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return",
"get_location_names(): response = util.get_location_names() print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location",
"int(request.form['bhk']) bath = float(request.form['bhk']) response = util.get_location_names() #response =jsonify({ estimated_price = util.get_estimateud_price(location,total_sqft,bhk,bath) #})",
"= util.get_estimateud_price(location,total_sqft,bhk,bath) #}) return render_template('app.html', response=response,price=estimated_price) if __name__==\"__main__\": print(\"Starting Python flask server from",
"print(response) #response.headers.add('Access-control-Allow-origin','*') return render_template('app.html',response=response) @app.route('/predict_house_price',methods=['POST']) def predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk =",
"predict_house_price(): total_sqft=float(request.form['total_sqft']) location = float(request.form['location']) bhk = int(request.form['bhk']) bath = float(request.form['bhk']) response ="
] |
[
"individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col)",
"= _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual",
"cluster_by (str): column name of the variable to cluster by. seed (int): Random",
"arrays with positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is None:",
"cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory issues you should",
"positional indices of observations in data. Returns: list: list of DataFrames \"\"\" out",
"with positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is None: bootstrap_indices",
"None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters =",
"for datasets with many variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column",
"cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data,",
"is None. Returns: list: list of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data,",
"list of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, )",
"should use get_bootstrap_indices instead and construct the full samples only as needed. Args:",
") datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices",
"\"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy())",
"data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing positional indices",
"draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap",
"positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is None: bootstrap_indices =",
"construct the full samples only as needed. Args: data (pandas.DataFrame): original dataset. cluster_by",
"\"\"\"Convert the drawn clusters to positional indices of individual observations. Args: cluster_col (pandas.Series):",
"Returns: list: list of DataFrames \"\"\" out = [data.iloc[idx] for idx in bootstrap_indices]",
"variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of the variable",
"the drawn clusters to positional indices of individual observations. Args: cluster_col (pandas.Series): \"\"\"",
"and construct the full samples only as needed. Args: data (pandas.DataFrame): original dataset.",
"= [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices",
"None. Returns: list: list of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by,",
"of the variable to cluster by. seed (int): Random seed. n_draws (int): number",
"\"\"\"convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices",
"samples only as needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name",
"indices instead of the full bootstrap samples saves a lot of memory for",
"dataset. bootstrap_indices (list): List with numpy arrays containing positional indices of observations in",
"Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of the variable to",
"[] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def",
"instead and construct the full samples only as needed. Args: data (pandas.DataFrame): original",
"the positional indices instead of the full bootstrap samples saves a lot of",
"np import pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices",
"_convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters",
"of bootstrap samples. Storing the positional indices instead of the full bootstrap samples",
"bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional indices of individual",
"drawn clusters to positional indices of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices",
"cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices):",
"_convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional indices of individual observations. Args:",
"Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing positional",
"Returns: list: list of numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs =",
"is None. Returns: list: list of numpy arrays with positional indices \"\"\" np.random.seed(seed)",
"of draws, only relevant if seeds is None. Returns: list: list of resampled",
"observations in data. Returns: list: list of DataFrames \"\"\" out = [data.iloc[idx] for",
"name of the variable to cluster by. seed (int): Random seed. n_draws (int):",
"indices for the construction of bootstrap samples. Storing the positional indices instead of",
"get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory issues you",
"variable to cluster by. seed (int): Random seed. n_draws (int): number of draws,",
"observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for",
"seeds is None. Returns: list: list of numpy arrays with positional indices \"\"\"",
"n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap",
"get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction of bootstrap samples.",
"numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is",
"bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you",
"memory for datasets with many variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str):",
") return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional indices",
"seed. n_draws (int): number of draws, only relevant if seeds is None. Returns:",
"saves a lot of memory for datasets with many variables. Args: data (pandas.DataFrame):",
"bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list):",
"n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory issues you should use get_bootstrap_indices",
"n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True )",
"cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique()",
"in data. Returns: list: list of DataFrames \"\"\" out = [data.iloc[idx] for idx",
"pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None,",
"(pandas.DataFrame): original dataset. cluster_by (str): column name of the variable to cluster by.",
"index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000):",
"issues you should use get_bootstrap_indices instead and construct the full samples only as",
"only relevant if seeds is None. Returns: list: list of resampled datasets. \"\"\"",
"if seeds is None. Returns: list: list of resampled datasets. \"\"\" indices =",
"the construction of bootstrap samples. Storing the positional indices instead of the full",
"n_draws (int): number of draws, only relevant if seeds is None. Returns: list:",
"(int): Random seed. n_draws (int): number of draws, only relevant if seeds is",
"\"\"\"Draw bootstrap samples. If you have memory issues you should use get_bootstrap_indices instead",
"for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw",
"data (pandas.DataFrame): original dataset. cluster_by (str): column name of the variable to cluster",
"Returns: list: list of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed,",
"of memory for datasets with many variables. Args: data (pandas.DataFrame): original dataset. cluster_by",
"clusters to positional indices of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices =",
"of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets",
"as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction",
"import pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for",
"def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional indices of individual observations.",
"import numpy as np import pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000):",
"positional indices for the construction of bootstrap samples. Storing the positional indices instead",
"def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction of bootstrap",
"get_bootstrap_indices instead and construct the full samples only as needed. Args: data (pandas.DataFrame):",
"(str): column name of the variable to cluster by. seed (int): Random seed.",
"actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy",
"(pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters:",
"= pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None,",
"np.random.seed(seed) n_obs = len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws,",
"you have memory issues you should use get_bootstrap_indices instead and construct the full",
"is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters",
"list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws,",
"n_draws=1000): \"\"\"Draw positional indices for the construction of bootstrap samples. Storing the positional",
"seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert",
"bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return",
"samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing",
"you should use get_bootstrap_indices instead and construct the full samples only as needed.",
"indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List",
"\"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices)",
"len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters",
"numpy arrays containing positional indices of observations in data. Returns: list: list of",
"instead of the full bootstrap samples saves a lot of memory for datasets",
"to positional indices of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = []",
"of draws, only relevant if seeds is None. Returns: list: list of numpy",
"positional indices of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs",
"as needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of the",
"column name of the variable to cluster by. seed (int): Random seed. n_draws",
"list: list of resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws,",
"for the construction of bootstrap samples. Storing the positional indices instead of the",
"bootstrap samples. Storing the positional indices instead of the full bootstrap samples saves",
"with many variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of",
") bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert",
"None. Returns: list: list of numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs",
"bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples.",
"list of numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if",
"list: list of DataFrames \"\"\" out = [data.iloc[idx] for idx in bootstrap_indices] return",
"a lot of memory for datasets with many variables. Args: data (pandas.DataFrame): original",
"return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples. Args:",
"use get_bootstrap_indices instead and construct the full samples only as needed. Args: data",
"list: list of numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs = len(data)",
"datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data,",
"arrays containing positional indices of observations in data. Returns: list: list of DataFrames",
"bootstrap samples. If you have memory issues you should use get_bootstrap_indices instead and",
"\"\"\"Draw positional indices for the construction of bootstrap samples. Storing the positional indices",
"np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return",
"original dataset. bootstrap_indices (list): List with numpy arrays containing positional indices of observations",
"positional indices instead of the full bootstrap samples saves a lot of memory",
"indices of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs =",
"= data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices(",
"the full samples only as needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str):",
"of observations in data. Returns: list: list of DataFrames \"\"\" out = [data.iloc[idx]",
"indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0,",
"= list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters,",
"Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw",
"into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with",
"else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices",
"return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional indices of",
"draws, only relevant if seeds is None. Returns: list: list of numpy arrays",
"to cluster by. seed (int): Random seed. n_draws (int): number of draws, only",
"= get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets",
"def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame):",
"clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices",
"number of draws, only relevant if seeds is None. Returns: list: list of",
"draws, only relevant if seeds is None. Returns: list: list of resampled datasets.",
"pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction of",
"datasets with many variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name",
"len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col,",
"the variable to cluster by. seed (int): Random seed. n_draws (int): number of",
"bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays",
"data. Returns: list: list of DataFrames \"\"\" out = [data.iloc[idx] for idx in",
"cluster by. seed (int): Random seed. n_draws (int): number of draws, only relevant",
"original dataset. cluster_by (str): column name of the variable to cluster by. seed",
"only as needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of",
"seeds is None. Returns: list: list of resampled datasets. \"\"\" indices = get_bootstrap_indices(",
"datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples. Args: data",
"data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data,",
"n_obs = len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs)))",
"clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices =",
"the full bootstrap samples saves a lot of memory for datasets with many",
"cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)), index=cluster_col) for draw in",
"List with numpy arrays containing positional indices of observations in data. Returns: list:",
"drawn_clusters): \"\"\"Convert the drawn clusters to positional indices of individual observations. Args: cluster_col",
"replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters):",
"if seeds is None. Returns: list: list of numpy arrays with positional indices",
"needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of the variable",
"(list): List with numpy arrays containing positional indices of observations in data. Returns:",
"size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def",
"of the full bootstrap samples saves a lot of memory for datasets with",
"of numpy arrays with positional indices \"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by",
"(int): number of draws, only relevant if seeds is None. Returns: list: list",
"resampled datasets. \"\"\" indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets =",
"seed (int): Random seed. n_draws (int): number of draws, only relevant if seeds",
"Random seed. n_draws (int): number of draws, only relevant if seeds is None.",
"full bootstrap samples saves a lot of memory for datasets with many variables.",
"relevant if seeds is None. Returns: list: list of numpy arrays with positional",
"get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def",
"with numpy arrays containing positional indices of observations in data. Returns: list: list",
"have memory issues you should use get_bootstrap_indices instead and construct the full samples",
"indices of observations in data. Returns: list: list of DataFrames \"\"\" out =",
"= _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn",
"drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to positional",
"drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters",
"return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have",
"dataset. cluster_by (str): column name of the variable to cluster by. seed (int):",
"_get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap",
"bootstrap samples saves a lot of memory for datasets with many variables. Args:",
"bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the",
"relevant if seeds is None. Returns: list: list of resampled datasets. \"\"\" indices",
"of individual observations. Args: cluster_col (pandas.Series): \"\"\" bootstrap_indices = [] cluster_to_locs = pd.Series(np.arange(len(cluster_col)),",
"Storing the positional indices instead of the full bootstrap samples saves a lot",
"drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If",
"seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory issues you should use",
"_get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original",
"\"\"\" np.random.seed(seed) n_obs = len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs,",
"data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by],",
"bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory",
"only relevant if seeds is None. Returns: list: list of numpy arrays with",
"if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters =",
"numpy as np import pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw",
"size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True",
"bootstrap_indices): \"\"\"convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset.",
"containing positional indices of observations in data. Returns: list: list of DataFrames \"\"\"",
"lot of memory for datasets with many variables. Args: data (pandas.DataFrame): original dataset.",
"= np.random.choice( clusters, size=(n_draws, len(clusters)), replace=True ) bootstrap_indices = _convert_cluster_ids_to_indices( data[cluster_by], drawn_clusters )",
"indices = get_bootstrap_indices( data=data, cluster_by=cluster_by, seed=seed, n_draws=n_draws, ) datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return",
"n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice( clusters, size=(n_draws, len(clusters)),",
"full samples only as needed. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column",
"seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction of bootstrap samples. Storing the",
"If you have memory issues you should use get_bootstrap_indices instead and construct the",
"samples. Storing the positional indices instead of the full bootstrap samples saves a",
"cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the construction of bootstrap samples. Storing",
"pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional indices for the",
"by. seed (int): Random seed. n_draws (int): number of draws, only relevant if",
"= len(data) if cluster_by is None: bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else:",
"datasets = _get_bootstrap_samples_from_indices(data=data, bootstrap_indices=indices) return datasets def _get_bootstrap_samples_from_indices(data, bootstrap_indices): \"\"\"convert bootstrap indices into",
"bootstrap_indices = list(np.random.randint(0, n_obs, size=(n_draws, n_obs))) else: clusters = data[cluster_by].unique() drawn_clusters = np.random.choice(",
"memory issues you should use get_bootstrap_indices instead and construct the full samples only",
"list of DataFrames \"\"\" out = [data.iloc[idx] for idx in bootstrap_indices] return out",
"as np import pandas as pd def get_bootstrap_indices(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw positional",
"in drawn_clusters: bootstrap_indices.append(cluster_to_locs[draw].to_numpy()) return bootstrap_indices def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples.",
"many variables. Args: data (pandas.DataFrame): original dataset. cluster_by (str): column name of the",
"def get_bootstrap_samples(data, cluster_by=None, seed=None, n_draws=1000): \"\"\"Draw bootstrap samples. If you have memory issues",
"(pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing positional indices of",
"bootstrap_indices (list): List with numpy arrays containing positional indices of observations in data.",
"construction of bootstrap samples. Storing the positional indices instead of the full bootstrap",
"data[cluster_by], drawn_clusters ) return bootstrap_indices def _convert_cluster_ids_to_indices(cluster_col, drawn_clusters): \"\"\"Convert the drawn clusters to",
"samples saves a lot of memory for datasets with many variables. Args: data",
"samples. If you have memory issues you should use get_bootstrap_indices instead and construct"
] |
[
"class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as",
"**kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call, self.tasks))",
"from concurrent.futures import ThreadPoolExecutor from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args,",
"t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call, self.tasks)) return self.f(results, *args, **kwargs)",
"*args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call,",
"concurrent.futures import ThreadPoolExecutor from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs):",
"def __call__(self, *args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results",
"from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return",
"def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call, self.tasks)) return",
"call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call, self.tasks)) return self.f(results,",
"Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4)",
"__call__(self, *args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results =",
"garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return t.__call__()",
"import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return t.__call__() with",
"ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t): return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool:",
"ThreadPoolExecutor from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def call(t):",
"return t.__call__() with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(call, self.tasks)) return self.f(results, *args,",
"import ThreadPoolExecutor from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self, *args, **kwargs): def",
"<gh_stars>0 from concurrent.futures import ThreadPoolExecutor from garnish.garnish import Layer class ConcurrentFetchLayer(Layer): def __call__(self,"
] |
[
"= secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if",
"None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL)",
"None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION",
"db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT',",
"= env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN', None))",
"Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True)",
"= env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn):",
"DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN', None)) FROM_EMAIL = env('FROM_EMAIL', None)",
"secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response",
"= env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else:",
"endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return",
"env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN', None)) FROM_EMAIL",
"AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client",
"return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION",
"Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED",
"= boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response =",
"'') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION =",
"None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION',",
"= env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None:",
"None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN', None)) FROM_EMAIL =",
"env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if",
"if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN', None)) FROM_EMAIL = env('FROM_EMAIL',",
"env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION",
"None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn",
"LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION)",
"env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return",
"environs import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST',",
"env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED =",
"import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None)",
"import boto3 from environs import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None)",
"default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None",
"json import boto3 from environs import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL',",
"fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT",
"import json import boto3 from environs import Env env = Env() AWS_ENDPOINT_URL =",
"DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION = json.loads(DB_CONNECTION) else: DB_CONNECTION = fetch_db_secret(env('DB_SECRET_ARN',",
"boto3 from environs import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST",
"env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager',",
"boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn)",
"def fetch_db_secret(db_secret_arn): if db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString'])",
"if db_secret_arn is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT =",
"from environs import Env env = Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST =",
"is None: return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '')",
"= Env() AWS_ENDPOINT_URL = env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED',",
"return None response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION =",
"secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION:",
"json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None) if DB_CONNECTION: DB_CONNECTION =",
"EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def fetch_db_secret(db_secret_arn): if db_secret_arn is",
"SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client = boto3.client('secretsmanager', endpoint_url=AWS_ENDPOINT_URL) def",
"response = secrets_manager_client.get_secret_value(SecretId=db_secret_arn) return json.loads(response['SecretString']) LAMBDA_TASK_ROOT = env('LAMBDA_TASK_ROOT', '') DB_CONNECTION = env('DB_CONNECTION', None)",
"= env('AWS_ENDPOINT_URL', None) SMTP_HOST = env('SMTP_HOST', None) EMAIL_ENABLED = env.bool('EMAIL_ENABLED', default=True) secrets_manager_client ="
] |
[
"expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack()",
"btn_txt.set(\"Stop\") tt = time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def",
"= time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if",
"= CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack()",
"frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True)",
"if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running = not running",
"time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get()",
"= CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but",
"CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\",",
"= CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch)",
"= False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm",
"lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch)",
"running = False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\")",
"textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but = CMD.Button(root, textvariable=btn_txt,",
"CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but =",
"btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running",
"command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt,",
"textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt,",
"tt = time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch():",
"but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but",
"threading import time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time()",
"lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but",
"time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while running:",
"= CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but",
"textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root,",
"running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\":",
"running threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt =",
"False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm =",
"def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running =",
"= CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but =",
"import time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while",
"CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t =",
"CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt)",
"root = CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root)",
"while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() ==",
"import threading import time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt =",
"running = not running threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt =",
"btn_txt.set(\"Start\") txt.set(\"\") return global running running = not running threading.Thread(target=counter).start() running = False",
"global running running = not running threading.Thread(target=counter).start() running = False root = CMD.CMDUI()",
"return global running running = not running threading.Thread(target=counter).start() running = False root =",
"= f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\")",
"CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t)",
"def counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01)",
"import sys sys.path.insert(0,'..') import threading import time import CMDUI as CMD def counter():",
"sys sys.path.insert(0,'..') import threading import time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\")",
"CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but =",
"but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"left\")",
"t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\")",
"txt.set(\"\") return global running running = not running threading.Thread(target=counter).start() running = False root",
"time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running",
"frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt,",
"= not running threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt = CMD.StringVar()",
"btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running = not running threading.Thread(target=counter).start()",
"command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but = CMD.Button(root, textvariable=btn_txt, command=stopwatch)",
"btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\")",
"btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root,",
"txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab =",
"but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"left\") root.mainloop()",
"stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running = not",
"CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab",
"\"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running = not running threading.Thread(target=counter).start() running =",
"f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return",
"sys.path.insert(0,'..') import threading import time import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt",
"= CMD.StringVar() btn_txt = CMD.StringVar() btn_txt.set(\"Start\") frm = CMD.Frame(root) frm.pack() lab = CMD.Label(frm,",
"CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root,",
"as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t = f\"{time.time()-tt:.2f}\"",
"running running = not running threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt",
"but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch)",
"<filename>examples/cmdui_example.py import sys sys.path.insert(0,'..') import threading import time import CMDUI as CMD def",
"import CMDUI as CMD def counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t",
"txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\") def stopwatch(): if btn_txt.get() == \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global",
"but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\")",
"counter(): btn_txt.set(\"Stop\") tt = time.time() while running: t = f\"{time.time()-tt:.2f}\" txt.set(t) time.sleep(0.01) btn_txt.set(\"Reset\")",
"== \"Reset\": btn_txt.set(\"Start\") txt.set(\"\") return global running running = not running threading.Thread(target=counter).start() running",
"not running threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt",
"= CMD.Label(frm, textvariable=txt) lab.pack(side=\"bottom\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"top\", expand=True) but =",
"CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack(side=\"right\") but = CMD.Button(root, textvariable=btn_txt, command=stopwatch) but.pack() but = CMD.Button(root,",
"threading.Thread(target=counter).start() running = False root = CMD.CMDUI() txt = CMD.StringVar() btn_txt = CMD.StringVar()"
] |